pax_global_header00006660000000000000000000000064145053205350014514gustar00rootroot0000000000000052 comment=3ac2d0ef5fa36ebdf5f5caa4f61b2bde7aecb77b sight-23.1.0/000077500000000000000000000000001450532053500127155ustar00rootroot00000000000000sight-23.1.0/.clang-tidy000066400000000000000000000067651450532053500147670ustar00rootroot00000000000000--- Checks: '*,-llvm-header-guard,-llvm-include-order,-llvmlibc-*,-fuchsia-*,-altera-struct-pack-align,-modernize-use-trailing-return-type,-misc-non-private-member-variables-in-classes,-google-readability-namespace-comments,-cppcoreguidelines-avoid-magic-numbers,-readability-magic-numbers,-google-readability-todo,-cppcoreguidelines-special-member-functions,-hicpp-special-member-functions,-cppcoreguidelines-pro-bounds-pointer-arithmetic,-altera-unroll-loops,-cppcoreguidelines-pro-bounds-constant-array-index,-cppcoreguidelines-avoid-non-const-global-variables,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-hicpp-no-array-decay,-google-default-arguments,-altera-id-dependent-backward-branch,-cppcoreguidelines-pro-type-reinterpret-cast,-cert-err58-cpp,-bugprone-easily-swappable-parameters,-cppcoreguidelines-owning-memory,-misc-no-recursion,-concurrency-mt-unsafe,-abseil-*,-clang-analyzer-cplusplus.NewDelete,-bugprone-exception-escape,-cppcoreguidelines-pro-type-static-cast-downcast,-cppcoreguidelines-pro-type-union-access,-readability-redundant-access-specifiers,-readability-function-cognitive-complexity,-clang-analyzer-cplusplus.NewDeleteLeaks,-android-cloexec-fopen,-hicpp-signed-bitwise,-bugprone-unhandled-exception-at-new,-openmp-use-default-none,-performance-no-int-to-ptr,-clang-diagnostic-*,-google-readability-casting,-readability-identifier-length,-clang-analyzer-cplusplus.StringChecker,-readability-redundant-string-cstr,-performance-unnecessary-value-param,-performance-inefficient-string-concatenation,-misc-include-cleaner,-misc-const-correctness,-cppcoreguidelines-avoid-do-while,-performance-avoid-endl,-bugprone-unchecked-optional-access,-misc-use-anonymous-namespace,-readability-simplify-boolean-expr' WarningsAsErrors: '*' HeaderFilterRegex: '^((?!/3rd-party/|/patch/).)*$' CheckOptions: - key: readability-simplify-boolean-expr.ChainedConditionalReturn value: true - key: readability-simplify-boolean-expr.ChainedConditionalAssignment value: true - key: google-runtime-int.UnsignedTypePrefix value: std::uint - key: google-runtime-int.SignedTypePrefix value: std::int - key: google-runtime-int.TypeSuffix value: _t - key: cppcoreguidelines-init-variables.MathHeader value: - key: modernize-loop-convert.MinConfidence value: risky - key: bugprone-misplaced-widening-cast.CheckImplicitCasts value: true - key: cppcoreguidelines-macro-usage.AllowedRegexp value: ^ASSERT* - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic value: true - key: bugprone-assert-side-effect.AssertMacros value: SIGHT_ASSERT - key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression value: true - key: bugprone-suspicious-enum-usage.StrictMode value: 1 - key: readability-identifier-naming.ClassCase value: CamelCase - key: readability-identifier-naming.NamespaceCase value: camelBack - key: readability-identifier-naming.FunctionCase value: camelBack - key: readability-identifier-naming.MethodCase value: camelBack - key: readability-identifier-naming.MethodIgnoredRegexp value: New - key: readability-identifier-naming.PrivateMemberCase value: camelBack - key: readability-identifier-naming.PrivateMemberPrefix value: m_ - key: readability-identifier-naming.EnumCase value: CamelCase - key: readability-identifier-naming.EnumConstantCase value: UPPER_CASE ... sight-23.1.0/.githooks/000077500000000000000000000000001450532053500146225ustar00rootroot00000000000000sight-23.1.0/.githooks/commit-msg000077500000000000000000000017151450532053500166300ustar00rootroot00000000000000#!/usr/bin/env python import re import sys commit_msg_path = sys.argv[1] commit_msg_help = """ Required commit message: type(scope): description - type: enh, feat, fix, refactor - scope: build, ci, core, doc, filter, geometry, io, navigation, test, ui, viz or type: description - type: merge, misc, style """ with open(commit_msg_path) as commit_msg_file: commit_msg_content = commit_msg_file.readline() message_regex = r'(?:(?Penh|feat|fix|refactor)\((?Pbuild|ci|core|doc|filter|geometry|io|navigation|test|ui|viz)\)|(?Pmerge|misc|style)): (?P[a-z].*?(?:\b|[\]\)\'\"\`])$)' if not re.match(message_regex, commit_msg_content): sys.stderr.write("\n'" + commit_msg_content.strip() + "' message doesn't follow commit rules.\n") sys.stderr.write(commit_msg_help) sys.stderr.write('Take a look at the project push rules regex, and experiment https://regex101.com\n') sys.exit(1) sight-23.1.0/.gitignore000066400000000000000000000007021450532053500147040ustar00rootroot00000000000000# use glob syntax. syntax: glob # vim swap file *.swp # eclipse stuff *.cproject *.project # python *.pyc *.pyo # tmp files .*~ *.autosave # qtcreator cmake preferences *.txt.user* # reject and backup file *.rej *.orig # macos .DS_Store # VisualStudio .vs/ CMakeSettings\.json # VSCode *.code-workspace .vscode/ /build/ /.build/ # JetBrains IDEs .idea/ # Just for the CI sight-git # various logs *.log compile_commands.json CMakeUserPresets.json sight-23.1.0/.gitlab-ci.yml000066400000000000000000000437431450532053500153640ustar00rootroot00000000000000stages: - lint - prebuild - build - deploy-test - deploy include: - project: "sight/sight-gitlab" ref: dev file: "/.templates/deploy.yml" - project: "sight/sight-gitlab" ref: dev file: "/.templates/build.yml" lint:sheldon: extends: .lint variables: ENABLE_CLANG_TIDY: "ON" .linux_build: extends: .linux_before stage: build needs: - job: lint:sheldon optional: true variables: SIGHT_BUILD_DOC: "OFF" SIGHT_BUILD_PACKAGES: "OFF" SIGHT_BUILD_SDK: "OFF" SIGHT_ENABLE_REALSENSE: "OFF" SIGHT_ENABLE_GDB: "OFF" script: # Reset the modified time of all files to improve ccache performance - /usr/lib/git-core/git-restore-mtime --force --skip-missing --commit-time # Print CCache statistics - ccache -s # Launch CMake - cd $CI_PROJECT_DIR/.build - > cmake $CI_PROJECT_DIR -G Ninja -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_INSTALL_PREFIX=$CI_PROJECT_DIR/.install -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DSIGHT_ARCH=sandybridge -DSIGHT_BUILD_TESTS=ON -DSIGHT_BUILD_DOC=${SIGHT_BUILD_DOC} -DSIGHT_ENABLE_PCH=ON -DSIGHT_DEPS_ROOT_DIRECTORY=/cache/.sight-deps -DSIGHT_ENABLE_OPENVSLAM=ON -DSIGHT_ENABLE_REALSENSE=${SIGHT_ENABLE_REALSENSE} -DSIGHT_ENABLE_COVERAGE=${SIGHT_ENABLE_COVERAGE} -DSIGHT_ENABLE_GDB=${SIGHT_ENABLE_GDB} -DSIGHT_BUILD_MANPAGES=ON # Touch all generated files to improve CCache performance - find . -type f -name '*.?pp' -o -name '*.?xx' -exec touch -t 197001010000 {} \; # Build - ninja -j${RUNNER_THREADS} | tee output.log # Generate metrics information - nb_warnings=$(grep -c "warning:" output.log) - nb_deprecated=$(grep -ce "-Wdeprecated-declarations" output.log) - echo -e "Cpp_Warnings $nb_warnings\nCpp_Deprecated_declaration $nb_deprecated" >metrics.txt # Print CCache statistics (Cache hit rate should have raised) - ccache -s # Clone sight-data. - SIGHT_DATA_DIR=$(cmake -DOUTPUT_FOLDER=/cache/sight-data -DBRANCH=dev -P "${CI_PROJECT_DIR}/cmake/build/download_test_data.cmake" 2>&1 | grep sight-data) - export FWTEST_DATA_DIR=${SIGHT_DATA_DIR} - export IMAGE_OUTPUT_PATH=$CI_PROJECT_DIR/.build/testImages - mkdir -p $IMAGE_OUTPUT_PATH # Launch tests - > if [ "$SIGHT_ENABLE_COVERAGE" = "ON" ] || [ "$BUILD_TYPE" = "Debug" ]; then TIMEOUT="1200" else TIMEOUT="600" fi - ctest -E "(guitest)|(dicom)" --timeout $TIMEOUT --output-on-failure -O ctest1.log -j10 --output-junit junit1.xml --repeat until-pass:2 - ctest -R "(dicom)" --timeout $TIMEOUT --output-on-failure -O ctest2.log -j10 --output-junit junit2.xml --repeat until-pass:2 - ctest -R "(guitest)" --timeout $TIMEOUT --output-on-failure -O ctest3.log -j10 --output-junit junit3.xml --repeat until-pass:2 # Build documentation if needed - > if [ "${SIGHT_BUILD_DOC}" == "ON" ]; then ninja -j${RUNNER_THREADS} doc fi - > if [ "${SIGHT_BUILD_PACKAGES}" == "ON" ]; then ninja -j${RUNNER_THREADS} SightViewer_package rm -rf ${CI_PROJECT_DIR}/.install ninja -j${RUNNER_THREADS} SightCalibrator_package rm -rf ${CI_PROJECT_DIR}/.install fi - > if [ "${SIGHT_BUILD_SDK}" == "ON" ]; then ninja -j${RUNNER_THREADS} install ninja -j${RUNNER_THREADS} package fi - > if [ "${SIGHT_ENABLE_COVERAGE}" == "ON" ]; then ninja coverage fi artifacts: &linux_build_artifacts when: always paths: - .build/ctest*.log - .build/Documentation/Doxygen/ - .build/packages/*.tar.zst - .build/coverage - .build/bin/*.core - .build/testImages reports: junit: .build/junit*.xml metrics: .build/metrics.txt .linux_deploy_test: stage: deploy-test variables: BUILD_TYPE: "Debug" SIGHT_TEST_PACKAGES: "OFF" SIGHT_TEST_SDK: "OFF" script: - cd .build - > if [ "${SIGHT_TEST_PACKAGES}" == "ON" ]; then tar -xf packages/SightViewer-*.tar.zst echo Testing SightViewer: timeout 5s xvfb-run -a SightViewer-*/bin/sightviewer || [ $? -eq 124 ] tar -xf packages/SightCalibrator-*.tar.zst echo Testing SightCalibrator: timeout 5s xvfb-run -a SightCalibrator-*/bin/sightcalibrator || [ $? -eq 124 ] fi - > if [ "${SIGHT_TEST_SDK}" == "ON" ]; then tar -xf packages/sight-*.tar.zst PACKAGE_NAME=$(cmake -DGET_ARCHIVE_FOLDER=ON -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -P "${CI_PROJECT_DIR}/cmake/build/download_deps.cmake" 2>&1) for program in sight-*/bin/{ex*,tuto*,sightviewer,sightcalibrator,dicomxplorer}; do echo Testing $(basename $program): LD_LIBRARY_PATH=/cache/.sight-deps/$PACKAGE_NAME/lib timeout 5s xvfb-run -a $program || [ $? -eq 124 ] done for program in sight-*/bin/{arucomarker,dicomanonymizer,networkproxy}; do echo Testing $(basename $program): $program --help done fi build:linux-22.04-debug-gcc: extends: .linux_build image: "${SIGHT_CI_UBUNTU22_04}:dev" variables: BUILD_TYPE: "Debug" SIGHT_BUILD_SDK: "ON" SIGHT_ENABLE_GDB: "ON" CC: "gcc" CXX: "g++" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:linux-22.04-release-gcc: extends: .linux_build image: "${SIGHT_CI_UBUNTU22_04}:dev" variables: BUILD_TYPE: "Release" SIGHT_BUILD_SDK: "ON" SIGHT_BUILD_PACKAGES: "ON" SIGHT_IGNORE_UNSTABLE_TESTS: 1 CC: "gcc" CXX: "g++" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:linux-22.04-RelWithDebInfo-clang: extends: .linux_build image: "${SIGHT_CI_UBUNTU22_04}:dev" variables: BUILD_TYPE: "RelWithDebInfo" SIGHT_IGNORE_UNSTABLE_TESTS: 1 SIGHT_ENABLE_GDB: "ON" CC: "clang" CXX: "clang++" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:linux-22.04-coverage-gcc: extends: .linux_build image: "${SIGHT_CI_UBUNTU22_04}:dev" variables: BUILD_TYPE: "RelWithDebInfo" SIGHT_BUILD_DOC: "ON" SIGHT_ENABLE_COVERAGE: "ON" SIGHT_IGNORE_UNSTABLE_TESTS: 1 CC: "gcc" CXX: "g++" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:linux-22.04-coverage-gcc-draft: extends: .linux_build image: "${SIGHT_CI_UBUNTU22_04}:dev" variables: BUILD_TYPE: "RelWithDebInfo" SIGHT_ENABLE_COVERAGE: "ON" SIGHT_IGNORE_UNSTABLE_TESTS: 1 CC: "gcc" CXX: "g++" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE =~ "/^Draft.*/" deploy-test:linux-debug: extends: .linux_deploy_test image: "${SIGHT_CI_UBUNTU22_04}:dev" needs: - job: build:linux-22.04-debug-gcc artifacts: true variables: BUILD_TYPE: "Debug" SIGHT_TEST_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:linux-debug: extends: .linux_deploy image: "${SIGHT_CI_UBUNTU22_04}:dev" needs: - job: build:linux-22.04-debug-gcc artifacts: true - job: deploy-test:linux-debug variables: APPS: "sight-" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy-test:linux-release: extends: .linux_deploy_test image: "${SIGHT_CI_UBUNTU22_04}:dev" needs: - job: build:linux-22.04-release-gcc artifacts: true variables: BUILD_TYPE: "Release" SIGHT_TEST_PACKAGES: "ON" SIGHT_TEST_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:linux-release: extends: .linux_deploy image: "${SIGHT_CI_UBUNTU22_04}:dev" needs: - job: build:linux-22.04-release-gcc artifacts: true - job: deploy-test:linux-release variables: APPS: "sight-" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:apps-linux-release: extends: .linux_deploy image: "${SIGHT_CI_UBUNTU22_04}:dev" needs: - job: build:linux-22.04-release-gcc artifacts: true - job: deploy-test:linux-release variables: APPS: "SightViewer,SightCalibrator" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" .windows_build: extends: .windows_before needs: - job: lint:sheldon optional: true - job: prebuild:windows variables: TOOLCHAIN: "scripts\\buildsystems\\vcpkg.cmake" SIGHT_BUILD_PACKAGES: "OFF" SIGHT_BUILD_SDK: "OFF" stage: build script: # Get the package_name name from our CMake script - $PACKAGE_NAME = cmd /c cmake -DGET_ARCHIVE_FOLDER=ON -P "${env:CI_PROJECT_DIR}\cmake\build\download_deps.cmake" '2>&1' # Build the project on the merge result. - cd "${env:CI_PROJECT_DIR}/build" - cmake "$env:CI_PROJECT_DIR" -G Ninja -DCMAKE_TOOLCHAIN_FILE="$CACHE\$PACKAGE_NAME\$TOOLCHAIN" -DCMAKE_INSTALL_PREFIX="$env:CI_PROJECT_DIR/install" -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DSIGHT_BUILD_TESTS=ON -DSIGHT_ENABLE_PCH=OFF -DCMAKE_C_COMPILER_LAUNCHER="ccache" -DCMAKE_CXX_COMPILER_LAUNCHER="ccache" - $env:TMP="$CACHE\tmp" - $env:TEMP="$CACHE\tmp" - ninja # Clone sight-data. - cmd /c cmake -DOUTPUT_FOLDER="$CACHE\sight-data" -DBRANCH=dev -P "${env:CI_PROJECT_DIR}\cmake\build\download_test_data.cmake" - $env:FWTEST_DATA_DIR=cmd /c cmake -DOUTPUT_FOLDER="$CACHE\sight-data" -DBRANCH=dev -P "${env:CI_PROJECT_DIR}\cmake\build\download_test_data.cmake" '2>&1' | Select-String sight-data - $env:IMAGE_OUTPUT_PATH="${env:CI_PROJECT_DIR}/build/testImages" - md "${env:IMAGE_OUTPUT_PATH}" - $env:DISABLE_ABORT_DIALOG="1" - | if ("${SIGHT_ENABLE_COVERAGE}" -eq "ON" -or "${BUILD_TYPE}" -eq "Debug") { $env:TIMEOUT="1200" } else { $env:TIMEOUT="600" } # Launch tests - ctest -E "(guitest)|(dicom)" --timeout $TIMEOUT --output-on-failure -O ctest1.log -j6 --output-junit junit1.xml --repeat until-pass:2 - ctest -R "(dicom)" --timeout $TIMEOUT --output-on-failure -O ctest2.log -j6 --output-junit junit2.xml --repeat until-pass:2 - ctest -R "(guitest)" --timeout $TIMEOUT --output-on-failure -O ctes3.log -j6 --output-junit junit3.xml --repeat until-pass:2 - | if ("${SIGHT_BUILD_PACKAGES}" -eq "ON") { ninja SightViewer_package (Remove-Item -Path "${env:CI_PROJECT_DIR}/install" -Force -Recurse -ErrorAction Ignore) ninja SightCalibrator_package (Remove-Item -Path "${env:CI_PROJECT_DIR}/install" -Force -Recurse -ErrorAction Ignore) } - | if ("${SIGHT_BUILD_SDK}" -eq "ON") { ninja install # Check if the package is relocatable Try { if (Select-String -Pattern "[A-Z]:[\/\\]\w+" -Path "${env:CI_PROJECT_DIR}/install/lib/cmake/sight/*.cmake") { echo "The package is not relocatable, some absolute paths are present" exit 1 } else { echo "The package is relocatable, no absolute path found." } } Catch { echo "Error when looking for absolute paths, see output below." echo $Error[0] exit 1 } ninja package } artifacts: when: always name: "${env:CI_JOB_NAME}-${env:CI_COMMIT_REF_SLUG}" paths: - build/ctest*.log - build/fwTest.log - build/packages/*.exe - build/packages/sight-*.zip - build/testImages reports: junit: build/junit.xml .windows_deploy_test: stage: deploy-test variables: SIGHT_TEST_PACKAGES: "OFF" SIGHT_TEST_SDK: "OFF" CACHE: "D:\\gitlab-cache" # Ideally, we would like to use `none` but we need the `git clean -ddfx` to be performed to clean previous artifacts GIT_STRATEGY: fetch script: - $PACKAGE_NAME = cmd /c cmake -DGET_ARCHIVE_FOLDER=ON -P "${env:CI_PROJECT_DIR}\cmake\build\download_deps.cmake" '2>&1' - cd build - | if("${SIGHT_TEST_PACKAGES}" -eq "ON"){ Start-Process -Wait .\packages\SightViewer-*.exe /S,/D=${pwd}\SightViewer $process = Start-Process -PassThru -NoNewWindow SightViewer\bin\sightviewer.bat --no-abort-dialog,--clog $process | Wait-Process -Timeout 5 -ErrorAction SilentlyContinue ForEach($p in Get-CimInstance Win32_Process | Where-Object {$_.ParentProcessId -eq $process.Id}){ (Get-Process -Id $p.ProcessId).CloseMainWindow() | out-null $process | Wait-Process } if($process.ExitCode -ne 0){ Write-Error "SightViewer crashed." -ErrorAction Stop } Start-Process -Wait .\packages\SightCalibrator-*.exe /S,/D=${pwd}\SightCalibrator $process = Start-Process -PassThru -NoNewWindow SightCalibrator\bin\sightcalibrator.bat --no-abort-dialog,--clog $process | Wait-Process -Timeout 5 -ErrorAction SilentlyContinue ForEach($p in Get-CimInstance Win32_Process | Where-Object {$_.ParentProcessId -eq $process.Id}){ (Get-Process -Id $p.ProcessId).CloseMainWindow() | out-null $process | Wait-Process } if($process.ExitCode -ne 0){ Write-Error "SightCalibrator crashed." -ErrorAction Stop } } - | Expand-Archive packages/sight-*.zip if("${SIGHT_TEST_SDK}" -eq "ON"){ if ( ${BUILD_TYPE} -eq "Debug" ) { $env:PATH = "$CACHE\$PACKAGE_NAME\installed\x64-windows\debug\bin;$env:PATH" } else { $env:PATH = "$CACHE\$PACKAGE_NAME\installed\x64-windows\bin\;$env:PATH" } cd sight-*/*/bin ForEach($program in Get-ChildItem ex*.bat,tuto*.bat,sightviewer.bat,sightcalibrator.bat,dicomxplorer.bat){ $programName = Split-Path -Leaf $program Write-Host Testing $programName $process = Start-Process -PassThru -NoNewWindow $program --no-abort-dialog,--clog $process | Wait-Process -Timeout 5 -ErrorAction SilentlyContinue ForEach($p in Get-CimInstance Win32_Process | Where-Object {$_.ParentProcessId -eq $process.Id}){ (Get-Process -Id $p.ProcessId).CloseMainWindow() | out-null $process | Wait-Process -Timeout 5 if(!$process.HasExited){ (Get-Process -Id $p.ProcessId).Kill() $process | Wait-Process } } if(!($process.ExitCode -in -1,0)){ Write-Error "$programName crashed." -ErrorAction Stop } } ForEach($program in Get-ChildItem arucomarker.exe,dicomanonymizer.exe){ $programName = Split-Path -Leaf $program Write-Host Testing $programName Start-Process -NoNewWindow -Wait $program --help } } tags: - windows build:windows-debug: extends: .windows_build variables: BUILD_TYPE: "Debug" SIGHT_BUILD_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:windows-release: extends: .windows_build variables: BUILD_TYPE: "Release" SIGHT_BUILD_PACKAGES: "ON" SIGHT_BUILD_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" build:windows-release-draft: extends: .windows_build variables: BUILD_TYPE: "Release" SIGHT_BUILD_PACKAGES: "OFF" SIGHT_BUILD_SDK: "OFF" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE =~ "/^Draft.*/" deploy-test:windows-debug: extends: .windows_deploy_test needs: - job: build:windows-debug artifacts: true variables: BUILD_TYPE: "Debug" SIGHT_TEST_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:windows-debug: extends: .windows_deploy needs: - job: build:windows-debug artifacts: true - job: deploy-test:windows-debug variables: APPS: "sight-" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy-test:windows-release: extends: .windows_deploy_test needs: - job: build:windows-release artifacts: true variables: BUILD_TYPE: "Release" SIGHT_TEST_PACKAGES: "ON" SIGHT_TEST_SDK: "ON" rules: - if: $CI_PIPELINE_SOURCE == 'merge_request_event' && $CI_MERGE_REQUEST_TITLE !~ "/^Draft.*/" - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:windows-release: extends: .windows_deploy needs: - job: build:windows-release artifacts: true - job: deploy-test:windows-release variables: APPS: "sight-" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" deploy:apps-windows-release: extends: .windows_deploy needs: - job: build:windows-release artifacts: true - job: deploy-test:windows-release variables: APPS: "SightViewer,SightCalibrator" URL: "IRCAD%20-%20Open/" rules: - if: $CI_COMMIT_BRANCH == "master" || $CI_COMMIT_BRANCH == "dev" pages: image: "${SIGHT_CI_UBUNTU22_04}:dev" stage: deploy needs: - job: build:linux-22.04-coverage-gcc artifacts: true script: - mv .build/Documentation/Doxygen/html/ public/ - mv .build/coverage/ public/coverage artifacts: paths: - public only: - dev sight-23.1.0/.gitlab/000077500000000000000000000000001450532053500142355ustar00rootroot00000000000000sight-23.1.0/.gitlab/CODEOWNERS000066400000000000000000000003331450532053500156270ustar00rootroot00000000000000[Build] /cmake @fbridault [Visualisation] /libs/viz/ @fbridault /modules/viz/ @fbridault [Serialisation] libs/io/bitmap @dweckmann libs/io/session @dweckmann modules/io/bitmap @dweckmann modules/io/session @dweckmann sight-23.1.0/.gitlab/issue_templates/000077500000000000000000000000001450532053500174435ustar00rootroot00000000000000sight-23.1.0/.gitlab/issue_templates/Bug.md000066400000000000000000000013431450532053500205030ustar00rootroot00000000000000### Description _Summarize the bug encountered concisely_ ### Steps to reproduce _How one can reproduce the issue - this is very important._ _If the bug depends on a particular environment or platform, please give all relevant details._ _Paste any relevant logs. Please use code blocks (```) to format these._ ### Proposal _Optional section to give some functional or technical hints_ ### Functional specifications _If there is any change to the workflow, UX/UI design, screenshots, etc..., please describe it here_ ### Technical specifications _Details of the implementation of the fix_ ### Test plan _Describe how you will verify that the implementation fulfils the specifications_ /label ~"Type::bugfix" ~"Priority::medium" sight-23.1.0/.gitlab/issue_templates/Enhancement.md000066400000000000000000000007421450532053500222150ustar00rootroot00000000000000### Description _Describe briefly the existing feature and what is the enhancement, use cases, benefits, and goals_ ### Proposal _Optional section to give some functional or technical hints_ ### Functional specifications _Workflow, UX/UI design, screenshots, etc..._ ### Technical specifications _Details of the implementation_ ### Test plan _Describe how you will verify that the implementation fulfils the specifications_ /label ~"Type::enhancement" ~"Priority::medium" sight-23.1.0/.gitlab/issue_templates/Feature.md000066400000000000000000000007111450532053500213570ustar00rootroot00000000000000### Description _Describe the need, what would be the feature, use cases, benefits, and goals_ ### Proposal _Optional section to give some functional or technical hints_ ### Functional specifications _Workflow, UX/UI design, screenshots, etc..._ ### Technical specifications _Details of the implementation_ ### Test plan _Describe how you will verify that the implementation fulfils the specifications_ /label ~"Type::feature" ~"Priority::medium" sight-23.1.0/.gitlab/issue_templates/Refactor.md000066400000000000000000000011161450532053500215310ustar00rootroot00000000000000### Description _Describe the existing code and why there is a need for a refactor, benefits, and goals_ ### Proposal _Optional section to give some functional or technical hints_ ### Functional specifications _Usually a refactor does not alter functional specifications,_ _but if there is any change to the workflow, UX/UI design, screenshots, etc..., please describe it here_ ### Technical specifications _Details of the implementation_ ### Test plan _Describe how you will verify that the implementation fulfils the specifications_ /label ~"Type::refactor" ~"Priority::medium" sight-23.1.0/.gitlab/issue_templates/Research.md000066400000000000000000000021031450532053500215150ustar00rootroot00000000000000# Goal and general information _Brief description of the goal of this algorithm research task._ # Specification _Specifications include functional, performance, language and data. The algorithms should focus on solving a specific problem with well-defined interfaces._ # Background _Background check to see what algorithms exist for solving the problem. Do they meet our needs? Have better new algorithms been published?_ # Data _Collection of data required for testing (or training in the case of learning-based algorithms). Formatting of data so that it can be inputted to the algorithm._ # Evaluation _Evaluation framework is used to test the algorithm for correctness and meeting performance specification._ # Baseline _Existing algorithm selection, implementation and evaluation._ # Prototyping _The main algorithm research cycle: evaluate performance, make improvements, repeat._ # Integration _Integration of algorithm code into production system._ # Communication _Communicate how the algorithm works (internal and/or article publication)._ /label ~"Type:research" sight-23.1.0/.gitlab/issue_templates/Story.md000066400000000000000000000005361450532053500211110ustar00rootroot00000000000000### Description (Description of the feature to be implemented as a story: task of a project work package, associated deliverable ...) ### Task list (The complete task list must be created at the issue creation and then the associated issue links must be appended to each associated task) - [ ] Task 1 - [ ] Task 2 - [ ] ... /label ~"Type:story" sight-23.1.0/.gitlab/merge_request_templates/000077500000000000000000000000001450532053500211625ustar00rootroot00000000000000sight-23.1.0/.gitlab/merge_request_templates/Merge_Request.md000066400000000000000000000005671450532053500242630ustar00rootroot00000000000000## Description (Briefly describe what this merge request is about) Closes #number ## How to test it? (Describe how to test this feature step by step) ## Data (Links to the needed data) ## Some results (Some interesting results, screenshots, perfs, ...) ## Additional tests/tasks to run (If you need some specific tests/tasks...) - [ ] Additional test 1 - [ ] ... sight-23.1.0/.sheldonignore000066400000000000000000000003711450532053500155570ustar00rootroot00000000000000/3rd-party /libs/core/data/dicom/Attribute.* /libs/core/data/dicom/Sop.* /libs/core/data/test/tu/dicom/AttributeTest.* /libs/core/data/test/tu/dicom/SopTest.* /libs/io/igtl/patch/ /libs/io/itk/patched_itk_compiler_detection.h /libs/io/itk/compilers/sight-23.1.0/.sight000066400000000000000000000000061450532053500140300ustar00rootroot00000000000000sight sight-23.1.0/3rd-party/000077500000000000000000000000001450532053500145425ustar00rootroot00000000000000sight-23.1.0/3rd-party/CMakeLists.txt000066400000000000000000000000321450532053500172750ustar00rootroot00000000000000add_subdirectory(minizip) sight-23.1.0/3rd-party/minizip/000077500000000000000000000000001450532053500162215ustar00rootroot00000000000000sight-23.1.0/3rd-party/minizip/CMakeLists.txt000066400000000000000000000044441450532053500207670ustar00rootroot00000000000000file(GLOB MINIZIP_SOURCES *.c *.h) add_library(minizip STATIC ${MINIZIP_SOURCES}) target_compile_options(minizip PRIVATE "$<$:-w>$<$:/w>") include(CheckIncludeFile) include(CheckTypeSize) include(CheckFunctionExists) # Check for system includes check_include_file(stdint.h HAVE_STDINT_H) if(HAVE_STDINT_H) target_compile_definitions(minizip PRIVATE "-DHAVE_STDINT_H") endif() check_include_file(inttypes.h HAVE_INTTYPES_H) if(HAVE_INTTYPES_H) target_compile_definitions(minizip PRIVATE "-DHAVE_INTTYPES_H") endif() # Check for large file support check_type_size(off64_t OFF64_T) if(HAVE_OFF64_T) target_compile_definitions(minizip PRIVATE "-D__USE_LARGEFILE64") target_compile_definitions(minizip PRIVATE "-D_LARGEFILE64_SOURCE") endif() # Check for fseeko support check_function_exists(fseeko HAVE_FSEEKO) if(NOT HAVE_FSEEKO) target_compile_definitions(minizip PRIVATE "-DNO_FSEEKO") endif() # ZLIB find_package(ZLIB QUIET REQUIRED) target_link_libraries(minizip PRIVATE ZLIB::ZLIB) target_compile_definitions(minizip PRIVATE "-DHAVE_ZLIB") target_compile_definitions(minizip PRIVATE "-DZLIB_COMPAT") # ZSTD find_package(PkgConfig QUIET) if(PKGCONFIG_FOUND) pkg_check_modules(ZSTD libzstd) endif() if(ZSTD_FOUND) target_include_directories(minizip SYSTEM PRIVATE ${ZSTD_INCLUDE_DIRS}) target_link_libraries(minizip PRIVATE ${ZSTD_LIBRARIES}) else() find_package(zstd CONFIG REQUIRED) target_link_libraries(minizip PRIVATE zstd::libzstd_shared) endif() target_compile_definitions(minizip PRIVATE "-DHAVE_ZSTD") # OpenSSL find_package(OpenSSL QUIET REQUIRED COMPONENTS Crypto) target_link_libraries(minizip PRIVATE OpenSSL::Crypto) # Windows specific if(WIN32) target_compile_definitions(minizip PRIVATE "-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE") endif() # Unix specific if(UNIX) # ICONV find_package(Iconv QUIET REQUIRED) target_include_directories(minizip SYSTEM PRIVATE ${Iconv_INCLUDE_DIRS}) target_link_libraries(minizip PRIVATE ${Iconv_LIBRARIES}) target_compile_definitions(minizip PRIVATE "-DHAVE_ICONV") endif() # Setup predefined macros target_compile_definitions(minizip PRIVATE "-DMZ_ZIP_SIGNING") # Include WinZIP AES encryption target_compile_definitions(minizip PRIVATE "-DHAVE_WZAES") sight-23.1.0/3rd-party/minizip/LICENSE000066400000000000000000000015551450532053500172340ustar00rootroot00000000000000Condition of use and distribution are the same as zlib: This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. sight-23.1.0/3rd-party/minizip/mz.h000066400000000000000000000172771450532053500170360ustar00rootroot00000000000000/* mz.h -- Errors codes, zip flags and magic part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_H #define MZ_H /***************************************************************************/ /* MZ_VERSION */ #define MZ_VERSION ("4.0.1") #define MZ_VERSION_BUILD (040001) /* MZ_ERROR */ #define MZ_OK (0) /* zlib */ #define MZ_STREAM_ERROR (-1) /* zlib */ #define MZ_DATA_ERROR (-3) /* zlib */ #define MZ_MEM_ERROR (-4) /* zlib */ #define MZ_BUF_ERROR (-5) /* zlib */ #define MZ_VERSION_ERROR (-6) /* zlib */ #define MZ_END_OF_LIST (-100) #define MZ_END_OF_STREAM (-101) #define MZ_PARAM_ERROR (-102) #define MZ_FORMAT_ERROR (-103) #define MZ_INTERNAL_ERROR (-104) #define MZ_CRC_ERROR (-105) #define MZ_CRYPT_ERROR (-106) #define MZ_EXIST_ERROR (-107) #define MZ_PASSWORD_ERROR (-108) #define MZ_SUPPORT_ERROR (-109) #define MZ_HASH_ERROR (-110) #define MZ_OPEN_ERROR (-111) #define MZ_CLOSE_ERROR (-112) #define MZ_SEEK_ERROR (-113) #define MZ_TELL_ERROR (-114) #define MZ_READ_ERROR (-115) #define MZ_WRITE_ERROR (-116) #define MZ_SIGN_ERROR (-117) #define MZ_SYMLINK_ERROR (-118) /* MZ_OPEN */ #define MZ_OPEN_MODE_READ (0x01) #define MZ_OPEN_MODE_WRITE (0x02) #define MZ_OPEN_MODE_READWRITE (MZ_OPEN_MODE_READ | MZ_OPEN_MODE_WRITE) #define MZ_OPEN_MODE_APPEND (0x04) #define MZ_OPEN_MODE_CREATE (0x08) #define MZ_OPEN_MODE_EXISTING (0x10) /* MZ_SEEK */ #define MZ_SEEK_SET (0) #define MZ_SEEK_CUR (1) #define MZ_SEEK_END (2) /* MZ_COMPRESS */ #define MZ_COMPRESS_METHOD_STORE (0) #define MZ_COMPRESS_METHOD_DEFLATE (8) #define MZ_COMPRESS_METHOD_BZIP2 (12) #define MZ_COMPRESS_METHOD_LZMA (14) #define MZ_COMPRESS_METHOD_ZSTD (93) #define MZ_COMPRESS_METHOD_XZ (95) #define MZ_COMPRESS_METHOD_AES (99) #define MZ_COMPRESS_LEVEL_DEFAULT (-1) #define MZ_COMPRESS_LEVEL_FAST (2) #define MZ_COMPRESS_LEVEL_NORMAL (6) #define MZ_COMPRESS_LEVEL_BEST (9) /* MZ_ZIP_FLAG */ #define MZ_ZIP_FLAG_ENCRYPTED (1 << 0) #define MZ_ZIP_FLAG_LZMA_EOS_MARKER (1 << 1) #define MZ_ZIP_FLAG_DEFLATE_MAX (1 << 1) #define MZ_ZIP_FLAG_DEFLATE_NORMAL (0) #define MZ_ZIP_FLAG_DEFLATE_FAST (1 << 2) #define MZ_ZIP_FLAG_DEFLATE_SUPER_FAST (MZ_ZIP_FLAG_DEFLATE_FAST | \ MZ_ZIP_FLAG_DEFLATE_MAX) #define MZ_ZIP_FLAG_DATA_DESCRIPTOR (1 << 3) #define MZ_ZIP_FLAG_UTF8 (1 << 11) #define MZ_ZIP_FLAG_MASK_LOCAL_INFO (1 << 13) /* MZ_ZIP_EXTENSION */ #define MZ_ZIP_EXTENSION_ZIP64 (0x0001) #define MZ_ZIP_EXTENSION_NTFS (0x000a) #define MZ_ZIP_EXTENSION_AES (0x9901) #define MZ_ZIP_EXTENSION_UNIX1 (0x000d) #define MZ_ZIP_EXTENSION_SIGN (0x10c5) #define MZ_ZIP_EXTENSION_HASH (0x1a51) #define MZ_ZIP_EXTENSION_CDCD (0xcdcd) /* MZ_ZIP64 */ #define MZ_ZIP64_AUTO (0) #define MZ_ZIP64_FORCE (1) #define MZ_ZIP64_DISABLE (2) /* MZ_HOST_SYSTEM */ #define MZ_HOST_SYSTEM(VERSION_MADEBY) ((uint8_t)(VERSION_MADEBY >> 8)) #define MZ_HOST_SYSTEM_MSDOS (0) #define MZ_HOST_SYSTEM_UNIX (3) #define MZ_HOST_SYSTEM_WINDOWS_NTFS (10) #define MZ_HOST_SYSTEM_RISCOS (13) #define MZ_HOST_SYSTEM_OSX_DARWIN (19) /* MZ_PKCRYPT */ #define MZ_PKCRYPT_HEADER_SIZE (12) /* MZ_AES */ #define MZ_AES_VERSION (1) #define MZ_AES_MODE_ECB (0) #define MZ_AES_MODE_CBC (1) #define MZ_AES_MODE_GCM (2) #define MZ_AES_STRENGTH_128 (1) #define MZ_AES_STRENGTH_192 (2) #define MZ_AES_STRENGTH_256 (3) #define MZ_AES_KEY_LENGTH_MAX (32) #define MZ_AES_BLOCK_SIZE (16) #define MZ_AES_FOOTER_SIZE (10) /* MZ_HASH */ #define MZ_HASH_MD5 (10) #define MZ_HASH_MD5_SIZE (16) #define MZ_HASH_SHA1 (20) #define MZ_HASH_SHA1_SIZE (20) #define MZ_HASH_SHA224 (22) #define MZ_HASH_SHA224_SIZE (28) #define MZ_HASH_SHA256 (23) #define MZ_HASH_SHA256_SIZE (32) #define MZ_HASH_SHA384 (24) #define MZ_HASH_SHA384_SIZE (48) #define MZ_HASH_SHA512 (25) #define MZ_HASH_SHA512_SIZE (64) #define MZ_HASH_MAX_SIZE (256) /* MZ_ENCODING */ #define MZ_ENCODING_CODEPAGE_437 (437) #define MZ_ENCODING_CODEPAGE_932 (932) #define MZ_ENCODING_CODEPAGE_936 (936) #define MZ_ENCODING_CODEPAGE_950 (950) #define MZ_ENCODING_UTF8 (65001) /* MZ_UTILITY */ #define MZ_UNUSED(SYMBOL) ((void)SYMBOL) #if defined(_WIN32) && defined(MZ_EXPORTS) #define MZ_EXPORT __declspec(dllexport) #else #define MZ_EXPORT #endif /***************************************************************************/ #include /* size_t, NULL, malloc */ #include /* time_t, time() */ #include /* memset, strncpy, strlen */ #include #if defined(HAVE_STDINT_H) # include #elif defined(__has_include) # if __has_include() # include # endif #endif #ifndef INT8_MAX typedef signed char int8_t; #endif #ifndef INT16_MAX typedef short int16_t; #endif #ifndef INT32_MAX typedef int int32_t; #endif #ifndef INT64_MAX typedef long long int64_t; #endif #ifndef UINT8_MAX typedef unsigned char uint8_t; #endif #ifndef UINT16_MAX typedef unsigned short uint16_t; #endif #ifndef UINT32_MAX typedef unsigned int uint32_t; #endif #ifndef UINT64_MAX typedef unsigned long long uint64_t; #endif #if defined(HAVE_INTTYPES_H) # include #elif defined(__has_include) # if __has_include() # include # endif #endif #ifndef PRId8 # define PRId8 "hhd" #endif #ifndef PRIu8 # define PRIu8 "hhu" #endif #ifndef PRIx8 # define PRIx8 "hhx" #endif #ifndef PRId16 # define PRId16 "hd" #endif #ifndef PRIu16 # define PRIu16 "hu" #endif #ifndef PRIx16 # define PRIx16 "hx" #endif #ifndef PRId32 # define PRId32 "d" #endif #ifndef PRIu32 # define PRIu32 "u" #endif #ifndef PRIx32 # define PRIx32 "x" #endif #if ULONG_MAX == 0xfffffffful # ifndef PRId64 # define PRId64 "ld" # endif # ifndef PRIu64 # define PRIu64 "lu" # endif # ifndef PRIx64 # define PRIx64 "lx" # endif #else # ifndef PRId64 # define PRId64 "lld" # endif # ifndef PRIu64 # define PRIu64 "llu" # endif # ifndef PRIx64 # define PRIx64 "llx" # endif #endif #ifndef INT16_MAX # define INT16_MAX 32767 #endif #ifndef INT32_MAX # define INT32_MAX 2147483647L #endif #ifndef INT64_MAX # define INT64_MAX 9223372036854775807LL #endif #ifndef UINT16_MAX # define UINT16_MAX 65535U #endif #ifndef UINT32_MAX # define UINT32_MAX 4294967295UL #endif #ifndef UINT64_MAX # define UINT64_MAX 18446744073709551615ULL #endif /***************************************************************************/ #endif sight-23.1.0/3rd-party/minizip/mz_compat.c000066400000000000000000001232201450532053500203560ustar00rootroot00000000000000/* mz_compat.c -- Backwards compatible interface for older versions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_os.h" #include "mz_strm.h" #include "mz_strm_mem.h" #include "mz_strm_os.h" #include "mz_strm_zlib.h" #include "mz_zip.h" #include /* SEEK */ #include "mz_compat.h" /***************************************************************************/ typedef struct mz_compat_s { void *stream; void *handle; uint64_t entry_index; int64_t entry_pos; int64_t total_out; } mz_compat; /***************************************************************************/ typedef struct mz_stream_ioapi_s { mz_stream stream; void *handle; zlib_filefunc_def filefunc; zlib_filefunc64_def filefunc64; } mz_stream_ioapi; /***************************************************************************/ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode); static int32_t mz_stream_ioapi_is_open(void *stream); static int32_t mz_stream_ioapi_read(void *stream, void *buf, int32_t size); static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size); static int64_t mz_stream_ioapi_tell(void *stream); static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin); static int32_t mz_stream_ioapi_close(void *stream); static int32_t mz_stream_ioapi_error(void *stream); static void *mz_stream_ioapi_create(void); static void mz_stream_ioapi_delete(void **stream); /***************************************************************************/ static mz_stream_vtbl mz_stream_ioapi_vtbl = { mz_stream_ioapi_open, mz_stream_ioapi_is_open, mz_stream_ioapi_read, mz_stream_ioapi_write, mz_stream_ioapi_tell, mz_stream_ioapi_seek, mz_stream_ioapi_close, mz_stream_ioapi_error, mz_stream_ioapi_create, mz_stream_ioapi_delete, NULL, NULL }; /***************************************************************************/ static int32_t mz_stream_ioapi_open(void *stream, const char *path, int32_t mode) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; int32_t ioapi_mode = 0; if ((mode & MZ_OPEN_MODE_READWRITE) == MZ_OPEN_MODE_READ) ioapi_mode = ZLIB_FILEFUNC_MODE_READ; else if (mode & MZ_OPEN_MODE_APPEND) ioapi_mode = ZLIB_FILEFUNC_MODE_EXISTING; else if (mode & MZ_OPEN_MODE_CREATE) ioapi_mode = ZLIB_FILEFUNC_MODE_CREATE; else return MZ_OPEN_ERROR; if (ioapi->filefunc64.zopen64_file) ioapi->handle = ioapi->filefunc64.zopen64_file(ioapi->filefunc64.opaque, path, ioapi_mode); else if (ioapi->filefunc.zopen_file) ioapi->handle = ioapi->filefunc.zopen_file(ioapi->filefunc.opaque, path, ioapi_mode); if (!ioapi->handle) return MZ_PARAM_ERROR; return MZ_OK; } static int32_t mz_stream_ioapi_is_open(void *stream) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; if (!ioapi->handle) return MZ_OPEN_ERROR; return MZ_OK; } static int32_t mz_stream_ioapi_read(void *stream, void *buf, int32_t size) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; read_file_func zread = NULL; void *opaque = NULL; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc64.zread_file) { zread = ioapi->filefunc64.zread_file; opaque = ioapi->filefunc64.opaque; } else if (ioapi->filefunc.zread_file) { zread = ioapi->filefunc.zread_file; opaque = ioapi->filefunc.opaque; } else return MZ_PARAM_ERROR; return zread(opaque, ioapi->handle, buf, size); } static int32_t mz_stream_ioapi_write(void *stream, const void *buf, int32_t size) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; write_file_func zwrite = NULL; int32_t written = 0; void *opaque = NULL; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc64.zwrite_file) { zwrite = ioapi->filefunc64.zwrite_file; opaque = ioapi->filefunc64.opaque; } else if (ioapi->filefunc.zwrite_file) { zwrite = ioapi->filefunc.zwrite_file; opaque = ioapi->filefunc.opaque; } else return MZ_PARAM_ERROR; written = zwrite(opaque, ioapi->handle, buf, size); return written; } static int64_t mz_stream_ioapi_tell(void *stream) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc64.ztell64_file) return ioapi->filefunc64.ztell64_file(ioapi->filefunc64.opaque, ioapi->handle); else if (ioapi->filefunc.ztell_file) return ioapi->filefunc.ztell_file(ioapi->filefunc.opaque, ioapi->handle); return MZ_INTERNAL_ERROR; } static int32_t mz_stream_ioapi_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc64.zseek64_file) { if (ioapi->filefunc64.zseek64_file(ioapi->filefunc64.opaque, ioapi->handle, offset, origin) != 0) return MZ_INTERNAL_ERROR; } else if (ioapi->filefunc.zseek_file) { if (ioapi->filefunc.zseek_file(ioapi->filefunc.opaque, ioapi->handle, (int32_t)offset, origin) != 0) return MZ_INTERNAL_ERROR; } else return MZ_PARAM_ERROR; return MZ_OK; } static int32_t mz_stream_ioapi_close(void *stream) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; close_file_func zclose = NULL; void *opaque = NULL; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc.zclose_file) { zclose = ioapi->filefunc.zclose_file; opaque = ioapi->filefunc.opaque; } else if (ioapi->filefunc64.zclose_file) { zclose = ioapi->filefunc64.zclose_file; opaque = ioapi->filefunc64.opaque; } else return MZ_PARAM_ERROR; if (zclose(opaque, ioapi->handle) != 0) return MZ_CLOSE_ERROR; ioapi->handle = NULL; return MZ_OK; } static int32_t mz_stream_ioapi_error(void *stream) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; testerror_file_func zerror = NULL; void *opaque = NULL; if (mz_stream_ioapi_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (ioapi->filefunc.zerror_file) { zerror = ioapi->filefunc.zerror_file; opaque = ioapi->filefunc.opaque; } else if (ioapi->filefunc64.zerror_file) { zerror = ioapi->filefunc64.zerror_file; opaque = ioapi->filefunc64.opaque; } else return MZ_PARAM_ERROR; return zerror(opaque, ioapi->handle); } static int32_t mz_stream_ioapi_set_filefunc(void *stream, zlib_filefunc_def *filefunc) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; memcpy(&ioapi->filefunc, filefunc, sizeof(zlib_filefunc_def)); return MZ_OK; } static int32_t mz_stream_ioapi_set_filefunc64(void *stream, zlib_filefunc64_def *filefunc) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)stream; memcpy(&ioapi->filefunc64, filefunc, sizeof(zlib_filefunc64_def)); return MZ_OK; } static void *mz_stream_ioapi_create(void) { mz_stream_ioapi *ioapi = (mz_stream_ioapi *)calloc(1, sizeof(mz_stream_ioapi)); if (ioapi) ioapi->stream.vtbl = &mz_stream_ioapi_vtbl; return ioapi; } static void mz_stream_ioapi_delete(void **stream) { mz_stream_ioapi *ioapi = NULL; if (!stream) return; ioapi = (mz_stream_ioapi *)*stream; if (ioapi) free(ioapi); *stream = NULL; } /***************************************************************************/ void fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { /* For 32-bit file support only, compile with MZ_FILE32_API */ if (pzlib_filefunc_def) memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); } void fill_fopen64_filefunc(zlib_filefunc64_def *pzlib_filefunc_def) { /* All mz_stream_os_* support large files if compilation supports it */ if (pzlib_filefunc_def) memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); } void fill_win32_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { /* Handled by mz_stream_os_win32 */ if (pzlib_filefunc_def) memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); } void fill_win32_filefunc64(zlib_filefunc64_def *pzlib_filefunc_def) { /* Automatically supported in mz_stream_os_win32 */ if (pzlib_filefunc_def) memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); } void fill_win32_filefunc64A(zlib_filefunc64_def *pzlib_filefunc_def) { /* Automatically supported in mz_stream_os_win32 */ if (pzlib_filefunc_def) memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc64_def)); } /* NOTE: fill_win32_filefunc64W is no longer necessary since wide-character support is automatically handled by the underlying os stream. Do not pass wide-characters to zipOpen or unzOpen. */ void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def) { /* Use opaque to indicate which stream interface to create */ if (pzlib_filefunc_def) { memset(pzlib_filefunc_def, 0, sizeof(zlib_filefunc_def)); pzlib_filefunc_def->opaque = mz_stream_mem_get_interface(); } } /***************************************************************************/ static int32_t zipConvertAppendToStreamMode(int append) { int32_t mode = MZ_OPEN_MODE_WRITE; switch (append) { case APPEND_STATUS_CREATE: mode |= MZ_OPEN_MODE_CREATE; break; case APPEND_STATUS_CREATEAFTER: mode |= MZ_OPEN_MODE_CREATE | MZ_OPEN_MODE_APPEND; break; case APPEND_STATUS_ADDINZIP: mode |= MZ_OPEN_MODE_READ | MZ_OPEN_MODE_APPEND; break; } return mode; } zipFile zipOpen(const char *path, int append) { return zipOpen2(path, append, NULL, NULL); } zipFile zipOpen64(const void *path, int append) { return zipOpen2(path, append, NULL, NULL); } zipFile zipOpen2(const char *path, int append, const char **globalcomment, zlib_filefunc_def *pzlib_filefunc_def) { zipFile zip = NULL; int32_t mode = zipConvertAppendToStreamMode(append); void *stream = NULL; if (pzlib_filefunc_def) { if (pzlib_filefunc_def->zopen_file) { stream = mz_stream_ioapi_create(); if (!stream) return NULL; mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); } else if (pzlib_filefunc_def->opaque) { stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); if (!stream) return NULL; } } if (!stream) { stream = mz_stream_os_create(); if (!stream) return NULL; } if (mz_stream_open(stream, path, mode) != MZ_OK) { mz_stream_delete(&stream); return NULL; } zip = zipOpen_MZ(stream, append, globalcomment); if (!zip) { mz_stream_delete(&stream); return NULL; } return zip; } zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, zlib_filefunc64_def *pzlib_filefunc_def) { zipFile zip = NULL; int32_t mode = zipConvertAppendToStreamMode(append); void *stream = NULL; if (pzlib_filefunc_def) { if (pzlib_filefunc_def->zopen64_file) { stream = mz_stream_ioapi_create(); if (!stream) return NULL; mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); } else if (pzlib_filefunc_def->opaque) { stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); if (!stream) return NULL; } } if (!stream) { stream = mz_stream_os_create(); if (!stream) return NULL; } if (mz_stream_open(stream, path, mode) != MZ_OK) { mz_stream_delete(&stream); return NULL; } zip = zipOpen_MZ(stream, append, globalcomment); if (!zip) { mz_stream_delete(&stream); return NULL; } return zip; } zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment) { mz_compat *compat = NULL; int32_t err = MZ_OK; int32_t mode = zipConvertAppendToStreamMode(append); void *handle = NULL; handle = mz_zip_create(); if (!handle) return NULL; err = mz_zip_open(handle, stream, mode); if (err != MZ_OK) { mz_zip_delete(&handle); return NULL; } if (globalcomment) mz_zip_get_comment(handle, globalcomment); compat = (mz_compat *)calloc(1, sizeof(mz_compat)); if (compat) { compat->handle = handle; compat->stream = stream; } else { mz_zip_delete(&handle); } return (zipFile)compat; } void* zipGetHandle_MZ(zipFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return NULL; return compat->handle; } void* zipGetStream_MZ(zipFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return NULL; return (void *)compat->stream; } int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base, int zip64) { mz_compat *compat = (mz_compat *)file; mz_zip_file file_info; MZ_UNUSED(strategy); MZ_UNUSED(memLevel); MZ_UNUSED(windowBits); MZ_UNUSED(size_extrafield_local); MZ_UNUSED(extrafield_local); MZ_UNUSED(crc_for_crypting); if (!compat) return ZIP_PARAMERROR; memset(&file_info, 0, sizeof(file_info)); if (zipfi) { uint64_t dos_date = 0; if (zipfi->mz_dos_date != 0) dos_date = zipfi->mz_dos_date; else dos_date = mz_zip_tm_to_dosdate(&zipfi->tmz_date); file_info.modified_date = mz_zip_dosdate_to_time_t(dos_date); file_info.external_fa = zipfi->external_fa; file_info.internal_fa = zipfi->internal_fa; } if (!filename) filename = "-"; file_info.compression_method = (uint16_t)compression_method; file_info.filename = filename; /* file_info.extrafield_local = extrafield_local; */ /* file_info.extrafield_local_size = size_extrafield_local; */ file_info.extrafield = extrafield_global; file_info.extrafield_size = size_extrafield_global; file_info.version_madeby = (uint16_t)version_madeby; file_info.comment = comment; if (file_info.comment) file_info.comment_size = (uint16_t)strlen(file_info.comment); file_info.flag = (uint16_t)flag_base; if (zip64) file_info.zip64 = MZ_ZIP64_FORCE; else file_info.zip64 = MZ_ZIP64_DISABLE; #ifdef HAVE_WZAES if (password || (raw && (file_info.flag & MZ_ZIP_FLAG_ENCRYPTED))) file_info.aes_version = MZ_AES_VERSION; #endif return mz_zip_entry_write_open(compat->handle, &file_info, (int16_t)level, (uint8_t)raw, password); } int zipOpenNewFileInZip4_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base, int zip64) { return zipOpenNewFileInZip5(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, memLevel, strategy, password, crc_for_crypting, version_madeby, flag_base, zip64); } int zipOpenNewFileInZip4(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base) { return zipOpenNewFileInZip4_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, memLevel, strategy, password, crc_for_crypting, version_madeby, flag_base, 0); } int zipOpenNewFileInZip3(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting) { return zipOpenNewFileInZip3_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, memLevel, strategy, password, crc_for_crypting, 0); } int zipOpenNewFileInZip3_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, uint32_t crc_for_crypting, int zip64) { return zipOpenNewFileInZip4_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, windowBits, memLevel, strategy, password, crc_for_crypting, MZ_VERSION_MADEBY, 0, zip64); } int zipOpenNewFileInZip2(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw) { return zipOpenNewFileInZip3_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, 0, 0, 0, NULL, 0, 0); } int zipOpenNewFileInZip2_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int zip64) { return zipOpenNewFileInZip3_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, raw, 0, 0, 0, NULL, 0, zip64); } int zipOpenNewFileInZip(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level) { return zipOpenNewFileInZip_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, 0); } int zipOpenNewFileInZip_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int zip64) { return zipOpenNewFileInZip2_64(file, filename, zipfi, extrafield_local, size_extrafield_local, extrafield_global, size_extrafield_global, comment, compression_method, level, 0, zip64); } int zipWriteInFileInZip(zipFile file, const void *buf, uint32_t len) { mz_compat *compat = (mz_compat *)file; int32_t written = 0; if (!compat || len >= INT32_MAX) return ZIP_PARAMERROR; written = mz_zip_entry_write(compat->handle, buf, (int32_t)len); if ((written < 0) || ((uint32_t)written != len)) return ZIP_ERRNO; return ZIP_OK; } int zipCloseFileInZipRaw(zipFile file, unsigned long uncompressed_size, unsigned long crc32) { return zipCloseFileInZipRaw64(file, uncompressed_size, crc32); } int zipCloseFileInZipRaw64(zipFile file, uint64_t uncompressed_size, unsigned long crc32) { mz_compat *compat = (mz_compat *)file; if (!compat) return ZIP_PARAMERROR; return mz_zip_entry_close_raw(compat->handle, (int64_t)uncompressed_size, crc32); } int zipCloseFileInZip(zipFile file) { return zipCloseFileInZip64(file); } int zipCloseFileInZip64(zipFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return ZIP_PARAMERROR; return mz_zip_entry_close(compat->handle); } int zipClose(zipFile file, const char *global_comment) { return zipClose_64(file, global_comment); } int zipClose_64(zipFile file, const char *global_comment) { return zipClose2_64(file, global_comment, MZ_VERSION_MADEBY); } int zipClose2_64(zipFile file, const char *global_comment, uint16_t version_madeby) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (compat->handle) err = zipClose2_MZ(file, global_comment, version_madeby); if (compat->stream) { mz_stream_close(compat->stream); mz_stream_delete(&compat->stream); } free(compat); return err; } /* Only closes the zip handle, does not close the stream */ int zipClose_MZ(zipFile file, const char *global_comment) { return zipClose2_MZ(file, global_comment, MZ_VERSION_MADEBY); } /* Only closes the zip handle, does not close the stream */ int zipClose2_MZ(zipFile file, const char *global_comment, uint16_t version_madeby) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat) return ZIP_PARAMERROR; if (!compat->handle) return err; if (global_comment) mz_zip_set_comment(compat->handle, global_comment); mz_zip_set_version_madeby(compat->handle, version_madeby); err = mz_zip_close(compat->handle); mz_zip_delete(&compat->handle); return err; } /***************************************************************************/ unzFile unzOpen(const char *path) { return unzOpen64(path); } unzFile unzOpen64(const void *path) { return unzOpen2(path, NULL); } unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def) { unzFile unz = NULL; void *stream = NULL; if (pzlib_filefunc_def) { if (pzlib_filefunc_def->zopen_file) { stream = mz_stream_ioapi_create(); if (!stream) return NULL; mz_stream_ioapi_set_filefunc(stream, pzlib_filefunc_def); } else if (pzlib_filefunc_def->opaque) { stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); if (!stream) return NULL; } } if (!stream) { stream = mz_stream_os_create(); if (!stream) return NULL; } if (mz_stream_open(stream, path, MZ_OPEN_MODE_READ) != MZ_OK) { mz_stream_delete(&stream); return NULL; } unz = unzOpen_MZ(stream); if (!unz) { mz_stream_close(stream); mz_stream_delete(&stream); return NULL; } return unz; } unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def) { unzFile unz = NULL; void *stream = NULL; if (pzlib_filefunc_def) { if (pzlib_filefunc_def->zopen64_file) { stream = mz_stream_ioapi_create(); if (!stream) return NULL; mz_stream_ioapi_set_filefunc64(stream, pzlib_filefunc_def); } else if (pzlib_filefunc_def->opaque) { stream = mz_stream_create((mz_stream_vtbl *)pzlib_filefunc_def->opaque); if (!stream) return NULL; } } if (!stream) { stream = mz_stream_os_create(); if (!stream) return NULL; } if (mz_stream_open(stream, path, MZ_OPEN_MODE_READ) != MZ_OK) { mz_stream_delete(&stream); return NULL; } unz = unzOpen_MZ(stream); if (!unz) { mz_stream_close(stream); mz_stream_delete(&stream); return NULL; } return unz; } void* unzGetHandle_MZ(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return NULL; return compat->handle; } void* unzGetStream_MZ(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return NULL; return compat->stream; } unzFile unzOpen_MZ(void *stream) { mz_compat *compat = NULL; int32_t err = MZ_OK; void *handle = NULL; handle = mz_zip_create(); if (!handle) return NULL; err = mz_zip_open(handle, stream, MZ_OPEN_MODE_READ); if (err != MZ_OK) { mz_zip_delete(&handle); return NULL; } compat = (mz_compat *)calloc(1, sizeof(mz_compat)); if (compat) { compat->handle = handle; compat->stream = stream; mz_zip_goto_first_entry(compat->handle); } else { mz_zip_delete(&handle); } return (unzFile)compat; } int unzClose(unzFile file) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; if (compat->handle) err = unzClose_MZ(file); if (compat->stream) { mz_stream_close(compat->stream); mz_stream_delete(&compat->stream); } free(compat); return err; } /* Only closes the zip handle, does not close the stream */ int unzClose_MZ(unzFile file) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_close(compat->handle); mz_zip_delete(&compat->handle); return err; } int unzGetGlobalInfo(unzFile file, unz_global_info* pglobal_info32) { mz_compat *compat = (mz_compat *)file; unz_global_info64 global_info64; int32_t err = MZ_OK; memset(pglobal_info32, 0, sizeof(unz_global_info)); if (!compat) return UNZ_PARAMERROR; err = unzGetGlobalInfo64(file, &global_info64); if (err == MZ_OK) { pglobal_info32->number_entry = (uint32_t)global_info64.number_entry; pglobal_info32->size_comment = global_info64.size_comment; pglobal_info32->number_disk_with_CD = global_info64.number_disk_with_CD; } return err; } int unzGetGlobalInfo64(unzFile file, unz_global_info64 *pglobal_info) { mz_compat *compat = (mz_compat *)file; const char *comment_ptr = NULL; int32_t err = MZ_OK; memset(pglobal_info, 0, sizeof(unz_global_info64)); if (!compat) return UNZ_PARAMERROR; err = mz_zip_get_comment(compat->handle, &comment_ptr); if (err == MZ_OK) pglobal_info->size_comment = (uint16_t)strlen(comment_ptr); if ((err == MZ_OK) || (err == MZ_EXIST_ERROR)) err = mz_zip_get_number_entry(compat->handle, &pglobal_info->number_entry); if (err == MZ_OK) err = mz_zip_get_disk_number_with_cd(compat->handle, &pglobal_info->number_disk_with_CD); return err; } int unzGetGlobalComment(unzFile file, char *comment, unsigned long comment_size) { mz_compat *compat = (mz_compat *)file; const char *comment_ptr = NULL; int32_t err = MZ_OK; if (!comment || !comment_size) return UNZ_PARAMERROR; err = mz_zip_get_comment(compat->handle, &comment_ptr); if (err == MZ_OK) { strncpy(comment, comment_ptr, comment_size - 1); comment[comment_size - 1] = 0; } return err; } int unzOpenCurrentFile3(unzFile file, int *method, int *level, int raw, const char *password) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; int32_t err = MZ_OK; void *stream = NULL; if (!compat) return UNZ_PARAMERROR; if (method) *method = 0; if (level) *level = 0; if (mz_zip_entry_is_open(compat->handle) == MZ_OK) { /* zlib minizip does not error out here if close returns errors */ unzCloseCurrentFile(file); } compat->total_out = 0; err = mz_zip_entry_read_open(compat->handle, (uint8_t)raw, password); if (err == MZ_OK) err = mz_zip_entry_get_info(compat->handle, &file_info); if (err == MZ_OK) { if (method) { *method = file_info->compression_method; } if (level) { *level = 6; switch (file_info->flag & 0x06) { case MZ_ZIP_FLAG_DEFLATE_SUPER_FAST: *level = 1; break; case MZ_ZIP_FLAG_DEFLATE_FAST: *level = 2; break; case MZ_ZIP_FLAG_DEFLATE_MAX: *level = 9; break; } } } if (err == MZ_OK) err = mz_zip_get_stream(compat->handle, &stream); if (err == MZ_OK) compat->entry_pos = mz_stream_tell(stream); return err; } int unzOpenCurrentFile(unzFile file) { return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL); } int unzOpenCurrentFilePassword(unzFile file, const char *password) { return unzOpenCurrentFile3(file, NULL, NULL, 0, password); } int unzOpenCurrentFile2(unzFile file, int *method, int *level, int raw) { return unzOpenCurrentFile3(file, method, level, raw, NULL); } int unzReadCurrentFile(unzFile file, void *buf, uint32_t len) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat || len >= INT32_MAX) return UNZ_PARAMERROR; err = mz_zip_entry_read(compat->handle, buf, (int32_t)len); if (err > 0) compat->total_out += (uint32_t)err; return err; } int unzCloseCurrentFile(unzFile file) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_entry_close(compat->handle); return err; } int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filename, unsigned long filename_size, void *extrafield, unsigned long extrafield_size, char *comment, unsigned long comment_size) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; uint16_t bytes_to_copy = 0; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_entry_get_info(compat->handle, &file_info); if (err != MZ_OK) return err; if (pfile_info) { pfile_info->version = file_info->version_madeby; pfile_info->version_needed = file_info->version_needed; pfile_info->flag = file_info->flag; pfile_info->compression_method = file_info->compression_method; pfile_info->mz_dos_date = mz_zip_time_t_to_dos_date(file_info->modified_date); mz_zip_time_t_to_tm(file_info->modified_date, &pfile_info->tmu_date); pfile_info->tmu_date.tm_year += 1900; pfile_info->crc = file_info->crc; pfile_info->size_filename = file_info->filename_size; pfile_info->size_file_extra = file_info->extrafield_size; pfile_info->size_file_comment = file_info->comment_size; pfile_info->disk_num_start = (uint16_t)file_info->disk_number; pfile_info->internal_fa = file_info->internal_fa; pfile_info->external_fa = file_info->external_fa; pfile_info->compressed_size = (uint32_t)file_info->compressed_size; pfile_info->uncompressed_size = (uint32_t)file_info->uncompressed_size; } if (filename_size > 0 && filename && file_info->filename) { bytes_to_copy = (uint16_t)filename_size; if (bytes_to_copy > file_info->filename_size) bytes_to_copy = file_info->filename_size; memcpy(filename, file_info->filename, bytes_to_copy); if (bytes_to_copy < filename_size) filename[bytes_to_copy] = 0; } if (extrafield_size > 0 && extrafield) { bytes_to_copy = (uint16_t)extrafield_size; if (bytes_to_copy > file_info->extrafield_size) bytes_to_copy = file_info->extrafield_size; memcpy(extrafield, file_info->extrafield, bytes_to_copy); } if (comment_size > 0 && comment && file_info->comment) { bytes_to_copy = (uint16_t)comment_size; if (bytes_to_copy > file_info->comment_size) bytes_to_copy = file_info->comment_size; memcpy(comment, file_info->comment, bytes_to_copy); if (bytes_to_copy < comment_size) comment[bytes_to_copy] = 0; } return err; } int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *filename, unsigned long filename_size, void *extrafield, unsigned long extrafield_size, char *comment, unsigned long comment_size) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; uint16_t bytes_to_copy = 0; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_entry_get_info(compat->handle, &file_info); if (err != MZ_OK) return err; if (pfile_info) { pfile_info->version = file_info->version_madeby; pfile_info->version_needed = file_info->version_needed; pfile_info->flag = file_info->flag; pfile_info->compression_method = file_info->compression_method; pfile_info->mz_dos_date = mz_zip_time_t_to_dos_date(file_info->modified_date); mz_zip_time_t_to_tm(file_info->modified_date, &pfile_info->tmu_date); pfile_info->tmu_date.tm_year += 1900; pfile_info->crc = file_info->crc; pfile_info->size_filename = file_info->filename_size; pfile_info->size_file_extra = file_info->extrafield_size; pfile_info->size_file_comment = file_info->comment_size; pfile_info->disk_num_start = file_info->disk_number; pfile_info->internal_fa = file_info->internal_fa; pfile_info->external_fa = file_info->external_fa; pfile_info->compressed_size = (uint64_t)file_info->compressed_size; pfile_info->uncompressed_size = (uint64_t)file_info->uncompressed_size; } if (filename_size > 0 && filename && file_info->filename) { bytes_to_copy = (uint16_t)filename_size; if (bytes_to_copy > file_info->filename_size) bytes_to_copy = file_info->filename_size; memcpy(filename, file_info->filename, bytes_to_copy); if (bytes_to_copy < filename_size) filename[bytes_to_copy] = 0; } if (extrafield_size > 0 && extrafield) { bytes_to_copy = (uint16_t)extrafield_size; if (bytes_to_copy > file_info->extrafield_size) bytes_to_copy = file_info->extrafield_size; memcpy(extrafield, file_info->extrafield, bytes_to_copy); } if (comment_size > 0 && comment && file_info->comment) { bytes_to_copy = (uint16_t)comment_size; if (bytes_to_copy > file_info->comment_size) bytes_to_copy = file_info->comment_size; memcpy(comment, file_info->comment, bytes_to_copy); if (bytes_to_copy < comment_size) comment[bytes_to_copy] = 0; } return err; } int unzGoToFirstFile(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return UNZ_PARAMERROR; compat->entry_index = 0; return mz_zip_goto_first_entry(compat->handle); } int unzGoToNextFile(unzFile file) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_goto_next_entry(compat->handle); if (err != MZ_END_OF_LIST) compat->entry_index += 1; return err; } int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; uint64_t preserve_index = 0; int32_t err = MZ_OK; int32_t result = 0; if (!compat) return UNZ_PARAMERROR; preserve_index = compat->entry_index; err = mz_zip_goto_first_entry(compat->handle); while (err == MZ_OK) { err = mz_zip_entry_get_info(compat->handle, &file_info); if (err != MZ_OK) break; if ((intptr_t)filename_compare_func > 2) { result = filename_compare_func(file, filename, file_info->filename); } else { int32_t case_sensitive = (int32_t)(intptr_t)filename_compare_func; result = mz_path_compare_wc(filename, file_info->filename, !case_sensitive); } if (result == 0) return MZ_OK; err = mz_zip_goto_next_entry(compat->handle); } compat->entry_index = preserve_index; return err; } /***************************************************************************/ int unzGetFilePos(unzFile file, unz_file_pos *file_pos) { unz64_file_pos file_pos64; int32_t err = 0; err = unzGetFilePos64(file, &file_pos64); if (err < 0) return err; file_pos->pos_in_zip_directory = (uint32_t)file_pos64.pos_in_zip_directory; file_pos->num_of_file = (uint32_t)file_pos64.num_of_file; return err; } int unzGoToFilePos(unzFile file, unz_file_pos *file_pos) { mz_compat *compat = (mz_compat *)file; unz64_file_pos file_pos64; if (!compat || !file_pos) return UNZ_PARAMERROR; file_pos64.pos_in_zip_directory = file_pos->pos_in_zip_directory; file_pos64.num_of_file = file_pos->num_of_file; return unzGoToFilePos64(file, &file_pos64); } int unzGetFilePos64(unzFile file, unz64_file_pos *file_pos) { mz_compat *compat = (mz_compat *)file; int64_t offset = 0; if (!compat || !file_pos) return UNZ_PARAMERROR; offset = unzGetOffset64(file); if (offset < 0) return (int)offset; file_pos->pos_in_zip_directory = offset; file_pos->num_of_file = compat->entry_index; return UNZ_OK; } int unzGoToFilePos64(unzFile file, const unz64_file_pos *file_pos) { mz_compat *compat = (mz_compat *)file; int32_t err = MZ_OK; if (!compat || !file_pos) return UNZ_PARAMERROR; err = mz_zip_goto_entry(compat->handle, file_pos->pos_in_zip_directory); if (err == MZ_OK) compat->entry_index = file_pos->num_of_file; return err; } unsigned long unzGetOffset(unzFile file) { return (uint32_t)unzGetOffset64(file); } int64_t unzGetOffset64(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return UNZ_PARAMERROR; return mz_zip_get_entry(compat->handle); } int unzSetOffset(unzFile file, unsigned long pos) { return unzSetOffset64(file, pos); } int unzSetOffset64(unzFile file, int64_t pos) { mz_compat *compat = (mz_compat *)file; if (!compat) return UNZ_PARAMERROR; return (int)mz_zip_goto_entry(compat->handle, pos); } int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; int32_t err = MZ_OK; int32_t bytes_to_copy = 0; if (!compat || !buf || len >= INT32_MAX) return UNZ_PARAMERROR; err = mz_zip_entry_get_local_info(compat->handle, &file_info); if (err != MZ_OK) return err; bytes_to_copy = (int32_t)len; if (bytes_to_copy > file_info->extrafield_size) bytes_to_copy = file_info->extrafield_size; memcpy(buf, file_info->extrafield, bytes_to_copy); return MZ_OK; } int32_t unzTell(unzFile file) { return unztell(file); } int32_t unztell(unzFile file) { return (int32_t)unztell64(file); } uint64_t unzTell64(unzFile file) { return unztell64(file); } uint64_t unztell64(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return UNZ_PARAMERROR; return compat->total_out; } int unzSeek(unzFile file, int32_t offset, int origin) { return unzSeek64(file, offset, origin); } int unzSeek64(unzFile file, int64_t offset, int origin) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; int64_t position = 0; int32_t err = MZ_OK; void *stream = NULL; if (!compat) return UNZ_PARAMERROR; err = mz_zip_entry_get_info(compat->handle, &file_info); if (err != MZ_OK) return err; if (file_info->compression_method != MZ_COMPRESS_METHOD_STORE) return UNZ_ERRNO; if (origin == SEEK_SET) position = offset; else if (origin == SEEK_CUR) position = compat->total_out + offset; else if (origin == SEEK_END) position = (int64_t)file_info->compressed_size + offset; else return UNZ_PARAMERROR; if (position > (int64_t)file_info->compressed_size) return UNZ_PARAMERROR; err = mz_zip_get_stream(compat->handle, &stream); if (err == MZ_OK) err = mz_stream_seek(stream, compat->entry_pos + position, MZ_SEEK_SET); if (err == MZ_OK) compat->total_out = position; return err; } int unzEndOfFile(unzFile file) { return unzeof(file); } int unzeof(unzFile file) { mz_compat *compat = (mz_compat *)file; mz_zip_file *file_info = NULL; int32_t err = MZ_OK; if (!compat) return UNZ_PARAMERROR; err = mz_zip_entry_get_info(compat->handle, &file_info); if (err != MZ_OK) return err; if (compat->total_out == (int64_t)file_info->uncompressed_size) return 1; return 0; } void* unzGetStream(unzFile file) { mz_compat *compat = (mz_compat *)file; if (!compat) return NULL; return (void *)compat->stream; } /***************************************************************************/ sight-23.1.0/3rd-party/minizip/mz_compat.h000066400000000000000000000437541450532053500204000ustar00rootroot00000000000000/* mz_compat.h -- Backwards compatible interface for older versions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_COMPAT_H #define MZ_COMPAT_H #include "mz.h" #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ #if defined(HAVE_ZLIB) && defined(MAX_MEM_LEVEL) #ifndef DEF_MEM_LEVEL # if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 # else # define DEF_MEM_LEVEL MAX_MEM_LEVEL # endif #endif #endif #ifndef MAX_WBITS #define MAX_WBITS (15) #endif #ifndef DEF_MEM_LEVEL #define DEF_MEM_LEVEL (8) #endif #ifndef ZEXPORT # define ZEXPORT MZ_EXPORT #endif /***************************************************************************/ #if defined(STRICTZIP) || defined(STRICTZIPUNZIP) /* like the STRICT of WIN32, we define a pointer that cannot be converted from (void*) without cast */ typedef struct TagzipFile__ { int unused; } zip_file__; typedef zip_file__ *zipFile; #else typedef void *zipFile; #endif /***************************************************************************/ typedef uint64_t ZPOS64_T; #ifndef ZCALLBACK #define ZCALLBACK #endif typedef void* (ZCALLBACK *open_file_func) (void *opaque, const char *filename, int mode); typedef void* (ZCALLBACK *open64_file_func) (void *opaque, const void *filename, int mode); typedef unsigned long (ZCALLBACK *read_file_func) (void *opaque, void *stream, void* buf, unsigned long size); typedef unsigned long (ZCALLBACK *write_file_func) (void *opaque, void *stream, const void* buf, unsigned long size); typedef int (ZCALLBACK *close_file_func) (void *opaque, void *stream); typedef int (ZCALLBACK *testerror_file_func)(void *opaque, void *stream); typedef long (ZCALLBACK *tell_file_func) (void *opaque, void *stream); typedef ZPOS64_T (ZCALLBACK *tell64_file_func) (void *opaque, void *stream); typedef long (ZCALLBACK *seek_file_func) (void *opaque, void *stream, unsigned long offset, int origin); typedef long (ZCALLBACK *seek64_file_func) (void *opaque, void *stream, ZPOS64_T offset, int origin); typedef struct zlib_filefunc_def_s { open_file_func zopen_file; read_file_func zread_file; write_file_func zwrite_file; tell_file_func ztell_file; seek_file_func zseek_file; close_file_func zclose_file; testerror_file_func zerror_file; void* opaque; } zlib_filefunc_def; typedef struct zlib_filefunc64_def_s { open64_file_func zopen64_file; read_file_func zread_file; write_file_func zwrite_file; tell64_file_func ztell64_file; seek64_file_func zseek64_file; close_file_func zclose_file; testerror_file_func zerror_file; void* opaque; } zlib_filefunc64_def; /***************************************************************************/ #define ZLIB_FILEFUNC_SEEK_SET (0) #define ZLIB_FILEFUNC_SEEK_CUR (1) #define ZLIB_FILEFUNC_SEEK_END (2) #define ZLIB_FILEFUNC_MODE_READ (1) #define ZLIB_FILEFUNC_MODE_WRITE (2) #define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3) #define ZLIB_FILEFUNC_MODE_EXISTING (4) #define ZLIB_FILEFUNC_MODE_CREATE (8) /***************************************************************************/ ZEXPORT void fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def); ZEXPORT void fill_fopen64_filefunc(zlib_filefunc64_def *pzlib_filefunc_def); ZEXPORT void fill_win32_filefunc(zlib_filefunc_def *pzlib_filefunc_def); ZEXPORT void fill_win32_filefunc64(zlib_filefunc64_def *pzlib_filefunc_def); ZEXPORT void fill_win32_filefunc64A(zlib_filefunc64_def *pzlib_filefunc_def); ZEXPORT void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def); /***************************************************************************/ #if MZ_COMPAT_VERSION <= 110 #define mz_dos_date dosDate #else #define mz_dos_date dos_date #endif typedef struct tm tm_unz; typedef struct tm tm_zip; typedef struct { uint32_t mz_dos_date; struct tm tmz_date; uint16_t internal_fa; /* internal file attributes 2 bytes */ uint32_t external_fa; /* external file attributes 4 bytes */ } zip_fileinfo; typedef const char *zipcharpc; /***************************************************************************/ #define ZIP_OK (0) #define ZIP_EOF (0) #define ZIP_ERRNO (-1) #define ZIP_PARAMERROR (-102) #define ZIP_BADZIPFILE (-103) #define ZIP_INTERNALERROR (-104) #ifndef Z_DEFLATED #define Z_DEFLATED (8) #endif #define Z_BZIP2ED (12) #define APPEND_STATUS_CREATE (0) #define APPEND_STATUS_CREATEAFTER (1) #define APPEND_STATUS_ADDINZIP (2) /***************************************************************************/ /* Writing a zip file */ ZEXPORT zipFile zipOpen(const char *path, int append); ZEXPORT zipFile zipOpen64(const void *path, int append); ZEXPORT zipFile zipOpen2(const char *path, int append, const char **globalcomment, zlib_filefunc_def *pzlib_filefunc_def); ZEXPORT zipFile zipOpen2_64(const void *path, int append, const char **globalcomment, zlib_filefunc64_def *pzlib_filefunc_def); ZEXPORT zipFile zipOpen_MZ(void *stream, int append, const char **globalcomment); ZEXPORT void* zipGetHandle_MZ(zipFile); ZEXPORT void* zipGetStream_MZ(zipFile file); ZEXPORT int zipOpenNewFileInZip(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level); ZEXPORT int zipOpenNewFileInZip_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int zip64); ZEXPORT int zipOpenNewFileInZip2(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw); ZEXPORT int zipOpenNewFileInZip2_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int zip64); ZEXPORT int zipOpenNewFileInZip3(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting); ZEXPORT int zipOpenNewFileInZip3_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, uint32_t crc_for_crypting, int zip64); ZEXPORT int zipOpenNewFileInZip4(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base); ZEXPORT int zipOpenNewFileInZip4_64(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base, int zip64); ZEXPORT int zipOpenNewFileInZip5(zipFile file, const char *filename, const zip_fileinfo *zipfi, const void *extrafield_local, uint16_t size_extrafield_local, const void *extrafield_global, uint16_t size_extrafield_global, const char *comment, int compression_method, int level, int raw, int windowBits, int memLevel, int strategy, const char *password, unsigned long crc_for_crypting, unsigned long version_madeby, unsigned long flag_base, int zip64); ZEXPORT int zipWriteInFileInZip(zipFile file, const void *buf, uint32_t len); ZEXPORT int zipCloseFileInZipRaw(zipFile file, unsigned long uncompressed_size, unsigned long crc32); ZEXPORT int zipCloseFileInZipRaw64(zipFile file, uint64_t uncompressed_size, unsigned long crc32); ZEXPORT int zipCloseFileInZip(zipFile file); ZEXPORT int zipCloseFileInZip64(zipFile file); ZEXPORT int zipClose(zipFile file, const char *global_comment); ZEXPORT int zipClose_64(zipFile file, const char *global_comment); ZEXPORT int zipClose2_64(zipFile file, const char *global_comment, uint16_t version_madeby); int zipClose_MZ(zipFile file, const char *global_comment); int zipClose2_MZ(zipFile file, const char *global_comment, uint16_t version_madeby); /***************************************************************************/ #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) /* like the STRICT of WIN32, we define a pointer that cannot be converted from (void*) without cast */ typedef struct TagunzFile__ { int unused; } unz_file__; typedef unz_file__ *unzFile; #else typedef void *unzFile; #endif /***************************************************************************/ #define UNZ_OK (0) #define UNZ_END_OF_LIST_OF_FILE (-100) #define UNZ_ERRNO (-1) #define UNZ_EOF (0) #define UNZ_PARAMERROR (-102) #define UNZ_BADZIPFILE (-103) #define UNZ_INTERNALERROR (-104) #define UNZ_CRCERROR (-105) #define UNZ_BADPASSWORD (-106) /***************************************************************************/ typedef struct unz_global_info64_s { uint64_t number_entry; /* total number of entries in the central dir on this disk */ uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ uint16_t size_comment; /* size of the global comment of the zipfile */ } unz_global_info64; typedef struct unz_global_info_s { uint32_t number_entry; /* total number of entries in the central dir on this disk */ uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP */ uint16_t size_comment; /* size of the global comment of the zipfile */ } unz_global_info; typedef struct unz_file_info64_s { uint16_t version; /* version made by 2 bytes */ uint16_t version_needed; /* version needed to extract 2 bytes */ uint16_t flag; /* general purpose bit flag 2 bytes */ uint16_t compression_method; /* compression method 2 bytes */ uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ struct tm tmu_date; uint32_t crc; /* crc-32 4 bytes */ uint64_t compressed_size; /* compressed size 8 bytes */ uint64_t uncompressed_size; /* uncompressed size 8 bytes */ uint16_t size_filename; /* filename length 2 bytes */ uint16_t size_file_extra; /* extra field length 2 bytes */ uint16_t size_file_comment; /* file comment length 2 bytes */ uint32_t disk_num_start; /* disk number start 4 bytes */ uint16_t internal_fa; /* internal file attributes 2 bytes */ uint32_t external_fa; /* external file attributes 4 bytes */ uint64_t disk_offset; uint16_t size_file_extra_internal; } unz_file_info64; typedef struct unz_file_info_s { uint16_t version; /* version made by 2 bytes */ uint16_t version_needed; /* version needed to extract 2 bytes */ uint16_t flag; /* general purpose bit flag 2 bytes */ uint16_t compression_method; /* compression method 2 bytes */ uint32_t mz_dos_date; /* last mod file date in Dos fmt 4 bytes */ struct tm tmu_date; uint32_t crc; /* crc-32 4 bytes */ uint32_t compressed_size; /* compressed size 4 bytes */ uint32_t uncompressed_size; /* uncompressed size 4 bytes */ uint16_t size_filename; /* filename length 2 bytes */ uint16_t size_file_extra; /* extra field length 2 bytes */ uint16_t size_file_comment; /* file comment length 2 bytes */ uint16_t disk_num_start; /* disk number start 2 bytes */ uint16_t internal_fa; /* internal file attributes 2 bytes */ uint32_t external_fa; /* external file attributes 4 bytes */ uint64_t disk_offset; } unz_file_info; /***************************************************************************/ typedef int (*unzFileNameComparer)(unzFile file, const char *filename1, const char *filename2); typedef int (*unzIteratorFunction)(unzFile file); typedef int (*unzIteratorFunction2)(unzFile file, unz_file_info64 *pfile_info, char *filename, uint16_t filename_size, void *extrafield, uint16_t extrafield_size, char *comment, uint16_t comment_size); /***************************************************************************/ /* Reading a zip file */ ZEXPORT unzFile unzOpen(const char *path); ZEXPORT unzFile unzOpen64(const void *path); ZEXPORT unzFile unzOpen2(const char *path, zlib_filefunc_def *pzlib_filefunc_def); ZEXPORT unzFile unzOpen2_64(const void *path, zlib_filefunc64_def *pzlib_filefunc_def); unzFile unzOpen_MZ(void *stream); ZEXPORT int unzClose(unzFile file); ZEXPORT int unzClose_MZ(unzFile file); ZEXPORT void* unzGetHandle_MZ(unzFile file); ZEXPORT void* unzGetStream_MZ(zipFile file); ZEXPORT int unzGetGlobalInfo(unzFile file, unz_global_info* pglobal_info32); ZEXPORT int unzGetGlobalInfo64(unzFile file, unz_global_info64 *pglobal_info); ZEXPORT int unzGetGlobalComment(unzFile file, char *comment, unsigned long comment_size); ZEXPORT int unzOpenCurrentFile(unzFile file); ZEXPORT int unzOpenCurrentFilePassword(unzFile file, const char *password); ZEXPORT int unzOpenCurrentFile2(unzFile file, int *method, int *level, int raw); ZEXPORT int unzOpenCurrentFile3(unzFile file, int *method, int *level, int raw, const char *password); ZEXPORT int unzReadCurrentFile(unzFile file, void *buf, uint32_t len); ZEXPORT int unzCloseCurrentFile(unzFile file); ZEXPORT int unzGetCurrentFileInfo(unzFile file, unz_file_info *pfile_info, char *filename, unsigned long filename_size, void *extrafield, unsigned long extrafield_size, char *comment, unsigned long comment_size); ZEXPORT int unzGetCurrentFileInfo64(unzFile file, unz_file_info64 * pfile_info, char *filename, unsigned long filename_size, void *extrafield, unsigned long extrafield_size, char *comment, unsigned long comment_size); ZEXPORT int unzGoToFirstFile(unzFile file); ZEXPORT int unzGoToNextFile(unzFile file); ZEXPORT int unzLocateFile(unzFile file, const char *filename, unzFileNameComparer filename_compare_func); ZEXPORT int unzGetLocalExtrafield(unzFile file, void *buf, unsigned int len); /***************************************************************************/ /* Raw access to zip file */ typedef struct unz_file_pos_s { uint32_t pos_in_zip_directory; /* offset in zip file directory */ uint32_t num_of_file; /* # of file */ } unz_file_pos; ZEXPORT int unzGetFilePos(unzFile file, unz_file_pos *file_pos); ZEXPORT int unzGoToFilePos(unzFile file, unz_file_pos *file_pos); typedef struct unz64_file_pos_s { int64_t pos_in_zip_directory; /* offset in zip file directory */ uint64_t num_of_file; /* # of file */ } unz64_file_pos; ZEXPORT int unzGetFilePos64(unzFile file, unz64_file_pos *file_pos); ZEXPORT int unzGoToFilePos64(unzFile file, const unz64_file_pos *file_pos); ZEXPORT int64_t unzGetOffset64(unzFile file); ZEXPORT unsigned long unzGetOffset(unzFile file); ZEXPORT int unzSetOffset64(unzFile file, int64_t pos); ZEXPORT int unzSetOffset(unzFile file, unsigned long pos); ZEXPORT int32_t unztell(unzFile file); ZEXPORT int32_t unzTell(unzFile file); ZEXPORT uint64_t unztell64(unzFile file); ZEXPORT uint64_t unzTell64(unzFile file); ZEXPORT int unzSeek(unzFile file, int32_t offset, int origin); ZEXPORT int unzSeek64(unzFile file, int64_t offset, int origin); ZEXPORT int unzEndOfFile(unzFile file); ZEXPORT int unzeof(unzFile file); ZEXPORT void* unzGetStream(unzFile file); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_crypt.c000066400000000000000000000164771450532053500202530ustar00rootroot00000000000000/* mz_crypt.c -- Crypto/hash functions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_os.h" #include "mz_crypt.h" #if defined(HAVE_ZLIB) # if !defined(ZLIB_COMPAT) # include "zlib-ng.h" # define ZLIB_PREFIX(x) zng_##x # else # include "zlib.h" # define ZLIB_PREFIX(x) x # endif #elif defined(HAVE_LZMA) # include "lzma.h" #endif /***************************************************************************/ #if defined(MZ_ZIP_NO_CRYPTO) int32_t mz_crypt_rand(uint8_t *buf, int32_t size) { return mz_os_rand(buf, size); } #endif uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size) { #if defined(HAVE_ZLIB) /* Define z_crc_t in zlib 1.2.5 and less or if using zlib-ng */ # if (ZLIB_VERNUM < 0x1270) typedef unsigned long z_crc_t; # else typedef uint32_t z_crc_t; # endif return (uint32_t)ZLIB_PREFIX(crc32)((z_crc_t)value, buf, (uInt)size); #elif defined(HAVE_LZMA) return (uint32_t)lzma_crc32(buf, (size_t)size, (uint32_t)value); #else static uint32_t crc32_table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; value = ~value; while (size > 0) { value = (value >> 8) ^ crc32_table[(value ^ *buf) & 0xFF]; buf += 1; size -= 1; } return ~value; #endif } #if defined(HAVE_WZAES) int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length) { void *hmac1 = NULL; void *hmac2 = NULL; void *hmac3 = NULL; int32_t err = MZ_OK; uint16_t i = 0; uint32_t j = 0; uint16_t k = 0; uint16_t block_count = 0; uint8_t uu[MZ_HASH_SHA1_SIZE]; uint8_t ux[MZ_HASH_SHA1_SIZE]; if (!password || !salt || !key) return MZ_PARAM_ERROR; memset(key, 0, key_length); hmac1 = mz_crypt_hmac_create(); hmac2 = mz_crypt_hmac_create(); hmac3 = mz_crypt_hmac_create(); if (!hmac1 || !hmac2 || !hmac3) { err = MZ_MEM_ERROR; goto pbkdf2_cleanup; } mz_crypt_hmac_set_algorithm(hmac1, MZ_HASH_SHA1); mz_crypt_hmac_set_algorithm(hmac2, MZ_HASH_SHA1); mz_crypt_hmac_set_algorithm(hmac3, MZ_HASH_SHA1); err = mz_crypt_hmac_init(hmac1, password, password_length); if (err == MZ_OK) err = mz_crypt_hmac_init(hmac2, password, password_length); if (err == MZ_OK) err = mz_crypt_hmac_update(hmac2, salt, salt_length); block_count = 1 + ((uint16_t)key_length - 1) / MZ_HASH_SHA1_SIZE; for (i = 0; (err == MZ_OK) && (i < block_count); i += 1) { memset(ux, 0, sizeof(ux)); err = mz_crypt_hmac_copy(hmac2, hmac3); if (err != MZ_OK) break; uu[0] = (uint8_t)((i + 1) >> 24); uu[1] = (uint8_t)((i + 1) >> 16); uu[2] = (uint8_t)((i + 1) >> 8); uu[3] = (uint8_t)(i + 1); for (j = 0, k = 4; j < iteration_count; j += 1) { err = mz_crypt_hmac_update(hmac3, uu, k); if (err == MZ_OK) err = mz_crypt_hmac_end(hmac3, uu, sizeof(uu)); if (err != MZ_OK) break; for (k = 0; k < MZ_HASH_SHA1_SIZE; k += 1) ux[k] ^= uu[k]; err = mz_crypt_hmac_copy(hmac1, hmac3); if (err != MZ_OK) break; } if (err != MZ_OK) break; j = 0; k = i * MZ_HASH_SHA1_SIZE; while (j < MZ_HASH_SHA1_SIZE && k < key_length) key[k++] = ux[j++]; } pbkdf2_cleanup: /* hmac3 uses the same provider as hmac2, so it must be deleted before the context is destroyed. */ mz_crypt_hmac_delete(&hmac3); mz_crypt_hmac_delete(&hmac1); mz_crypt_hmac_delete(&hmac2); return err; } #endif /***************************************************************************/ sight-23.1.0/3rd-party/minizip/mz_crypt.h000066400000000000000000000053241450532053500202450ustar00rootroot00000000000000/* mz_crypt.h -- Crypto/hash functions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_CRYPT_H #define MZ_CRYPT_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ uint32_t mz_crypt_crc32_update(uint32_t value, const uint8_t *buf, int32_t size); int32_t mz_crypt_pbkdf2(uint8_t *password, int32_t password_length, uint8_t *salt, int32_t salt_length, uint32_t iteration_count, uint8_t *key, uint16_t key_length); /***************************************************************************/ int32_t mz_crypt_rand(uint8_t *buf, int32_t size); void mz_crypt_sha_reset(void *handle); int32_t mz_crypt_sha_begin(void *handle); int32_t mz_crypt_sha_update(void *handle, const void *buf, int32_t size); int32_t mz_crypt_sha_end(void *handle, uint8_t *digest, int32_t digest_size); int32_t mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm); void* mz_crypt_sha_create(void); void mz_crypt_sha_delete(void **handle); void mz_crypt_aes_reset(void *handle); int32_t mz_crypt_aes_encrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); int32_t mz_crypt_aes_encrypt_final(void *handle, uint8_t *buf, int32_t size, uint8_t *tag, int32_t tag_size); int32_t mz_crypt_aes_decrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size); int32_t mz_crypt_aes_decrypt_final(void *handle, uint8_t *buf, int32_t size, const uint8_t *tag, int32_t tag_size); int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length, const void *iv, int32_t iv_length); int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length, const void *iv, int32_t iv_length); void mz_crypt_aes_set_mode(void *handle, int32_t mode); void* mz_crypt_aes_create(void); void mz_crypt_aes_delete(void **handle); void mz_crypt_hmac_reset(void *handle); int32_t mz_crypt_hmac_init(void *handle, const void *key, int32_t key_length); int32_t mz_crypt_hmac_update(void *handle, const void *buf, int32_t size); int32_t mz_crypt_hmac_end(void *handle, uint8_t *digest, int32_t digest_size); int32_t mz_crypt_hmac_copy(void *src_handle, void *target_handle); void mz_crypt_hmac_set_algorithm(void *handle, uint16_t algorithm); void* mz_crypt_hmac_create(void); void mz_crypt_hmac_delete(void **handle); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_crypt_openssl.c000066400000000000000000000436751450532053500220160ustar00rootroot00000000000000/* mz_crypt_openssl.c -- Crypto/hash functions for OpenSSL part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_crypt.h" #include #include #include #include #include #include #include #include #if OPENSSL_VERSION_NUMBER >= 0x30000000L # include #endif /***************************************************************************/ static void mz_crypt_init(void) { static int32_t openssl_initialized = 0; if (!openssl_initialized) { #if OPENSSL_VERSION_NUMBER < 0x10100000L OpenSSL_add_all_algorithms(); ERR_load_BIO_strings(); ERR_load_crypto_strings(); ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); #else OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_ALL_BUILTIN, NULL); #endif openssl_initialized = 1; } } int32_t mz_crypt_rand(uint8_t *buf, int32_t size) { if (!RAND_bytes(buf, size)) return MZ_CRYPT_ERROR; return size; } /***************************************************************************/ typedef struct mz_crypt_sha_s { #if OPENSSL_VERSION_NUMBER < 0x10100000L union { SHA512_CTX ctx512; SHA256_CTX ctx256; SHA_CTX ctx1; }; #else EVP_MD_CTX *ctx; #endif int32_t initialized; int32_t error; uint16_t algorithm; } mz_crypt_sha; /***************************************************************************/ static const uint8_t mz_crypt_sha_digest_size[] = { MZ_HASH_SHA1_SIZE, 0, MZ_HASH_SHA224_SIZE, MZ_HASH_SHA256_SIZE, MZ_HASH_SHA384_SIZE, MZ_HASH_SHA512_SIZE }; /***************************************************************************/ static void mz_crypt_sha_free(void *handle) { #if OPENSSL_VERSION_NUMBER >= 0x10100000L mz_crypt_sha *sha = (mz_crypt_sha *)handle; if (sha->ctx) EVP_MD_CTX_free(sha->ctx); sha->ctx = NULL; #else MZ_UNUSED(handle); #endif } void mz_crypt_sha_reset(void *handle) { mz_crypt_sha *sha = (mz_crypt_sha *)handle; mz_crypt_init(); mz_crypt_sha_free(handle); sha->error = 0; sha->initialized = 0; } int32_t mz_crypt_sha_begin(void *handle) { mz_crypt_sha *sha = (mz_crypt_sha *)handle; int32_t result = 0; if (!sha) return MZ_PARAM_ERROR; mz_crypt_sha_reset(handle); #if OPENSSL_VERSION_NUMBER < 0x10100000L switch (sha->algorithm) { case MZ_HASH_SHA1: result = SHA1_Init(&sha->ctx1); break; case MZ_HASH_SHA224: result = SHA224_Init(&sha->ctx256); break; case MZ_HASH_SHA256: result = SHA256_Init(&sha->ctx256); break; case MZ_HASH_SHA384: result = SHA384_Init(&sha->ctx512); break; case MZ_HASH_SHA512: result = SHA512_Init(&sha->ctx512); break; } #else const EVP_MD *md = NULL; switch (sha->algorithm) { case MZ_HASH_SHA1: md = EVP_sha1(); break; case MZ_HASH_SHA224: md = EVP_sha224(); break; case MZ_HASH_SHA256: md = EVP_sha256(); break; case MZ_HASH_SHA384: md = EVP_sha384(); break; case MZ_HASH_SHA512: md = EVP_sha512(); break; } if (!md) return MZ_PARAM_ERROR; sha->ctx = EVP_MD_CTX_new(); if (!sha->ctx) return MZ_MEM_ERROR; result = EVP_DigestInit_ex(sha->ctx, md, NULL); #endif if (!result) { sha->error = ERR_get_error(); return MZ_HASH_ERROR; } sha->initialized = 1; return MZ_OK; } int32_t mz_crypt_sha_update(void *handle, const void *buf, int32_t size) { mz_crypt_sha *sha = (mz_crypt_sha *)handle; int32_t result = 0; if (!sha || !buf || !sha->initialized) return MZ_PARAM_ERROR; #if OPENSSL_VERSION_NUMBER < 0x10100000L switch (sha->algorithm) { case MZ_HASH_SHA1: result = SHA1_Update(&sha->ctx1, buf, size); break; case MZ_HASH_SHA224: result = SHA224_Update(&sha->ctx256, buf, size); break; case MZ_HASH_SHA256: result = SHA256_Update(&sha->ctx256, buf, size); break; case MZ_HASH_SHA384: result = SHA384_Update(&sha->ctx512, buf, size); break; case MZ_HASH_SHA512: result = SHA512_Update(&sha->ctx512, buf, size); break; } #else result = EVP_DigestUpdate(sha->ctx, buf, size); #endif if (!result) { sha->error = ERR_get_error(); return MZ_HASH_ERROR; } return size; } int32_t mz_crypt_sha_end(void *handle, uint8_t *digest, int32_t digest_size) { mz_crypt_sha *sha = (mz_crypt_sha *)handle; int32_t result = 0; if (!sha || !digest || !sha->initialized) return MZ_PARAM_ERROR; if (digest_size < mz_crypt_sha_digest_size[sha->algorithm - MZ_HASH_SHA1]) return MZ_PARAM_ERROR; #if OPENSSL_VERSION_NUMBER < 0x10100000L switch (sha->algorithm) { case MZ_HASH_SHA1: result = SHA1_Final(digest, &sha->ctx1); break; case MZ_HASH_SHA224: result = SHA224_Final(digest, &sha->ctx256); break; case MZ_HASH_SHA256: result = SHA256_Final(digest, &sha->ctx256); break; case MZ_HASH_SHA384: result = SHA384_Final(digest, &sha->ctx512); break; case MZ_HASH_SHA512: result = SHA512_Final(digest, &sha->ctx512); break; } #else result = EVP_DigestFinal_ex(sha->ctx, digest, NULL); #endif if (!result) { sha->error = ERR_get_error(); return MZ_HASH_ERROR; } return MZ_OK; } int32_t mz_crypt_sha_set_algorithm(void *handle, uint16_t algorithm) { mz_crypt_sha *sha = (mz_crypt_sha *)handle; if (algorithm < MZ_HASH_SHA1 || algorithm > MZ_HASH_SHA512) return MZ_PARAM_ERROR; sha->algorithm = algorithm; return MZ_OK; } void *mz_crypt_sha_create(void) { mz_crypt_sha *sha = (mz_crypt_sha *)calloc(1, sizeof(mz_crypt_sha)); if (sha) sha->algorithm = MZ_HASH_SHA256; return sha; } void mz_crypt_sha_delete(void **handle) { mz_crypt_sha *sha = NULL; if (!handle) return; sha = (mz_crypt_sha *)*handle; if (sha) { mz_crypt_sha_free(*handle); free(sha); } *handle = NULL; } /***************************************************************************/ typedef struct mz_crypt_aes_s { int32_t mode; int32_t error; EVP_CIPHER_CTX *ctx; } mz_crypt_aes; /***************************************************************************/ static void mz_crypt_aes_free(void *handle) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; if (aes->ctx) EVP_CIPHER_CTX_free(aes->ctx); aes->ctx = NULL; } void mz_crypt_aes_reset(void *handle) { mz_crypt_init(); mz_crypt_aes_free(handle); } int32_t mz_crypt_aes_encrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; if (!aes || !buf || size % MZ_AES_BLOCK_SIZE != 0 || !aes->ctx) return MZ_PARAM_ERROR; if (aes->mode != MZ_AES_MODE_GCM && aad && aad_size > 0) return MZ_PARAM_ERROR; if (aad && aad_size > 0) { int32_t how_many = 0; if (!EVP_EncryptUpdate(aes->ctx, NULL, &how_many, aad, aad_size)) return MZ_CRYPT_ERROR; } if (!EVP_EncryptUpdate(aes->ctx, buf, &size, buf, size)) return MZ_CRYPT_ERROR; return size; } int32_t mz_crypt_aes_encrypt_final(void *handle, uint8_t *buf, int32_t size, uint8_t *tag, int32_t tag_size) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; int result = 0; int out_len = 0; if (!aes || !tag || !tag_size || !aes->ctx || aes->mode != MZ_AES_MODE_GCM) return MZ_PARAM_ERROR; if (buf && size) { if (!EVP_EncryptUpdate(aes->ctx, buf, &size, buf, size)) return MZ_CRYPT_ERROR; } /* Must call EncryptFinal for tag to be calculated */ result = EVP_EncryptFinal_ex(aes->ctx, NULL, &out_len); if (result) result = EVP_CIPHER_CTX_ctrl(aes->ctx, EVP_CTRL_GCM_GET_TAG, tag_size, tag); if (!result) { aes->error = ERR_get_error(); return MZ_CRYPT_ERROR; } return size; } int32_t mz_crypt_aes_decrypt(void *handle, const void *aad, int32_t aad_size, uint8_t *buf, int32_t size) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; if (!aes || !buf || size % MZ_AES_BLOCK_SIZE != 0 || !aes->ctx) return MZ_PARAM_ERROR; if (aes->mode != MZ_AES_MODE_GCM && aad && aad_size > 0) return MZ_PARAM_ERROR; if (aad && aad_size > 0) { int32_t how_many = 0; if (!EVP_DecryptUpdate(aes->ctx, NULL, &how_many, aad, aad_size)) return MZ_CRYPT_ERROR; } if (!EVP_DecryptUpdate(aes->ctx, buf, &size, buf, size)) return MZ_CRYPT_ERROR; return size; } int32_t mz_crypt_aes_decrypt_final(void *handle, uint8_t *buf, int32_t size, const uint8_t *tag, int32_t tag_length) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; int out_len = 0; if (!aes || !tag || !tag_length || !aes->ctx || aes->mode != MZ_AES_MODE_GCM) return MZ_PARAM_ERROR; if (buf && size) { if (!EVP_DecryptUpdate(aes->ctx, buf, &size, buf, size)) return MZ_CRYPT_ERROR; } /* Set expected tag */ if (!EVP_CIPHER_CTX_ctrl(aes->ctx, EVP_CTRL_GCM_SET_TAG, tag_length, (void *)tag)) { aes->error = ERR_get_error(); return MZ_CRYPT_ERROR; } /* Must call DecryptFinal for tag verification */ if (!EVP_DecryptFinal_ex(aes->ctx, NULL, &out_len)) { aes->error = ERR_get_error(); return MZ_CRYPT_ERROR; } return size; } static int32_t mz_crypt_aes_set_key(void *handle, const void *key, int32_t key_length, const void *iv, int32_t iv_length, int32_t encrypt) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; const EVP_CIPHER *type = NULL; switch (aes->mode) { case MZ_AES_MODE_CBC: if (key_length == 16) type = EVP_aes_128_cbc(); else if (key_length == 24) type = EVP_aes_192_cbc(); else if (key_length == 32) type = EVP_aes_256_cbc(); break; case MZ_AES_MODE_ECB: if (key_length == 16) type = EVP_aes_128_ecb(); else if (key_length == 24) type = EVP_aes_192_ecb(); else if (key_length == 32) type = EVP_aes_256_ecb(); break; case MZ_AES_MODE_GCM: if (key_length == 16) type = EVP_aes_128_gcm(); else if (key_length == 24) type = EVP_aes_192_gcm(); else if (key_length == 32) type = EVP_aes_256_gcm(); break; } if (!type) return MZ_PARAM_ERROR; aes->ctx = EVP_CIPHER_CTX_new(); if (!aes->ctx) return MZ_MEM_ERROR; if (!EVP_CipherInit_ex(aes->ctx, type, NULL, key, iv, encrypt)) { aes->error = ERR_get_error(); return MZ_HASH_ERROR; } EVP_CIPHER_CTX_set_padding(aes->ctx, aes->mode == MZ_AES_MODE_GCM); return MZ_OK; } int32_t mz_crypt_aes_set_encrypt_key(void *handle, const void *key, int32_t key_length, const void *iv, int32_t iv_length) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; if (!aes || !key || !key_length) return MZ_PARAM_ERROR; if (key_length != 16 && key_length != 24 && key_length != 32) return MZ_PARAM_ERROR; if (iv && iv_length != MZ_AES_BLOCK_SIZE) return MZ_PARAM_ERROR; mz_crypt_aes_reset(handle); return mz_crypt_aes_set_key(handle, key, key_length, iv, iv_length, 1); } int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length, const void *iv, int32_t iv_length) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; if (!aes || !key || !key_length) return MZ_PARAM_ERROR; if (key_length != 16 && key_length != 24 && key_length != 32) return MZ_PARAM_ERROR; if (iv && iv_length > MZ_AES_BLOCK_SIZE) return MZ_PARAM_ERROR; mz_crypt_aes_reset(handle); return mz_crypt_aes_set_key(handle, key, key_length, iv, iv_length, 0); } void mz_crypt_aes_set_mode(void *handle, int32_t mode) { mz_crypt_aes *aes = (mz_crypt_aes *)handle; aes->mode = mode; } void *mz_crypt_aes_create(void) { mz_crypt_aes *aes = (mz_crypt_aes *)calloc(1, sizeof(mz_crypt_aes)); return aes; } void mz_crypt_aes_delete(void **handle) { mz_crypt_aes *aes = NULL; if (!handle) return; aes = (mz_crypt_aes *)*handle; if (aes) { mz_crypt_aes_free(*handle); free(aes); } *handle = NULL; } /***************************************************************************/ typedef struct mz_crypt_hmac_s { #if OPENSSL_VERSION_NUMBER < 0x30000000L HMAC_CTX *ctx; #else EVP_MAC *mac; EVP_MAC_CTX *ctx; #endif int32_t initialized; int32_t error; uint16_t algorithm; } mz_crypt_hmac; /***************************************************************************/ #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \ (defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x2070000fL)) static HMAC_CTX *HMAC_CTX_new(void) { HMAC_CTX *ctx = OPENSSL_malloc(sizeof(HMAC_CTX)); if (ctx) HMAC_CTX_init(ctx); return ctx; } static void HMAC_CTX_free(HMAC_CTX *ctx) { if (ctx) { HMAC_CTX_cleanup(ctx); OPENSSL_free(ctx); } } #endif /***************************************************************************/ static void mz_crypt_hmac_free(void *handle) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; #if OPENSSL_VERSION_NUMBER < 0x30000000L HMAC_CTX_free(hmac->ctx); #else if (hmac->ctx) EVP_MAC_CTX_free(hmac->ctx); if (hmac->mac) EVP_MAC_free(hmac->mac); hmac->mac = NULL; #endif hmac->ctx = NULL; } void mz_crypt_hmac_reset(void *handle) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; mz_crypt_init(); mz_crypt_hmac_free(handle); hmac->error = 0; } int32_t mz_crypt_hmac_init(void *handle, const void *key, int32_t key_length) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; int32_t result = 0; if (!hmac || !key) return MZ_PARAM_ERROR; mz_crypt_hmac_reset(handle); #if OPENSSL_VERSION_NUMBER < 0x30000000L const EVP_MD *evp_md = NULL; if (hmac->algorithm == MZ_HASH_SHA1) evp_md = EVP_sha1(); else evp_md = EVP_sha256(); hmac->ctx = HMAC_CTX_new(); if (!hmac->ctx) return MZ_MEM_ERROR; result = HMAC_Init_ex(hmac->ctx, key, key_length, evp_md, NULL); #else char *digest_algorithm = NULL; OSSL_PARAM params[2]; if (hmac->algorithm == MZ_HASH_SHA1) digest_algorithm = "sha1"; else digest_algorithm = "sha256"; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_algorithm, 0); params[1] = OSSL_PARAM_construct_end(); hmac->mac = EVP_MAC_fetch(NULL, "HMAC", NULL); if (!hmac->mac) return MZ_MEM_ERROR; hmac->ctx = EVP_MAC_CTX_new(hmac->mac); if (!hmac->ctx) return MZ_MEM_ERROR; result = EVP_MAC_init(hmac->ctx, key, key_length, params); #endif if (!result) { hmac->error = ERR_get_error(); return MZ_HASH_ERROR; } return MZ_OK; } int32_t mz_crypt_hmac_update(void *handle, const void *buf, int32_t size) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; int32_t result = 0; if (!hmac || !buf) return MZ_PARAM_ERROR; #if OPENSSL_VERSION_NUMBER < 0x30000000L result = HMAC_Update(hmac->ctx, buf, size); #else result = EVP_MAC_update(hmac->ctx, buf, size); #endif if (!result) { hmac->error = ERR_get_error(); return MZ_HASH_ERROR; } return MZ_OK; } int32_t mz_crypt_hmac_end(void *handle, uint8_t *digest, int32_t digest_size) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; int32_t result = 0; if (!hmac || !digest) return MZ_PARAM_ERROR; #if OPENSSL_VERSION_NUMBER < 0x30000000L if (hmac->algorithm == MZ_HASH_SHA1) { if (digest_size < MZ_HASH_SHA1_SIZE) return MZ_BUF_ERROR; result = HMAC_Final(hmac->ctx, digest, (uint32_t *)&digest_size); } else { if (digest_size < MZ_HASH_SHA256_SIZE) return MZ_BUF_ERROR; result = HMAC_Final(hmac->ctx, digest, (uint32_t *)&digest_size); } #else { size_t digest_outsize = digest_size; result = EVP_MAC_final(hmac->ctx, digest, &digest_outsize, digest_size); } #endif if (!result) { hmac->error = ERR_get_error(); return MZ_HASH_ERROR; } return MZ_OK; } void mz_crypt_hmac_set_algorithm(void *handle, uint16_t algorithm) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)handle; hmac->algorithm = algorithm; } int32_t mz_crypt_hmac_copy(void *src_handle, void *target_handle) { mz_crypt_hmac *source = (mz_crypt_hmac *)src_handle; mz_crypt_hmac *target = (mz_crypt_hmac *)target_handle; if (!source || !target) return MZ_PARAM_ERROR; mz_crypt_hmac_reset(target_handle); #if OPENSSL_VERSION_NUMBER < 0x30000000L if (!target->ctx) target->ctx = HMAC_CTX_new(); if (!HMAC_CTX_copy(target->ctx, source->ctx)) { target->error = ERR_get_error(); return MZ_HASH_ERROR; } #else if (!target->ctx) target->ctx = EVP_MAC_CTX_dup(source->ctx); if (!target->ctx) return MZ_MEM_ERROR; #endif return MZ_OK; } void *mz_crypt_hmac_create(void) { mz_crypt_hmac *hmac = (mz_crypt_hmac *)calloc(1, sizeof(mz_crypt_hmac)); if (hmac) hmac->algorithm = MZ_HASH_SHA256; return hmac; } void mz_crypt_hmac_delete(void **handle) { mz_crypt_hmac *hmac = NULL; if (!handle) return; hmac = (mz_crypt_hmac *)*handle; if (hmac) { mz_crypt_hmac_free(*handle); free(hmac); } *handle = NULL; } sight-23.1.0/3rd-party/minizip/mz_os.c000066400000000000000000000214341450532053500175200ustar00rootroot00000000000000/* mz_os.c -- System functions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_crypt.h" #include "mz_os.h" #include "mz_strm.h" #include "mz_strm_os.h" #include /* tolower */ #include /***************************************************************************/ int32_t mz_path_combine(char *path, const char *join, int32_t max_path) { int32_t path_len = 0; if (!path || !join || !max_path) return MZ_PARAM_ERROR; path_len = (int32_t)strlen(path); if (path_len == 0) { strncpy(path, join, max_path - 1); path[max_path - 1] = 0; } else { mz_path_append_slash(path, max_path, MZ_PATH_SLASH_PLATFORM); path_len = (int32_t)strlen(path); if (max_path > path_len) strncat(path, join, max_path - path_len - 1); } return MZ_OK; } int32_t mz_path_append_slash(char *path, int32_t max_path, char slash) { int32_t path_len = (int32_t)strlen(path); if ((path_len + 2) >= max_path) return MZ_BUF_ERROR; if (path[path_len - 1] != '\\' && path[path_len - 1] != '/') { path[path_len] = slash; path[path_len + 1] = 0; } return MZ_OK; } int32_t mz_path_remove_slash(char *path) { int32_t path_len = (int32_t)strlen(path); while (path_len > 0) { if (path[path_len - 1] == '\\' || path[path_len - 1] == '/') path[path_len - 1] = 0; else break; path_len -= 1; } return MZ_OK; } int32_t mz_path_has_slash(const char *path) { int32_t path_len = (int32_t)strlen(path); if (path[path_len - 1] != '\\' && path[path_len - 1] != '/') return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_path_convert_slashes(char *path, char slash) { int32_t i = 0; for (i = 0; i < (int32_t)strlen(path); i += 1) { if (path[i] == '\\' || path[i] == '/') path[i] = slash; } return MZ_OK; } int32_t mz_path_compare_wc(const char *path, const char *wildcard, uint8_t ignore_case) { while (*path != 0) { switch (*wildcard) { case '*': if (*(wildcard + 1) == 0) return MZ_OK; while (*path != 0) { if (mz_path_compare_wc(path, (wildcard + 1), ignore_case) == MZ_OK) return MZ_OK; path += 1; } return MZ_EXIST_ERROR; default: /* Ignore differences in path slashes on platforms */ if ((*path == '\\' && *wildcard == '/') || (*path == '/' && *wildcard == '\\')) break; if (ignore_case) { if (tolower(*path) != tolower(*wildcard)) return MZ_EXIST_ERROR; } else { if (*path != *wildcard) return MZ_EXIST_ERROR; } break; } path += 1; wildcard += 1; } if ((*wildcard != 0) && (*wildcard != '*')) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_path_resolve(const char *path, char *output, int32_t max_output) { const char *source = path; const char *check = output; char *target = output; if (max_output <= 0) return MZ_PARAM_ERROR; while (*source != 0 && max_output > 1) { check = source; if ((*check == '\\') || (*check == '/')) check += 1; if ((source == path) || (target == output) || (check != source)) { /* Skip double paths */ if ((*check == '\\') || (*check == '/')) { source += 1; continue; } if (*check == '.') { check += 1; /* Remove . if at end of string and not at the beginning */ if ((*check == 0) && (source != path && target != output)) { /* Copy last slash */ *target = *source; target += 1; max_output -= 1; source += (check - source); continue; } /* Remove . if not at end of string */ else if ((*check == '\\') || (*check == '/')) { source += (check - source); /* Skip slash if at beginning of string */ if (target == output && *source != 0) source += 1; continue; } /* Go to parent directory .. */ else if (*check == '.') { check += 1; if ((*check == 0) || (*check == '\\' || *check == '/')) { source += (check - source); /* Search backwards for previous slash */ if (target != output) { target -= 1; do { if ((*target == '\\') || (*target == '/')) break; target -= 1; max_output += 1; } while (target > output); } if ((target == output) && (*source != 0)) source += 1; if ((*target == '\\' || *target == '/') && (*source == 0)) target += 1; *target = 0; continue; } } } } *target = *source; source += 1; target += 1; max_output -= 1; } *target = 0; if (*path == 0) return MZ_INTERNAL_ERROR; return MZ_OK; } int32_t mz_path_remove_filename(char *path) { char *path_ptr = NULL; if (!path) return MZ_PARAM_ERROR; path_ptr = path + strlen(path) - 1; while (path_ptr > path) { if ((*path_ptr == '/') || (*path_ptr == '\\')) { *path_ptr = 0; break; } path_ptr -= 1; } if (path_ptr == path) *path_ptr = 0; return MZ_OK; } int32_t mz_path_remove_extension(char *path) { char *path_ptr = NULL; if (!path) return MZ_PARAM_ERROR; path_ptr = path + strlen(path) - 1; while (path_ptr > path) { if ((*path_ptr == '/') || (*path_ptr == '\\')) break; if (*path_ptr == '.') { *path_ptr = 0; break; } path_ptr -= 1; } if (path_ptr == path) *path_ptr = 0; return MZ_OK; } int32_t mz_path_get_filename(const char *path, const char **filename) { const char *match = NULL; if (!path || !filename) return MZ_PARAM_ERROR; *filename = NULL; for (match = path; *match != 0; match += 1) { if ((*match == '\\') || (*match == '/')) *filename = match + 1; } if (!*filename) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_dir_make(const char *path) { int32_t err = MZ_OK; char *current_dir = NULL; char *match = NULL; char hold = 0; current_dir = strdup(path); if (!current_dir) return MZ_MEM_ERROR; mz_path_remove_slash(current_dir); err = mz_os_make_dir(current_dir); if (err != MZ_OK) { match = current_dir + 1; while (1) { while (*match != 0 && *match != '\\' && *match != '/') match += 1; hold = *match; *match = 0; err = mz_os_make_dir(current_dir); if (err != MZ_OK) break; if (hold == 0) break; *match = hold; match += 1; } } free(current_dir); return err; } int32_t mz_file_get_crc(const char *path, uint32_t *result_crc) { void *stream = NULL; uint32_t crc32 = 0; int32_t read = 0; int32_t err = MZ_OK; uint8_t buf[16384]; stream = mz_stream_os_create(); if (!stream) return MZ_MEM_ERROR; err = mz_stream_os_open(stream, path, MZ_OPEN_MODE_READ); if (err == MZ_OK) { do { read = mz_stream_os_read(stream, buf, sizeof(buf)); if (read < 0) { err = read; break; } crc32 = mz_crypt_crc32_update(crc32, buf, read); } while ((err == MZ_OK) && (read > 0)); mz_stream_os_close(stream); } *result_crc = crc32; mz_stream_os_delete(&stream); return err; } /***************************************************************************/ sight-23.1.0/3rd-party/minizip/mz_os.h000066400000000000000000000126561450532053500175330ustar00rootroot00000000000000/* mz_os.h -- System functions part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_OS_H #define MZ_OS_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ #if defined(__APPLE__) # define MZ_VERSION_MADEBY_HOST_SYSTEM (MZ_HOST_SYSTEM_OSX_DARWIN) #elif defined(__riscos__) # define MZ_VERSION_MADEBY_HOST_SYSTEM (MZ_HOST_SYSTEM_RISCOS) #elif defined(_WIN32) # define MZ_VERSION_MADEBY_HOST_SYSTEM (MZ_HOST_SYSTEM_WINDOWS_NTFS) #else # define MZ_VERSION_MADEBY_HOST_SYSTEM (MZ_HOST_SYSTEM_UNIX) #endif #if defined(HAVE_LZMA) || defined(HAVE_LIBCOMP) # define MZ_VERSION_MADEBY_ZIP_VERSION (63) #elif defined(HAVE_WZAES) # define MZ_VERSION_MADEBY_ZIP_VERSION (51) #elif defined(HAVE_BZIP2) # define MZ_VERSION_MADEBY_ZIP_VERSION (46) #else # define MZ_VERSION_MADEBY_ZIP_VERSION (45) #endif #define MZ_VERSION_MADEBY ((MZ_VERSION_MADEBY_HOST_SYSTEM << 8) | \ (MZ_VERSION_MADEBY_ZIP_VERSION)) #define MZ_PATH_SLASH_UNIX ('/') #define MZ_PATH_SLASH_WINDOWS ('\\') #if defined(_WIN32) # define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_WINDOWS) #else # define MZ_PATH_SLASH_PLATFORM (MZ_PATH_SLASH_UNIX) #endif /***************************************************************************/ #if defined(_WIN32) struct dirent { char d_name[256]; }; typedef void* DIR; #else #include #endif /***************************************************************************/ /* Shared functions */ int32_t mz_path_combine(char *path, const char *join, int32_t max_path); /* Combines two paths */ int32_t mz_path_append_slash(char *path, int32_t max_path, char slash); /* Appends a path slash on to the end of the path */ int32_t mz_path_remove_slash(char *path); /* Removes a path slash from the end of the path */ int32_t mz_path_has_slash(const char *path); /* Returns whether or not the path ends with slash */ int32_t mz_path_convert_slashes(char *path, char slash); /* Converts the slashes in a path */ int32_t mz_path_compare_wc(const char *path, const char *wildcard, uint8_t ignore_case); /* Compare two paths with wildcard */ int32_t mz_path_resolve(const char *path, char *target, int32_t max_target); /* Resolves path */ int32_t mz_path_remove_filename(char *path); /* Remove the filename from a path */ int32_t mz_path_remove_extension(char *path); /* Remove the extension from a path */ int32_t mz_path_get_filename(const char *path, const char **filename); /* Get the filename from a path */ int32_t mz_dir_make(const char *path); /* Creates a directory recursively */ int32_t mz_file_get_crc(const char *path, uint32_t *result_crc); /* Gets the crc32 hash of a file */ /***************************************************************************/ /* Platform specific functions */ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding); /* Create unicode string from a utf8 string */ void mz_os_unicode_string_delete(wchar_t **string); /* Delete a unicode string that was created */ char *mz_os_utf8_string_create(const char *string, int32_t encoding); /* Create a utf8 string from a string with another encoding */ void mz_os_utf8_string_delete(char **string); /* Delete a utf8 string that was created */ int32_t mz_os_rand(uint8_t *buf, int32_t size); /* Random number generator (not cryptographically secure) */ int32_t mz_os_rename(const char *source_path, const char *target_path); /* Rename a file */ int32_t mz_os_unlink(const char *path); /* Delete an existing file */ int32_t mz_os_file_exists(const char *path); /* Check to see if a file exists */ int64_t mz_os_get_file_size(const char *path); /* Gets the length of a file */ int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *accessed_date, time_t *creation_date); /* Gets a file's modified, access, and creation dates if supported */ int32_t mz_os_set_file_date(const char *path, time_t modified_date, time_t accessed_date, time_t creation_date); /* Sets a file's modified, access, and creation dates if supported */ int32_t mz_os_get_file_attribs(const char *path, uint32_t *attributes); /* Gets a file's attributes */ int32_t mz_os_set_file_attribs(const char *path, uint32_t attributes); /* Sets a file's attributes */ int32_t mz_os_make_dir(const char *path); /* Recursively creates a directory */ DIR* mz_os_open_dir(const char *path); /* Opens a directory for listing */ struct dirent* mz_os_read_dir(DIR *dir); /* Reads a directory listing entry */ int32_t mz_os_close_dir(DIR *dir); /* Closes a directory that has been opened for listing */ int32_t mz_os_is_dir(const char *path); /* Checks to see if path is a directory */ int32_t mz_os_is_symlink(const char *path); /* Checks to see if path is a symbolic link */ int32_t mz_os_make_symlink(const char *path, const char *target_path); /* Creates a symbolic link pointing to a target */ int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_target_path); /* Gets the target path for a symbolic link */ uint64_t mz_os_ms_time(void); /* Gets the time in milliseconds */ /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_os_posix.c000066400000000000000000000207111450532053500207370ustar00rootroot00000000000000/* mz_os_posix.c -- System functions for posix part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef WIN32 #include "mz.h" #include "mz_strm.h" #include "mz_os.h" #include /* rename */ #include #if defined(HAVE_ICONV) #include #endif #include #include #include #ifndef _WIN32 # include # include #endif #if defined(__APPLE__) # include # include #endif #if defined(HAVE_GETRANDOM) # include #endif #if defined(HAVE_LIBBSD) # include /* arc4random_buf */ #endif /***************************************************************************/ #if defined(HAVE_ICONV) char *mz_os_utf8_string_create(const char *string, int32_t encoding) { iconv_t cd; const char *from_encoding = NULL; size_t result = 0; size_t string_length = 0; size_t string_utf8_size = 0; char *string_utf8 = NULL; char *string_utf8_ptr = NULL; if (!string) return NULL; if (encoding == MZ_ENCODING_CODEPAGE_437) from_encoding = "CP437"; else if (encoding == MZ_ENCODING_CODEPAGE_932) from_encoding = "CP932"; else if (encoding == MZ_ENCODING_CODEPAGE_936) from_encoding = "CP936"; else if (encoding == MZ_ENCODING_CODEPAGE_950) from_encoding = "CP950"; else if (encoding == MZ_ENCODING_UTF8) from_encoding = "UTF-8"; else return NULL; cd = iconv_open("UTF-8", from_encoding); if (cd == (iconv_t)-1) return NULL; string_length = strlen(string); string_utf8_size = string_length * 2; string_utf8 = (char *)calloc((int32_t)(string_utf8_size + 1), sizeof(char)); string_utf8_ptr = string_utf8; if (string_utf8) { result = iconv(cd, (char **)&string, &string_length, (char **)&string_utf8_ptr, &string_utf8_size); } iconv_close(cd); if (result == (size_t)-1) { free(string_utf8); string_utf8 = NULL; } return string_utf8; } #else char *mz_os_utf8_string_create(const char *string, int32_t encoding) { return strdup(string); } #endif void mz_os_utf8_string_delete(char **string) { if (string) { free(*string); *string = NULL; } } /***************************************************************************/ #if defined(HAVE_GETRANDOM) int32_t mz_os_rand(uint8_t *buf, int32_t size) { int32_t left = size; int32_t written = 0; while (left > 0) { written = getrandom(buf, left, 0); if (written < 0) return MZ_INTERNAL_ERROR; buf += written; left -= written; } return size - left; } #elif defined(HAVE_ARC4RANDOM_BUF) int32_t mz_os_rand(uint8_t *buf, int32_t size) { if (size < 0) return 0; arc4random_buf(buf, (uint32_t)size); return size; } #elif defined(HAVE_ARC4RANDOM) int32_t mz_os_rand(uint8_t *buf, int32_t size) { int32_t left = size; for (; left > 2; left -= 3, buf += 3) { uint32_t val = arc4random(); buf[0] = (val) & 0xFF; buf[1] = (val >> 8) & 0xFF; buf[2] = (val >> 16) & 0xFF; } for (; left > 0; left--, buf++) { *buf = arc4random() & 0xFF; } return size - left; } #else int32_t mz_os_rand(uint8_t *buf, int32_t size) { static unsigned calls = 0; int32_t i = 0; /* Ensure different random header each time */ if (++calls == 1) { #define PI_SEED 3141592654UL srand((unsigned)(time(NULL) ^ PI_SEED)); } while (i < size) buf[i++] = (rand() >> 7) & 0xff; return size; } #endif int32_t mz_os_rename(const char *source_path, const char *target_path) { if (rename(source_path, target_path) == -1) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_os_unlink(const char *path) { if (unlink(path) == -1) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_os_file_exists(const char *path) { struct stat path_stat; memset(&path_stat, 0, sizeof(path_stat)); if (stat(path, &path_stat) == 0) return MZ_OK; return MZ_EXIST_ERROR; } int64_t mz_os_get_file_size(const char *path) { struct stat path_stat; memset(&path_stat, 0, sizeof(path_stat)); if (stat(path, &path_stat) == 0) { /* Stat returns size taken up by directory entry, so return 0 */ if (S_ISDIR(path_stat.st_mode)) return 0; return path_stat.st_size; } return 0; } int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *accessed_date, time_t *creation_date) { struct stat path_stat; char *name = NULL; int32_t err = MZ_INTERNAL_ERROR; memset(&path_stat, 0, sizeof(path_stat)); if (strcmp(path, "-") != 0) { /* Not all systems allow stat'ing a file with / appended */ name = strdup(path); mz_path_remove_slash(name); if (stat(name, &path_stat) == 0) { if (modified_date) *modified_date = path_stat.st_mtime; if (accessed_date) *accessed_date = path_stat.st_atime; /* Creation date not supported */ if (creation_date) *creation_date = 0; err = MZ_OK; } free(name); } return err; } int32_t mz_os_set_file_date(const char *path, time_t modified_date, time_t accessed_date, time_t creation_date) { struct utimbuf ut; ut.actime = accessed_date; ut.modtime = modified_date; /* Creation date not supported */ MZ_UNUSED(creation_date); if (utime(path, &ut) != 0) return MZ_INTERNAL_ERROR; return MZ_OK; } int32_t mz_os_get_file_attribs(const char *path, uint32_t *attributes) { struct stat path_stat; int32_t err = MZ_OK; memset(&path_stat, 0, sizeof(path_stat)); if (lstat(path, &path_stat) == -1) err = MZ_INTERNAL_ERROR; *attributes = path_stat.st_mode; return err; } int32_t mz_os_set_file_attribs(const char *path, uint32_t attributes) { int32_t err = MZ_OK; if (chmod(path, (mode_t)attributes) == -1) err = MZ_INTERNAL_ERROR; return err; } int32_t mz_os_make_dir(const char *path) { int32_t err = 0; err = mkdir(path, 0755); if (err != 0 && errno != EEXIST) return MZ_INTERNAL_ERROR; return MZ_OK; } DIR* mz_os_open_dir(const char *path) { return opendir(path); } struct dirent* mz_os_read_dir(DIR *dir) { if (!dir) return NULL; return readdir(dir); } int32_t mz_os_close_dir(DIR *dir) { if (!dir) return MZ_PARAM_ERROR; if (closedir(dir) == -1) return MZ_INTERNAL_ERROR; return MZ_OK; } int32_t mz_os_is_dir(const char *path) { struct stat path_stat; memset(&path_stat, 0, sizeof(path_stat)); stat(path, &path_stat); if (S_ISDIR(path_stat.st_mode)) return MZ_OK; return MZ_EXIST_ERROR; } int32_t mz_os_is_symlink(const char *path) { struct stat path_stat; memset(&path_stat, 0, sizeof(path_stat)); lstat(path, &path_stat); if (S_ISLNK(path_stat.st_mode)) return MZ_OK; return MZ_EXIST_ERROR; } int32_t mz_os_make_symlink(const char *path, const char *target_path) { if (symlink(target_path, path) != 0) return MZ_INTERNAL_ERROR; return MZ_OK; } int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_target_path) { size_t length = 0; length = (size_t)readlink(path, target_path, max_target_path - 1); if (length == (size_t)-1) return MZ_EXIST_ERROR; target_path[length] = 0; return MZ_OK; } uint64_t mz_os_ms_time(void) { struct timespec ts; #if defined(__APPLE__) clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts.tv_sec = mts.tv_sec; ts.tv_nsec = mts.tv_nsec; #elif !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0 clock_gettime(CLOCK_REALTIME, &ts); #elif _POSIX_MONOTONIC_CLOCK > 0 clock_gettime(CLOCK_MONOTONIC, &ts); #else if (sysconf(_SC_MONOTONIC_CLOCK) > 0) clock_gettime(CLOCK_MONOTONIC, &ts); else clock_gettime(CLOCK_REALTIME, &ts); #endif return ((uint64_t)ts.tv_sec * 1000) + ((uint64_t)ts.tv_nsec / 1000000); } #endifsight-23.1.0/3rd-party/minizip/mz_os_win32.c000066400000000000000000000461401450532053500205430ustar00rootroot00000000000000/* mz_os_win32.c -- System functions for Windows part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifdef WIN32 #include "mz.h" #include "mz_os.h" #include "mz_strm_os.h" #include #include /***************************************************************************/ #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY # define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1 #endif #ifndef _WIN32_WINNT_WIN8 # define _WIN32_WINNT_WIN8 0x0602 #endif /***************************************************************************/ typedef struct DIR_int_s { void *find_handle; WIN32_FIND_DATAW find_data; struct dirent entry; uint8_t end; } DIR_int; /***************************************************************************/ wchar_t *mz_os_unicode_string_create(const char *string, int32_t encoding) { wchar_t *string_wide = NULL; uint32_t string_wide_size = 0; string_wide_size = MultiByteToWideChar(encoding, 0, string, -1, NULL, 0); if (string_wide_size == 0) return NULL; string_wide = (wchar_t *)calloc(string_wide_size + 1, sizeof(wchar_t)); if (!string_wide) return NULL; MultiByteToWideChar(encoding, 0, string, -1, string_wide, string_wide_size); return string_wide; } void mz_os_unicode_string_delete(wchar_t **string) { if (string) { free(*string); *string = NULL; } } char *mz_os_utf8_string_create(const char *string, int32_t encoding) { wchar_t *string_wide = NULL; char *string_utf8 = NULL; uint32_t string_utf8_size = 0; string_wide = mz_os_unicode_string_create(string, encoding); if (string_wide) { string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, NULL, 0, NULL, NULL); string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); if (string_utf8) WideCharToMultiByte(CP_UTF8, 0, string_wide, -1, string_utf8, string_utf8_size, NULL, NULL); mz_os_unicode_string_delete(&string_wide); } return string_utf8; } char *mz_os_utf8_string_create_from_unicode(const wchar_t *string, int32_t encoding) { char *string_utf8 = NULL; uint32_t string_utf8_size = 0; MZ_UNUSED(encoding); string_utf8_size = WideCharToMultiByte(CP_UTF8, 0, string, -1, NULL, 0, NULL, NULL); string_utf8 = (char *)calloc(string_utf8_size + 1, sizeof(char)); if (string_utf8) WideCharToMultiByte(CP_UTF8, 0, string, -1, string_utf8, string_utf8_size, NULL, NULL); return string_utf8; } void mz_os_utf8_string_delete(char **string) { if (string) { free(*string); *string = NULL; } } /***************************************************************************/ int32_t mz_os_rand(uint8_t *buf, int32_t size) { unsigned __int64 pentium_tsc[1]; int32_t len = 0; for (len = 0; len < (int)size; len += 1) { if (len % 8 == 0) QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc); buf[len] = ((unsigned char *)pentium_tsc)[len % 8]; } return len; } int32_t mz_os_rename(const char *source_path, const char *target_path) { wchar_t *source_path_wide = NULL; wchar_t *target_path_wide = NULL; int32_t result = 0; int32_t err = MZ_OK; if (!source_path || !target_path) return MZ_PARAM_ERROR; source_path_wide = mz_os_unicode_string_create(source_path, MZ_ENCODING_UTF8); if (!source_path_wide) { err = MZ_PARAM_ERROR; } else { target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); if (!target_path_wide) err = MZ_PARAM_ERROR; } if (err == MZ_OK) { #if _WIN32_WINNT >= _WIN32_WINNT_WINXP result = MoveFileExW(source_path_wide, target_path_wide, MOVEFILE_WRITE_THROUGH); #else result = MoveFileW(source_path_wide, target_path_wide); #endif if (result == 0) err = MZ_EXIST_ERROR; } if (target_path_wide) mz_os_unicode_string_delete(&target_path_wide); if (source_path_wide) mz_os_unicode_string_delete(&source_path_wide); return err; } int32_t mz_os_unlink(const char *path) { wchar_t *path_wide = NULL; int32_t result = 0; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; if (mz_os_is_dir(path) == MZ_OK) result = RemoveDirectoryW(path_wide); else result = DeleteFileW(path_wide); mz_os_unicode_string_delete(&path_wide); if (result == 0) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_os_file_exists(const char *path) { wchar_t *path_wide = NULL; DWORD attribs = 0; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; attribs = GetFileAttributesW(path_wide); mz_os_unicode_string_delete(&path_wide); if (attribs == 0xFFFFFFFF) return MZ_EXIST_ERROR; return MZ_OK; } int64_t mz_os_get_file_size(const char *path) { HANDLE handle = NULL; LARGE_INTEGER large_size; wchar_t *path_wide = NULL; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 handle = CreateFile2(path_wide, GENERIC_READ, 0, OPEN_EXISTING, NULL); #else handle = CreateFileW(path_wide, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); #endif mz_os_unicode_string_delete(&path_wide); large_size.QuadPart = 0; if (handle != INVALID_HANDLE_VALUE) { GetFileSizeEx(handle, &large_size); CloseHandle(handle); } return large_size.QuadPart; } static void mz_os_file_to_unix_time(FILETIME file_time, time_t *unix_time) { uint64_t quad_file_time = 0; quad_file_time = file_time.dwLowDateTime; quad_file_time |= ((uint64_t)file_time.dwHighDateTime << 32); *unix_time = (time_t)((quad_file_time - 116444736000000000LL) / 10000000); } static void mz_os_unix_to_file_time(time_t unix_time, FILETIME *file_time) { uint64_t quad_file_time = 0; quad_file_time = ((uint64_t)unix_time * 10000000) + 116444736000000000LL; file_time->dwHighDateTime = (quad_file_time >> 32); file_time->dwLowDateTime = (uint32_t)(quad_file_time); } int32_t mz_os_get_file_date(const char *path, time_t *modified_date, time_t *accessed_date, time_t *creation_date) { WIN32_FIND_DATAW ff32; HANDLE handle = NULL; wchar_t *path_wide = NULL; int32_t err = MZ_INTERNAL_ERROR; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; handle = FindFirstFileW(path_wide, &ff32); free(path_wide); if (handle != INVALID_HANDLE_VALUE) { if (modified_date) mz_os_file_to_unix_time(ff32.ftLastWriteTime, modified_date); if (accessed_date) mz_os_file_to_unix_time(ff32.ftLastAccessTime, accessed_date); if (creation_date) mz_os_file_to_unix_time(ff32.ftCreationTime, creation_date); FindClose(handle); err = MZ_OK; } return err; } int32_t mz_os_set_file_date(const char *path, time_t modified_date, time_t accessed_date, time_t creation_date) { HANDLE handle = NULL; FILETIME ftm_creation, ftm_accessed, ftm_modified; wchar_t *path_wide = NULL; int32_t err = MZ_OK; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 handle = CreateFile2(path_wide, GENERIC_READ | GENERIC_WRITE, 0, OPEN_EXISTING, NULL); #else handle = CreateFileW(path_wide, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); #endif mz_os_unicode_string_delete(&path_wide); if (handle != INVALID_HANDLE_VALUE) { GetFileTime(handle, &ftm_creation, &ftm_accessed, &ftm_modified); if (modified_date != 0) mz_os_unix_to_file_time(modified_date, &ftm_modified); if (accessed_date != 0) mz_os_unix_to_file_time(accessed_date, &ftm_accessed); if (creation_date != 0) mz_os_unix_to_file_time(creation_date, &ftm_creation); if (SetFileTime(handle, &ftm_creation, &ftm_accessed, &ftm_modified) == 0) err = MZ_INTERNAL_ERROR; CloseHandle(handle); } return err; } int32_t mz_os_get_file_attribs(const char *path, uint32_t *attributes) { wchar_t *path_wide = NULL; int32_t err = MZ_OK; if (!path || !attributes) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; *attributes = GetFileAttributesW(path_wide); mz_os_unicode_string_delete(&path_wide); if (*attributes == INVALID_FILE_ATTRIBUTES) err = MZ_INTERNAL_ERROR; return err; } int32_t mz_os_set_file_attribs(const char *path, uint32_t attributes) { wchar_t *path_wide = NULL; int32_t err = MZ_OK; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; if (SetFileAttributesW(path_wide, attributes) == 0) err = MZ_INTERNAL_ERROR; mz_os_unicode_string_delete(&path_wide); return err; } int32_t mz_os_make_dir(const char *path) { wchar_t *path_wide = NULL; int32_t err = MZ_OK; if (!path) return MZ_PARAM_ERROR; /* Don't try to create a drive letter */ if ((path[0] != 0) && (strlen(path) <= 3) && (path[1] == ':')) return mz_os_is_dir(path); path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; if (CreateDirectoryW(path_wide, NULL) == 0) { if (GetLastError() != ERROR_ALREADY_EXISTS) err = MZ_INTERNAL_ERROR; } mz_os_unicode_string_delete(&path_wide); return err; } DIR *mz_os_open_dir(const char *path) { WIN32_FIND_DATAW find_data; DIR_int *dir_int = NULL; wchar_t *path_wide = NULL; char fixed_path[320]; void *handle = NULL; if (!path) return NULL; strncpy(fixed_path, path, sizeof(fixed_path) - 1); fixed_path[sizeof(fixed_path) - 1] = 0; mz_path_append_slash(fixed_path, sizeof(fixed_path), MZ_PATH_SLASH_PLATFORM); mz_path_combine(fixed_path, "*", sizeof(fixed_path)); path_wide = mz_os_unicode_string_create(fixed_path, MZ_ENCODING_UTF8); if (!path_wide) return NULL; handle = FindFirstFileW(path_wide, &find_data); mz_os_unicode_string_delete(&path_wide); if (handle == INVALID_HANDLE_VALUE) return NULL; dir_int = (DIR_int *)malloc(sizeof(DIR_int)); if (!dir_int) { FindClose(handle); return NULL; } dir_int->find_handle = handle; dir_int->end = 0; memcpy(&dir_int->find_data, &find_data, sizeof(dir_int->find_data)); return (DIR *)dir_int; } struct dirent* mz_os_read_dir(DIR *dir) { DIR_int *dir_int; if (!dir) return NULL; dir_int = (DIR_int *)dir; if (dir_int->end) return NULL; WideCharToMultiByte(CP_UTF8, 0, dir_int->find_data.cFileName, -1, dir_int->entry.d_name, sizeof(dir_int->entry.d_name), NULL, NULL); if (FindNextFileW(dir_int->find_handle, &dir_int->find_data) == 0) { if (GetLastError() != ERROR_NO_MORE_FILES) return NULL; dir_int->end = 1; } return &dir_int->entry; } int32_t mz_os_close_dir(DIR *dir) { DIR_int *dir_int; if (!dir) return MZ_PARAM_ERROR; dir_int = (DIR_int *)dir; if (dir_int->find_handle != INVALID_HANDLE_VALUE) FindClose(dir_int->find_handle); free(dir_int); return MZ_OK; } int32_t mz_os_is_dir(const char *path) { wchar_t *path_wide = NULL; uint32_t attribs = 0; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; attribs = GetFileAttributesW(path_wide); mz_os_unicode_string_delete(&path_wide); if (attribs != 0xFFFFFFFF) { if (attribs & FILE_ATTRIBUTE_DIRECTORY) return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_os_is_symlink(const char *path) { wchar_t *path_wide = NULL; uint32_t attribs = 0; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; attribs = GetFileAttributesW(path_wide); mz_os_unicode_string_delete(&path_wide); if (attribs != 0xFFFFFFFF) { if (attribs & FILE_ATTRIBUTE_REPARSE_POINT) return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_os_make_symlink(const char *path, const char *target_path) { typedef BOOLEAN (WINAPI *LPCREATESYMBOLICLINKW)(LPCWSTR, LPCWSTR, DWORD); MEMORY_BASIC_INFORMATION mbi; LPCREATESYMBOLICLINKW create_symbolic_link_w = NULL; HMODULE kernel32_mod = NULL; wchar_t *path_wide = NULL; wchar_t *target_path_wide = NULL; int32_t err = MZ_OK; int32_t flags = 0; if (!path) return MZ_PARAM_ERROR; // Use VirtualQuery instead of GetModuleHandleW for UWP memset(&mbi, 0, sizeof(mbi)); VirtualQuery(VirtualQuery, &mbi, sizeof(mbi)); kernel32_mod = (HMODULE)mbi.AllocationBase; if (!kernel32_mod) return MZ_SUPPORT_ERROR; create_symbolic_link_w = (LPCREATESYMBOLICLINKW)GetProcAddress(kernel32_mod, "CreateSymbolicLinkW"); if (!create_symbolic_link_w) { return MZ_SUPPORT_ERROR; } path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) { return MZ_PARAM_ERROR; } target_path_wide = mz_os_unicode_string_create(target_path, MZ_ENCODING_UTF8); if (target_path_wide) { if (mz_path_has_slash(target_path) == MZ_OK) flags |= SYMBOLIC_LINK_FLAG_DIRECTORY; if (create_symbolic_link_w(path_wide, target_path_wide, flags) == FALSE) err = MZ_SYMLINK_ERROR; mz_os_unicode_string_delete(&target_path_wide); } else { err = MZ_PARAM_ERROR; } mz_os_unicode_string_delete(&path_wide); return err; } int32_t mz_os_read_symlink(const char *path, char *target_path, int32_t max_target_path) { typedef struct _REPARSE_DATA_BUFFER { ULONG ReparseTag; USHORT ReparseDataLength; USHORT Reserved; union { struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; ULONG Flags; WCHAR PathBuffer[1]; } SymbolicLinkReparseBuffer; struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; WCHAR PathBuffer[1]; } MountPointReparseBuffer; struct { UCHAR DataBuffer[1]; } GenericReparseBuffer; }; } REPARSE_DATA_BUFFER; REPARSE_DATA_BUFFER *reparse_data = NULL; DWORD length = 0; HANDLE handle = NULL; wchar_t *path_wide = NULL; wchar_t *target_path_wide = NULL; uint8_t buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; int32_t target_path_len = 0; int32_t target_path_idx = 0; int32_t err = MZ_OK; char *target_path_utf8 = NULL; if (!path) return MZ_PARAM_ERROR; path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 CREATEFILE2_EXTENDED_PARAMETERS extended_params; memset(&extended_params, 0, sizeof(extended_params)); extended_params.dwSize = sizeof(extended_params); extended_params.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; extended_params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT; extended_params.dwSecurityQosFlags = SECURITY_ANONYMOUS; extended_params.lpSecurityAttributes = NULL; extended_params.hTemplateFile = NULL; handle = CreateFile2(path_wide, FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, &extended_params); #else handle = CreateFileW(path_wide, FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL); #endif if (handle == INVALID_HANDLE_VALUE) { mz_os_unicode_string_delete(&path_wide); return MZ_OPEN_ERROR; } if (DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buffer, sizeof(buffer), &length, NULL) == TRUE) { reparse_data = (REPARSE_DATA_BUFFER *)buffer; if ((IsReparseTagMicrosoft(reparse_data->ReparseTag)) && (reparse_data->ReparseTag == IO_REPARSE_TAG_SYMLINK)) { target_path_len = max_target_path * sizeof(wchar_t); if (target_path_len > reparse_data->SymbolicLinkReparseBuffer.PrintNameLength) target_path_len = reparse_data->SymbolicLinkReparseBuffer.PrintNameLength; target_path_wide = (wchar_t *)malloc(target_path_len + sizeof(wchar_t)); if (target_path_wide) { target_path_idx = reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(wchar_t); memcpy(target_path_wide, &reparse_data->SymbolicLinkReparseBuffer.PathBuffer[target_path_idx], target_path_len); target_path_wide[target_path_len / sizeof(wchar_t)] = 0; target_path_utf8 = mz_os_utf8_string_create_from_unicode(target_path_wide, MZ_ENCODING_UTF8); if (target_path_utf8) { strncpy(target_path, target_path_utf8, max_target_path - 1); target_path[max_target_path - 1] = 0; /* Ensure directories have slash at the end so we can recreate them later */ if (mz_os_is_dir(target_path_utf8) == MZ_OK) mz_path_append_slash(target_path, max_target_path, MZ_PATH_SLASH_PLATFORM); mz_os_utf8_string_delete(&target_path_utf8); } else { err = MZ_MEM_ERROR; } free(target_path_wide); } else { err = MZ_MEM_ERROR; } } } else { err = MZ_INTERNAL_ERROR; } CloseHandle(handle); mz_os_unicode_string_delete(&path_wide); return err; } uint64_t mz_os_ms_time(void) { SYSTEMTIME system_time; FILETIME file_time; uint64_t quad_file_time = 0; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); quad_file_time = file_time.dwLowDateTime; quad_file_time |= ((uint64_t)file_time.dwHighDateTime << 32); return quad_file_time / 10000 - 11644473600000LL; } #endifsight-23.1.0/3rd-party/minizip/mz_strm.c000066400000000000000000000367071450532053500200750ustar00rootroot00000000000000/* mz_strm.c -- Stream interface part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_strm.h" /***************************************************************************/ #define MZ_STREAM_FIND_SIZE (1024) /***************************************************************************/ int32_t mz_stream_open(void *stream, const char *path, int32_t mode) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->open) return MZ_STREAM_ERROR; return strm->vtbl->open(strm, path, mode); } int32_t mz_stream_is_open(void *stream) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->is_open) return MZ_STREAM_ERROR; return strm->vtbl->is_open(strm); } int32_t mz_stream_read(void *stream, void *buf, int32_t size) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->read) return MZ_PARAM_ERROR; if (mz_stream_is_open(stream) != MZ_OK) return MZ_STREAM_ERROR; return strm->vtbl->read(strm, buf, size); } static int32_t mz_stream_read_value(void *stream, uint64_t *value, int32_t len) { uint8_t buf[8]; int32_t n = 0; int32_t i = 0; *value = 0; if (mz_stream_read(stream, buf, len) == len) { for (n = 0; n < len; n += 1, i += 8) *value += ((uint64_t)buf[n]) << i; } else if (mz_stream_error(stream)) return MZ_STREAM_ERROR; else return MZ_END_OF_STREAM; return MZ_OK; } int32_t mz_stream_read_uint8(void *stream, uint8_t *value) { int32_t err = MZ_OK; uint64_t value64 = 0; *value = 0; err = mz_stream_read_value(stream, &value64, sizeof(uint8_t)); if (err == MZ_OK) *value = (uint8_t)value64; return err; } int32_t mz_stream_read_uint16(void *stream, uint16_t *value) { int32_t err = MZ_OK; uint64_t value64 = 0; *value = 0; err = mz_stream_read_value(stream, &value64, sizeof(uint16_t)); if (err == MZ_OK) *value = (uint16_t)value64; return err; } int32_t mz_stream_read_uint32(void *stream, uint32_t *value) { int32_t err = MZ_OK; uint64_t value64 = 0; *value = 0; err = mz_stream_read_value(stream, &value64, sizeof(uint32_t)); if (err == MZ_OK) *value = (uint32_t)value64; return err; } int32_t mz_stream_read_int64(void *stream, int64_t *value) { return mz_stream_read_value(stream, (uint64_t *)value, sizeof(uint64_t)); } int32_t mz_stream_read_uint64(void *stream, uint64_t *value) { return mz_stream_read_value(stream, value, sizeof(uint64_t)); } int32_t mz_stream_write(void *stream, const void *buf, int32_t size) { mz_stream *strm = (mz_stream *)stream; if (size == 0) return size; if (!strm || !strm->vtbl || !strm->vtbl->write) return MZ_PARAM_ERROR; if (mz_stream_is_open(stream) != MZ_OK) return MZ_STREAM_ERROR; return strm->vtbl->write(strm, buf, size); } static int32_t mz_stream_write_value(void *stream, uint64_t value, int32_t len) { uint8_t buf[8]; int32_t n = 0; for (n = 0; n < len; n += 1) { buf[n] = (uint8_t)(value & 0xff); value >>= 8; } if (value != 0) { /* Data overflow - hack for ZIP64 (X Roche) */ for (n = 0; n < len; n += 1) buf[n] = 0xff; } if (mz_stream_write(stream, buf, len) != len) return MZ_STREAM_ERROR; return MZ_OK; } int32_t mz_stream_write_uint8(void *stream, uint8_t value) { return mz_stream_write_value(stream, value, sizeof(uint8_t)); } int32_t mz_stream_write_uint16(void *stream, uint16_t value) { return mz_stream_write_value(stream, value, sizeof(uint16_t)); } int32_t mz_stream_write_uint32(void *stream, uint32_t value) { return mz_stream_write_value(stream, value, sizeof(uint32_t)); } int32_t mz_stream_write_int64(void *stream, int64_t value) { return mz_stream_write_value(stream, (uint64_t)value, sizeof(uint64_t)); } int32_t mz_stream_write_uint64(void *stream, uint64_t value) { return mz_stream_write_value(stream, value, sizeof(uint64_t)); } int32_t mz_stream_copy(void *target, void *source, int32_t len) { return mz_stream_copy_stream(target, NULL, source, NULL, len); } int32_t mz_stream_copy_to_end(void *target, void *source) { return mz_stream_copy_stream_to_end(target, NULL, source, NULL); } int32_t mz_stream_copy_stream(void *target, mz_stream_write_cb write_cb, void *source, mz_stream_read_cb read_cb, int32_t len) { uint8_t buf[16384]; int32_t bytes_to_copy = 0; int32_t read = 0; int32_t written = 0; if (!write_cb) write_cb = mz_stream_write; if (!read_cb) read_cb = mz_stream_read; while (len > 0) { bytes_to_copy = len; if (bytes_to_copy > (int32_t)sizeof(buf)) bytes_to_copy = sizeof(buf); read = read_cb(source, buf, bytes_to_copy); if (read <= 0) return MZ_STREAM_ERROR; written = write_cb(target, buf, read); if (written != read) return MZ_STREAM_ERROR; len -= read; } return MZ_OK; } int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, void *source, mz_stream_read_cb read_cb) { uint8_t buf[16384]; int32_t read = 0; int32_t written = 0; if (!write_cb) write_cb = mz_stream_write; if (!read_cb) read_cb = mz_stream_read; read = read_cb(source, buf, sizeof(buf)); while (read > 0) { written = write_cb(target, buf, read); if (written != read) return MZ_STREAM_ERROR; read = read_cb(source, buf, sizeof(buf)); } if (read < 0) return MZ_STREAM_ERROR; return MZ_OK; } int64_t mz_stream_tell(void *stream) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->tell) return MZ_PARAM_ERROR; if (mz_stream_is_open(stream) != MZ_OK) return MZ_STREAM_ERROR; return strm->vtbl->tell(strm); } int32_t mz_stream_seek(void *stream, int64_t offset, int32_t origin) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->seek) return MZ_PARAM_ERROR; if (mz_stream_is_open(stream) != MZ_OK) return MZ_STREAM_ERROR; if (origin == MZ_SEEK_SET && offset < 0) return MZ_SEEK_ERROR; return strm->vtbl->seek(strm, offset, origin); } int32_t mz_stream_find(void *stream, const void *find, int32_t find_size, int64_t max_seek, int64_t *position) { uint8_t buf[MZ_STREAM_FIND_SIZE]; int32_t buf_pos = 0; int32_t read_size = sizeof(buf); int32_t read = 0; int64_t read_pos = 0; int64_t start_pos = 0; int64_t disk_pos = 0; int32_t i = 0; uint8_t first = 1; int32_t err = MZ_OK; if (!stream || !find || !position) return MZ_PARAM_ERROR; if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) return MZ_PARAM_ERROR; *position = -1; start_pos = mz_stream_tell(stream); while (read_pos < max_seek) { if (read_size > (int32_t)(max_seek - read_pos - buf_pos) && (max_seek - read_pos - buf_pos) < (int64_t)sizeof(buf)) read_size = (int32_t)(max_seek - read_pos - buf_pos); read = mz_stream_read(stream, buf + buf_pos, read_size); if ((read <= 0) || (read + buf_pos < find_size)) break; for (i = 0; i <= read + buf_pos - find_size; i += 1) { if (memcmp(&buf[i], find, find_size) != 0) continue; disk_pos = mz_stream_tell(stream); /* Seek to position on disk where the data was found */ err = mz_stream_seek(stream, disk_pos - ((int64_t)read + buf_pos - i), MZ_SEEK_SET); if (err != MZ_OK) return MZ_EXIST_ERROR; *position = start_pos + read_pos + i; return MZ_OK; } if (first) { read -= find_size; read_size -= find_size; buf_pos = find_size; first = 0; } memmove(buf, buf + read, find_size); read_pos += read; } return MZ_EXIST_ERROR; } int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size, int64_t max_seek, int64_t *position) { uint8_t buf[MZ_STREAM_FIND_SIZE]; int32_t buf_pos = 0; int32_t read_size = MZ_STREAM_FIND_SIZE; int64_t read_pos = 0; int32_t read = 0; int64_t start_pos = 0; int64_t disk_pos = 0; uint8_t first = 1; int32_t i = 0; int32_t err = MZ_OK; if (!stream || !find || !position) return MZ_PARAM_ERROR; if (find_size < 0 || find_size >= (int32_t)sizeof(buf)) return MZ_PARAM_ERROR; *position = -1; start_pos = mz_stream_tell(stream); while (read_pos < max_seek) { if (read_size > (int32_t)(max_seek - read_pos) && (max_seek - read_pos) < (int64_t)sizeof(buf)) read_size = (int32_t)(max_seek - read_pos); if (mz_stream_seek(stream, start_pos - (read_pos + read_size), MZ_SEEK_SET) != MZ_OK) break; read = mz_stream_read(stream, buf, read_size); if ((read <= 0) || (read + buf_pos < find_size)) break; if (read + buf_pos < MZ_STREAM_FIND_SIZE) memmove(buf + MZ_STREAM_FIND_SIZE - (read + buf_pos), buf, read); for (i = find_size; i <= (read + buf_pos); i += 1) { if (memcmp(&buf[MZ_STREAM_FIND_SIZE - i], find, find_size) != 0) continue; disk_pos = mz_stream_tell(stream); /* Seek to position on disk where the data was found */ err = mz_stream_seek(stream, disk_pos + buf_pos - i, MZ_SEEK_SET); if (err != MZ_OK) return MZ_EXIST_ERROR; *position = start_pos - (read_pos - buf_pos + i); return MZ_OK; } if (first) { read -= find_size; read_size -= find_size; buf_pos = find_size; first = 0; } if (read == 0) break; memmove(buf + read_size, buf, find_size); read_pos += read; } return MZ_EXIST_ERROR; } int32_t mz_stream_close(void *stream) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->close) return MZ_PARAM_ERROR; if (mz_stream_is_open(stream) != MZ_OK) return MZ_STREAM_ERROR; return strm->vtbl->close(strm); } int32_t mz_stream_error(void *stream) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->error) return MZ_PARAM_ERROR; return strm->vtbl->error(strm); } int32_t mz_stream_set_base(void *stream, void *base) { mz_stream *strm = (mz_stream *)stream; strm->base = (mz_stream *)base; return MZ_OK; } void* mz_stream_get_interface(void *stream) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl) return NULL; return (void *)strm->vtbl; } int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->get_prop_int64) return MZ_PARAM_ERROR; return strm->vtbl->get_prop_int64(stream, prop, value); } int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream *strm = (mz_stream *)stream; if (!strm || !strm->vtbl || !strm->vtbl->set_prop_int64) return MZ_PARAM_ERROR; return strm->vtbl->set_prop_int64(stream, prop, value); } void *mz_stream_create(mz_stream_vtbl *vtbl) { if (!vtbl || !vtbl->create) return NULL; return vtbl->create(); } void mz_stream_delete(void **stream) { mz_stream *strm = NULL; if (!stream) return; strm = (mz_stream *)*stream; if (strm && strm->vtbl && strm->vtbl->destroy) strm->vtbl->destroy(stream); *stream = NULL; } /***************************************************************************/ typedef struct mz_stream_raw_s { mz_stream stream; int64_t total_in; int64_t total_out; int64_t max_total_in; } mz_stream_raw; /***************************************************************************/ int32_t mz_stream_raw_open(void *stream, const char *path, int32_t mode) { MZ_UNUSED(stream); MZ_UNUSED(path); MZ_UNUSED(mode); return MZ_OK; } int32_t mz_stream_raw_is_open(void *stream) { mz_stream_raw *raw = (mz_stream_raw *)stream; return mz_stream_is_open(raw->stream.base); } int32_t mz_stream_raw_read(void *stream, void *buf, int32_t size) { mz_stream_raw *raw = (mz_stream_raw *)stream; int32_t bytes_to_read = size; int32_t read = 0; if (raw->max_total_in > 0) { if ((int64_t)bytes_to_read > (raw->max_total_in - raw->total_in)) bytes_to_read = (int32_t)(raw->max_total_in - raw->total_in); } read = mz_stream_read(raw->stream.base, buf, bytes_to_read); if (read > 0) { raw->total_in += read; raw->total_out += read; } return read; } int32_t mz_stream_raw_write(void *stream, const void *buf, int32_t size) { mz_stream_raw *raw = (mz_stream_raw *)stream; int32_t written = 0; written = mz_stream_write(raw->stream.base, buf, size); if (written > 0) { raw->total_out += written; raw->total_in += written; } return written; } int64_t mz_stream_raw_tell(void *stream) { mz_stream_raw *raw = (mz_stream_raw *)stream; return mz_stream_tell(raw->stream.base); } int32_t mz_stream_raw_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_raw *raw = (mz_stream_raw *)stream; return mz_stream_seek(raw->stream.base, offset, origin); } int32_t mz_stream_raw_close(void *stream) { MZ_UNUSED(stream); return MZ_OK; } int32_t mz_stream_raw_error(void *stream) { mz_stream_raw *raw = (mz_stream_raw *)stream; return mz_stream_error(raw->stream.base); } int32_t mz_stream_raw_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream_raw *raw = (mz_stream_raw *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN: *value = raw->total_in; return MZ_OK; case MZ_STREAM_PROP_TOTAL_OUT: *value = raw->total_out; return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_stream_raw_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream_raw *raw = (mz_stream_raw *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN_MAX: raw->max_total_in = value; return MZ_OK; } return MZ_EXIST_ERROR; } /***************************************************************************/ static mz_stream_vtbl mz_stream_raw_vtbl = { mz_stream_raw_open, mz_stream_raw_is_open, mz_stream_raw_read, mz_stream_raw_write, mz_stream_raw_tell, mz_stream_raw_seek, mz_stream_raw_close, mz_stream_raw_error, mz_stream_raw_create, mz_stream_raw_delete, mz_stream_raw_get_prop_int64, mz_stream_raw_set_prop_int64 }; /***************************************************************************/ void *mz_stream_raw_create(void) { mz_stream_raw *raw = (mz_stream_raw *)calloc(1, sizeof(mz_stream_raw)); if (raw) raw->stream.vtbl = &mz_stream_raw_vtbl; return raw; } void mz_stream_raw_delete(void **stream) { mz_stream_raw *raw = NULL; if (!stream) return; raw = (mz_stream_raw *)*stream; if (raw) free(raw); *stream = NULL; } sight-23.1.0/3rd-party/minizip/mz_strm.h000066400000000000000000000134231450532053500200700ustar00rootroot00000000000000/* mz_strm.h -- Stream interface part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_H #define MZ_STREAM_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ #define MZ_STREAM_PROP_TOTAL_IN (1) #define MZ_STREAM_PROP_TOTAL_IN_MAX (2) #define MZ_STREAM_PROP_TOTAL_OUT (3) #define MZ_STREAM_PROP_TOTAL_OUT_MAX (4) #define MZ_STREAM_PROP_HEADER_SIZE (5) #define MZ_STREAM_PROP_FOOTER_SIZE (6) #define MZ_STREAM_PROP_DISK_SIZE (7) #define MZ_STREAM_PROP_DISK_NUMBER (8) #define MZ_STREAM_PROP_COMPRESS_LEVEL (9) #define MZ_STREAM_PROP_COMPRESS_METHOD (10) #define MZ_STREAM_PROP_COMPRESS_WINDOW (11) /***************************************************************************/ typedef int32_t (*mz_stream_open_cb) (void *stream, const char *path, int32_t mode); typedef int32_t (*mz_stream_is_open_cb) (void *stream); typedef int32_t (*mz_stream_read_cb) (void *stream, void *buf, int32_t size); typedef int32_t (*mz_stream_write_cb) (void *stream, const void *buf, int32_t size); typedef int64_t (*mz_stream_tell_cb) (void *stream); typedef int32_t (*mz_stream_seek_cb) (void *stream, int64_t offset, int32_t origin); typedef int32_t (*mz_stream_close_cb) (void *stream); typedef int32_t (*mz_stream_error_cb) (void *stream); typedef void* (*mz_stream_create_cb) (void); typedef void (*mz_stream_destroy_cb) (void **stream); typedef int32_t (*mz_stream_get_prop_int64_cb) (void *stream, int32_t prop, int64_t *value); typedef int32_t (*mz_stream_set_prop_int64_cb) (void *stream, int32_t prop, int64_t value); typedef int32_t (*mz_stream_find_cb) (void *stream, const void *find, int32_t find_size, int64_t max_seek, int64_t *position); /***************************************************************************/ typedef struct mz_stream_vtbl_s { mz_stream_open_cb open; mz_stream_is_open_cb is_open; mz_stream_read_cb read; mz_stream_write_cb write; mz_stream_tell_cb tell; mz_stream_seek_cb seek; mz_stream_close_cb close; mz_stream_error_cb error; mz_stream_create_cb create; mz_stream_destroy_cb destroy; mz_stream_get_prop_int64_cb get_prop_int64; mz_stream_set_prop_int64_cb set_prop_int64; } mz_stream_vtbl; typedef struct mz_stream_s { mz_stream_vtbl *vtbl; struct mz_stream_s *base; } mz_stream; /***************************************************************************/ int32_t mz_stream_open(void *stream, const char *path, int32_t mode); int32_t mz_stream_is_open(void *stream); int32_t mz_stream_read(void *stream, void *buf, int32_t size); int32_t mz_stream_read_uint8(void *stream, uint8_t *value); int32_t mz_stream_read_uint16(void *stream, uint16_t *value); int32_t mz_stream_read_uint32(void *stream, uint32_t *value); int32_t mz_stream_read_int64(void *stream, int64_t *value); int32_t mz_stream_read_uint64(void *stream, uint64_t *value); int32_t mz_stream_write(void *stream, const void *buf, int32_t size); int32_t mz_stream_write_uint8(void *stream, uint8_t value); int32_t mz_stream_write_uint16(void *stream, uint16_t value); int32_t mz_stream_write_uint32(void *stream, uint32_t value); int32_t mz_stream_write_int64(void *stream, int64_t value); int32_t mz_stream_write_uint64(void *stream, uint64_t value); int32_t mz_stream_copy(void *target, void *source, int32_t len); int32_t mz_stream_copy_to_end(void *target, void *source); int32_t mz_stream_copy_stream(void *target, mz_stream_write_cb write_cb, void *source, mz_stream_read_cb read_cb, int32_t len); int32_t mz_stream_copy_stream_to_end(void *target, mz_stream_write_cb write_cb, void *source, mz_stream_read_cb read_cb); int64_t mz_stream_tell(void *stream); int32_t mz_stream_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_find(void *stream, const void *find, int32_t find_size, int64_t max_seek, int64_t *position); int32_t mz_stream_find_reverse(void *stream, const void *find, int32_t find_size, int64_t max_seek, int64_t *position); int32_t mz_stream_close(void *stream); int32_t mz_stream_error(void *stream); int32_t mz_stream_set_base(void *stream, void *base); void* mz_stream_get_interface(void *stream); int32_t mz_stream_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_create(mz_stream_vtbl *vtbl); void mz_stream_delete(void **stream); /***************************************************************************/ int32_t mz_stream_raw_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_raw_is_open(void *stream); int32_t mz_stream_raw_read(void *stream, void *buf, int32_t size); int32_t mz_stream_raw_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_raw_tell(void *stream); int32_t mz_stream_raw_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_raw_close(void *stream); int32_t mz_stream_raw_error(void *stream); int32_t mz_stream_raw_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_raw_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_raw_create(void); void mz_stream_raw_delete(void **stream); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_buf.c000066400000000000000000000315271450532053500207240ustar00rootroot00000000000000/* mz_strm_buf.c -- Stream for buffering reads/writes part of the minizip-ng project This version of ioapi is designed to buffer IO. Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_strm.h" #include "mz_strm_buf.h" /***************************************************************************/ static mz_stream_vtbl mz_stream_buffered_vtbl = { mz_stream_buffered_open, mz_stream_buffered_is_open, mz_stream_buffered_read, mz_stream_buffered_write, mz_stream_buffered_tell, mz_stream_buffered_seek, mz_stream_buffered_close, mz_stream_buffered_error, mz_stream_buffered_create, mz_stream_buffered_delete, NULL, NULL }; /***************************************************************************/ typedef struct mz_stream_buffered_s { mz_stream stream; int32_t error; char readbuf[INT16_MAX]; int32_t readbuf_len; int32_t readbuf_pos; int32_t readbuf_hits; int32_t readbuf_misses; char writebuf[INT16_MAX]; int32_t writebuf_len; int32_t writebuf_pos; int32_t writebuf_hits; int32_t writebuf_misses; int64_t position; } mz_stream_buffered; /***************************************************************************/ #if 0 # define mz_stream_buffered_print printf #else # define mz_stream_buffered_print(fmt,...) #endif /***************************************************************************/ static int32_t mz_stream_buffered_reset(void *stream) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; buffered->readbuf_len = 0; buffered->readbuf_pos = 0; buffered->writebuf_len = 0; buffered->writebuf_pos = 0; buffered->position = 0; return MZ_OK; } int32_t mz_stream_buffered_open(void *stream, const char *path, int32_t mode) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; mz_stream_buffered_print("Buffered - Open (mode %" PRId32 ")\n", mode); mz_stream_buffered_reset(buffered); return mz_stream_open(buffered->stream.base, path, mode); } int32_t mz_stream_buffered_is_open(void *stream) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; return mz_stream_is_open(buffered->stream.base); } static int32_t mz_stream_buffered_flush(void *stream, int32_t *written) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int32_t total_bytes_written = 0; int32_t bytes_to_write = buffered->writebuf_len; int32_t bytes_left_to_write = buffered->writebuf_len; int32_t bytes_written = 0; *written = 0; while (bytes_left_to_write > 0) { bytes_written = mz_stream_write(buffered->stream.base, buffered->writebuf + (bytes_to_write - bytes_left_to_write), bytes_left_to_write); if (bytes_written != bytes_left_to_write) return MZ_WRITE_ERROR; buffered->writebuf_misses += 1; mz_stream_buffered_print("Buffered - Write flush (%" PRId32 ":%" PRId32 " len %" PRId32 ")\n", bytes_to_write, bytes_left_to_write, buffered->writebuf_len); total_bytes_written += bytes_written; bytes_left_to_write -= bytes_written; buffered->position += bytes_written; } buffered->writebuf_len = 0; buffered->writebuf_pos = 0; *written = total_bytes_written; return MZ_OK; } int32_t mz_stream_buffered_read(void *stream, void *buf, int32_t size) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int32_t buf_len = 0; int32_t bytes_to_read = 0; int32_t bytes_to_copy = 0; int32_t bytes_left_to_read = size; int32_t bytes_read = 0; int32_t bytes_flushed = 0; mz_stream_buffered_print("Buffered - Read (size %" PRId32 " pos %" PRId64 ")\n", size, buffered->position); if (buffered->writebuf_len > 0) { int64_t position = buffered->position + buffered->writebuf_pos mz_stream_buffered_print("Buffered - Switch from write to read, flushing (pos %" PRId64 ")\n", position); mz_stream_buffered_flush(stream, &bytes_flushed); mz_stream_buffered_seek(stream, position, MZ_SEEK_SET); } while (bytes_left_to_read > 0) { if ((buffered->readbuf_len == 0) || (buffered->readbuf_pos == buffered->readbuf_len)) { if (buffered->readbuf_len == sizeof(buffered->readbuf)) { buffered->readbuf_pos = 0; buffered->readbuf_len = 0; } bytes_to_read = (int32_t)sizeof(buffered->readbuf) - (buffered->readbuf_len - buffered->readbuf_pos); bytes_read = mz_stream_read(buffered->stream.base, buffered->readbuf + buffered->readbuf_pos, bytes_to_read); if (bytes_read < 0) return bytes_read; buffered->readbuf_misses += 1; buffered->readbuf_len += bytes_read; buffered->position += bytes_read; mz_stream_buffered_print("Buffered - Filled (read %" PRId32 "/%" PRId32 " buf %" PRId32 ":%" PRId32 " pos %" PRId64 ")\n", bytes_read, bytes_to_read, buffered->readbuf_pos, buffered->readbuf_len, buffered->position); if (bytes_read == 0) break; } if ((buffered->readbuf_len - buffered->readbuf_pos) > 0) { bytes_to_copy = buffered->readbuf_len - buffered->readbuf_pos; if (bytes_to_copy > bytes_left_to_read) bytes_to_copy = bytes_left_to_read; memcpy((char *)buf + buf_len, buffered->readbuf + buffered->readbuf_pos, bytes_to_copy); buf_len += bytes_to_copy; bytes_left_to_read -= bytes_to_copy; buffered->readbuf_hits += 1; buffered->readbuf_pos += bytes_to_copy; mz_stream_buffered_print("Buffered - Emptied (copied %" PRId32 " remaining %" PRId32 " buf %" PRId32 ":%" PRId32 " pos %" PRId64 ")\n", bytes_to_copy, bytes_left_to_read, buffered->readbuf_pos, buffered->readbuf_len, buffered->position); } } return size - bytes_left_to_read; } int32_t mz_stream_buffered_write(void *stream, const void *buf, int32_t size) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int32_t bytes_to_write = size; int32_t bytes_left_to_write = size; int32_t bytes_to_copy = 0; int32_t bytes_used = 0; int32_t bytes_flushed = 0; int32_t err = MZ_OK; mz_stream_buffered_print("Buffered - Write (size %" PRId32 " len %" PRId32 " pos %" PRId64 ")\n", size, buffered->writebuf_len, buffered->position); if (buffered->readbuf_len > 0) { buffered->position -= buffered->readbuf_len; buffered->position += buffered->readbuf_pos; buffered->readbuf_len = 0; buffered->readbuf_pos = 0; mz_stream_buffered_print("Buffered - Switch from read to write (pos %" PRId64 ")\n", buffered->position); err = mz_stream_seek(buffered->stream.base, buffered->position, MZ_SEEK_SET); if (err != MZ_OK) return err; } while (bytes_left_to_write > 0) { bytes_used = buffered->writebuf_len; if (bytes_used > buffered->writebuf_pos) bytes_used = buffered->writebuf_pos; bytes_to_copy = (int32_t)sizeof(buffered->writebuf) - bytes_used; if (bytes_to_copy > bytes_left_to_write) bytes_to_copy = bytes_left_to_write; if (bytes_to_copy == 0) { err = mz_stream_buffered_flush(stream, &bytes_flushed); if (err != MZ_OK) return err; if (bytes_flushed == 0) return 0; continue; } memcpy(buffered->writebuf + buffered->writebuf_pos, (const char *)buf + (bytes_to_write - bytes_left_to_write), bytes_to_copy); mz_stream_buffered_print("Buffered - Write copy (remaining %" PRId32 " write %" PRId32 ":%" PRId32 " len %" PRId32 ")\n", bytes_to_copy, bytes_to_write, bytes_left_to_write, buffered->writebuf_len); bytes_left_to_write -= bytes_to_copy; buffered->writebuf_pos += bytes_to_copy; buffered->writebuf_hits += 1; if (buffered->writebuf_pos > buffered->writebuf_len) buffered->writebuf_len += buffered->writebuf_pos - buffered->writebuf_len; } return size - bytes_left_to_write; } int64_t mz_stream_buffered_tell(void *stream) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int64_t position = mz_stream_tell(buffered->stream.base); buffered->position = position; mz_stream_buffered_print("Buffered - Tell (pos %" PRId64 " readpos %" PRId32 " writepos %" PRId32 ")\n", buffered->position, buffered->readbuf_pos, buffered->writebuf_pos); if (buffered->readbuf_len > 0) position -= ((int64_t)buffered->readbuf_len - buffered->readbuf_pos); if (buffered->writebuf_len > 0) position += buffered->writebuf_pos; return position; } int32_t mz_stream_buffered_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int32_t bytes_flushed = 0; int32_t err = MZ_OK; mz_stream_buffered_print("Buffered - Seek (origin %" PRId32 " offset %" PRId64 " pos %" PRId64 ")\n", origin, offset, buffered->position); switch (origin) { case MZ_SEEK_SET: if ((buffered->readbuf_len > 0) && (offset < buffered->position) && (offset >= buffered->position - buffered->readbuf_len)) { buffered->readbuf_pos = (int32_t)(offset - (buffered->position - buffered->readbuf_len)); return MZ_OK; } if (buffered->writebuf_len > 0) { if ((offset >= buffered->position) && (offset <= buffered->position + buffered->writebuf_len)) { buffered->writebuf_pos = (int32_t)(offset - buffered->position); return MZ_OK; } } err = mz_stream_buffered_flush(stream, &bytes_flushed); if (err != MZ_OK) return err; buffered->position = offset; break; case MZ_SEEK_CUR: if (buffered->readbuf_len > 0) { if (offset <= ((int64_t)buffered->readbuf_len - buffered->readbuf_pos)) { buffered->readbuf_pos += (uint32_t)offset; return MZ_OK; } offset -= ((int64_t)buffered->readbuf_len - buffered->readbuf_pos); buffered->position += offset; } if (buffered->writebuf_len > 0) { if (offset <= ((int64_t)buffered->writebuf_len - buffered->writebuf_pos)) { buffered->writebuf_pos += (uint32_t)offset; return MZ_OK; } /* offset -= (buffered->writebuf_len - buffered->writebuf_pos); */ } err = mz_stream_buffered_flush(stream, &bytes_flushed); if (err != MZ_OK) return err; break; case MZ_SEEK_END: if (buffered->writebuf_len > 0) { buffered->writebuf_pos = buffered->writebuf_len; return MZ_OK; } break; } buffered->readbuf_len = 0; buffered->readbuf_pos = 0; buffered->writebuf_len = 0; buffered->writebuf_pos = 0; return mz_stream_seek(buffered->stream.base, offset, origin); } int32_t mz_stream_buffered_close(void *stream) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; int32_t bytes_flushed = 0; mz_stream_buffered_flush(stream, &bytes_flushed); mz_stream_buffered_print("Buffered - Close (flushed %" PRId32 ")\n", bytes_flushed); if (buffered->readbuf_hits + buffered->readbuf_misses > 0) { mz_stream_buffered_print("Buffered - Read efficiency %.02f%%\n", (buffered->readbuf_hits / ((float)buffered->readbuf_hits + buffered->readbuf_misses)) * 100); } if (buffered->writebuf_hits + buffered->writebuf_misses > 0) { mz_stream_buffered_print("Buffered - Write efficiency %.02f%%\n", (buffered->writebuf_hits / ((float)buffered->writebuf_hits + buffered->writebuf_misses)) * 100); } mz_stream_buffered_reset(buffered); return mz_stream_close(buffered->stream.base); } int32_t mz_stream_buffered_error(void *stream) { mz_stream_buffered *buffered = (mz_stream_buffered *)stream; return mz_stream_error(buffered->stream.base); } void *mz_stream_buffered_create(void) { mz_stream_buffered *buffered = (mz_stream_buffered *)calloc(1, sizeof(mz_stream_buffered)); if (buffered) buffered->stream.vtbl = &mz_stream_buffered_vtbl; return buffered; } void mz_stream_buffered_delete(void **stream) { mz_stream_buffered *buffered = NULL; if (!stream) return; buffered = (mz_stream_buffered *)*stream; if (buffered) free(buffered); *stream = NULL; } void *mz_stream_buffered_get_interface(void) { return (void *)&mz_stream_buffered_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_buf.h000066400000000000000000000024351450532053500207250ustar00rootroot00000000000000/* mz_strm_buf.h -- Stream for buffering reads/writes part of the minizip-ng project This version of ioapi is designed to buffer IO. Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_BUFFERED_H #define MZ_STREAM_BUFFERED_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_buffered_open(void *stream, const char *path, int32_t mode); int32_t mz_stream_buffered_is_open(void *stream); int32_t mz_stream_buffered_read(void *stream, void *buf, int32_t size); int32_t mz_stream_buffered_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_buffered_tell(void *stream); int32_t mz_stream_buffered_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_buffered_close(void *stream); int32_t mz_stream_buffered_error(void *stream); void* mz_stream_buffered_create(void); void mz_stream_buffered_delete(void **stream); void* mz_stream_buffered_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_mem.c000066400000000000000000000155531450532053500207270ustar00rootroot00000000000000/* mz_strm_mem.c -- Stream for memory access part of the minizip-ng project This interface is designed to access memory rather than files. We do use a region of memory to put data in to and take it out of. Based on Unzip ioapi.c version 0.22, May 19th, 2003 Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 2003 Justin Fletcher Copyright (C) 1998-2003 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_strm.h" #include "mz_strm_mem.h" /***************************************************************************/ static mz_stream_vtbl mz_stream_mem_vtbl = { mz_stream_mem_open, mz_stream_mem_is_open, mz_stream_mem_read, mz_stream_mem_write, mz_stream_mem_tell, mz_stream_mem_seek, mz_stream_mem_close, mz_stream_mem_error, mz_stream_mem_create, mz_stream_mem_delete, NULL, NULL }; /***************************************************************************/ typedef struct mz_stream_mem_s { mz_stream stream; int32_t mode; uint8_t *buffer; /* Memory buffer pointer */ int32_t size; /* Size of the memory buffer */ int32_t limit; /* Furthest we've written */ int32_t position; /* Current position in the memory */ int32_t grow_size; /* Size to grow when full */ } mz_stream_mem; /***************************************************************************/ static int32_t mz_stream_mem_set_size(void *stream, int32_t size) { mz_stream_mem *mem = (mz_stream_mem *)stream; int32_t new_size = size; uint8_t *new_buf = NULL; new_buf = (uint8_t *)malloc((uint32_t)new_size); if (!new_buf) return MZ_BUF_ERROR; if (mem->buffer) { memcpy(new_buf, mem->buffer, mem->size); free(mem->buffer); } mem->buffer = new_buf; mem->size = new_size; return MZ_OK; } int32_t mz_stream_mem_open(void *stream, const char *path, int32_t mode) { mz_stream_mem *mem = (mz_stream_mem *)stream; int32_t err = MZ_OK; MZ_UNUSED(path); mem->mode = mode; mem->limit = 0; mem->position = 0; if (mem->mode & MZ_OPEN_MODE_CREATE) err = mz_stream_mem_set_size(stream, mem->grow_size); else mem->limit = mem->size; return err; } int32_t mz_stream_mem_is_open(void *stream) { mz_stream_mem *mem = (mz_stream_mem *)stream; if (!mem->buffer) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_mem_read(void *stream, void *buf, int32_t size) { mz_stream_mem *mem = (mz_stream_mem *)stream; if (size > mem->size - mem->position) size = mem->size - mem->position; if (mem->position + size > mem->limit) size = mem->limit - mem->position; if (size <= 0) return 0; memcpy(buf, mem->buffer + mem->position, size); mem->position += size; return size; } int32_t mz_stream_mem_write(void *stream, const void *buf, int32_t size) { mz_stream_mem *mem = (mz_stream_mem *)stream; int32_t new_size = 0; int32_t err = MZ_OK; if (!size) return size; if (size > mem->size - mem->position) { if (mem->mode & MZ_OPEN_MODE_CREATE) { new_size = mem->size; if (size < mem->grow_size) new_size += mem->grow_size; else new_size += size; err = mz_stream_mem_set_size(stream, new_size); if (err != MZ_OK) return err; } else { size = mem->size - mem->position; } } memcpy(mem->buffer + mem->position, buf, size); mem->position += size; if (mem->position > mem->limit) mem->limit = mem->position; return size; } int64_t mz_stream_mem_tell(void *stream) { mz_stream_mem *mem = (mz_stream_mem *)stream; return mem->position; } int32_t mz_stream_mem_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_mem *mem = (mz_stream_mem *)stream; int64_t new_pos = 0; int32_t err = MZ_OK; switch (origin) { case MZ_SEEK_CUR: new_pos = mem->position + offset; break; case MZ_SEEK_END: new_pos = mem->limit + offset; break; case MZ_SEEK_SET: new_pos = offset; break; default: return MZ_SEEK_ERROR; } if (new_pos > mem->size) { if ((mem->mode & MZ_OPEN_MODE_CREATE) == 0) return MZ_SEEK_ERROR; err = mz_stream_mem_set_size(stream, (int32_t)new_pos); if (err != MZ_OK) return err; } else if (new_pos < 0) { return MZ_SEEK_ERROR; } mem->position = (int32_t)new_pos; return MZ_OK; } int32_t mz_stream_mem_close(void *stream) { MZ_UNUSED(stream); /* We never return errors */ return MZ_OK; } int32_t mz_stream_mem_error(void *stream) { MZ_UNUSED(stream); /* We never return errors */ return MZ_OK; } void mz_stream_mem_set_buffer(void *stream, void *buf, int32_t size) { mz_stream_mem *mem = (mz_stream_mem *)stream; mem->buffer = (uint8_t *)buf; mem->size = size; mem->limit = size; } int32_t mz_stream_mem_get_buffer(void *stream, const void **buf) { return mz_stream_mem_get_buffer_at(stream, 0, buf); } int32_t mz_stream_mem_get_buffer_at(void *stream, int64_t position, const void **buf) { mz_stream_mem *mem = (mz_stream_mem *)stream; if (!buf || position < 0 || !mem->buffer|| mem->size < position) return MZ_SEEK_ERROR; *buf = mem->buffer + position; return MZ_OK; } int32_t mz_stream_mem_get_buffer_at_current(void *stream, const void **buf) { mz_stream_mem *mem = (mz_stream_mem *)stream; return mz_stream_mem_get_buffer_at(stream, mem->position, buf); } void mz_stream_mem_get_buffer_length(void *stream, int32_t *length) { mz_stream_mem *mem = (mz_stream_mem *)stream; *length = mem->limit; } void mz_stream_mem_set_buffer_limit(void *stream, int32_t limit) { mz_stream_mem *mem = (mz_stream_mem *)stream; mem->limit = limit; } void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size) { mz_stream_mem *mem = (mz_stream_mem *)stream; mem->grow_size = grow_size; } void *mz_stream_mem_create(void) { mz_stream_mem *mem = (mz_stream_mem *)calloc(1, sizeof(mz_stream_mem)); if (mem) { mem->stream.vtbl = &mz_stream_mem_vtbl; mem->grow_size = 4096; } return mem; } void mz_stream_mem_delete(void **stream) { mz_stream_mem *mem = NULL; if (!stream) return; mem = (mz_stream_mem *)*stream; if (mem) { if ((mem->mode & MZ_OPEN_MODE_CREATE) && (mem->buffer)) free(mem->buffer); free(mem); } *stream = NULL; } void *mz_stream_mem_get_interface(void) { return (void *)&mz_stream_mem_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_mem.h000066400000000000000000000032461450532053500207300ustar00rootroot00000000000000/* mz_strm_mem.h -- Stream for memory access part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_MEM_H #define MZ_STREAM_MEM_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_mem_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_mem_is_open(void *stream); int32_t mz_stream_mem_read(void *stream, void *buf, int32_t size); int32_t mz_stream_mem_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_mem_tell(void *stream); int32_t mz_stream_mem_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_mem_close(void *stream); int32_t mz_stream_mem_error(void *stream); void mz_stream_mem_set_buffer(void *stream, void *buf, int32_t size); int32_t mz_stream_mem_get_buffer(void *stream, const void **buf); int32_t mz_stream_mem_get_buffer_at(void *stream, int64_t position, const void **buf); int32_t mz_stream_mem_get_buffer_at_current(void *stream, const void **buf); void mz_stream_mem_get_buffer_length(void *stream, int32_t *length); void mz_stream_mem_set_buffer_limit(void *stream, int32_t limit); void mz_stream_mem_set_grow_size(void *stream, int32_t grow_size); void* mz_stream_mem_create(void); void mz_stream_mem_delete(void **stream); void* mz_stream_mem_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_os.h000066400000000000000000000022251450532053500205670ustar00rootroot00000000000000/* mz_sstrm_os.h -- Stream for filesystem access part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_OS_H #define MZ_STREAM_OS_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode); int32_t mz_stream_os_is_open(void *stream); int32_t mz_stream_os_read(void *stream, void *buf, int32_t size); int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_os_tell(void *stream); int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_os_close(void *stream); int32_t mz_stream_os_error(void *stream); void* mz_stream_os_create(void); void mz_stream_os_delete(void **stream); void* mz_stream_os_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_os_posix.c000066400000000000000000000120571450532053500220100ustar00rootroot00000000000000/* mz_strm_posix.c -- Stream for filesystem access for posix/linux part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Modifications for Zip64 support Copyright (C) 2009-2010 Mathias Svensson http://result42.com Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef WIN32 #include "mz.h" #include "mz_strm.h" #include "mz_strm_os.h" #include /* fopen, fread.. */ #include /***************************************************************************/ #define fopen64 fopen #ifndef MZ_FILE32_API # ifndef NO_FSEEKO # define ftello64 ftello # define fseeko64 fseeko # elif defined(_MSC_VER) && (_MSC_VER >= 1400) # define ftello64 _ftelli64 # define fseeko64 _fseeki64 # endif #endif #ifndef ftello64 # define ftello64 ftell #endif #ifndef fseeko64 # define fseeko64 fseek #endif /***************************************************************************/ static mz_stream_vtbl mz_stream_os_vtbl = { mz_stream_os_open, mz_stream_os_is_open, mz_stream_os_read, mz_stream_os_write, mz_stream_os_tell, mz_stream_os_seek, mz_stream_os_close, mz_stream_os_error, mz_stream_os_create, mz_stream_os_delete, NULL, NULL }; /***************************************************************************/ typedef struct mz_stream_posix_s { mz_stream stream; int32_t error; FILE *handle; } mz_stream_posix; /***************************************************************************/ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { mz_stream_posix *posix = (mz_stream_posix *)stream; const char *mode_fopen = NULL; if (!path) return MZ_PARAM_ERROR; if ((mode & MZ_OPEN_MODE_READWRITE) == MZ_OPEN_MODE_READ) mode_fopen = "rb"; else if (mode & MZ_OPEN_MODE_APPEND) mode_fopen = "r+b"; else if (mode & MZ_OPEN_MODE_CREATE) mode_fopen = "wb"; else return MZ_OPEN_ERROR; posix->handle = fopen64(path, mode_fopen); if (!posix->handle) { posix->error = errno; return MZ_OPEN_ERROR; } if (mode & MZ_OPEN_MODE_APPEND) return mz_stream_os_seek(stream, 0, MZ_SEEK_END); return MZ_OK; } int32_t mz_stream_os_is_open(void *stream) { mz_stream_posix *posix = (mz_stream_posix *)stream; if (!posix->handle) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { mz_stream_posix *posix = (mz_stream_posix *)stream; int32_t read = (int32_t)fread(buf, 1, (size_t)size, posix->handle); if (read < size && ferror(posix->handle)) { posix->error = errno; return MZ_READ_ERROR; } return read; } int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { mz_stream_posix *posix = (mz_stream_posix *)stream; int32_t written = (int32_t)fwrite(buf, 1, (size_t)size, posix->handle); if (written < size && ferror(posix->handle)) { posix->error = errno; return MZ_WRITE_ERROR; } return written; } int64_t mz_stream_os_tell(void *stream) { mz_stream_posix *posix = (mz_stream_posix *)stream; int64_t position = ftello64(posix->handle); if (position == -1) { posix->error = errno; return MZ_TELL_ERROR; } return position; } int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_posix *posix = (mz_stream_posix *)stream; int32_t fseek_origin = 0; switch (origin) { case MZ_SEEK_CUR: fseek_origin = SEEK_CUR; break; case MZ_SEEK_END: fseek_origin = SEEK_END; break; case MZ_SEEK_SET: fseek_origin = SEEK_SET; break; default: return MZ_SEEK_ERROR; } if (fseeko64(posix->handle, offset, fseek_origin) != 0) { posix->error = errno; return MZ_SEEK_ERROR; } return MZ_OK; } int32_t mz_stream_os_close(void *stream) { mz_stream_posix *posix = (mz_stream_posix *)stream; int32_t closed = 0; if (posix->handle) { closed = fclose(posix->handle); posix->handle = NULL; } if (closed != 0) { posix->error = errno; return MZ_CLOSE_ERROR; } return MZ_OK; } int32_t mz_stream_os_error(void *stream) { mz_stream_posix *posix = (mz_stream_posix *)stream; return posix->error; } void *mz_stream_os_create(void) { mz_stream_posix *posix = (mz_stream_posix *)calloc(1, sizeof(mz_stream_posix)); if (posix) posix->stream.vtbl = &mz_stream_os_vtbl; return posix; } void mz_stream_os_delete(void **stream) { mz_stream_posix *posix = NULL; if (!stream) return; posix = (mz_stream_posix *)*stream; if (posix) free(posix); *stream = NULL; } void *mz_stream_os_get_interface(void) { return (void *)&mz_stream_os_vtbl; } #endifsight-23.1.0/3rd-party/minizip/mz_strm_os_win32.c000066400000000000000000000172201450532053500216050ustar00rootroot00000000000000/* mz_strm_win32.c -- Stream for filesystem access for windows part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 2009-2010 Mathias Svensson Modifications for Zip64 support http://result42.com Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifdef WIN32 #include "mz.h" #include "mz_os.h" #include "mz_strm.h" #include "mz_strm_os.h" #include /***************************************************************************/ #ifndef INVALID_HANDLE_VALUE # define INVALID_HANDLE_VALUE 0xFFFFFFFF #endif #ifndef INVALID_SET_FILE_POINTER # define INVALID_SET_FILE_POINTER (DWORD)-1 #endif #ifndef _WIN32_WINNT_WIN8 # define _WIN32_WINNT_WIN8 0x0602 #endif /***************************************************************************/ static mz_stream_vtbl mz_stream_os_vtbl = { mz_stream_os_open, mz_stream_os_is_open, mz_stream_os_read, mz_stream_os_write, mz_stream_os_tell, mz_stream_os_seek, mz_stream_os_close, mz_stream_os_error, mz_stream_os_create, mz_stream_os_delete, NULL, NULL }; /***************************************************************************/ typedef struct mz_stream_win32_s { mz_stream stream; HANDLE handle; int32_t error; } mz_stream_win32; /***************************************************************************/ #if 0 # define mz_stream_os_print printf #else # define mz_stream_os_print(fmt, ...) #endif /***************************************************************************/ int32_t mz_stream_os_open(void *stream, const char *path, int32_t mode) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; uint32_t desired_access = 0; uint32_t creation_disposition = 0; uint32_t share_mode = FILE_SHARE_READ; uint32_t flags_attribs = FILE_ATTRIBUTE_NORMAL; wchar_t *path_wide = NULL; if (!path) return MZ_PARAM_ERROR; /* Some use cases require write sharing as well */ share_mode |= FILE_SHARE_WRITE; if ((mode & MZ_OPEN_MODE_READWRITE) == MZ_OPEN_MODE_READ) { desired_access = GENERIC_READ; creation_disposition = OPEN_EXISTING; } else if (mode & MZ_OPEN_MODE_APPEND) { desired_access = GENERIC_WRITE | GENERIC_READ; creation_disposition = OPEN_EXISTING; } else if (mode & MZ_OPEN_MODE_CREATE) { desired_access = GENERIC_WRITE | GENERIC_READ; creation_disposition = CREATE_ALWAYS; } else { return MZ_PARAM_ERROR; } mz_stream_os_print("Win32 - Open - %s (mode %" PRId32 ")\n", path); path_wide = mz_os_unicode_string_create(path, MZ_ENCODING_UTF8); if (!path_wide) return MZ_PARAM_ERROR; #if _WIN32_WINNT >= _WIN32_WINNT_WIN8 win32->handle = CreateFile2(path_wide, desired_access, share_mode, creation_disposition, NULL); #else win32->handle = CreateFileW(path_wide, desired_access, share_mode, NULL, creation_disposition, flags_attribs, NULL); #endif mz_os_unicode_string_delete(&path_wide); if (mz_stream_os_is_open(stream) != MZ_OK) { win32->error = GetLastError(); return MZ_OPEN_ERROR; } if (mode & MZ_OPEN_MODE_APPEND) return mz_stream_os_seek(stream, 0, MZ_SEEK_END); return MZ_OK; } int32_t mz_stream_os_is_open(void *stream) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; if (!win32->handle || win32->handle == INVALID_HANDLE_VALUE) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_os_read(void *stream, void *buf, int32_t size) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; uint32_t read = 0; if (mz_stream_os_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (!ReadFile(win32->handle, buf, size, (DWORD *)&read, NULL)) { win32->error = GetLastError(); if (win32->error == ERROR_HANDLE_EOF) win32->error = 0; } mz_stream_os_print("Win32 - Read - %" PRId32 "\n", read); return read; } int32_t mz_stream_os_write(void *stream, const void *buf, int32_t size) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; int32_t written = 0; if (mz_stream_os_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; if (!WriteFile(win32->handle, buf, size, (DWORD *)&written, NULL)) { win32->error = GetLastError(); if (win32->error == ERROR_HANDLE_EOF) win32->error = 0; } mz_stream_os_print("Win32 - Write - %" PRId32 "\n", written); return written; } static int32_t mz_stream_os_seekinternal(HANDLE handle, LARGE_INTEGER large_pos, LARGE_INTEGER *new_pos, uint32_t move_method) { #if _WIN32_WINNT >= _WIN32_WINNT_WINXP BOOL success = FALSE; success = SetFilePointerEx(handle, large_pos, new_pos, move_method); if ((success == FALSE) && (GetLastError() != NO_ERROR)) return MZ_SEEK_ERROR; return MZ_OK; #else LONG high_part = 0; uint32_t pos = 0; high_part = large_pos.HighPart; pos = SetFilePointer(handle, large_pos.LowPart, &high_part, move_method); if ((pos == INVALID_SET_FILE_POINTER) && (GetLastError() != NO_ERROR)) return MZ_SEEK_ERROR; if (new_pos) { new_pos->LowPart = pos; new_pos->HighPart = high_part; } return MZ_OK; #endif } int64_t mz_stream_os_tell(void *stream) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; LARGE_INTEGER large_pos; if (mz_stream_os_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; large_pos.QuadPart = 0; if (mz_stream_os_seekinternal(win32->handle, large_pos, &large_pos, FILE_CURRENT) != MZ_OK) win32->error = GetLastError(); mz_stream_os_print("Win32 - Tell - %" PRId64 "\n", large_pos.QuadPart); return large_pos.QuadPart; } int32_t mz_stream_os_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; uint32_t move_method = 0xFFFFFFFF; int32_t err = MZ_OK; LARGE_INTEGER large_pos; if (mz_stream_os_is_open(stream) != MZ_OK) return MZ_OPEN_ERROR; switch (origin) { case MZ_SEEK_CUR: move_method = FILE_CURRENT; break; case MZ_SEEK_END: move_method = FILE_END; break; case MZ_SEEK_SET: move_method = FILE_BEGIN; break; default: return MZ_SEEK_ERROR; } mz_stream_os_print("Win32 - Seek - %" PRId64 " (origin %" PRId32 ")\n", offset, origin); large_pos.QuadPart = offset; err = mz_stream_os_seekinternal(win32->handle, large_pos, NULL, move_method); if (err != MZ_OK) { win32->error = GetLastError(); return err; } return MZ_OK; } int32_t mz_stream_os_close(void *stream) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; if (win32->handle) CloseHandle(win32->handle); mz_stream_os_print("Win32 - Close\n"); win32->handle = NULL; return MZ_OK; } int32_t mz_stream_os_error(void *stream) { mz_stream_win32 *win32 = (mz_stream_win32 *)stream; return win32->error; } void *mz_stream_os_create(void) { mz_stream_win32 *win32 = (mz_stream_win32 *)calloc(1, sizeof(mz_stream_win32)); if (win32) win32->stream.vtbl = &mz_stream_os_vtbl; return win32; } void mz_stream_os_delete(void **stream) { mz_stream_win32 *win32 = NULL; if (!stream) return; win32 = (mz_stream_win32 *)*stream; if (win32) free(win32); *stream = NULL; } void *mz_stream_os_get_interface(void) { return (void *)&mz_stream_os_vtbl; } #endifsight-23.1.0/3rd-party/minizip/mz_strm_split.c000066400000000000000000000310331450532053500212730ustar00rootroot00000000000000/* mz_strm_split.c -- Stream for split files part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_os.h" #include "mz_strm.h" #include "mz_strm_split.h" #include /* snprintf */ #include #if defined(_MSC_VER) && (_MSC_VER < 1900) # define snprintf _snprintf #endif /***************************************************************************/ #define MZ_ZIP_MAGIC_DISKHEADER (0x08074b50) /***************************************************************************/ static mz_stream_vtbl mz_stream_split_vtbl = { mz_stream_split_open, mz_stream_split_is_open, mz_stream_split_read, mz_stream_split_write, mz_stream_split_tell, mz_stream_split_seek, mz_stream_split_close, mz_stream_split_error, mz_stream_split_create, mz_stream_split_delete, mz_stream_split_get_prop_int64, mz_stream_split_set_prop_int64 }; /***************************************************************************/ typedef struct mz_stream_split_s { mz_stream stream; int32_t is_open; int64_t disk_size; int64_t total_in; int64_t total_in_disk; int64_t total_out; int64_t total_out_disk; int32_t mode; char *path_cd; char *path_disk; uint32_t path_disk_size; int32_t number_disk; int32_t current_disk; int64_t current_disk_size; int32_t reached_end; } mz_stream_split; /***************************************************************************/ #if 0 # define mz_stream_split_print printf #else # define mz_stream_split_print(fmt, ...) #endif /***************************************************************************/ static int32_t mz_stream_split_open_disk(void *stream, int32_t number_disk) { mz_stream_split *split = (mz_stream_split *)stream; uint32_t magic = 0; int64_t position = 0; int32_t i = 0; int32_t err = MZ_OK; int16_t disk_part = 0; /* Check if we are reading or writing a disk part or the cd disk */ if (number_disk >= 0) { if ((split->mode & MZ_OPEN_MODE_WRITE) == 0) disk_part = MZ_OPEN_MODE_READ; else if (split->disk_size > 0) disk_part = MZ_OPEN_MODE_WRITE; } /* Construct disk path */ if (disk_part > 0) { for (i = (int32_t)strlen(split->path_disk) - 1; i >= 0; i -= 1) { if (split->path_disk[i] != '.') continue; snprintf(&split->path_disk[i], split->path_disk_size - (uint32_t)i, ".z%02" PRId32, number_disk + 1); break; } } else { strncpy(split->path_disk, split->path_cd, split->path_disk_size - 1); split->path_disk[split->path_disk_size - 1] = 0; } mz_stream_split_print("Split - Goto disk - %s (disk %" PRId32 ")\n", split->path_disk, number_disk); /* If disk part doesn't exist during reading then return MZ_EXIST_ERROR */ if (disk_part == MZ_OPEN_MODE_READ) err = mz_os_file_exists(split->path_disk); if (err == MZ_OK) err = mz_stream_open(split->stream.base, split->path_disk, split->mode); if (err == MZ_OK) { split->total_in_disk = 0; split->total_out_disk = 0; split->current_disk = number_disk; if (split->mode & MZ_OPEN_MODE_WRITE) { if ((split->current_disk == 0) && (split->disk_size > 0)) { err = mz_stream_write_uint32(split->stream.base, MZ_ZIP_MAGIC_DISKHEADER); split->total_out_disk += 4; split->total_out += split->total_out_disk; } } else if (split->mode & MZ_OPEN_MODE_READ) { if (split->current_disk == 0) { err = mz_stream_read_uint32(split->stream.base, &magic); if (magic != MZ_ZIP_MAGIC_DISKHEADER) err = MZ_FORMAT_ERROR; } } } if (err == MZ_OK) { /* Get the size of the current disk we are on */ position = mz_stream_tell(split->stream.base); mz_stream_seek(split->stream.base, 0, MZ_SEEK_END); split->current_disk_size = mz_stream_tell(split->stream.base); mz_stream_seek(split->stream.base, position, MZ_SEEK_SET); split->is_open = 1; } return err; } static int32_t mz_stream_split_close_disk(void *stream) { mz_stream_split *split = (mz_stream_split *)stream; if (mz_stream_is_open(split->stream.base) != MZ_OK) return MZ_OK; mz_stream_split_print("Split - Close disk\n"); return mz_stream_close(split->stream.base); } static int32_t mz_stream_split_goto_disk(void *stream, int32_t number_disk) { mz_stream_split *split = (mz_stream_split *)stream; int32_t err = MZ_OK; int32_t err_is_open = MZ_OK; err_is_open = mz_stream_is_open(split->stream.base); if ((split->disk_size == 0) && (split->mode & MZ_OPEN_MODE_WRITE)) { if (err_is_open != MZ_OK) err = mz_stream_split_open_disk(stream, number_disk); } else if ((number_disk != split->current_disk) || (err_is_open != MZ_OK)) { err = mz_stream_split_close_disk(stream); if (err == MZ_OK) { err = mz_stream_split_open_disk(stream, number_disk); if (err == MZ_OK) split->number_disk = number_disk; } } return err; } int32_t mz_stream_split_open(void *stream, const char *path, int32_t mode) { mz_stream_split *split = (mz_stream_split *)stream; int32_t number_disk = 0; split->mode = mode; split->path_cd = strdup(path); if (!split->path_cd) return MZ_MEM_ERROR; mz_stream_split_print("Split - Open - %s (disk %" PRId32 ")\n", split->path_cd, number_disk); split->path_disk_size = (uint32_t)strlen(path) + 10; split->path_disk = (char *)malloc(split->path_disk_size); if (!split->path_disk) { free(split->path_cd); return MZ_MEM_ERROR; } strncpy(split->path_disk, path, split->path_disk_size - 1); split->path_disk[split->path_disk_size - 1] = 0; if ((mode & MZ_OPEN_MODE_WRITE) && ((mode & MZ_OPEN_MODE_APPEND) == 0)) { number_disk = 0; split->current_disk = -1; } else { number_disk = -1; split->current_disk = 0; } return mz_stream_split_goto_disk(stream, number_disk); } int32_t mz_stream_split_is_open(void *stream) { mz_stream_split *split = (mz_stream_split *)stream; if (split->is_open != 1) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_split_read(void *stream, void *buf, int32_t size) { mz_stream_split *split = (mz_stream_split *)stream; int32_t bytes_left = size; int32_t read = 0; int32_t err = MZ_OK; uint8_t *buf_ptr = (uint8_t *)buf; err = mz_stream_split_goto_disk(stream, split->number_disk); if (err != MZ_OK) return err; while (bytes_left > 0) { read = mz_stream_read(split->stream.base, buf_ptr, bytes_left); mz_stream_split_print("Split - Read disk - %" PRId32 "\n", read); if (read < 0) return read; if (read == 0) { if (split->current_disk < 0) /* No more disks to goto */ break; err = mz_stream_split_goto_disk(stream, split->current_disk + 1); if (err == MZ_EXIST_ERROR) { split->current_disk = -1; break; } if (err != MZ_OK) return err; } bytes_left -= read; buf_ptr += read; split->total_in += read; split->total_in_disk += read; } return size - bytes_left; } int32_t mz_stream_split_write(void *stream, const void *buf, int32_t size) { mz_stream_split *split = (mz_stream_split *)stream; int64_t position = 0; int32_t written = 0; int32_t bytes_left = size; int32_t bytes_to_write = 0; int32_t bytes_avail = 0; int32_t number_disk = -1; int32_t err = MZ_OK; const uint8_t *buf_ptr = (const uint8_t *)buf; position = mz_stream_tell(split->stream.base); while (bytes_left > 0) { bytes_to_write = bytes_left; if (split->disk_size > 0) { if ((split->total_out_disk == split->disk_size && split->total_out > 0) || (split->number_disk == -1 && split->number_disk != split->current_disk)) { if (split->number_disk != -1) number_disk = split->current_disk + 1; err = mz_stream_split_goto_disk(stream, number_disk); if (err != MZ_OK) return err; position = 0; } if (split->number_disk != -1) { bytes_avail = (int32_t)(split->disk_size - split->total_out_disk); if (bytes_to_write > bytes_avail) bytes_to_write = bytes_avail; } } written = mz_stream_write(split->stream.base, buf_ptr, bytes_to_write); if (written != bytes_to_write) return MZ_WRITE_ERROR; mz_stream_split_print("Split - Write disk - %" PRId32 "\n", written); bytes_left -= written; buf_ptr += written; split->total_out += written; split->total_out_disk += written; position += written; if (position > split->current_disk_size) split->current_disk_size = position; } return size - bytes_left; } int64_t mz_stream_split_tell(void *stream) { mz_stream_split *split = (mz_stream_split *)stream; int32_t err = MZ_OK; err = mz_stream_split_goto_disk(stream, split->number_disk); if (err != MZ_OK) return err; return mz_stream_tell(split->stream.base); } int32_t mz_stream_split_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_split *split = (mz_stream_split *)stream; int64_t disk_left = 0; int64_t position = 0; int32_t err = MZ_OK; err = mz_stream_split_goto_disk(stream, split->number_disk); if (err != MZ_OK) return err; mz_stream_split_print("Split - Seek disk - %" PRId64 " (origin %" PRId32 ")\n", offset, origin); if ((origin == MZ_SEEK_CUR) && (split->number_disk != -1)) { position = mz_stream_tell(split->stream.base); disk_left = split->current_disk_size - position; while (offset > disk_left) { err = mz_stream_split_goto_disk(stream, split->current_disk + 1); if (err != MZ_OK) return err; offset -= disk_left; disk_left = split->current_disk_size; } } return mz_stream_seek(split->stream.base, offset, origin); } int32_t mz_stream_split_close(void *stream) { mz_stream_split *split = (mz_stream_split *)stream; int32_t err = MZ_OK; err = mz_stream_split_close_disk(stream); split->is_open = 0; return err; } int32_t mz_stream_split_error(void *stream) { mz_stream_split *split = (mz_stream_split *)stream; return mz_stream_error(split->stream.base); } int32_t mz_stream_split_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream_split *split = (mz_stream_split *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_OUT: *value = split->total_out; break; case MZ_STREAM_PROP_DISK_NUMBER: *value = split->number_disk; break; case MZ_STREAM_PROP_DISK_SIZE: *value = split->disk_size; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } int32_t mz_stream_split_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream_split *split = (mz_stream_split *)stream; switch (prop) { case MZ_STREAM_PROP_DISK_NUMBER: split->number_disk = (int32_t)value; break; case MZ_STREAM_PROP_DISK_SIZE: split->disk_size = value; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } void *mz_stream_split_create(void) { mz_stream_split *split = (mz_stream_split *)calloc(1, sizeof(mz_stream_split)); if (split) split->stream.vtbl = &mz_stream_split_vtbl; return split; } void mz_stream_split_delete(void **stream) { mz_stream_split *split = NULL; if (!stream) return; split = (mz_stream_split *)*stream; if (split) { if (split->path_cd) free(split->path_cd); if (split->path_disk) free(split->path_disk); free(split); } *stream = NULL; } void *mz_stream_split_get_interface(void) { return (void *)&mz_stream_split_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_split.h000066400000000000000000000025451450532053500213060ustar00rootroot00000000000000/* mz_strm_split.h -- Stream for split files part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_SPLIT_H #define MZ_STREAM_SPLIT_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_split_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_split_is_open(void *stream); int32_t mz_stream_split_read(void *stream, void *buf, int32_t size); int32_t mz_stream_split_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_split_tell(void *stream); int32_t mz_stream_split_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_split_close(void *stream); int32_t mz_stream_split_error(void *stream); int32_t mz_stream_split_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_split_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_split_create(void); void mz_stream_split_delete(void **stream); void* mz_stream_split_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_wzaes.c000066400000000000000000000265601450532053500213020ustar00rootroot00000000000000/* mz_strm_wzaes.c -- Stream for WinZip AES encryption part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 1998-2010 Brian Gladman, Worcester, UK This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_crypt.h" #include "mz_strm.h" #include "mz_strm_wzaes.h" /***************************************************************************/ #define MZ_AES_KEY_LENGTH(STRENGTH) (8 * (STRENGTH & 3) + 8) #define MZ_AES_KEYING_ITERATIONS (1000) #define MZ_AES_SALT_LENGTH(STRENGTH) (4 * (STRENGTH & 3) + 4) #define MZ_AES_SALT_LENGTH_MAX (16) #define MZ_AES_PW_LENGTH_MAX (128) #define MZ_AES_PW_VERIFY_SIZE (2) #define MZ_AES_AUTHCODE_SIZE (10) /***************************************************************************/ static mz_stream_vtbl mz_stream_wzaes_vtbl = { mz_stream_wzaes_open, mz_stream_wzaes_is_open, mz_stream_wzaes_read, mz_stream_wzaes_write, mz_stream_wzaes_tell, mz_stream_wzaes_seek, mz_stream_wzaes_close, mz_stream_wzaes_error, mz_stream_wzaes_create, mz_stream_wzaes_delete, mz_stream_wzaes_get_prop_int64, mz_stream_wzaes_set_prop_int64 }; /***************************************************************************/ typedef struct mz_stream_wzaes_s { mz_stream stream; int32_t mode; int32_t error; int16_t initialized; uint8_t buffer[UINT16_MAX]; int64_t total_in; int64_t max_total_in; int64_t total_out; uint8_t strength; const char *password; void *aes; uint32_t crypt_pos; uint8_t crypt_block[MZ_AES_BLOCK_SIZE]; void *hmac; uint8_t nonce[MZ_AES_BLOCK_SIZE]; } mz_stream_wzaes; /***************************************************************************/ int32_t mz_stream_wzaes_open(void *stream, const char *path, int32_t mode) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; uint16_t salt_length = 0; uint16_t password_length = 0; uint16_t key_length = 0; uint8_t kbuf[2 * MZ_AES_KEY_LENGTH_MAX + MZ_AES_PW_VERIFY_SIZE]; uint8_t verify[MZ_AES_PW_VERIFY_SIZE]; uint8_t verify_expected[MZ_AES_PW_VERIFY_SIZE]; uint8_t salt_value[MZ_AES_SALT_LENGTH_MAX]; const char *password = path; wzaes->total_in = 0; wzaes->total_out = 0; wzaes->initialized = 0; if (mz_stream_is_open(wzaes->stream.base) != MZ_OK) return MZ_OPEN_ERROR; if (!password) password = wzaes->password; if (!password) return MZ_PARAM_ERROR; password_length = (uint16_t)strlen(password); if (password_length > MZ_AES_PW_LENGTH_MAX) return MZ_PARAM_ERROR; if (wzaes->strength < 1 || wzaes->strength > 3) return MZ_PARAM_ERROR; key_length = MZ_AES_KEY_LENGTH(wzaes->strength); salt_length = MZ_AES_SALT_LENGTH(wzaes->strength); if (mode & MZ_OPEN_MODE_WRITE) { mz_crypt_rand(salt_value, salt_length); } else if (mode & MZ_OPEN_MODE_READ) { if (mz_stream_read(wzaes->stream.base, salt_value, salt_length) != salt_length) return MZ_READ_ERROR; } /* Derive the encryption and authentication keys and the password verifier */ mz_crypt_pbkdf2((uint8_t *)password, password_length, salt_value, salt_length, MZ_AES_KEYING_ITERATIONS, kbuf, 2 * key_length + MZ_AES_PW_VERIFY_SIZE); /* Initialize the buffer pos */ wzaes->crypt_pos = MZ_AES_BLOCK_SIZE; /* Use fixed zeroed IV/nonce for CTR mode */ memset(wzaes->nonce, 0, sizeof(wzaes->nonce)); /* Initialize for encryption using key 1 */ mz_crypt_aes_reset(wzaes->aes); mz_crypt_aes_set_encrypt_key(wzaes->aes, kbuf, key_length, NULL, 0); /* Initialize for authentication using key 2 */ mz_crypt_hmac_reset(wzaes->hmac); mz_crypt_hmac_set_algorithm(wzaes->hmac, MZ_HASH_SHA1); mz_crypt_hmac_init(wzaes->hmac, kbuf + key_length, key_length); memcpy(verify, kbuf + (2 * key_length), MZ_AES_PW_VERIFY_SIZE); if (mode & MZ_OPEN_MODE_WRITE) { if (mz_stream_write(wzaes->stream.base, salt_value, salt_length) != salt_length) return MZ_WRITE_ERROR; wzaes->total_out += salt_length; if (mz_stream_write(wzaes->stream.base, verify, MZ_AES_PW_VERIFY_SIZE) != MZ_AES_PW_VERIFY_SIZE) return MZ_WRITE_ERROR; wzaes->total_out += MZ_AES_PW_VERIFY_SIZE; } else if (mode & MZ_OPEN_MODE_READ) { wzaes->total_in += salt_length; if (mz_stream_read(wzaes->stream.base, verify_expected, MZ_AES_PW_VERIFY_SIZE) != MZ_AES_PW_VERIFY_SIZE) return MZ_READ_ERROR; wzaes->total_in += MZ_AES_PW_VERIFY_SIZE; if (memcmp(verify_expected, verify, MZ_AES_PW_VERIFY_SIZE) != 0) return MZ_PASSWORD_ERROR; } wzaes->mode = mode; wzaes->initialized = 1; return MZ_OK; } int32_t mz_stream_wzaes_is_open(void *stream) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; if (!wzaes->initialized) return MZ_OPEN_ERROR; return MZ_OK; } static int32_t mz_stream_wzaes_ctr_encrypt(void *stream, uint8_t *buf, int32_t size) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; uint32_t pos = wzaes->crypt_pos; uint32_t i = 0; int32_t err = MZ_OK; while (i < (uint32_t)size) { if (pos == MZ_AES_BLOCK_SIZE) { uint32_t j = 0; /* Increment encryption nonce */ while (j < 8 && !++wzaes->nonce[j]) j += 1; /* Encrypt the nonce using ECB mode to form next xor buffer */ memcpy(wzaes->crypt_block, wzaes->nonce, MZ_AES_BLOCK_SIZE); mz_crypt_aes_encrypt(wzaes->aes, NULL, 0, wzaes->crypt_block, sizeof(wzaes->crypt_block)); pos = 0; } buf[i++] ^= wzaes->crypt_block[pos++]; } wzaes->crypt_pos = pos; return err; } int32_t mz_stream_wzaes_read(void *stream, void *buf, int32_t size) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; int64_t max_total_in = 0; int32_t bytes_to_read = size; int32_t read = 0; max_total_in = wzaes->max_total_in - MZ_AES_FOOTER_SIZE; if ((int64_t)bytes_to_read > (max_total_in - wzaes->total_in)) bytes_to_read = (int32_t)(max_total_in - wzaes->total_in); read = mz_stream_read(wzaes->stream.base, buf, bytes_to_read); if (read > 0) { mz_crypt_hmac_update(wzaes->hmac, (uint8_t *)buf, read); mz_stream_wzaes_ctr_encrypt(stream, (uint8_t *)buf, read); wzaes->total_in += read; } return read; } int32_t mz_stream_wzaes_write(void *stream, const void *buf, int32_t size) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; const uint8_t *buf_ptr = (const uint8_t *)buf; int32_t bytes_to_write = sizeof(wzaes->buffer); int32_t total_written = 0; int32_t written = 0; if (size < 0) return MZ_PARAM_ERROR; do { if (bytes_to_write > (size - total_written)) bytes_to_write = (size - total_written); memcpy(wzaes->buffer, buf_ptr, bytes_to_write); buf_ptr += bytes_to_write; mz_stream_wzaes_ctr_encrypt(stream, (uint8_t *)wzaes->buffer, bytes_to_write); mz_crypt_hmac_update(wzaes->hmac, wzaes->buffer, bytes_to_write); written = mz_stream_write(wzaes->stream.base, wzaes->buffer, bytes_to_write); if (written < 0) return written; total_written += written; } while (total_written < size && written > 0); wzaes->total_out += total_written; return total_written; } int64_t mz_stream_wzaes_tell(void *stream) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; return mz_stream_tell(wzaes->stream.base); } int32_t mz_stream_wzaes_seek(void *stream, int64_t offset, int32_t origin) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; return mz_stream_seek(wzaes->stream.base, offset, origin); } int32_t mz_stream_wzaes_close(void *stream) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; uint8_t expected_hash[MZ_AES_AUTHCODE_SIZE]; uint8_t computed_hash[MZ_HASH_SHA1_SIZE]; mz_crypt_hmac_end(wzaes->hmac, computed_hash, sizeof(computed_hash)); if (wzaes->mode & MZ_OPEN_MODE_WRITE) { if (mz_stream_write(wzaes->stream.base, computed_hash, MZ_AES_AUTHCODE_SIZE) != MZ_AES_AUTHCODE_SIZE) return MZ_WRITE_ERROR; wzaes->total_out += MZ_AES_AUTHCODE_SIZE; } else if (wzaes->mode & MZ_OPEN_MODE_READ) { if (mz_stream_read(wzaes->stream.base, expected_hash, MZ_AES_AUTHCODE_SIZE) != MZ_AES_AUTHCODE_SIZE) return MZ_READ_ERROR; wzaes->total_in += MZ_AES_AUTHCODE_SIZE; /* If entire entry was not read this will fail */ if (memcmp(computed_hash, expected_hash, MZ_AES_AUTHCODE_SIZE) != 0) return MZ_CRC_ERROR; } wzaes->initialized = 0; return MZ_OK; } int32_t mz_stream_wzaes_error(void *stream) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; return wzaes->error; } void mz_stream_wzaes_set_password(void *stream, const char *password) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; wzaes->password = password; } void mz_stream_wzaes_set_strength(void *stream, uint8_t strength) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; wzaes->strength = strength; } int32_t mz_stream_wzaes_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN: *value = wzaes->total_in; break; case MZ_STREAM_PROP_TOTAL_OUT: *value = wzaes->total_out; break; case MZ_STREAM_PROP_TOTAL_IN_MAX: *value = wzaes->max_total_in; break; case MZ_STREAM_PROP_HEADER_SIZE: *value = MZ_AES_SALT_LENGTH((int64_t)wzaes->strength) + MZ_AES_PW_VERIFY_SIZE; break; case MZ_STREAM_PROP_FOOTER_SIZE: *value = MZ_AES_AUTHCODE_SIZE; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } int32_t mz_stream_wzaes_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN_MAX: wzaes->max_total_in = value; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } void *mz_stream_wzaes_create(void) { mz_stream_wzaes *wzaes = (mz_stream_wzaes *)calloc(1, sizeof(mz_stream_wzaes)); if (wzaes) { wzaes->stream.vtbl = &mz_stream_wzaes_vtbl; wzaes->strength = MZ_AES_STRENGTH_256; wzaes->hmac = mz_crypt_hmac_create(); if (!wzaes->hmac) { free(wzaes); return NULL; } wzaes->aes = mz_crypt_aes_create(); if (!wzaes->aes) { mz_crypt_hmac_delete(&wzaes->hmac); free(wzaes); return NULL; } } return wzaes; } void mz_stream_wzaes_delete(void **stream) { mz_stream_wzaes *wzaes = NULL; if (!stream) return; wzaes = (mz_stream_wzaes *)*stream; if (wzaes) { mz_crypt_aes_delete(&wzaes->aes); mz_crypt_hmac_delete(&wzaes->hmac); free(wzaes); } *stream = NULL; } void *mz_stream_wzaes_get_interface(void) { return (void *)&mz_stream_wzaes_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_wzaes.h000066400000000000000000000030121450532053500212720ustar00rootroot00000000000000/* mz_strm_wzaes.h -- Stream for WinZIP AES encryption part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_WZAES_SHA1_H #define MZ_STREAM_WZAES_SHA1_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_wzaes_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_wzaes_is_open(void *stream); int32_t mz_stream_wzaes_read(void *stream, void *buf, int32_t size); int32_t mz_stream_wzaes_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_wzaes_tell(void *stream); int32_t mz_stream_wzaes_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_wzaes_close(void *stream); int32_t mz_stream_wzaes_error(void *stream); void mz_stream_wzaes_set_password(void *stream, const char *password); void mz_stream_wzaes_set_strength(void *stream, uint8_t strength); int32_t mz_stream_wzaes_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_wzaes_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_wzaes_create(void); void mz_stream_wzaes_delete(void **stream); void* mz_stream_wzaes_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_zlib.c000066400000000000000000000237431450532053500211110ustar00rootroot00000000000000/* mz_strm_zlib.c -- Stream for zlib inflate/deflate part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_strm.h" #include "mz_strm_zlib.h" #if !defined(ZLIB_COMPAT) # include "zlib-ng.h" #else # include "zlib.h" #endif /***************************************************************************/ #if !defined(ZLIB_COMPAT) # define ZLIB_PREFIX(x) zng_ ## x typedef zng_stream zlib_stream; #else # define ZLIB_PREFIX(x) x typedef z_stream zlib_stream; #endif #if !defined(DEF_MEM_LEVEL) # if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 # else # define DEF_MEM_LEVEL MAX_MEM_LEVEL # endif #endif /***************************************************************************/ static mz_stream_vtbl mz_stream_zlib_vtbl = { mz_stream_zlib_open, mz_stream_zlib_is_open, mz_stream_zlib_read, mz_stream_zlib_write, mz_stream_zlib_tell, mz_stream_zlib_seek, mz_stream_zlib_close, mz_stream_zlib_error, mz_stream_zlib_create, mz_stream_zlib_delete, mz_stream_zlib_get_prop_int64, mz_stream_zlib_set_prop_int64 }; /***************************************************************************/ typedef struct mz_stream_zlib_s { mz_stream stream; zlib_stream zstream; uint8_t buffer[INT16_MAX]; int32_t buffer_len; int64_t total_in; int64_t total_out; int64_t max_total_in; int8_t initialized; int16_t level; int32_t window_bits; int32_t mode; int32_t error; } mz_stream_zlib; /***************************************************************************/ int32_t mz_stream_zlib_open(void *stream, const char *path, int32_t mode) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; MZ_UNUSED(path); zlib->zstream.data_type = Z_BINARY; zlib->zstream.zalloc = Z_NULL; zlib->zstream.zfree = Z_NULL; zlib->zstream.opaque = Z_NULL; zlib->zstream.total_in = 0; zlib->zstream.total_out = 0; zlib->total_in = 0; zlib->total_out = 0; if (mode & MZ_OPEN_MODE_WRITE) { #ifdef MZ_ZIP_NO_COMPRESSION return MZ_SUPPORT_ERROR; #else zlib->zstream.next_out = zlib->buffer; zlib->zstream.avail_out = sizeof(zlib->buffer); zlib->error = ZLIB_PREFIX(deflateInit2)(&zlib->zstream, (int8_t)zlib->level, Z_DEFLATED, zlib->window_bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); #endif } else if (mode & MZ_OPEN_MODE_READ) { #ifdef MZ_ZIP_NO_DECOMPRESSION return MZ_SUPPORT_ERROR; #else zlib->zstream.next_in = zlib->buffer; zlib->zstream.avail_in = 0; zlib->error = ZLIB_PREFIX(inflateInit2)(&zlib->zstream, zlib->window_bits); #endif } if (zlib->error != Z_OK) return MZ_OPEN_ERROR; zlib->initialized = 1; zlib->mode = mode; return MZ_OK; } int32_t mz_stream_zlib_is_open(void *stream) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; if (zlib->initialized != 1) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size) { #ifdef MZ_ZIP_NO_DECOMPRESSION MZ_UNUSED(stream); MZ_UNUSED(buf); MZ_UNUSED(size); return MZ_SUPPORT_ERROR; #else mz_stream_zlib *zlib = (mz_stream_zlib *)stream; uint64_t total_in_before = 0; uint64_t total_in_after = 0; uint64_t total_out_before = 0; uint64_t total_out_after = 0; uint32_t total_in = 0; uint32_t total_out = 0; uint32_t in_bytes = 0; uint32_t out_bytes = 0; int32_t bytes_to_read = sizeof(zlib->buffer); int32_t read = 0; int32_t err = Z_OK; zlib->zstream.next_out = (Bytef *)buf; zlib->zstream.avail_out = (uInt)size; do { if (zlib->zstream.avail_in == 0) { if (zlib->max_total_in > 0) { if ((int64_t)bytes_to_read > (zlib->max_total_in - zlib->total_in)) bytes_to_read = (int32_t)(zlib->max_total_in - zlib->total_in); } read = mz_stream_read(zlib->stream.base, zlib->buffer, bytes_to_read); if (read < 0) return read; zlib->zstream.next_in = zlib->buffer; zlib->zstream.avail_in = read; } total_in_before = zlib->zstream.avail_in; total_out_before = zlib->zstream.total_out; err = ZLIB_PREFIX(inflate)(&zlib->zstream, Z_SYNC_FLUSH); if ((err >= Z_OK) && (zlib->zstream.msg)) { zlib->error = Z_DATA_ERROR; break; } total_in_after = zlib->zstream.avail_in; total_out_after = zlib->zstream.total_out; in_bytes = (uint32_t)(total_in_before - total_in_after); out_bytes = (uint32_t)(total_out_after - total_out_before); total_in += in_bytes; total_out += out_bytes; zlib->total_in += in_bytes; zlib->total_out += out_bytes; if (err == Z_STREAM_END) break; if (err != Z_OK) { zlib->error = err; break; } } while (zlib->zstream.avail_out > 0); MZ_UNUSED(total_in); if (zlib->error != 0) { /* Zlib errors are compatible with MZ */ return zlib->error; } return total_out; #endif } #ifndef MZ_ZIP_NO_COMPRESSION static int32_t mz_stream_zlib_flush(void *stream) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; if (mz_stream_write(zlib->stream.base, zlib->buffer, zlib->buffer_len) != zlib->buffer_len) return MZ_WRITE_ERROR; return MZ_OK; } static int32_t mz_stream_zlib_deflate(void *stream, int flush) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; uint64_t total_out_before = 0; uint64_t total_out_after = 0; int32_t out_bytes = 0; int32_t err = Z_OK; do { if (zlib->zstream.avail_out == 0) { err = mz_stream_zlib_flush(zlib); if (err != MZ_OK) return err; zlib->zstream.avail_out = sizeof(zlib->buffer); zlib->zstream.next_out = zlib->buffer; zlib->buffer_len = 0; } total_out_before = zlib->zstream.total_out; err = ZLIB_PREFIX(deflate)(&zlib->zstream, flush); total_out_after = zlib->zstream.total_out; out_bytes = (uint32_t)(total_out_after - total_out_before); zlib->buffer_len += out_bytes; zlib->total_out += out_bytes; if (err == Z_STREAM_END) break; if (err != Z_OK) { zlib->error = err; return MZ_DATA_ERROR; } } while ((zlib->zstream.avail_in > 0) || (flush == Z_FINISH && err == Z_OK)); return MZ_OK; } #endif int32_t mz_stream_zlib_write(void *stream, const void *buf, int32_t size) { #ifdef MZ_ZIP_NO_COMPRESSION MZ_UNUSED(stream); MZ_UNUSED(buf); MZ_UNUSED(size); return MZ_SUPPORT_ERROR; #else mz_stream_zlib *zlib = (mz_stream_zlib *)stream; int32_t err = MZ_OK; zlib->zstream.next_in = (Bytef *)(intptr_t)buf; zlib->zstream.avail_in = (uInt)size; err = mz_stream_zlib_deflate(stream, Z_NO_FLUSH); if (err != MZ_OK) { return err; } zlib->total_in += size; return size; #endif } int64_t mz_stream_zlib_tell(void *stream) { MZ_UNUSED(stream); return MZ_TELL_ERROR; } int32_t mz_stream_zlib_seek(void *stream, int64_t offset, int32_t origin) { MZ_UNUSED(stream); MZ_UNUSED(offset); MZ_UNUSED(origin); return MZ_SEEK_ERROR; } int32_t mz_stream_zlib_close(void *stream) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; if (zlib->mode & MZ_OPEN_MODE_WRITE) { #ifdef MZ_ZIP_NO_COMPRESSION return MZ_SUPPORT_ERROR; #else mz_stream_zlib_deflate(stream, Z_FINISH); mz_stream_zlib_flush(stream); ZLIB_PREFIX(deflateEnd)(&zlib->zstream); #endif } else if (zlib->mode & MZ_OPEN_MODE_READ) { #ifdef MZ_ZIP_NO_DECOMPRESSION return MZ_SUPPORT_ERROR; #else ZLIB_PREFIX(inflateEnd)(&zlib->zstream); #endif } zlib->initialized = 0; if (zlib->error != Z_OK) return MZ_CLOSE_ERROR; return MZ_OK; } int32_t mz_stream_zlib_error(void *stream) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; return zlib->error; } int32_t mz_stream_zlib_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN: *value = zlib->total_in; break; case MZ_STREAM_PROP_TOTAL_IN_MAX: *value = zlib->max_total_in; break; case MZ_STREAM_PROP_TOTAL_OUT: *value = zlib->total_out; break; case MZ_STREAM_PROP_HEADER_SIZE: *value = 0; break; case MZ_STREAM_PROP_COMPRESS_WINDOW: *value = zlib->window_bits; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream_zlib *zlib = (mz_stream_zlib *)stream; switch (prop) { case MZ_STREAM_PROP_COMPRESS_LEVEL: zlib->level = (int16_t)value; break; case MZ_STREAM_PROP_TOTAL_IN_MAX: zlib->max_total_in = value; break; case MZ_STREAM_PROP_COMPRESS_WINDOW: zlib->window_bits = (int32_t)value; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } void *mz_stream_zlib_create(void) { mz_stream_zlib *zlib = zlib = (mz_stream_zlib *)calloc(1, sizeof(mz_stream_zlib)); if (zlib) { zlib->stream.vtbl = &mz_stream_zlib_vtbl; zlib->level = Z_DEFAULT_COMPRESSION; zlib->window_bits = -MAX_WBITS; } return zlib; } void mz_stream_zlib_delete(void **stream) { mz_stream_zlib *zlib = NULL; if (!stream) return; zlib = (mz_stream_zlib *)*stream; if (zlib) free(zlib); *stream = NULL; } void *mz_stream_zlib_get_interface(void) { return (void *)&mz_stream_zlib_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_zlib.h000066400000000000000000000025361450532053500211130ustar00rootroot00000000000000/* mz_strm_zlib.h -- Stream for zlib inflate/deflate part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_ZLIB_H #define MZ_STREAM_ZLIB_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_zlib_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_zlib_is_open(void *stream); int32_t mz_stream_zlib_read(void *stream, void *buf, int32_t size); int32_t mz_stream_zlib_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_zlib_tell(void *stream); int32_t mz_stream_zlib_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_zlib_close(void *stream); int32_t mz_stream_zlib_error(void *stream); int32_t mz_stream_zlib_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_zlib_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_zlib_create(void); void mz_stream_zlib_delete(void **stream); void* mz_stream_zlib_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_strm_zstd.c000066400000000000000000000223461450532053500211330ustar00rootroot00000000000000/* mz_strm_zstd.c -- Stream for zstd compress/decompress part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Authors: Force Charlie https://github.com/fcharlie This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_strm.h" #include "mz_strm_zstd.h" #include /***************************************************************************/ static mz_stream_vtbl mz_stream_zstd_vtbl = { mz_stream_zstd_open, mz_stream_zstd_is_open, mz_stream_zstd_read, mz_stream_zstd_write, mz_stream_zstd_tell, mz_stream_zstd_seek, mz_stream_zstd_close, mz_stream_zstd_error, mz_stream_zstd_create, mz_stream_zstd_delete, mz_stream_zstd_get_prop_int64, mz_stream_zstd_set_prop_int64 }; /***************************************************************************/ typedef struct mz_stream_zstd_s { mz_stream stream; ZSTD_CStream *zcstream; ZSTD_DStream *zdstream; ZSTD_outBuffer out; ZSTD_inBuffer in; int32_t mode; int32_t error; uint8_t buffer[INT16_MAX]; int32_t buffer_len; int64_t total_in; int64_t total_out; int64_t max_total_in; int64_t max_total_out; int8_t initialized; uint32_t preset; } mz_stream_zstd; /***************************************************************************/ int32_t mz_stream_zstd_open(void *stream, const char *path, int32_t mode) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; MZ_UNUSED(path); if (mode & MZ_OPEN_MODE_WRITE) { #ifdef MZ_ZIP_NO_COMPRESSION return MZ_SUPPORT_ERROR; #else zstd->zcstream = ZSTD_createCStream(); zstd->out.dst = zstd->buffer; zstd->out.size = sizeof(zstd->buffer); zstd->out.pos = 0; ZSTD_CCtx_setParameter(zstd->zcstream, ZSTD_c_compressionLevel, zstd->preset); #endif } else if (mode & MZ_OPEN_MODE_READ) { #ifdef MZ_ZIP_NO_DECOMPRESSION return MZ_SUPPORT_ERROR; #else zstd->zdstream = ZSTD_createDStream(); memset(&zstd->out, 0, sizeof(ZSTD_outBuffer)); #endif } memset(&zstd->in, 0, sizeof(ZSTD_inBuffer)); zstd->initialized = 1; zstd->mode = mode; zstd->error = MZ_OK; return MZ_OK; } int32_t mz_stream_zstd_is_open(void *stream) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; if (zstd->initialized != 1) return MZ_OPEN_ERROR; return MZ_OK; } int32_t mz_stream_zstd_read(void *stream, void *buf, int32_t size) { #ifdef MZ_ZIP_NO_DECOMPRESSION MZ_UNUSED(stream); MZ_UNUSED(buf); MZ_UNUSED(size); return MZ_SUPPORT_ERROR; #else mz_stream_zstd *zstd = (mz_stream_zstd *)stream; uint64_t total_in_before = 0; uint64_t total_in_after = 0; uint64_t total_out_before = 0; uint64_t total_out_after = 0; int32_t total_in = 0; int32_t total_out = 0; int32_t in_bytes = 0; int32_t out_bytes = 0; int32_t bytes_to_read = sizeof(zstd->buffer); int32_t read = 0; size_t result = 0; zstd->out.dst = (void *)buf; zstd->out.size = (size_t)size; zstd->out.pos = 0; do { if (zstd->in.pos == zstd->in.size) { if (zstd->max_total_in > 0) { if ((int64_t)bytes_to_read > (zstd->max_total_in - zstd->total_in)) bytes_to_read = (int32_t)(zstd->max_total_in - zstd->total_in); } read = mz_stream_read(zstd->stream.base, zstd->buffer, bytes_to_read); if (read < 0) return read; zstd->in.src = (const void *)zstd->buffer; zstd->in.pos = 0; zstd->in.size = (size_t)read; } total_in_before = zstd->in.pos; total_out_before = zstd->out.pos; result = ZSTD_decompressStream(zstd->zdstream, &zstd->out, &zstd->in); if (ZSTD_isError(result)) { zstd->error = (int32_t)result; return MZ_DATA_ERROR; } total_in_after = zstd->in.pos; total_out_after = zstd->out.pos; if ((zstd->max_total_out != -1) && (int64_t)total_out_after > zstd->max_total_out) total_out_after = (uint64_t)zstd->max_total_out; in_bytes = (int32_t)(total_in_after - total_in_before); out_bytes = (int32_t)(total_out_after - total_out_before); total_in += in_bytes; total_out += out_bytes; zstd->total_in += in_bytes; zstd->total_out += out_bytes; } while ((zstd->in.size > 0 || out_bytes > 0) && (zstd->out.pos < zstd->out.size)); return total_out; #endif } #ifndef MZ_ZIP_NO_COMPRESSION static int32_t mz_stream_zstd_flush(void *stream) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; if (mz_stream_write(zstd->stream.base, zstd->buffer, zstd->buffer_len) != zstd->buffer_len) return MZ_WRITE_ERROR; return MZ_OK; } static int32_t mz_stream_zstd_compress(void *stream, ZSTD_EndDirective flush) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; uint64_t total_out_before = 0; uint64_t total_out_after = 0; int32_t out_bytes = 0; size_t result = 0; int32_t err = 0; do { if (zstd->out.pos == zstd->out.size) { err = mz_stream_zstd_flush(zstd); if (err != MZ_OK) return err; zstd->out.dst = zstd->buffer; zstd->out.size = sizeof(zstd->buffer); zstd->out.pos = 0; zstd->buffer_len = 0; } total_out_before = zstd->out.pos; result = ZSTD_compressStream2(zstd->zcstream, &zstd->out, &zstd->in, flush); total_out_after = zstd->out.pos; out_bytes = (uint32_t)(total_out_after - total_out_before); zstd->buffer_len += out_bytes; zstd->total_out += out_bytes; if (ZSTD_isError(result)) { zstd->error = (int32_t)result; return MZ_DATA_ERROR; } } while ((zstd->in.pos < zstd->in.size) || (flush == ZSTD_e_end && result != 0)); return MZ_OK; } #endif int32_t mz_stream_zstd_write(void *stream, const void *buf, int32_t size) { #ifdef MZ_ZIP_NO_COMPRESSION MZ_UNUSED(stream); MZ_UNUSED(buf); MZ_UNUSED(size); return MZ_SUPPORT_ERROR; #else mz_stream_zstd *zstd = (mz_stream_zstd *)stream; int32_t err = MZ_OK; zstd->in.src = buf; zstd->in.pos = 0; zstd->in.size = size; err = mz_stream_zstd_compress(stream, ZSTD_e_continue); if (err != MZ_OK) { return err; } zstd->total_in += size; return size; #endif } int64_t mz_stream_zstd_tell(void *stream) { MZ_UNUSED(stream); return MZ_TELL_ERROR; } int32_t mz_stream_zstd_seek(void *stream, int64_t offset, int32_t origin) { MZ_UNUSED(stream); MZ_UNUSED(offset); MZ_UNUSED(origin); return MZ_SEEK_ERROR; } int32_t mz_stream_zstd_close(void *stream) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; if (zstd->mode & MZ_OPEN_MODE_WRITE) { #ifdef MZ_ZIP_NO_COMPRESSION return MZ_SUPPORT_ERROR; #else mz_stream_zstd_compress(stream, ZSTD_e_end); mz_stream_zstd_flush(stream); ZSTD_freeCStream(zstd->zcstream); zstd->zcstream = NULL; #endif } else if (zstd->mode & MZ_OPEN_MODE_READ) { #ifdef MZ_ZIP_NO_DECOMPRESSION return MZ_SUPPORT_ERROR; #else ZSTD_freeDStream(zstd->zdstream); zstd->zdstream = NULL; #endif } zstd->initialized = 0; return MZ_OK; } int32_t mz_stream_zstd_error(void *stream) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; return zstd->error; } int32_t mz_stream_zstd_get_prop_int64(void *stream, int32_t prop, int64_t *value) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; switch (prop) { case MZ_STREAM_PROP_TOTAL_IN: *value = zstd->total_in; break; case MZ_STREAM_PROP_TOTAL_IN_MAX: *value = zstd->max_total_in; break; case MZ_STREAM_PROP_TOTAL_OUT: *value = zstd->total_out; break; case MZ_STREAM_PROP_TOTAL_OUT_MAX: *value = zstd->max_total_out; break; case MZ_STREAM_PROP_HEADER_SIZE: *value = 0; break; default: return MZ_EXIST_ERROR; } return MZ_OK; } int32_t mz_stream_zstd_set_prop_int64(void *stream, int32_t prop, int64_t value) { mz_stream_zstd *zstd = (mz_stream_zstd *)stream; switch (prop) { case MZ_STREAM_PROP_COMPRESS_LEVEL: if (value < 0) zstd->preset = 6; else zstd->preset = (int16_t)value; return MZ_OK; case MZ_STREAM_PROP_TOTAL_IN_MAX: zstd->max_total_in = value; return MZ_OK; } return MZ_EXIST_ERROR; } void *mz_stream_zstd_create(void) { mz_stream_zstd *zstd = (mz_stream_zstd *)calloc(1, sizeof(mz_stream_zstd)); if (zstd) { zstd->stream.vtbl = &mz_stream_zstd_vtbl; zstd->max_total_out = -1; } return zstd; } void mz_stream_zstd_delete(void **stream) { mz_stream_zstd *zstd = NULL; if (!stream) return; zstd = (mz_stream_zstd *)*stream; if (zstd) free(zstd); *stream = NULL; } void *mz_stream_zstd_get_interface(void) { return (void *)&mz_stream_zstd_vtbl; } sight-23.1.0/3rd-party/minizip/mz_strm_zstd.h000066400000000000000000000026021450532053500211310ustar00rootroot00000000000000/* mz_strm_zlib.h -- Stream for zlib inflate/deflate Version 2.9.2, February 12, 2020 part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_STREAM_ZSTD_H #define MZ_STREAM_ZSTD_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ int32_t mz_stream_zstd_open(void *stream, const char *filename, int32_t mode); int32_t mz_stream_zstd_is_open(void *stream); int32_t mz_stream_zstd_read(void *stream, void *buf, int32_t size); int32_t mz_stream_zstd_write(void *stream, const void *buf, int32_t size); int64_t mz_stream_zstd_tell(void *stream); int32_t mz_stream_zstd_seek(void *stream, int64_t offset, int32_t origin); int32_t mz_stream_zstd_close(void *stream); int32_t mz_stream_zstd_error(void *stream); int32_t mz_stream_zstd_get_prop_int64(void *stream, int32_t prop, int64_t *value); int32_t mz_stream_zstd_set_prop_int64(void *stream, int32_t prop, int64_t value); void* mz_stream_zstd_create(void); void mz_stream_zstd_delete(void **stream); void* mz_stream_zstd_get_interface(void); /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/mz_zip.c000066400000000000000000003127211450532053500177030ustar00rootroot00000000000000/* zip.c -- Zip manipulation part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 2009-2010 Mathias Svensson Modifications for Zip64 support http://result42.com Copyright (C) 2007-2008 Even Rouault Modifications of Unzip for Zip64 Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_crypt.h" #include "mz_strm.h" #ifdef HAVE_BZIP2 # include "mz_strm_bzip.h" #endif #ifdef HAVE_LIBCOMP # include "mz_strm_libcomp.h" #endif #ifdef HAVE_LZMA # include "mz_strm_lzma.h" #endif #include "mz_strm_mem.h" #ifdef HAVE_PKCRYPT # include "mz_strm_pkcrypt.h" #endif #ifdef HAVE_WZAES # include "mz_strm_wzaes.h" #endif #ifdef HAVE_ZLIB # include "mz_strm_zlib.h" #endif #ifdef HAVE_ZSTD # include "mz_strm_zstd.h" #endif #include "mz_zip.h" #include /* tolower */ #include /* snprintf */ #if defined(_MSC_VER) || defined(__MINGW32__) # define localtime_r(t1, t2) (localtime_s(t2, t1) == 0 ? t1 : NULL) #endif #if defined(_MSC_VER) && (_MSC_VER < 1900) # define snprintf _snprintf #endif /***************************************************************************/ #define MZ_ZIP_MAGIC_LOCALHEADER (0x04034b50) #define MZ_ZIP_MAGIC_LOCALHEADERU8 { 0x50, 0x4b, 0x03, 0x04 } #define MZ_ZIP_MAGIC_CENTRALHEADER (0x02014b50) #define MZ_ZIP_MAGIC_CENTRALHEADERU8 { 0x50, 0x4b, 0x01, 0x02 } #define MZ_ZIP_MAGIC_ENDHEADER (0x06054b50) #define MZ_ZIP_MAGIC_ENDHEADERU8 { 0x50, 0x4b, 0x05, 0x06 } #define MZ_ZIP_MAGIC_ENDHEADER64 (0x06064b50) #define MZ_ZIP_MAGIC_ENDLOCHEADER64 (0x07064b50) #define MZ_ZIP_MAGIC_DATADESCRIPTOR (0x08074b50) #define MZ_ZIP_MAGIC_DATADESCRIPTORU8 { 0x50, 0x4b, 0x07, 0x08 } #define MZ_ZIP_SIZE_LD_ITEM (30) #define MZ_ZIP_SIZE_CD_ITEM (46) #define MZ_ZIP_SIZE_CD_LOCATOR64 (20) #define MZ_ZIP_SIZE_MAX_DATA_DESCRIPTOR (24) #define MZ_ZIP_OFFSET_CRC_SIZES (14) #define MZ_ZIP_UNCOMPR_SIZE64_CUSHION (2 * 1024 * 1024) #ifndef MZ_ZIP_EOCD_MAX_BACK #define MZ_ZIP_EOCD_MAX_BACK (1 << 20) #endif /***************************************************************************/ typedef struct mz_zip_s { mz_zip_file file_info; mz_zip_file local_file_info; void *stream; /* main stream */ void *cd_stream; /* pointer to the stream with the cd */ void *cd_mem_stream; /* memory stream for central directory */ void *compress_stream; /* compression stream */ void *crypt_stream; /* encryption stream */ void *file_info_stream; /* memory stream for storing file info */ void *local_file_info_stream; /* memory stream for storing local file info */ int32_t open_mode; uint8_t recover; uint8_t data_descriptor; uint32_t disk_number_with_cd; /* number of the disk with the central dir */ int64_t disk_offset_shift; /* correction for zips that have wrong offset start of cd */ int64_t cd_start_pos; /* pos of the first file in the central dir stream */ int64_t cd_current_pos; /* pos of the current file in the central dir */ int64_t cd_offset; /* offset of start of central directory */ int64_t cd_size; /* size of the central directory */ uint32_t cd_signature; /* signature of central directory */ uint8_t entry_scanned; /* entry header information read ok */ uint8_t entry_opened; /* entry is open for read/write */ uint8_t entry_raw; /* entry opened with raw mode */ uint32_t entry_crc32; /* entry crc32 */ uint64_t number_entry; uint16_t version_madeby; char *comment; } mz_zip; /***************************************************************************/ #if 0 # define mz_zip_print printf #else # define mz_zip_print(fmt, ...) #endif /***************************************************************************/ /* Locate the end of central directory */ static int32_t mz_zip_search_eocd(void *stream, int64_t *central_pos) { int64_t file_size = 0; int64_t max_back = MZ_ZIP_EOCD_MAX_BACK; uint8_t find[4] = MZ_ZIP_MAGIC_ENDHEADERU8; int32_t err = MZ_OK; err = mz_stream_seek(stream, 0, MZ_SEEK_END); if (err != MZ_OK) return err; file_size = mz_stream_tell(stream); if (max_back <= 0 || max_back > file_size) max_back = file_size; return mz_stream_find_reverse(stream, (const void *)find, sizeof(find), max_back, central_pos); } /* Locate the end of central directory 64 of a zip file */ static int32_t mz_zip_search_zip64_eocd(void *stream, const int64_t end_central_offset, int64_t *central_pos) { int64_t offset = 0; uint32_t value32 = 0; int32_t err = MZ_OK; *central_pos = 0; /* Zip64 end of central directory locator */ err = mz_stream_seek(stream, end_central_offset - MZ_ZIP_SIZE_CD_LOCATOR64, MZ_SEEK_SET); /* Read locator signature */ if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &value32); if (value32 != MZ_ZIP_MAGIC_ENDLOCHEADER64) err = MZ_FORMAT_ERROR; } /* Number of the disk with the start of the zip64 end of central directory */ if (err == MZ_OK) err = mz_stream_read_uint32(stream, &value32); /* Relative offset of the zip64 end of central directory record8 */ if (err == MZ_OK) err = mz_stream_read_uint64(stream, (uint64_t *)&offset); /* Total number of disks */ if (err == MZ_OK) err = mz_stream_read_uint32(stream, &value32); /* Goto end of central directory record */ if (err == MZ_OK) err = mz_stream_seek(stream, (int64_t)offset, MZ_SEEK_SET); /* The signature */ if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &value32); if (value32 != MZ_ZIP_MAGIC_ENDHEADER64) err = MZ_FORMAT_ERROR; } if (err == MZ_OK) *central_pos = offset; return err; } #ifdef HAVE_PKCRYPT /* Get PKWARE traditional encryption verifier */ static uint16_t mz_zip_get_pk_verify(uint32_t dos_date, uint64_t crc, uint16_t flag) { /* Info-ZIP modification to ZipCrypto format: if bit 3 of the general * purpose bit flag is set, it uses high byte of 16-bit File Time. */ if (flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) return ((dos_date >> 16) & 0xff) << 8 | ((dos_date >> 8) & 0xff); return ((crc >> 16) & 0xff) << 8 | ((crc >> 24) & 0xff); } #endif /* Get info about the current file in the zip file */ static int32_t mz_zip_entry_read_header(void *stream, uint8_t local, mz_zip_file *file_info, void *file_extra_stream) { uint64_t ntfs_time = 0; uint32_t reserved = 0; uint32_t magic = 0; uint32_t dos_date = 0; uint32_t field_pos = 0; uint16_t field_type = 0; uint16_t field_length = 0; uint32_t field_length_read = 0; uint16_t ntfs_attrib_id = 0; uint16_t ntfs_attrib_size = 0; uint16_t linkname_size; uint16_t value16 = 0; uint32_t value32 = 0; int64_t extrafield_pos = 0; int64_t comment_pos = 0; int64_t linkname_pos = 0; int64_t saved_pos = 0; int32_t err = MZ_OK; char *linkname = NULL; memset(file_info, 0, sizeof(mz_zip_file)); /* Check the magic */ err = mz_stream_read_uint32(stream, &magic); if (err == MZ_END_OF_STREAM) err = MZ_END_OF_LIST; else if (magic == MZ_ZIP_MAGIC_ENDHEADER || magic == MZ_ZIP_MAGIC_ENDHEADER64) err = MZ_END_OF_LIST; else if ((local) && (magic != MZ_ZIP_MAGIC_LOCALHEADER)) err = MZ_FORMAT_ERROR; else if ((!local) && (magic != MZ_ZIP_MAGIC_CENTRALHEADER)) err = MZ_FORMAT_ERROR; /* Read header fields */ if (err == MZ_OK) { if (!local) err = mz_stream_read_uint16(stream, &file_info->version_madeby); if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->version_needed); if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->flag); if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->compression_method); if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &dos_date); file_info->modified_date = mz_zip_dosdate_to_time_t(dos_date); } if (err == MZ_OK) err = mz_stream_read_uint32(stream, &file_info->crc); #ifdef HAVE_PKCRYPT if (err == MZ_OK && file_info->flag & MZ_ZIP_FLAG_ENCRYPTED) { /* Use dos_date from header instead of derived from time in zip extensions */ file_info->pk_verify = mz_zip_get_pk_verify(dos_date, file_info->crc, file_info->flag); } #endif if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &value32); file_info->compressed_size = value32; } if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &value32); file_info->uncompressed_size = value32; } if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->filename_size); if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->extrafield_size); if (!local) { if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->comment_size); if (err == MZ_OK) { err = mz_stream_read_uint16(stream, &value16); file_info->disk_number = value16; } if (err == MZ_OK) err = mz_stream_read_uint16(stream, &file_info->internal_fa); if (err == MZ_OK) err = mz_stream_read_uint32(stream, &file_info->external_fa); if (err == MZ_OK) { err = mz_stream_read_uint32(stream, &value32); file_info->disk_offset = value32; } } } if (err == MZ_OK) err = mz_stream_seek(file_extra_stream, 0, MZ_SEEK_SET); /* Copy variable length data to memory stream for later retrieval */ if ((err == MZ_OK) && (file_info->filename_size > 0)) err = mz_stream_copy(file_extra_stream, stream, file_info->filename_size); mz_stream_write_uint8(file_extra_stream, 0); extrafield_pos = mz_stream_tell(file_extra_stream); if ((err == MZ_OK) && (file_info->extrafield_size > 0)) err = mz_stream_copy(file_extra_stream, stream, file_info->extrafield_size); mz_stream_write_uint8(file_extra_stream, 0); comment_pos = mz_stream_tell(file_extra_stream); if ((err == MZ_OK) && (file_info->comment_size > 0)) err = mz_stream_copy(file_extra_stream, stream, file_info->comment_size); mz_stream_write_uint8(file_extra_stream, 0); linkname_pos = mz_stream_tell(file_extra_stream); /* Overwrite if we encounter UNIX1 extra block */ mz_stream_write_uint8(file_extra_stream, 0); if ((err == MZ_OK) && (file_info->extrafield_size > 0)) { /* Seek to and parse the extra field */ err = mz_stream_seek(file_extra_stream, extrafield_pos, MZ_SEEK_SET); while ((err == MZ_OK) && (field_pos + 4 <= file_info->extrafield_size)) { err = mz_zip_extrafield_read(file_extra_stream, &field_type, &field_length); if (err != MZ_OK) break; field_pos += 4; /* Don't allow field length to exceed size of remaining extrafield */ if (field_length > (file_info->extrafield_size - field_pos)) field_length = (uint16_t)(file_info->extrafield_size - field_pos); /* Read ZIP64 extra field */ if ((field_type == MZ_ZIP_EXTENSION_ZIP64) && (field_length >= 8)) { if ((err == MZ_OK) && (file_info->uncompressed_size == UINT32_MAX)) { err = mz_stream_read_int64(file_extra_stream, &file_info->uncompressed_size); if (file_info->uncompressed_size < 0) err = MZ_FORMAT_ERROR; } if ((err == MZ_OK) && (file_info->compressed_size == UINT32_MAX)) { err = mz_stream_read_int64(file_extra_stream, &file_info->compressed_size); if (file_info->compressed_size < 0) err = MZ_FORMAT_ERROR; } if ((err == MZ_OK) && (file_info->disk_offset == UINT32_MAX)) { err = mz_stream_read_int64(file_extra_stream, &file_info->disk_offset); if (file_info->disk_offset < 0) err = MZ_FORMAT_ERROR; } if ((err == MZ_OK) && (file_info->disk_number == UINT16_MAX)) err = mz_stream_read_uint32(file_extra_stream, &file_info->disk_number); } /* Read NTFS extra field */ else if ((field_type == MZ_ZIP_EXTENSION_NTFS) && (field_length > 4)) { if (err == MZ_OK) err = mz_stream_read_uint32(file_extra_stream, &reserved); field_length_read = 4; while ((err == MZ_OK) && (field_length_read + 4 <= field_length)) { err = mz_stream_read_uint16(file_extra_stream, &ntfs_attrib_id); if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &ntfs_attrib_size); field_length_read += 4; if ((err == MZ_OK) && (ntfs_attrib_id == 0x01) && (ntfs_attrib_size == 24)) { err = mz_stream_read_uint64(file_extra_stream, &ntfs_time); mz_zip_ntfs_to_unix_time(ntfs_time, &file_info->modified_date); if (err == MZ_OK) { err = mz_stream_read_uint64(file_extra_stream, &ntfs_time); mz_zip_ntfs_to_unix_time(ntfs_time, &file_info->accessed_date); } if (err == MZ_OK) { err = mz_stream_read_uint64(file_extra_stream, &ntfs_time); mz_zip_ntfs_to_unix_time(ntfs_time, &file_info->creation_date); } } else if ((err == MZ_OK) && (field_length_read + ntfs_attrib_size <= field_length)) { err = mz_stream_seek(file_extra_stream, ntfs_attrib_size, MZ_SEEK_CUR); } field_length_read += ntfs_attrib_size; } } /* Read UNIX1 extra field */ else if ((field_type == MZ_ZIP_EXTENSION_UNIX1) && (field_length >= 12)) { if (err == MZ_OK) { err = mz_stream_read_uint32(file_extra_stream, &value32); if (err == MZ_OK && file_info->accessed_date == 0) file_info->accessed_date = value32; } if (err == MZ_OK) { err = mz_stream_read_uint32(file_extra_stream, &value32); if (err == MZ_OK && file_info->modified_date == 0) file_info->modified_date = value32; } if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &value16); /* User id */ if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &value16); /* Group id */ /* Copy linkname to end of file extra stream so we can return null terminated string */ linkname_size = field_length - 12; if ((err == MZ_OK) && (linkname_size > 0)) { linkname = (char *)malloc(linkname_size); if (linkname) { if (mz_stream_read(file_extra_stream, linkname, linkname_size) != linkname_size) err = MZ_READ_ERROR; if (err == MZ_OK) { saved_pos = mz_stream_tell(file_extra_stream); mz_stream_seek(file_extra_stream, linkname_pos, MZ_SEEK_SET); mz_stream_write(file_extra_stream, linkname, linkname_size); mz_stream_write_uint8(file_extra_stream, 0); mz_stream_seek(file_extra_stream, saved_pos, MZ_SEEK_SET); } free(linkname); } } } #ifdef HAVE_WZAES /* Read AES extra field */ else if ((field_type == MZ_ZIP_EXTENSION_AES) && (field_length == 7)) { uint8_t value8 = 0; /* Verify version info */ err = mz_stream_read_uint16(file_extra_stream, &value16); /* Support AE-1 and AE-2 */ if (value16 != 1 && value16 != 2) err = MZ_FORMAT_ERROR; file_info->aes_version = value16; if (err == MZ_OK) err = mz_stream_read_uint8(file_extra_stream, &value8); if ((char)value8 != 'A') err = MZ_FORMAT_ERROR; if (err == MZ_OK) err = mz_stream_read_uint8(file_extra_stream, &value8); if ((char)value8 != 'E') err = MZ_FORMAT_ERROR; /* Get AES encryption strength and actual compression method */ if (err == MZ_OK) { err = mz_stream_read_uint8(file_extra_stream, &value8); file_info->aes_strength = value8; } if (err == MZ_OK) { err = mz_stream_read_uint16(file_extra_stream, &value16); file_info->compression_method = value16; } } #endif else if (field_length > 0) { err = mz_stream_seek(file_extra_stream, field_length, MZ_SEEK_CUR); } field_pos += field_length; } } /* Get pointers to variable length data */ mz_stream_mem_get_buffer(file_extra_stream, (const void **)&file_info->filename); mz_stream_mem_get_buffer_at(file_extra_stream, extrafield_pos, (const void **)&file_info->extrafield); mz_stream_mem_get_buffer_at(file_extra_stream, comment_pos, (const void **)&file_info->comment); mz_stream_mem_get_buffer_at(file_extra_stream, linkname_pos, (const void **)&file_info->linkname); /* Set to empty string just in-case */ if (!file_info->filename) file_info->filename = ""; if (!file_info->extrafield) file_info->extrafield_size = 0; if (!file_info->comment) file_info->comment = ""; if (!file_info->linkname) file_info->linkname = ""; if (err == MZ_OK) { mz_zip_print("Zip - Entry - Read header - %s (local %" PRId8 ")\n", file_info->filename, local); mz_zip_print("Zip - Entry - Read header compress (ucs %" PRId64 " cs %" PRId64 " crc 0x%08" PRIx32 ")\n", file_info->uncompressed_size, file_info->compressed_size, file_info->crc); if (!local) { mz_zip_print("Zip - Entry - Read header disk (disk %" PRIu32 " offset %" PRId64 ")\n", file_info->disk_number, file_info->disk_offset); } mz_zip_print("Zip - Entry - Read header variable (fnl %" PRId32 " efs %" PRId32 " cms %" PRId32 ")\n", file_info->filename_size, file_info->extrafield_size, file_info->comment_size); } return err; } static int32_t mz_zip_entry_read_descriptor(void *stream, uint8_t zip64, uint32_t *crc32, int64_t *compressed_size, int64_t *uncompressed_size) { uint32_t value32 = 0; int64_t value64 = 0; int32_t err = MZ_OK; err = mz_stream_read_uint32(stream, &value32); if (value32 != MZ_ZIP_MAGIC_DATADESCRIPTOR) err = MZ_FORMAT_ERROR; if (err == MZ_OK) err = mz_stream_read_uint32(stream, &value32); if (err == MZ_OK && crc32) *crc32 = value32; if (err == MZ_OK) { /* If zip 64 extension is enabled then read as 8 byte */ if (!zip64) { err = mz_stream_read_uint32(stream, &value32); value64 = value32; } else { err = mz_stream_read_int64(stream, &value64); if (value64 < 0) err = MZ_FORMAT_ERROR; } if (err == MZ_OK && compressed_size) *compressed_size = value64; } if (err == MZ_OK) { if (!zip64) { err = mz_stream_read_uint32(stream, &value32); value64 = value32; } else { err = mz_stream_read_int64(stream, &value64); if (value64 < 0) err = MZ_FORMAT_ERROR; } if (err == MZ_OK && uncompressed_size) *uncompressed_size = value64; } return err; } static int32_t mz_zip_entry_write_crc_sizes(void *stream, uint8_t zip64, uint8_t mask, mz_zip_file *file_info) { int32_t err = MZ_OK; if (mask) err = mz_stream_write_uint32(stream, 0); else err = mz_stream_write_uint32(stream, file_info->crc); /* crc */ /* For backwards-compatibility with older zip applications we set all sizes to UINT32_MAX * when zip64 is needed, instead of only setting sizes larger than UINT32_MAX. */ if (err == MZ_OK) { if (zip64) /* compr size */ err = mz_stream_write_uint32(stream, UINT32_MAX); else err = mz_stream_write_uint32(stream, (uint32_t)file_info->compressed_size); } if (err == MZ_OK) { if (mask) /* uncompr size */ err = mz_stream_write_uint32(stream, 0); else if (zip64) err = mz_stream_write_uint32(stream, UINT32_MAX); else err = mz_stream_write_uint32(stream, (uint32_t)file_info->uncompressed_size); } return err; } static int32_t mz_zip_entry_needs_zip64(mz_zip_file *file_info, uint8_t local, uint8_t *zip64) { uint32_t max_uncompressed_size = UINT32_MAX; uint8_t needs_zip64 = 0; if (!zip64) return MZ_PARAM_ERROR; *zip64 = 0; if (local) { /* At local header we might not know yet whether compressed size will overflow unsigned 32-bit integer which might happen for high entropy data so we give it some cushion */ max_uncompressed_size -= MZ_ZIP_UNCOMPR_SIZE64_CUSHION; } needs_zip64 = (file_info->uncompressed_size >= max_uncompressed_size) || (file_info->compressed_size >= UINT32_MAX); if (!local) { /* Disk offset and number only used in central directory header */ needs_zip64 |= (file_info->disk_offset >= UINT32_MAX) || (file_info->disk_number >= UINT16_MAX); } if (file_info->zip64 == MZ_ZIP64_AUTO) { /* If uncompressed size is unknown, assume zip64 for 64-bit data descriptors */ if (local && file_info->uncompressed_size == 0) { /* Don't use zip64 for local header directory entries */ if (mz_zip_attrib_is_dir(file_info->external_fa, file_info->version_madeby) != MZ_OK) { *zip64 = 1; } } *zip64 |= needs_zip64; } else if (file_info->zip64 == MZ_ZIP64_FORCE) { *zip64 = 1; } else if (file_info->zip64 == MZ_ZIP64_DISABLE) { /* Zip64 extension is required to zip file */ if (needs_zip64) return MZ_PARAM_ERROR; } return MZ_OK; } static int32_t mz_zip_entry_write_header(void *stream, uint8_t local, mz_zip_file *file_info) { uint64_t ntfs_time = 0; uint32_t reserved = 0; uint32_t dos_date = 0; uint16_t extrafield_size = 0; uint16_t field_type = 0; uint16_t field_length = 0; uint16_t field_length_zip64 = 0; uint16_t field_length_ntfs = 0; uint16_t field_length_aes = 0; uint16_t field_length_unix1 = 0; uint16_t filename_size = 0; uint16_t filename_length = 0; uint16_t linkname_size = 0; uint16_t version_needed = 0; int32_t comment_size = 0; int32_t err = MZ_OK; int32_t err_mem = MZ_OK; uint8_t zip64 = 0; uint8_t skip_aes = 0; uint8_t mask = 0; uint8_t write_end_slash = 0; const char *filename = NULL; char masked_name[64]; void *file_extra_stream = NULL; if (!file_info) return MZ_PARAM_ERROR; if ((local) && (file_info->flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO)) mask = 1; /* Determine if zip64 extra field is necessary */ err = mz_zip_entry_needs_zip64(file_info, local, &zip64); if (err != MZ_OK) return err; /* Start calculating extra field sizes */ if (zip64) { /* Both compressed and uncompressed sizes must be included (at least in local header) */ field_length_zip64 = 8 + 8; if ((!local) && (file_info->disk_offset >= UINT32_MAX)) field_length_zip64 += 8; extrafield_size += 4; extrafield_size += field_length_zip64; } /* Calculate extra field size and check for duplicates */ if (file_info->extrafield_size > 0) { file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(file_extra_stream, (void *)file_info->extrafield, file_info->extrafield_size); do { err_mem = mz_stream_read_uint16(file_extra_stream, &field_type); if (err_mem == MZ_OK) err_mem = mz_stream_read_uint16(file_extra_stream, &field_length); if (err_mem != MZ_OK) break; /* Prefer incoming aes extensions over ours */ if (field_type == MZ_ZIP_EXTENSION_AES) skip_aes = 1; /* Prefer our zip64, ntfs, unix1 extension over incoming */ if (field_type != MZ_ZIP_EXTENSION_ZIP64 && field_type != MZ_ZIP_EXTENSION_NTFS && field_type != MZ_ZIP_EXTENSION_UNIX1) extrafield_size += 4 + field_length; if (err_mem == MZ_OK) err_mem = mz_stream_seek(file_extra_stream, field_length, MZ_SEEK_CUR); } while (err_mem == MZ_OK); } #ifdef HAVE_WZAES if (!skip_aes) { if ((file_info->flag & MZ_ZIP_FLAG_ENCRYPTED) && (file_info->aes_version)) { field_length_aes = 1 + 1 + 1 + 2 + 2; extrafield_size += 4 + field_length_aes; } } #else MZ_UNUSED(field_length_aes); MZ_UNUSED(skip_aes); #endif /* NTFS timestamps */ if ((file_info->modified_date != 0) && (file_info->accessed_date != 0) && (file_info->creation_date != 0) && (!mask)) { field_length_ntfs = 8 + 8 + 8 + 4 + 2 + 2; extrafield_size += 4 + field_length_ntfs; } /* Unix1 symbolic links */ if (file_info->linkname && *file_info->linkname != 0) { linkname_size = (uint16_t)strlen(file_info->linkname); field_length_unix1 = 12 + linkname_size; extrafield_size += 4 + field_length_unix1; } if (local) err = mz_stream_write_uint32(stream, MZ_ZIP_MAGIC_LOCALHEADER); else { err = mz_stream_write_uint32(stream, MZ_ZIP_MAGIC_CENTRALHEADER); if (err == MZ_OK) err = mz_stream_write_uint16(stream, file_info->version_madeby); } /* Calculate version needed to extract */ if (err == MZ_OK) { version_needed = file_info->version_needed; if (version_needed == 0) { version_needed = 20; if (zip64) version_needed = 45; #ifdef HAVE_WZAES if ((file_info->flag & MZ_ZIP_FLAG_ENCRYPTED) && (file_info->aes_version)) version_needed = 51; #endif #if defined(HAVE_LZMA) || defined(HAVE_LIBCOMP) if ((file_info->compression_method == MZ_COMPRESS_METHOD_LZMA) || (file_info->compression_method == MZ_COMPRESS_METHOD_XZ)) version_needed = 63; #endif } err = mz_stream_write_uint16(stream, version_needed); } if (err == MZ_OK) err = mz_stream_write_uint16(stream, file_info->flag); if (err == MZ_OK) { #ifdef HAVE_WZAES if ((file_info->flag & MZ_ZIP_FLAG_ENCRYPTED) && (file_info->aes_version)) err = mz_stream_write_uint16(stream, MZ_COMPRESS_METHOD_AES); else #endif err = mz_stream_write_uint16(stream, file_info->compression_method); } if (err == MZ_OK) { if (file_info->modified_date != 0 && !mask) dos_date = mz_zip_time_t_to_dos_date(file_info->modified_date); err = mz_stream_write_uint32(stream, dos_date); } if (err == MZ_OK) err = mz_zip_entry_write_crc_sizes(stream, zip64, mask, file_info); if (mask) { snprintf(masked_name, sizeof(masked_name), "%" PRIx32 "_%" PRIx64, file_info->disk_number, file_info->disk_offset); filename = masked_name; } else { filename = file_info->filename; } filename_length = (uint16_t)strlen(filename); filename_size += filename_length; if ((mz_zip_attrib_is_dir(file_info->external_fa, file_info->version_madeby) == MZ_OK) && ((filename[filename_length - 1] != '/') && (filename[filename_length - 1] != '\\'))) { filename_size += 1; write_end_slash = 1; } if (err == MZ_OK) err = mz_stream_write_uint16(stream, filename_size); if (err == MZ_OK) err = mz_stream_write_uint16(stream, extrafield_size); if (!local) { if (file_info->comment) { comment_size = (int32_t)strlen(file_info->comment); if (comment_size > UINT16_MAX) comment_size = UINT16_MAX; } if (err == MZ_OK) err = mz_stream_write_uint16(stream, (uint16_t)comment_size); if (err == MZ_OK) err = mz_stream_write_uint16(stream, (uint16_t)file_info->disk_number); if (err == MZ_OK) err = mz_stream_write_uint16(stream, file_info->internal_fa); if (err == MZ_OK) err = mz_stream_write_uint32(stream, file_info->external_fa); if (err == MZ_OK) { if (file_info->disk_offset >= UINT32_MAX) err = mz_stream_write_uint32(stream, UINT32_MAX); else err = mz_stream_write_uint32(stream, (uint32_t)file_info->disk_offset); } } if (err == MZ_OK) { const char *backslash = NULL; const char *next = filename; int32_t left = filename_length; /* Ensure all slashes are written as forward slashes according to 4.4.17.1 */ while ((err == MZ_OK) && (backslash = strchr(next, '\\'))) { int32_t part_length = (int32_t)(backslash - next); if (mz_stream_write(stream, next, part_length) != part_length || mz_stream_write(stream, "/", 1) != 1) err = MZ_WRITE_ERROR; left -= part_length + 1; next = backslash + 1; } if (err == MZ_OK && left > 0) { if (mz_stream_write(stream, next, left) != left) err = MZ_WRITE_ERROR; } /* Ensure that directories have a slash appended to them for compatibility */ if (err == MZ_OK && write_end_slash) err = mz_stream_write_uint8(stream, '/'); } /* Write ZIP64 extra field first so we can update sizes later if data descriptor not used */ if ((err == MZ_OK) && (zip64)) { err = mz_zip_extrafield_write(stream, MZ_ZIP_EXTENSION_ZIP64, field_length_zip64); if (err == MZ_OK) { if (mask) err = mz_stream_write_int64(stream, 0); else err = mz_stream_write_int64(stream, file_info->uncompressed_size); } if (err == MZ_OK) err = mz_stream_write_int64(stream, file_info->compressed_size); if ((err == MZ_OK) && (!local) && (file_info->disk_offset >= UINT32_MAX)) err = mz_stream_write_int64(stream, file_info->disk_offset); if ((err == MZ_OK) && (!local) && (file_info->disk_number >= UINT16_MAX)) err = mz_stream_write_uint32(stream, file_info->disk_number); } /* Write NTFS extra field */ if ((err == MZ_OK) && (field_length_ntfs > 0)) { err = mz_zip_extrafield_write(stream, MZ_ZIP_EXTENSION_NTFS, field_length_ntfs); if (err == MZ_OK) err = mz_stream_write_uint32(stream, reserved); if (err == MZ_OK) err = mz_stream_write_uint16(stream, 0x01); if (err == MZ_OK) err = mz_stream_write_uint16(stream, field_length_ntfs - 8); if (err == MZ_OK) { mz_zip_unix_to_ntfs_time(file_info->modified_date, &ntfs_time); err = mz_stream_write_uint64(stream, ntfs_time); } if (err == MZ_OK) { mz_zip_unix_to_ntfs_time(file_info->accessed_date, &ntfs_time); err = mz_stream_write_uint64(stream, ntfs_time); } if (err == MZ_OK) { mz_zip_unix_to_ntfs_time(file_info->creation_date, &ntfs_time); err = mz_stream_write_uint64(stream, ntfs_time); } } /* Write UNIX extra block extra field */ if ((err == MZ_OK) && (field_length_unix1 > 0)) { err = mz_zip_extrafield_write(stream, MZ_ZIP_EXTENSION_UNIX1, field_length_unix1); if (err == MZ_OK) err = mz_stream_write_uint32(stream, (uint32_t)file_info->accessed_date); if (err == MZ_OK) err = mz_stream_write_uint32(stream, (uint32_t)file_info->modified_date); if (err == MZ_OK) /* User id */ err = mz_stream_write_uint16(stream, 0); if (err == MZ_OK) /* Group id */ err = mz_stream_write_uint16(stream, 0); if (err == MZ_OK && linkname_size > 0) { if (mz_stream_write(stream, file_info->linkname, linkname_size) != linkname_size) err = MZ_WRITE_ERROR; } } #ifdef HAVE_WZAES /* Write AES extra field */ if ((err == MZ_OK) && (!skip_aes) && (file_info->flag & MZ_ZIP_FLAG_ENCRYPTED) && (file_info->aes_version)) { err = mz_zip_extrafield_write(stream, MZ_ZIP_EXTENSION_AES, field_length_aes); if (err == MZ_OK) err = mz_stream_write_uint16(stream, file_info->aes_version); if (err == MZ_OK) err = mz_stream_write_uint8(stream, 'A'); if (err == MZ_OK) err = mz_stream_write_uint8(stream, 'E'); if (err == MZ_OK) err = mz_stream_write_uint8(stream, file_info->aes_strength); if (err == MZ_OK) err = mz_stream_write_uint16(stream, file_info->compression_method); } #endif if (file_info->extrafield_size > 0) { err_mem = mz_stream_mem_seek(file_extra_stream, 0, MZ_SEEK_SET); while (err == MZ_OK && err_mem == MZ_OK) { err_mem = mz_stream_read_uint16(file_extra_stream, &field_type); if (err_mem == MZ_OK) err_mem = mz_stream_read_uint16(file_extra_stream, &field_length); if (err_mem != MZ_OK) break; /* Prefer our zip 64, ntfs, unix1 extensions over incoming */ if (field_type == MZ_ZIP_EXTENSION_ZIP64 || field_type == MZ_ZIP_EXTENSION_NTFS || field_type == MZ_ZIP_EXTENSION_UNIX1) { err_mem = mz_stream_seek(file_extra_stream, field_length, MZ_SEEK_CUR); continue; } err = mz_stream_write_uint16(stream, field_type); if (err == MZ_OK) err = mz_stream_write_uint16(stream, field_length); if (err == MZ_OK) err = mz_stream_copy(stream, file_extra_stream, field_length); } mz_stream_mem_delete(&file_extra_stream); } if (err == MZ_OK && !local && file_info->comment) { if (mz_stream_write(stream, file_info->comment, file_info->comment_size) != file_info->comment_size) err = MZ_WRITE_ERROR; } return err; } static int32_t mz_zip_entry_write_descriptor(void *stream, uint8_t zip64, uint32_t crc32, int64_t compressed_size, int64_t uncompressed_size) { int32_t err = MZ_OK; err = mz_stream_write_uint32(stream, MZ_ZIP_MAGIC_DATADESCRIPTOR); if (err == MZ_OK) err = mz_stream_write_uint32(stream, crc32); /* Store data descriptor as 8 bytes if zip 64 extension enabled */ if (err == MZ_OK) { /* Zip 64 extension is enabled when uncompressed size is > UINT32_MAX */ if (!zip64) err = mz_stream_write_uint32(stream, (uint32_t)compressed_size); else err = mz_stream_write_int64(stream, compressed_size); } if (err == MZ_OK) { if (!zip64) err = mz_stream_write_uint32(stream, (uint32_t)uncompressed_size); else err = mz_stream_write_int64(stream, uncompressed_size); } return err; } static int32_t mz_zip_read_cd(void *handle) { mz_zip *zip = (mz_zip *)handle; uint64_t number_entry_cd64 = 0; uint64_t number_entry_cd = 0; int64_t eocd_pos = 0; int64_t eocd_pos64 = 0; int64_t value64i = 0; uint16_t value16 = 0; uint32_t value32 = 0; uint64_t value64 = 0; uint16_t comment_size = 0; int32_t comment_read = 0; int32_t err = MZ_OK; if (!zip) return MZ_PARAM_ERROR; /* Read and cache central directory records */ err = mz_zip_search_eocd(zip->stream, &eocd_pos); if (err == MZ_OK) { /* The signature, already checked */ err = mz_stream_read_uint32(zip->stream, &value32); /* Number of this disk */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &value16); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &value16); zip->disk_number_with_cd = value16; /* Total number of entries in the central dir on this disk */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &value16); zip->number_entry = value16; /* Total number of entries in the central dir */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &value16); number_entry_cd = value16; if (number_entry_cd != zip->number_entry) err = MZ_FORMAT_ERROR; /* Size of the central directory */ if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &value32); if (err == MZ_OK) zip->cd_size = value32; /* Offset of start of central directory with respect to the starting disk number */ if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &value32); if (err == MZ_OK) zip->cd_offset = value32; /* Zip file global comment length */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &comment_size); if ((err == MZ_OK) && (comment_size > 0)) { zip->comment = (char *)malloc(comment_size + 1); if (zip->comment) { comment_read = mz_stream_read(zip->stream, zip->comment, comment_size); /* Don't fail if incorrect comment length read, not critical */ if (comment_read < 0) comment_read = 0; zip->comment[comment_read] = 0; } } if ((err == MZ_OK) && ((number_entry_cd == UINT16_MAX) || (zip->cd_offset == UINT32_MAX))) { /* Format should be Zip64, as the central directory or file size is too large */ if (mz_zip_search_zip64_eocd(zip->stream, eocd_pos, &eocd_pos64) == MZ_OK) { eocd_pos = eocd_pos64; err = mz_stream_seek(zip->stream, eocd_pos, MZ_SEEK_SET); /* The signature, already checked */ if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &value32); /* Size of zip64 end of central directory record */ if (err == MZ_OK) err = mz_stream_read_uint64(zip->stream, &value64); /* Version made by */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &zip->version_madeby); /* Version needed to extract */ if (err == MZ_OK) err = mz_stream_read_uint16(zip->stream, &value16); /* Number of this disk */ if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &value32); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &zip->disk_number_with_cd); /* Total number of entries in the central directory on this disk */ if (err == MZ_OK) err = mz_stream_read_uint64(zip->stream, &zip->number_entry); /* Total number of entries in the central directory */ if (err == MZ_OK) err = mz_stream_read_uint64(zip->stream, &number_entry_cd64); if (zip->number_entry != number_entry_cd64) err = MZ_FORMAT_ERROR; /* Size of the central directory */ if (err == MZ_OK) { err = mz_stream_read_int64(zip->stream, &zip->cd_size); if (zip->cd_size < 0) err = MZ_FORMAT_ERROR; } /* Offset of start of central directory with respect to the starting disk number */ if (err == MZ_OK) { err = mz_stream_read_int64(zip->stream, &zip->cd_offset); if (zip->cd_offset < 0) err = MZ_FORMAT_ERROR; } } else if ((zip->number_entry == UINT16_MAX) || (number_entry_cd != zip->number_entry) || (zip->cd_size == UINT16_MAX) || (zip->cd_offset == UINT32_MAX)) { err = MZ_FORMAT_ERROR; } } } if (err == MZ_OK) { mz_zip_print("Zip - Read cd (disk %" PRId32 " entries %" PRId64 " offset %" PRId64 " size %" PRId64 ")\n", zip->disk_number_with_cd, zip->number_entry, zip->cd_offset, zip->cd_size); /* Verify central directory signature exists at offset */ err = mz_stream_seek(zip->stream, zip->cd_offset, MZ_SEEK_SET); if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &zip->cd_signature); if ((err == MZ_OK) && (zip->cd_signature != MZ_ZIP_MAGIC_CENTRALHEADER)) { /* If cd exists in large file and no zip-64 support, error for recover */ if (eocd_pos > UINT32_MAX && eocd_pos64 == 0) err = MZ_FORMAT_ERROR; /* If cd not found attempt to seek backward to find it */ if (err == MZ_OK) err = mz_stream_seek(zip->stream, eocd_pos - zip->cd_size, MZ_SEEK_SET); if (err == MZ_OK) err = mz_stream_read_uint32(zip->stream, &zip->cd_signature); if ((err == MZ_OK) && (zip->cd_signature == MZ_ZIP_MAGIC_CENTRALHEADER)) { /* If found compensate for incorrect locations */ value64i = zip->cd_offset; zip->cd_offset = eocd_pos - zip->cd_size; /* Assume disk has prepended data */ zip->disk_offset_shift = zip->cd_offset - value64i; } } } if (err == MZ_OK) { if (eocd_pos < zip->cd_offset) { /* End of central dir should always come after central dir */ err = MZ_FORMAT_ERROR; } else if ((uint64_t)eocd_pos < (uint64_t)zip->cd_offset + zip->cd_size) { /* Truncate size of cd if incorrect size or offset provided */ zip->cd_size = eocd_pos - zip->cd_offset; } } return err; } static int32_t mz_zip_write_cd(void *handle) { mz_zip *zip = (mz_zip *)handle; int64_t zip64_eocd_pos_inzip = 0; int64_t disk_number = 0; int64_t disk_size = 0; int32_t comment_size = 0; int32_t err = MZ_OK; if (!zip) return MZ_PARAM_ERROR; if (mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &disk_number) == MZ_OK) zip->disk_number_with_cd = (uint32_t)disk_number; if (mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_SIZE, &disk_size) == MZ_OK && disk_size > 0) zip->disk_number_with_cd += 1; mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, -1); if ((zip->disk_number_with_cd > 0) && (zip->open_mode & MZ_OPEN_MODE_APPEND)) { // Overwrite existing central directory if using split disks mz_stream_seek(zip->stream, 0, MZ_SEEK_SET); } zip->cd_offset = mz_stream_tell(zip->stream); mz_stream_seek(zip->cd_mem_stream, 0, MZ_SEEK_END); zip->cd_size = (uint32_t)mz_stream_tell(zip->cd_mem_stream); mz_stream_seek(zip->cd_mem_stream, 0, MZ_SEEK_SET); err = mz_stream_copy(zip->stream, zip->cd_mem_stream, (int32_t)zip->cd_size); mz_zip_print("Zip - Write cd (disk %" PRId32 " entries %" PRId64 " offset %" PRId64 " size %" PRId64 ")\n", zip->disk_number_with_cd, zip->number_entry, zip->cd_offset, zip->cd_size); if (zip->cd_size == 0 && zip->number_entry > 0) { // Zip does not contain central directory, open with recovery option return MZ_FORMAT_ERROR; } /* Write the ZIP64 central directory header */ if (zip->cd_offset >= UINT32_MAX || zip->number_entry >= UINT16_MAX) { zip64_eocd_pos_inzip = mz_stream_tell(zip->stream); err = mz_stream_write_uint32(zip->stream, MZ_ZIP_MAGIC_ENDHEADER64); /* Size of this 'zip64 end of central directory' */ if (err == MZ_OK) err = mz_stream_write_uint64(zip->stream, (uint64_t)44); /* Version made by */ if (err == MZ_OK) err = mz_stream_write_uint16(zip->stream, zip->version_madeby); /* Version needed */ if (err == MZ_OK) err = mz_stream_write_uint16(zip->stream, (uint16_t)45); /* Number of this disk */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, zip->disk_number_with_cd); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, zip->disk_number_with_cd); /* Total number of entries in the central dir on this disk */ if (err == MZ_OK) err = mz_stream_write_uint64(zip->stream, zip->number_entry); /* Total number of entries in the central dir */ if (err == MZ_OK) err = mz_stream_write_uint64(zip->stream, zip->number_entry); /* Size of the central directory */ if (err == MZ_OK) err = mz_stream_write_int64(zip->stream, zip->cd_size); /* Offset of start of central directory with respect to the starting disk number */ if (err == MZ_OK) err = mz_stream_write_int64(zip->stream, zip->cd_offset); if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, MZ_ZIP_MAGIC_ENDLOCHEADER64); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, zip->disk_number_with_cd); /* Relative offset to the end of zip64 central directory */ if (err == MZ_OK) err = mz_stream_write_int64(zip->stream, zip64_eocd_pos_inzip); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, zip->disk_number_with_cd + 1); } /* Write the central directory header */ /* Signature */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, MZ_ZIP_MAGIC_ENDHEADER); /* Number of this disk */ if (err == MZ_OK) err = mz_stream_write_uint16(zip->stream, (uint16_t)zip->disk_number_with_cd); /* Number of the disk with the start of the central directory */ if (err == MZ_OK) err = mz_stream_write_uint16(zip->stream, (uint16_t)zip->disk_number_with_cd); /* Total number of entries in the central dir on this disk */ if (err == MZ_OK) { if (zip->number_entry >= UINT16_MAX) err = mz_stream_write_uint16(zip->stream, UINT16_MAX); else err = mz_stream_write_uint16(zip->stream, (uint16_t)zip->number_entry); } /* Total number of entries in the central dir */ if (err == MZ_OK) { if (zip->number_entry >= UINT16_MAX) err = mz_stream_write_uint16(zip->stream, UINT16_MAX); else err = mz_stream_write_uint16(zip->stream, (uint16_t)zip->number_entry); } /* Size of the central directory */ if (err == MZ_OK) err = mz_stream_write_uint32(zip->stream, (uint32_t)zip->cd_size); /* Offset of start of central directory with respect to the starting disk number */ if (err == MZ_OK) { if (zip->cd_offset >= UINT32_MAX) err = mz_stream_write_uint32(zip->stream, UINT32_MAX); else err = mz_stream_write_uint32(zip->stream, (uint32_t)zip->cd_offset); } /* Write global comment */ if (zip->comment) { comment_size = (int32_t)strlen(zip->comment); if (comment_size > UINT16_MAX) comment_size = UINT16_MAX; } if (err == MZ_OK) err = mz_stream_write_uint16(zip->stream, (uint16_t)comment_size); if (err == MZ_OK) { if (mz_stream_write(zip->stream, zip->comment, comment_size) != comment_size) err = MZ_READ_ERROR; } return err; } static int32_t mz_zip_recover_cd(void *handle) { mz_zip *zip = (mz_zip *)handle; mz_zip_file local_file_info; void *local_file_info_stream = NULL; void *cd_mem_stream = NULL; uint64_t number_entry = 0; int64_t descriptor_pos = 0; int64_t next_header_pos = 0; int64_t disk_offset = 0; int64_t disk_number = 0; int64_t compressed_pos = 0; int64_t compressed_end_pos = 0; int64_t compressed_size = 0; int64_t uncompressed_size = 0; uint8_t descriptor_magic[4] = MZ_ZIP_MAGIC_DATADESCRIPTORU8; uint8_t local_header_magic[4] = MZ_ZIP_MAGIC_LOCALHEADERU8; uint8_t central_header_magic[4] = MZ_ZIP_MAGIC_CENTRALHEADERU8; uint32_t crc32 = 0; int32_t disk_number_with_cd = 0; int32_t err = MZ_OK; uint8_t zip64 = 0; uint8_t eof = 0; mz_zip_print("Zip - Recover - Start\n"); mz_zip_get_cd_mem_stream(handle, &cd_mem_stream); /* Determine if we are on a split disk or not */ mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, 0); if (mz_stream_tell(zip->stream) < 0) { mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, -1); mz_stream_seek(zip->stream, 0, MZ_SEEK_SET); } else disk_number_with_cd = 1; local_file_info_stream = mz_stream_mem_create(); if (!local_file_info_stream) return MZ_MEM_ERROR; if (mz_stream_is_open(cd_mem_stream) != MZ_OK) err = mz_stream_mem_open(cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); mz_stream_mem_open(local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); if (err == MZ_OK) { err = mz_stream_find(zip->stream, (const void *)local_header_magic, sizeof(local_header_magic), INT64_MAX, &next_header_pos); } while (err == MZ_OK && !eof) { /* Get current offset and disk number for central dir record */ disk_offset = mz_stream_tell(zip->stream); mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &disk_number); /* Read local headers */ memset(&local_file_info, 0, sizeof(local_file_info)); err = mz_zip_entry_read_header(zip->stream, 1, &local_file_info, local_file_info_stream); if (err != MZ_OK) break; local_file_info.disk_offset = disk_offset; if (disk_number < 0) disk_number = 0; local_file_info.disk_number = (uint32_t)disk_number; compressed_pos = mz_stream_tell(zip->stream); if ((err == MZ_OK) && (local_file_info.compressed_size > 0)) { mz_stream_seek(zip->stream, local_file_info.compressed_size, MZ_SEEK_CUR); } for (;;) { /* Search for the next local header */ err = mz_stream_find(zip->stream, (const void *)local_header_magic, sizeof(local_header_magic), INT64_MAX, &next_header_pos); if (err == MZ_EXIST_ERROR) { mz_stream_seek(zip->stream, compressed_pos, MZ_SEEK_SET); /* Search for central dir if no local header found */ err = mz_stream_find(zip->stream, (const void *)central_header_magic, sizeof(central_header_magic), INT64_MAX, &next_header_pos); if (err == MZ_EXIST_ERROR) { /* Get end of stream if no central header found */ mz_stream_seek(zip->stream, 0, MZ_SEEK_END); next_header_pos = mz_stream_tell(zip->stream); } eof = 1; } if (local_file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR || local_file_info.compressed_size == 0) { /* Search backwards for the descriptor, seeking too far back will be incorrect if compressed size is small */ err = mz_stream_find_reverse(zip->stream, (const void *)descriptor_magic, sizeof(descriptor_magic), MZ_ZIP_SIZE_MAX_DATA_DESCRIPTOR, &descriptor_pos); if (err == MZ_OK) { if (mz_zip_extrafield_contains(local_file_info.extrafield, local_file_info.extrafield_size, MZ_ZIP_EXTENSION_ZIP64, NULL) == MZ_OK) zip64 = 1; err = mz_zip_entry_read_descriptor(zip->stream, zip64, &crc32, &compressed_size, &uncompressed_size); if (err == MZ_OK) { if (local_file_info.crc == 0) local_file_info.crc = crc32; if (local_file_info.compressed_size == 0) local_file_info.compressed_size = compressed_size; if (local_file_info.uncompressed_size == 0) local_file_info.uncompressed_size = uncompressed_size; } compressed_end_pos = descriptor_pos; } else if (eof) { compressed_end_pos = next_header_pos; } else if (local_file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) { /* Wrong local file entry found, keep searching */ next_header_pos += 1; mz_stream_seek(zip->stream, next_header_pos, MZ_SEEK_SET); continue; } } else { compressed_end_pos = next_header_pos; } break; } compressed_size = compressed_end_pos - compressed_pos; if (compressed_size > UINT32_MAX) { /* Update sizes if 4GB file is written with no ZIP64 support */ if (local_file_info.uncompressed_size < UINT32_MAX) { local_file_info.compressed_size = compressed_size; local_file_info.uncompressed_size = 0; } } mz_zip_print("Zip - Recover - Entry %s (csize %" PRId64 " usize %" PRId64 " flags 0x%" PRIx16 ")\n", local_file_info.filename, local_file_info.compressed_size, local_file_info.uncompressed_size, local_file_info.flag); /* Rewrite central dir with local headers and offsets */ err = mz_zip_entry_write_header(cd_mem_stream, 0, &local_file_info); if (err == MZ_OK) number_entry += 1; err = mz_stream_seek(zip->stream, next_header_pos, MZ_SEEK_SET); } mz_stream_mem_delete(&local_file_info_stream); mz_zip_print("Zip - Recover - Complete (cddisk %" PRId32 " entries %" PRId64 ")\n", disk_number_with_cd, number_entry); if (number_entry == 0) return err; /* Set new upper seek boundary for central dir mem stream */ disk_offset = mz_stream_tell(cd_mem_stream); mz_stream_mem_set_buffer_limit(cd_mem_stream, (int32_t)disk_offset); /* Set new central directory info */ mz_zip_set_cd_stream(handle, 0, cd_mem_stream); mz_zip_set_number_entry(handle, number_entry); mz_zip_set_disk_number_with_cd(handle, disk_number_with_cd); return MZ_OK; } void *mz_zip_create(void) { mz_zip *zip = (mz_zip *)calloc(1, sizeof(mz_zip)); if (zip) zip->data_descriptor = 1; return zip; } void mz_zip_delete(void **handle) { mz_zip *zip = NULL; if (!handle) return; zip = (mz_zip *)*handle; if (zip) { free(zip); } *handle = NULL; } int32_t mz_zip_open(void *handle, void *stream, int32_t mode) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; if (!zip) return MZ_PARAM_ERROR; mz_zip_print("Zip - Open\n"); zip->stream = stream; zip->cd_mem_stream = mz_stream_mem_create(); if (!zip->cd_mem_stream) return MZ_MEM_ERROR; if (mode & MZ_OPEN_MODE_WRITE) { mz_stream_mem_open(zip->cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); zip->cd_stream = zip->cd_mem_stream; } else { zip->cd_stream = stream; } if ((mode & MZ_OPEN_MODE_READ) || (mode & MZ_OPEN_MODE_APPEND)) { if ((mode & MZ_OPEN_MODE_CREATE) == 0) { err = mz_zip_read_cd(zip); if (err != MZ_OK) { mz_zip_print("Zip - Error detected reading cd (%" PRId32 ")\n", err); if (zip->recover && mz_zip_recover_cd(zip) == MZ_OK) err = MZ_OK; } } if ((err == MZ_OK) && (mode & MZ_OPEN_MODE_APPEND)) { if (zip->cd_size > 0) { /* Store central directory in memory */ err = mz_stream_seek(zip->stream, zip->cd_offset, MZ_SEEK_SET); if (err == MZ_OK) err = mz_stream_copy(zip->cd_mem_stream, zip->stream, (int32_t)zip->cd_size); if (err == MZ_OK) err = mz_stream_seek(zip->stream, zip->cd_offset, MZ_SEEK_SET); } else { if (zip->cd_signature == MZ_ZIP_MAGIC_ENDHEADER) { /* If tiny zip then overwrite end header */ err = mz_stream_seek(zip->stream, zip->cd_offset, MZ_SEEK_SET); } else { /* If no central directory, append new zip to end of file */ err = mz_stream_seek(zip->stream, 0, MZ_SEEK_END); } } if (zip->disk_number_with_cd > 0) { /* Move to last disk to begin appending */ mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->disk_number_with_cd - 1); } } else { zip->cd_start_pos = zip->cd_offset; } } if (err != MZ_OK) { mz_zip_close(zip); return err; } /* Memory streams used to store variable length file info data */ zip->file_info_stream = mz_stream_mem_create(); if (!zip->file_info_stream) return MZ_MEM_ERROR; mz_stream_mem_open(zip->file_info_stream, NULL, MZ_OPEN_MODE_CREATE); zip->local_file_info_stream = mz_stream_mem_create(); if (!zip->local_file_info_stream) { mz_stream_delete(&zip->file_info_stream); return MZ_MEM_ERROR; } mz_stream_mem_open(zip->local_file_info_stream, NULL, MZ_OPEN_MODE_CREATE); zip->open_mode = mode; return err; } int32_t mz_zip_close(void *handle) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; if (!zip) return MZ_PARAM_ERROR; mz_zip_print("Zip - Close\n"); if (mz_zip_entry_is_open(handle) == MZ_OK) err = mz_zip_entry_close(handle); if ((err == MZ_OK) && (zip->open_mode & MZ_OPEN_MODE_WRITE)) err = mz_zip_write_cd(handle); if (zip->cd_mem_stream) { mz_stream_close(zip->cd_mem_stream); mz_stream_delete(&zip->cd_mem_stream); } if (zip->file_info_stream) { mz_stream_mem_close(zip->file_info_stream); mz_stream_mem_delete(&zip->file_info_stream); } if (zip->local_file_info_stream) { mz_stream_mem_close(zip->local_file_info_stream); mz_stream_mem_delete(&zip->local_file_info_stream); } if (zip->comment) { free(zip->comment); zip->comment = NULL; } zip->stream = NULL; zip->cd_stream = NULL; return err; } int32_t mz_zip_get_comment(void *handle, const char **comment) { mz_zip *zip = (mz_zip *)handle; if (!zip || !comment) return MZ_PARAM_ERROR; if (!zip->comment) return MZ_EXIST_ERROR; *comment = zip->comment; return MZ_OK; } int32_t mz_zip_set_comment(void *handle, const char *comment) { mz_zip *zip = (mz_zip *)handle; int32_t comment_size = 0; if (!zip || !comment) return MZ_PARAM_ERROR; if (zip->comment) free(zip->comment); comment_size = (int32_t)strlen(comment); if (comment_size > UINT16_MAX) return MZ_PARAM_ERROR; zip->comment = (char *)calloc(comment_size + 1, sizeof(char)); if (!zip->comment) return MZ_MEM_ERROR; strncpy(zip->comment, comment, comment_size); return MZ_OK; } int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby) { mz_zip *zip = (mz_zip *)handle; if (!zip || !version_madeby) return MZ_PARAM_ERROR; *version_madeby = zip->version_madeby; return MZ_OK; } int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->version_madeby = version_madeby; return MZ_OK; } int32_t mz_zip_set_recover(void *handle, uint8_t recover) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->recover = recover; return MZ_OK; } int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->data_descriptor = data_descriptor; return MZ_OK; } int32_t mz_zip_get_stream(void *handle, void **stream) { mz_zip *zip = (mz_zip *)handle; if (!zip || !stream) return MZ_PARAM_ERROR; *stream = zip->stream; if (!*stream) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream) { mz_zip *zip = (mz_zip *)handle; if (!zip || !cd_stream) return MZ_PARAM_ERROR; zip->cd_offset = 0; zip->cd_stream = cd_stream; zip->cd_start_pos = cd_start_pos; return MZ_OK; } int32_t mz_zip_get_cd_mem_stream(void *handle, void **cd_mem_stream) { mz_zip *zip = (mz_zip *)handle; if (!zip || !cd_mem_stream) return MZ_PARAM_ERROR; *cd_mem_stream = zip->cd_mem_stream; if (!*cd_mem_stream) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->number_entry = number_entry; return MZ_OK; } int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry) { mz_zip *zip = (mz_zip *)handle; if (!zip || !number_entry) return MZ_PARAM_ERROR; *number_entry = zip->number_entry; return MZ_OK; } int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_cd) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->disk_number_with_cd = disk_number_with_cd; return MZ_OK; } int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_cd) { mz_zip *zip = (mz_zip *)handle; if (!zip || !disk_number_with_cd) return MZ_PARAM_ERROR; *disk_number_with_cd = zip->disk_number_with_cd; return MZ_OK; } static int32_t mz_zip_entry_close_int(void *handle) { mz_zip *zip = (mz_zip *)handle; if (zip->crypt_stream) mz_stream_delete(&zip->crypt_stream); zip->crypt_stream = NULL; if (zip->compress_stream) mz_stream_delete(&zip->compress_stream); zip->compress_stream = NULL; zip->entry_opened = 0; return MZ_OK; } static int32_t mz_zip_entry_open_int(void *handle, uint8_t raw, int16_t compress_level, const char *password) { mz_zip *zip = (mz_zip *)handle; int64_t max_total_in = 0; int64_t header_size = 0; int64_t footer_size = 0; int32_t err = MZ_OK; uint8_t use_crypt = 0; if (!zip) return MZ_PARAM_ERROR; switch (zip->file_info.compression_method) { case MZ_COMPRESS_METHOD_STORE: case MZ_COMPRESS_METHOD_DEFLATE: #ifdef HAVE_BZIP2 case MZ_COMPRESS_METHOD_BZIP2: #endif #ifdef HAVE_LZMA case MZ_COMPRESS_METHOD_LZMA: #endif #if defined(HAVE_LZMA) || defined(HAVE_LIBCOMP) case MZ_COMPRESS_METHOD_XZ: #endif #ifdef HAVE_ZSTD case MZ_COMPRESS_METHOD_ZSTD: #endif err = MZ_OK; break; default: return MZ_SUPPORT_ERROR; } #ifndef HAVE_WZAES if (zip->file_info.aes_version) return MZ_SUPPORT_ERROR; #endif zip->entry_raw = raw; if ((zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) && (password)) { if (zip->open_mode & MZ_OPEN_MODE_WRITE) { /* Encrypt only when we are not trying to write raw and password is supplied. */ if (!zip->entry_raw) use_crypt = 1; } else if (zip->open_mode & MZ_OPEN_MODE_READ) { /* Decrypt only when password is supplied. Don't error when password */ /* is not supplied as we may want to read the raw encrypted data. */ use_crypt = 1; } } if ((err == MZ_OK) && (use_crypt)) { #ifdef HAVE_WZAES if (zip->file_info.aes_version) { zip->crypt_stream = mz_stream_wzaes_create(); if (!zip->crypt_stream) return MZ_MEM_ERROR; mz_stream_wzaes_set_password(zip->crypt_stream, password); mz_stream_wzaes_set_strength(zip->crypt_stream, zip->file_info.aes_strength); } else #endif { #ifdef HAVE_PKCRYPT uint8_t verify1 = (uint8_t)((zip->file_info.pk_verify >> 8) & 0xff); uint8_t verify2 = (uint8_t)((zip->file_info.pk_verify) & 0xff); zip->crypt_stream = mz_stream_pkcrypt_create(); if (!zip->crypt_stream) return MZ_MEM_ERROR; mz_stream_pkcrypt_set_password(zip->crypt_stream, password); mz_stream_pkcrypt_set_verify(zip->crypt_stream, verify1, verify2); #endif } } if (err == MZ_OK) { if (!zip->crypt_stream) zip->crypt_stream = mz_stream_raw_create(); if (!zip->crypt_stream) return MZ_MEM_ERROR; mz_stream_set_base(zip->crypt_stream, zip->stream); err = mz_stream_open(zip->crypt_stream, NULL, zip->open_mode); } if (err == MZ_OK) { if (zip->entry_raw || zip->file_info.compression_method == MZ_COMPRESS_METHOD_STORE) zip->compress_stream = mz_stream_raw_create(); #ifdef HAVE_ZLIB else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE) zip->compress_stream = mz_stream_zlib_create(); #endif #ifdef HAVE_BZIP2 else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_BZIP2) zip->compress_stream = mz_stream_bzip_create(); #endif #ifdef HAVE_LIBCOMP else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE || zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { zip->compress_stream = mz_stream_libcomp_create(); if (zip->compress_stream) mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, zip->file_info.compression_method); } #endif #ifdef HAVE_LZMA else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_LZMA || zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) { zip->compress_stream = mz_stream_lzma_create(); if (zip->compress_stream) mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_METHOD, zip->file_info.compression_method); } #endif #ifdef HAVE_ZSTD else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_ZSTD) zip->compress_stream = mz_stream_zstd_create(); #endif else err = MZ_PARAM_ERROR; } if (err == MZ_OK && !zip->compress_stream) err = MZ_MEM_ERROR; if (err == MZ_OK) { if (zip->open_mode & MZ_OPEN_MODE_WRITE) { mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_COMPRESS_LEVEL, compress_level); } else { int32_t set_end_of_stream = 0; #ifndef HAVE_LIBCOMP if (zip->entry_raw || zip->file_info.compression_method == MZ_COMPRESS_METHOD_STORE || zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) #endif { max_total_in = zip->file_info.compressed_size; mz_stream_set_prop_int64(zip->crypt_stream, MZ_STREAM_PROP_TOTAL_IN_MAX, max_total_in); if (mz_stream_get_prop_int64(zip->crypt_stream, MZ_STREAM_PROP_HEADER_SIZE, &header_size) == MZ_OK) max_total_in -= header_size; if (mz_stream_get_prop_int64(zip->crypt_stream, MZ_STREAM_PROP_FOOTER_SIZE, &footer_size) == MZ_OK) max_total_in -= footer_size; mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN_MAX, max_total_in); } switch (zip->file_info.compression_method) { case MZ_COMPRESS_METHOD_LZMA: case MZ_COMPRESS_METHOD_XZ: set_end_of_stream = (zip->file_info.flag & MZ_ZIP_FLAG_LZMA_EOS_MARKER); break; case MZ_COMPRESS_METHOD_ZSTD: set_end_of_stream = 1; break; } if (set_end_of_stream) { mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN_MAX, zip->file_info.compressed_size); mz_stream_set_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_OUT_MAX, zip->file_info.uncompressed_size); } } mz_stream_set_base(zip->compress_stream, zip->crypt_stream); err = mz_stream_open(zip->compress_stream, NULL, zip->open_mode); } if (err == MZ_OK) { zip->entry_opened = 1; zip->entry_crc32 = 0; } else { mz_zip_entry_close_int(handle); } return err; } int32_t mz_zip_entry_is_open(void *handle) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; if (zip->entry_opened == 0) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_zip_entry_read_open(void *handle, uint8_t raw, const char *password) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; int32_t err_shift = MZ_OK; #if defined(MZ_ZIP_NO_ENCRYPTION) if (password) return MZ_SUPPORT_ERROR; #endif if (!zip || !zip->entry_scanned) return MZ_PARAM_ERROR; if ((zip->open_mode & MZ_OPEN_MODE_READ) == 0) return MZ_PARAM_ERROR; mz_zip_print("Zip - Entry - Read open (raw %" PRId32 ")\n", raw); err = mz_zip_entry_seek_local_header(handle); if (err == MZ_OK) err = mz_zip_entry_read_header(zip->stream, 1, &zip->local_file_info, zip->local_file_info_stream); if (err == MZ_FORMAT_ERROR && zip->disk_offset_shift > 0) { /* Perhaps we didn't compensated correctly for incorrect cd offset */ err_shift = mz_stream_seek(zip->stream, zip->file_info.disk_offset, MZ_SEEK_SET); if (err_shift == MZ_OK) err_shift = mz_zip_entry_read_header(zip->stream, 1, &zip->local_file_info, zip->local_file_info_stream); if (err_shift == MZ_OK) { zip->disk_offset_shift = 0; err = err_shift; } } #ifdef MZ_ZIP_NO_DECOMPRESSION if (!raw && zip->file_info.compression_method != MZ_COMPRESS_METHOD_STORE) err = MZ_SUPPORT_ERROR; #endif if (err == MZ_OK) err = mz_zip_entry_open_int(handle, raw, 0, password); return err; } int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int16_t compress_level, uint8_t raw, const char *password) { mz_zip *zip = (mz_zip *)handle; int64_t filename_pos = -1; int64_t extrafield_pos = 0; int64_t comment_pos = 0; int64_t linkname_pos = 0; int64_t disk_number = 0; uint8_t is_dir = 0; int32_t err = MZ_OK; #if defined(MZ_ZIP_NO_ENCRYPTION) if (password) return MZ_SUPPORT_ERROR; #endif if (!zip || !file_info || !file_info->filename) return MZ_PARAM_ERROR; if (mz_zip_entry_is_open(handle) == MZ_OK) { err = mz_zip_entry_close(handle); if (err != MZ_OK) return err; } memcpy(&zip->file_info, file_info, sizeof(mz_zip_file)); mz_zip_print("Zip - Entry - Write open - %s (level %" PRId16 " raw %" PRId8 ")\n", zip->file_info.filename, compress_level, raw); mz_stream_seek(zip->file_info_stream, 0, MZ_SEEK_SET); mz_stream_write(zip->file_info_stream, file_info, sizeof(mz_zip_file)); /* Copy filename, extrafield, and comment internally */ filename_pos = mz_stream_tell(zip->file_info_stream); if (file_info->filename) mz_stream_write(zip->file_info_stream, file_info->filename, (int32_t)strlen(file_info->filename)); mz_stream_write_uint8(zip->file_info_stream, 0); extrafield_pos = mz_stream_tell(zip->file_info_stream); if (file_info->extrafield) mz_stream_write(zip->file_info_stream, file_info->extrafield, file_info->extrafield_size); mz_stream_write_uint8(zip->file_info_stream, 0); comment_pos = mz_stream_tell(zip->file_info_stream); if (file_info->comment) mz_stream_write(zip->file_info_stream, file_info->comment, file_info->comment_size); mz_stream_write_uint8(zip->file_info_stream, 0); linkname_pos = mz_stream_tell(zip->file_info_stream); if (file_info->linkname) mz_stream_write(zip->file_info_stream, file_info->linkname, (int32_t)strlen(file_info->linkname)); mz_stream_write_uint8(zip->file_info_stream, 0); mz_stream_mem_get_buffer_at(zip->file_info_stream, filename_pos, (const void **)&zip->file_info.filename); mz_stream_mem_get_buffer_at(zip->file_info_stream, extrafield_pos, (const void **)&zip->file_info.extrafield); mz_stream_mem_get_buffer_at(zip->file_info_stream, comment_pos, (const void **)&zip->file_info.comment); mz_stream_mem_get_buffer_at(zip->file_info_stream, linkname_pos, (const void **)&zip->file_info.linkname); if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_DEFLATE) { if ((compress_level == 8) || (compress_level == 9)) zip->file_info.flag |= MZ_ZIP_FLAG_DEFLATE_MAX; if (compress_level == 2) zip->file_info.flag |= MZ_ZIP_FLAG_DEFLATE_FAST; if (compress_level == 1) zip->file_info.flag |= MZ_ZIP_FLAG_DEFLATE_SUPER_FAST; } #if defined(HAVE_LZMA) || defined(HAVE_LIBCOMP) else if (zip->file_info.compression_method == MZ_COMPRESS_METHOD_LZMA || zip->file_info.compression_method == MZ_COMPRESS_METHOD_XZ) zip->file_info.flag |= MZ_ZIP_FLAG_LZMA_EOS_MARKER; #endif if (mz_zip_attrib_is_dir(zip->file_info.external_fa, zip->file_info.version_madeby) == MZ_OK) is_dir = 1; if (!is_dir) { if (zip->data_descriptor) zip->file_info.flag |= MZ_ZIP_FLAG_DATA_DESCRIPTOR; if (password) zip->file_info.flag |= MZ_ZIP_FLAG_ENCRYPTED; } mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &disk_number); zip->file_info.disk_number = (uint32_t)disk_number; zip->file_info.disk_offset = mz_stream_tell(zip->stream); if (zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) { #ifdef HAVE_PKCRYPT /* Pre-calculated CRC value is required for PKWARE traditional encryption */ uint32_t dos_date = mz_zip_time_t_to_dos_date(zip->file_info.modified_date); zip->file_info.pk_verify = mz_zip_get_pk_verify(dos_date, zip->file_info.crc, zip->file_info.flag); #endif #ifdef HAVE_WZAES if (zip->file_info.aes_version && zip->file_info.aes_strength == 0) zip->file_info.aes_strength = MZ_AES_STRENGTH_256; #endif } zip->file_info.crc = 0; zip->file_info.compressed_size = 0; if ((compress_level == 0) || (is_dir)) zip->file_info.compression_method = MZ_COMPRESS_METHOD_STORE; #ifdef MZ_ZIP_NO_COMPRESSION if (zip->file_info.compression_method != MZ_COMPRESS_METHOD_STORE) err = MZ_SUPPORT_ERROR; #endif if (err == MZ_OK) err = mz_zip_entry_write_header(zip->stream, 1, &zip->file_info); if (err == MZ_OK) err = mz_zip_entry_open_int(handle, raw, compress_level, password); return err; } int32_t mz_zip_entry_read(void *handle, void *buf, int32_t len) { mz_zip *zip = (mz_zip *)handle; int32_t read = 0; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (UINT_MAX == UINT16_MAX && len > UINT16_MAX) /* zlib limitation */ return MZ_PARAM_ERROR; if (len == 0) return MZ_PARAM_ERROR; if (zip->file_info.compressed_size == 0) return 0; /* Read entire entry even if uncompressed_size = 0, otherwise */ /* aes encryption validation will fail if compressed_size > 0 */ read = mz_stream_read(zip->compress_stream, buf, len); if (read > 0) zip->entry_crc32 = mz_crypt_crc32_update(zip->entry_crc32, buf, read); mz_zip_print("Zip - Entry - Read - %" PRId32 " (max %" PRId32 ")\n", read, len); return read; } int32_t mz_zip_entry_write(void *handle, const void *buf, int32_t len) { mz_zip *zip = (mz_zip *)handle; int32_t written = 0; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; written = mz_stream_write(zip->compress_stream, buf, len); if (written > 0) zip->entry_crc32 = mz_crypt_crc32_update(zip->entry_crc32, buf, written); mz_zip_print("Zip - Entry - Write - %" PRId32 " (max %" PRId32 ")\n", written, len); return written; } int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compressed_size, int64_t *uncompressed_size) { mz_zip *zip = (mz_zip *)handle; int64_t total_in = 0; int32_t err = MZ_OK; uint8_t zip64 = 0; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; mz_stream_close(zip->compress_stream); mz_zip_print("Zip - Entry - Read Close\n"); if (crc32) *crc32 = zip->file_info.crc; if (compressed_size) *compressed_size = zip->file_info.compressed_size; if (uncompressed_size) *uncompressed_size = zip->file_info.uncompressed_size; mz_stream_get_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN, &total_in); if ((zip->file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) && ((zip->file_info.flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO) == 0) && (crc32 || compressed_size || uncompressed_size)) { /* Check to see if data descriptor is zip64 bit format or not */ if (mz_zip_extrafield_contains(zip->local_file_info.extrafield, zip->local_file_info.extrafield_size, MZ_ZIP_EXTENSION_ZIP64, NULL) == MZ_OK) zip64 = 1; err = mz_zip_entry_seek_local_header(handle); /* Seek to end of compressed stream since we might have over-read during compression */ if (err == MZ_OK) err = mz_stream_seek(zip->stream, MZ_ZIP_SIZE_LD_ITEM + (int64_t)zip->local_file_info.filename_size + (int64_t)zip->local_file_info.extrafield_size + total_in, MZ_SEEK_CUR); /* Read data descriptor */ if (err == MZ_OK) err = mz_zip_entry_read_descriptor(zip->stream, zip64, crc32, compressed_size, uncompressed_size); } /* If entire entry was not read verification will fail */ if ((err == MZ_OK) && (total_in == zip->file_info.compressed_size) && (!zip->entry_raw)) { #ifdef HAVE_WZAES /* AES zip version AE-1 will expect a valid crc as well */ if (zip->file_info.aes_version <= 0x0001) #endif { if (zip->entry_crc32 != zip->file_info.crc) { mz_zip_print("Zip - Entry - Crc failed (actual 0x%08" PRIx32 " expected 0x%08" PRIx32 ")\n", zip->entry_crc32, zip->file_info.crc); err = MZ_CRC_ERROR; } } } mz_zip_entry_close_int(handle); return err; } int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compressed_size, int64_t uncompressed_size) { mz_zip *zip = (mz_zip *)handle; int64_t end_disk_number = 0; int32_t err = MZ_OK; uint8_t zip64 = 0; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; mz_stream_close(zip->compress_stream); if (!zip->entry_raw) crc32 = zip->entry_crc32; mz_zip_print("Zip - Entry - Write Close (crc 0x%08" PRIx32 " cs %" PRId64 " ucs %" PRId64 ")\n", crc32, compressed_size, uncompressed_size); /* If sizes are not set, then read them from the compression stream */ if (compressed_size < 0) mz_stream_get_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_OUT, &compressed_size); if (uncompressed_size < 0) mz_stream_get_prop_int64(zip->compress_stream, MZ_STREAM_PROP_TOTAL_IN, &uncompressed_size); if (zip->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED) { mz_stream_set_base(zip->crypt_stream, zip->stream); err = mz_stream_close(zip->crypt_stream); mz_stream_get_prop_int64(zip->crypt_stream, MZ_STREAM_PROP_TOTAL_OUT, &compressed_size); } mz_zip_entry_needs_zip64(&zip->file_info, 1, &zip64); if ((err == MZ_OK) && (zip->file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR)) { /* Determine if we need to write data descriptor in zip64 format, if local extrafield was saved with zip64 extrafield */ if (zip->file_info.flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO) err = mz_zip_entry_write_descriptor(zip->stream, zip64, 0, compressed_size, 0); else err = mz_zip_entry_write_descriptor(zip->stream, zip64, crc32, compressed_size, uncompressed_size); } /* Write file info to central directory */ mz_zip_print("Zip - Entry - Write cd (ucs %" PRId64 " cs %" PRId64 " crc 0x%08" PRIx32 ")\n", uncompressed_size, compressed_size, crc32); zip->file_info.crc = crc32; zip->file_info.compressed_size = compressed_size; zip->file_info.uncompressed_size = uncompressed_size; if (err == MZ_OK) err = mz_zip_entry_write_header(zip->cd_mem_stream, 0, &zip->file_info); /* Update local header with crc32 and sizes */ if ((err == MZ_OK) && ((zip->file_info.flag & MZ_ZIP_FLAG_DATA_DESCRIPTOR) == 0) && ((zip->file_info.flag & MZ_ZIP_FLAG_MASK_LOCAL_INFO) == 0)) { /* Save the disk number and position we are to seek back after updating local header */ int64_t end_pos = mz_stream_tell(zip->stream); mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, &end_disk_number); err = mz_zip_entry_seek_local_header(handle); if (err == MZ_OK) { /* Seek to crc32 and sizes offset in local header */ mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, zip->file_info.disk_number); err = mz_stream_seek(zip->stream, zip->file_info.disk_offset + MZ_ZIP_OFFSET_CRC_SIZES, MZ_SEEK_SET); } if (err == MZ_OK) err = mz_zip_entry_write_crc_sizes(zip->stream, zip64, 0, &zip->file_info); /* Seek to and update zip64 extension sizes */ if ((err == MZ_OK) && (zip64)) { int64_t filename_size = zip->file_info.filename_size; if (filename_size == 0) filename_size = strlen(zip->file_info.filename); /* Since we write zip64 extension first we know its offset */ err = mz_stream_seek(zip->stream, 2 + 2 + filename_size + 4, MZ_SEEK_CUR); if (err == MZ_OK) err = mz_stream_write_uint64(zip->stream, zip->file_info.uncompressed_size); if (err == MZ_OK) err = mz_stream_write_uint64(zip->stream, zip->file_info.compressed_size); } mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, end_disk_number); mz_stream_seek(zip->stream, end_pos, MZ_SEEK_SET); } zip->number_entry += 1; mz_zip_entry_close_int(handle); return err; } int32_t mz_zip_entry_seek_local_header(void *handle) { mz_zip *zip = (mz_zip *)handle; int64_t disk_size = 0; uint32_t disk_number = zip->file_info.disk_number; if (disk_number == zip->disk_number_with_cd) { mz_stream_get_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_SIZE, &disk_size); if ((disk_size == 0) || ((zip->open_mode & MZ_OPEN_MODE_WRITE) == 0)) disk_number = (uint32_t)-1; } mz_stream_set_prop_int64(zip->stream, MZ_STREAM_PROP_DISK_NUMBER, disk_number); mz_zip_print("Zip - Entry - Seek local (disk %" PRId32 " offset %" PRId64 ")\n", disk_number, zip->file_info.disk_offset); /* Guard against seek overflows */ if ((zip->disk_offset_shift > 0) && (zip->file_info.disk_offset > (INT64_MAX - zip->disk_offset_shift))) return MZ_FORMAT_ERROR; return mz_stream_seek(zip->stream, zip->file_info.disk_offset + zip->disk_offset_shift, MZ_SEEK_SET); } int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream) { mz_zip *zip = (mz_zip *)handle; if (!zip || !compress_stream) return MZ_PARAM_ERROR; *compress_stream = zip->compress_stream; if (!*compress_stream) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_zip_entry_close(void *handle) { return mz_zip_entry_close_raw(handle, UINT64_MAX, 0); } int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t crc32) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (zip->open_mode & MZ_OPEN_MODE_WRITE) err = mz_zip_entry_write_close(handle, crc32, UINT64_MAX, uncompressed_size); else err = mz_zip_entry_read_close(handle, NULL, NULL, NULL); return err; } int32_t mz_zip_entry_is_dir(void *handle) { mz_zip *zip = (mz_zip *)handle; int32_t filename_length = 0; if (!zip || !zip->entry_scanned) return MZ_PARAM_ERROR; if (mz_zip_attrib_is_dir(zip->file_info.external_fa, zip->file_info.version_madeby) == MZ_OK) return MZ_OK; filename_length = (int32_t)strlen(zip->file_info.filename); if (filename_length > 0) { if ((zip->file_info.filename[filename_length - 1] == '/') || (zip->file_info.filename[filename_length - 1] == '\\')) return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_zip_entry_is_symlink(void *handle) { mz_zip *zip = (mz_zip *)handle; if (!zip || !zip->entry_scanned) return MZ_PARAM_ERROR; if (mz_zip_attrib_is_symlink(zip->file_info.external_fa, zip->file_info.version_madeby) != MZ_OK) return MZ_EXIST_ERROR; return MZ_OK; } int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; if ((zip->open_mode & MZ_OPEN_MODE_WRITE) == 0) { if (!zip->entry_scanned) return MZ_PARAM_ERROR; } *file_info = &zip->file_info; return MZ_OK; } int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info) { mz_zip *zip = (mz_zip *)handle; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; *local_file_info = &zip->local_file_info; return MZ_OK; } int32_t mz_zip_entry_set_extrafield(void *handle, const uint8_t *extrafield, uint16_t extrafield_size) { mz_zip *zip = (mz_zip *)handle; if (!zip || mz_zip_entry_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; zip->file_info.extrafield = extrafield; zip->file_info.extrafield_size = extrafield_size; return MZ_OK; } static int32_t mz_zip_goto_next_entry_int(void *handle) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; if (!zip) return MZ_PARAM_ERROR; zip->entry_scanned = 0; mz_stream_set_prop_int64(zip->cd_stream, MZ_STREAM_PROP_DISK_NUMBER, -1); err = mz_stream_seek(zip->cd_stream, zip->cd_current_pos, MZ_SEEK_SET); if (err == MZ_OK) err = mz_zip_entry_read_header(zip->cd_stream, 0, &zip->file_info, zip->file_info_stream); if (err == MZ_OK) zip->entry_scanned = 1; return err; } int64_t mz_zip_get_entry(void *handle) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; return zip->cd_current_pos; } int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; if (cd_pos < zip->cd_start_pos || cd_pos > zip->cd_start_pos + zip->cd_size) return MZ_PARAM_ERROR; zip->cd_current_pos = cd_pos; return mz_zip_goto_next_entry_int(handle); } int32_t mz_zip_goto_first_entry(void *handle) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->cd_current_pos = zip->cd_start_pos; return mz_zip_goto_next_entry_int(handle); } int32_t mz_zip_goto_next_entry(void *handle) { mz_zip *zip = (mz_zip *)handle; if (!zip) return MZ_PARAM_ERROR; zip->cd_current_pos += (int64_t)MZ_ZIP_SIZE_CD_ITEM + zip->file_info.filename_size + zip->file_info.extrafield_size + zip->file_info.comment_size; return mz_zip_goto_next_entry_int(handle); } int32_t mz_zip_locate_entry(void *handle, const char *filename, uint8_t ignore_case) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; int32_t result = 0; if (!zip || !filename) return MZ_PARAM_ERROR; /* If we are already on the current entry, no need to search */ if (zip->entry_scanned && zip->file_info.filename) { result = mz_zip_path_compare(zip->file_info.filename, filename, ignore_case); if (result == 0) return MZ_OK; } /* Search all entries starting at the first */ err = mz_zip_goto_first_entry(handle); while (err == MZ_OK) { result = mz_zip_path_compare(zip->file_info.filename, filename, ignore_case); if (result == 0) return MZ_OK; err = mz_zip_goto_next_entry(handle); } return err; } int32_t mz_zip_locate_first_entry(void *handle, void *userdata, mz_zip_locate_entry_cb cb) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; int32_t result = 0; /* Search first entry looking for match */ err = mz_zip_goto_first_entry(handle); if (err != MZ_OK) return err; result = cb(handle, userdata, &zip->file_info); if (result == 0) return MZ_OK; return mz_zip_locate_next_entry(handle, userdata, cb); } int32_t mz_zip_locate_next_entry(void *handle, void *userdata, mz_zip_locate_entry_cb cb) { mz_zip *zip = (mz_zip *)handle; int32_t err = MZ_OK; int32_t result = 0; /* Search next entries looking for match */ err = mz_zip_goto_next_entry(handle); while (err == MZ_OK) { result = cb(handle, userdata, &zip->file_info); if (result == 0) return MZ_OK; err = mz_zip_goto_next_entry(handle); } return err; } /***************************************************************************/ int32_t mz_zip_attrib_is_dir(uint32_t attrib, int32_t version_madeby) { uint32_t posix_attrib = 0; uint8_t system = MZ_HOST_SYSTEM(version_madeby); int32_t err = MZ_OK; err = mz_zip_attrib_convert(system, attrib, MZ_HOST_SYSTEM_UNIX, &posix_attrib); if (err == MZ_OK) { if ((posix_attrib & 0170000) == 0040000) /* S_ISDIR */ return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_zip_attrib_is_symlink(uint32_t attrib, int32_t version_madeby) { uint32_t posix_attrib = 0; uint8_t system = MZ_HOST_SYSTEM(version_madeby); int32_t err = MZ_OK; err = mz_zip_attrib_convert(system, attrib, MZ_HOST_SYSTEM_UNIX, &posix_attrib); if (err == MZ_OK) { if ((posix_attrib & 0170000) == 0120000) /* S_ISLNK */ return MZ_OK; } return MZ_EXIST_ERROR; } int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t target_sys, uint32_t *target_attrib) { if (!target_attrib) return MZ_PARAM_ERROR; *target_attrib = 0; if ((src_sys == MZ_HOST_SYSTEM_MSDOS) || (src_sys == MZ_HOST_SYSTEM_WINDOWS_NTFS)) { if ((target_sys == MZ_HOST_SYSTEM_MSDOS) || (target_sys == MZ_HOST_SYSTEM_WINDOWS_NTFS)) { *target_attrib = src_attrib; return MZ_OK; } if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) return mz_zip_attrib_win32_to_posix(src_attrib, target_attrib); } else if ((src_sys == MZ_HOST_SYSTEM_UNIX) || (src_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (src_sys == MZ_HOST_SYSTEM_RISCOS)) { /* If high bytes are set, it contains unix specific attributes */ if ((src_attrib >> 16) != 0) src_attrib >>= 16; if ((target_sys == MZ_HOST_SYSTEM_UNIX) || (target_sys == MZ_HOST_SYSTEM_OSX_DARWIN) || (target_sys == MZ_HOST_SYSTEM_RISCOS)) { *target_attrib = src_attrib; return MZ_OK; } if ((target_sys == MZ_HOST_SYSTEM_MSDOS) || (target_sys == MZ_HOST_SYSTEM_WINDOWS_NTFS)) return mz_zip_attrib_posix_to_win32(src_attrib, target_attrib); } return MZ_SUPPORT_ERROR; } int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attrib) { if (!win32_attrib) return MZ_PARAM_ERROR; *win32_attrib = 0; /* S_IWUSR | S_IWGRP | S_IWOTH | S_IXUSR | S_IXGRP | S_IXOTH */ if ((posix_attrib & 0000333) == 0 && (posix_attrib & 0000444) != 0) *win32_attrib |= 0x01; /* FILE_ATTRIBUTE_READONLY */ /* S_IFLNK */ if ((posix_attrib & 0170000) == 0120000) *win32_attrib |= 0x400; /* FILE_ATTRIBUTE_REPARSE_POINT */ /* S_IFDIR */ else if ((posix_attrib & 0170000) == 0040000) *win32_attrib |= 0x10; /* FILE_ATTRIBUTE_DIRECTORY */ /* S_IFREG */ else *win32_attrib |= 0x80; /* FILE_ATTRIBUTE_NORMAL */ return MZ_OK; } int32_t mz_zip_attrib_win32_to_posix(uint32_t win32_attrib, uint32_t *posix_attrib) { if (!posix_attrib) return MZ_PARAM_ERROR; *posix_attrib = 0000444; /* S_IRUSR | S_IRGRP | S_IROTH */ /* FILE_ATTRIBUTE_READONLY */ if ((win32_attrib & 0x01) == 0) *posix_attrib |= 0000222; /* S_IWUSR | S_IWGRP | S_IWOTH */ /* FILE_ATTRIBUTE_REPARSE_POINT */ if ((win32_attrib & 0x400) == 0x400) *posix_attrib |= 0120000; /* S_IFLNK */ /* FILE_ATTRIBUTE_DIRECTORY */ else if ((win32_attrib & 0x10) == 0x10) *posix_attrib |= 0040111; /* S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH */ else *posix_attrib |= 0100000; /* S_IFREG */ return MZ_OK; } /***************************************************************************/ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, uint16_t *length) { int32_t err = MZ_OK; uint16_t field_type = 0; uint16_t field_length = 0; if (max_seek < 4) return MZ_EXIST_ERROR; do { err = mz_stream_read_uint16(stream, &field_type); if (err == MZ_OK) err = mz_stream_read_uint16(stream, &field_length); if (err != MZ_OK) break; if (type == field_type) { if (length) *length = field_length; return MZ_OK; } max_seek -= field_length - 4; if (max_seek < 0) return MZ_EXIST_ERROR; err = mz_stream_seek(stream, field_length, MZ_SEEK_CUR); } while (err == MZ_OK); return MZ_EXIST_ERROR; } int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield_size, uint16_t type, uint16_t *length) { void *file_extra_stream = NULL; int32_t err = MZ_OK; if (!extrafield || !extrafield_size) return MZ_PARAM_ERROR; file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(file_extra_stream, (void *)extrafield, extrafield_size); err = mz_zip_extrafield_find(file_extra_stream, type, extrafield_size, length); mz_stream_mem_delete(&file_extra_stream); return err; } int32_t mz_zip_extrafield_read(void *stream, uint16_t *type, uint16_t *length) { int32_t err = MZ_OK; if (!type || !length) return MZ_PARAM_ERROR; err = mz_stream_read_uint16(stream, type); if (err == MZ_OK) err = mz_stream_read_uint16(stream, length); return err; } int32_t mz_zip_extrafield_write(void *stream, uint16_t type, uint16_t length) { int32_t err = MZ_OK; err = mz_stream_write_uint16(stream, type); if (err == MZ_OK) err = mz_stream_write_uint16(stream, length); return err; } /***************************************************************************/ static int32_t mz_zip_invalid_date(const struct tm *ptm) { #define datevalue_in_range(min, max, value) ((min) <= (value) && (value) <= (max)) return (!datevalue_in_range(0, 127 + 80, ptm->tm_year) || /* 1980-based year, allow 80 extra */ !datevalue_in_range(0, 11, ptm->tm_mon) || !datevalue_in_range(1, 31, ptm->tm_mday) || !datevalue_in_range(0, 23, ptm->tm_hour) || !datevalue_in_range(0, 59, ptm->tm_min) || !datevalue_in_range(0, 59, ptm->tm_sec)); #undef datevalue_in_range } static void mz_zip_dosdate_to_raw_tm(uint64_t dos_date, struct tm *ptm) { uint64_t date = (uint64_t)(dos_date >> 16); ptm->tm_mday = (uint16_t)(date & 0x1f); ptm->tm_mon = (uint16_t)(((date & 0x1E0) / 0x20) - 1); ptm->tm_year = (uint16_t)(((date & 0x0FE00) / 0x0200) + 80); ptm->tm_hour = (uint16_t)((dos_date & 0xF800) / 0x800); ptm->tm_min = (uint16_t)((dos_date & 0x7E0) / 0x20); ptm->tm_sec = (uint16_t)(2 * (dos_date & 0x1f)); ptm->tm_isdst = -1; } int32_t mz_zip_dosdate_to_tm(uint64_t dos_date, struct tm *ptm) { if (!ptm) return MZ_PARAM_ERROR; mz_zip_dosdate_to_raw_tm(dos_date, ptm); if (mz_zip_invalid_date(ptm)) { /* Invalid date stored, so don't return it */ memset(ptm, 0, sizeof(struct tm)); return MZ_FORMAT_ERROR; } return MZ_OK; } time_t mz_zip_dosdate_to_time_t(uint64_t dos_date) { struct tm ptm; mz_zip_dosdate_to_raw_tm(dos_date, &ptm); return mktime(&ptm); } int32_t mz_zip_time_t_to_tm(time_t unix_time, struct tm *ptm) { struct tm ltm; if (!ptm) return MZ_PARAM_ERROR; if (!localtime_r(&unix_time, <m)) { /* Returns a 1900-based year */ /* Invalid date stored, so don't return it */ memset(ptm, 0, sizeof(struct tm)); return MZ_INTERNAL_ERROR; } memcpy(ptm, <m, sizeof(struct tm)); return MZ_OK; } uint32_t mz_zip_time_t_to_dos_date(time_t unix_time) { struct tm ptm; mz_zip_time_t_to_tm(unix_time, &ptm); return mz_zip_tm_to_dosdate((const struct tm *)&ptm); } uint32_t mz_zip_tm_to_dosdate(const struct tm *ptm) { struct tm fixed_tm; /* Years supported: */ /* [00, 79] (assumed to be between 2000 and 2079) */ /* [80, 207] (assumed to be between 1980 and 2107, typical output of old */ /* software that does 'year-1900' to get a double digit year) */ /* [1980, 2107] (due to format limitations, only years 1980-2107 can be stored.) */ memcpy(&fixed_tm, ptm, sizeof(struct tm)); if (fixed_tm.tm_year >= 1980) /* range [1980, 2107] */ fixed_tm.tm_year -= 1980; else if (fixed_tm.tm_year >= 80) /* range [80, 207] */ fixed_tm.tm_year -= 80; else /* range [00, 79] */ fixed_tm.tm_year += 20; if (mz_zip_invalid_date(&fixed_tm)) return 0; return (((uint32_t)fixed_tm.tm_mday + (32 * ((uint32_t)fixed_tm.tm_mon + 1)) + (512 * (uint32_t)fixed_tm.tm_year)) << 16) | (((uint32_t)fixed_tm.tm_sec / 2) + (32 * (uint32_t)fixed_tm.tm_min) + (2048 * (uint32_t)fixed_tm.tm_hour)); } int32_t mz_zip_ntfs_to_unix_time(uint64_t ntfs_time, time_t *unix_time) { *unix_time = (time_t)((ntfs_time - 116444736000000000LL) / 10000000); return MZ_OK; } int32_t mz_zip_unix_to_ntfs_time(time_t unix_time, uint64_t *ntfs_time) { *ntfs_time = ((uint64_t)unix_time * 10000000) + 116444736000000000LL; return MZ_OK; } /***************************************************************************/ int32_t mz_zip_path_compare(const char *path1, const char *path2, uint8_t ignore_case) { do { if ((*path1 == '\\' && *path2 == '/') || (*path2 == '\\' && *path1 == '/')) { /* Ignore comparison of path slashes */ } else if (ignore_case) { if (tolower(*path1) != tolower(*path2)) break; } else if (*path1 != *path2) { break; } path1 += 1; path2 += 1; } while (*path1 != 0 && *path2 != 0); if (ignore_case) return (int32_t)(tolower(*path1) - tolower(*path2)); return (int32_t)(*path1 - *path2); } /***************************************************************************/ const char* mz_zip_get_compression_method_string(int32_t compression_method) { const char *method = "?"; switch (compression_method) { case MZ_COMPRESS_METHOD_STORE: method = "stored"; break; case MZ_COMPRESS_METHOD_DEFLATE: method = "deflate"; break; case MZ_COMPRESS_METHOD_BZIP2: method = "bzip2"; break; case MZ_COMPRESS_METHOD_LZMA: method = "lzma"; break; case MZ_COMPRESS_METHOD_XZ: method = "xz"; break; case MZ_COMPRESS_METHOD_ZSTD: method = "zstd"; break; } return method; } /***************************************************************************/ sight-23.1.0/3rd-party/minizip/mz_zip.h000066400000000000000000000253271450532053500177130ustar00rootroot00000000000000/* mz_zip.h -- Zip manipulation part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng Copyright (C) 2009-2010 Mathias Svensson Modifications for Zip64 support http://result42.com Copyright (C) 1998-2010 Gilles Vollant https://www.winimage.com/zLibDll/minizip.html This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_ZIP_H #define MZ_ZIP_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ typedef struct mz_zip_file_s { uint16_t version_madeby; /* version made by */ uint16_t version_needed; /* version needed to extract */ uint16_t flag; /* general purpose bit flag */ uint16_t compression_method; /* compression method */ time_t modified_date; /* last modified date in unix time */ time_t accessed_date; /* last accessed date in unix time */ time_t creation_date; /* creation date in unix time */ uint32_t crc; /* crc-32 */ int64_t compressed_size; /* compressed size */ int64_t uncompressed_size; /* uncompressed size */ uint16_t filename_size; /* filename length */ uint16_t extrafield_size; /* extra field length */ uint16_t comment_size; /* file comment length */ uint32_t disk_number; /* disk number start */ int64_t disk_offset; /* relative offset of local header */ uint16_t internal_fa; /* internal file attributes */ uint32_t external_fa; /* external file attributes */ const char *filename; /* filename utf8 null-terminated string */ const uint8_t *extrafield; /* extrafield data */ const char *comment; /* comment utf8 null-terminated string */ const char *linkname; /* sym-link filename utf8 null-terminated string */ uint16_t zip64; /* zip64 extension mode */ uint16_t aes_version; /* winzip aes extension if not 0 */ uint8_t aes_strength; /* winzip aes encryption strength */ uint16_t pk_verify; /* pkware encryption verifier */ } mz_zip_file, mz_zip_entry; /***************************************************************************/ typedef int32_t (*mz_zip_locate_entry_cb)(void *handle, void *userdata, mz_zip_file *file_info); /***************************************************************************/ void * mz_zip_create(void); /* Create zip instance for opening */ void mz_zip_delete(void **handle); /* Delete zip object */ int32_t mz_zip_open(void *handle, void *stream, int32_t mode); /* Create a zip file, no delete file in zip functionality */ int32_t mz_zip_close(void *handle); /* Close the zip file */ int32_t mz_zip_get_comment(void *handle, const char **comment); /* Get a pointer to the global comment */ int32_t mz_zip_set_comment(void *handle, const char *comment); /* Sets the global comment used for writing zip file */ int32_t mz_zip_get_version_madeby(void *handle, uint16_t *version_madeby); /* Get the version made by */ int32_t mz_zip_set_version_madeby(void *handle, uint16_t version_madeby); /* Sets the version made by used for writing zip file */ int32_t mz_zip_set_recover(void *handle, uint8_t recover); /* Sets the ability to recover the central dir by reading local file headers */ int32_t mz_zip_set_data_descriptor(void *handle, uint8_t data_descriptor); /* Sets the use of data descriptor flag when writing zip entries */ int32_t mz_zip_get_stream(void *handle, void **stream); /* Get a pointer to the stream used to open */ int32_t mz_zip_set_cd_stream(void *handle, int64_t cd_start_pos, void *cd_stream); /* Sets the stream to use for reading the central dir */ int32_t mz_zip_get_cd_mem_stream(void *handle, void **cd_mem_stream); /* Get a pointer to the stream used to store the central dir in memory */ int32_t mz_zip_set_number_entry(void *handle, uint64_t number_entry); /* Sets the total number of entries */ int32_t mz_zip_get_number_entry(void *handle, uint64_t *number_entry); /* Get the total number of entries */ int32_t mz_zip_set_disk_number_with_cd(void *handle, uint32_t disk_number_with_cd); /* Sets the disk number containing the central directory record */ int32_t mz_zip_get_disk_number_with_cd(void *handle, uint32_t *disk_number_with_cd); /* Get the disk number containing the central directory record */ /***************************************************************************/ int32_t mz_zip_entry_is_open(void *handle); /* Check to see if entry is open for read/write */ int32_t mz_zip_entry_read_open(void *handle, uint8_t raw, const char *password); /* Open for reading the current file in the zip file */ int32_t mz_zip_entry_read(void *handle, void *buf, int32_t len); /* Read bytes from the current file in the zip file */ int32_t mz_zip_entry_read_close(void *handle, uint32_t *crc32, int64_t *compressed_size, int64_t *uncompressed_size); /* Close the current file for reading and get data descriptor values */ int32_t mz_zip_entry_write_open(void *handle, const mz_zip_file *file_info, int16_t compress_level, uint8_t raw, const char *password); /* Open for writing the current file in the zip file */ int32_t mz_zip_entry_write(void *handle, const void *buf, int32_t len); /* Write bytes from the current file in the zip file */ int32_t mz_zip_entry_write_close(void *handle, uint32_t crc32, int64_t compressed_size, int64_t uncompressed_size); /* Close the current file for writing and set data descriptor values */ int32_t mz_zip_entry_seek_local_header(void *handle); /* Seeks to the local header for the entry */ int32_t mz_zip_entry_get_compress_stream(void *handle, void **compress_stream); /* Get a pointer to the compression stream used for the current entry */ int32_t mz_zip_entry_close_raw(void *handle, int64_t uncompressed_size, uint32_t crc32); /* Close the current file in the zip file where raw is compressed data */ int32_t mz_zip_entry_close(void *handle); /* Close the current file in the zip file */ /***************************************************************************/ int32_t mz_zip_entry_is_dir(void *handle); /* Checks to see if the entry is a directory */ int32_t mz_zip_entry_is_symlink(void *handle); /* Checks to see if the entry is a symbolic link */ int32_t mz_zip_entry_get_info(void *handle, mz_zip_file **file_info); /* Get info about the current file, only valid while current entry is open */ int32_t mz_zip_entry_get_local_info(void *handle, mz_zip_file **local_file_info); /* Get local info about the current file, only valid while current entry is being read */ int32_t mz_zip_entry_set_extrafield(void *handle, const uint8_t *extrafield, uint16_t extrafield_size); /* Sets or updates the extra field for the entry to be used before writing cd */ int64_t mz_zip_get_entry(void *handle); /* Return offset of the current entry in the zip file */ int32_t mz_zip_goto_entry(void *handle, int64_t cd_pos); /* Go to specified entry in the zip file */ int32_t mz_zip_goto_first_entry(void *handle); /* Go to the first entry in the zip file */ int32_t mz_zip_goto_next_entry(void *handle); /* Go to the next entry in the zip file or MZ_END_OF_LIST if reaching the end */ int32_t mz_zip_locate_entry(void *handle, const char *filename, uint8_t ignore_case); /* Locate the file with the specified name in the zip file or MZ_END_LIST if not found */ int32_t mz_zip_locate_first_entry(void *handle, void *userdata, mz_zip_locate_entry_cb cb); /* Locate the first matching entry based on a match callback */ int32_t mz_zip_locate_next_entry(void *handle, void *userdata, mz_zip_locate_entry_cb cb); /* Locate the next matching entry based on a match callback */ /***************************************************************************/ int32_t mz_zip_attrib_is_dir(uint32_t attrib, int32_t version_madeby); /* Checks to see if the attribute is a directory based on platform */ int32_t mz_zip_attrib_is_symlink(uint32_t attrib, int32_t version_madeby); /* Checks to see if the attribute is a symbolic link based on platform */ int32_t mz_zip_attrib_convert(uint8_t src_sys, uint32_t src_attrib, uint8_t target_sys, uint32_t *target_attrib); /* Converts file attributes from one host system to another */ int32_t mz_zip_attrib_posix_to_win32(uint32_t posix_attrib, uint32_t *win32_attrib); /* Converts posix file attributes to win32 file attributes */ int32_t mz_zip_attrib_win32_to_posix(uint32_t win32_attrib, uint32_t *posix_attrib); /* Converts win32 file attributes to posix file attributes */ /***************************************************************************/ int32_t mz_zip_extrafield_find(void *stream, uint16_t type, int32_t max_seek, uint16_t *length); /* Seeks to extra field by its type and returns its length */ int32_t mz_zip_extrafield_contains(const uint8_t *extrafield, int32_t extrafield_size, uint16_t type, uint16_t *length); /* Gets whether an extrafield exists and its size */ int32_t mz_zip_extrafield_read(void *stream, uint16_t *type, uint16_t *length); /* Reads an extrafield header from a stream */ int32_t mz_zip_extrafield_write(void *stream, uint16_t type, uint16_t length); /* Writes an extrafield header to a stream */ /***************************************************************************/ int32_t mz_zip_dosdate_to_tm(uint64_t dos_date, struct tm *ptm); /* Convert dos date/time format to struct tm */ time_t mz_zip_dosdate_to_time_t(uint64_t dos_date); /* Convert dos date/time format to time_t */ int32_t mz_zip_time_t_to_tm(time_t unix_time, struct tm *ptm); /* Convert time_t to time struct */ uint32_t mz_zip_time_t_to_dos_date(time_t unix_time); /* Convert time_t to dos date/time format */ uint32_t mz_zip_tm_to_dosdate(const struct tm *ptm); /* Convert struct tm to dos date/time format */ int32_t mz_zip_ntfs_to_unix_time(uint64_t ntfs_time, time_t *unix_time); /* Convert ntfs time to unix time */ int32_t mz_zip_unix_to_ntfs_time(time_t unix_time, uint64_t *ntfs_time); /* Convert unix time to ntfs time */ /***************************************************************************/ int32_t mz_zip_path_compare(const char *path1, const char *path2, uint8_t ignore_case); /* Compare two paths without regard to slashes */ /***************************************************************************/ const char* mz_zip_get_compression_method_string(int32_t compression_method); /* Gets a string representing the compression method */ /***************************************************************************/ #ifdef __cplusplus } #endif #endif /* _ZIP_H */ sight-23.1.0/3rd-party/minizip/mz_zip_rw.c000066400000000000000000001723301450532053500204130ustar00rootroot00000000000000/* mz_zip_rw.c -- Zip reader/writer part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #include "mz.h" #include "mz_crypt.h" #include "mz_os.h" #include "mz_strm.h" #include "mz_strm_buf.h" #include "mz_strm_mem.h" #include "mz_strm_os.h" #include "mz_strm_split.h" #include "mz_strm_wzaes.h" #include "mz_zip.h" #include "mz_zip_rw.h" /***************************************************************************/ #define MZ_DEFAULT_PROGRESS_INTERVAL (1000u) #define MZ_ZIP_CD_FILENAME ("__cdcd__") /***************************************************************************/ typedef struct mz_zip_reader_s { void *zip_handle; void *file_stream; void *buffered_stream; void *split_stream; void *mem_stream; void *hash; uint16_t hash_algorithm; uint16_t hash_digest_size; mz_zip_file *file_info; const char *pattern; uint8_t pattern_ignore_case; const char *password; void *overwrite_userdata; mz_zip_reader_overwrite_cb overwrite_cb; void *password_userdata; mz_zip_reader_password_cb password_cb; void *progress_userdata; mz_zip_reader_progress_cb progress_cb; uint32_t progress_cb_interval_ms; void *entry_userdata; mz_zip_reader_entry_cb entry_cb; uint8_t raw; uint8_t buffer[UINT16_MAX]; int32_t encoding; uint8_t sign_required; uint8_t cd_verified; uint8_t cd_zipped; uint8_t entry_verified; uint8_t recover; } mz_zip_reader; /***************************************************************************/ int32_t mz_zip_reader_is_open(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (!reader) return MZ_PARAM_ERROR; if (!reader->zip_handle) return MZ_PARAM_ERROR; return MZ_OK; } int32_t mz_zip_reader_open(void *handle, void *stream) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; reader->cd_verified = 0; reader->cd_zipped = 0; reader->zip_handle = mz_zip_create(); if (!reader->zip_handle) return MZ_MEM_ERROR; mz_zip_set_recover(reader->zip_handle, reader->recover); err = mz_zip_open(reader->zip_handle, stream, MZ_OPEN_MODE_READ); if (err != MZ_OK) { mz_zip_reader_close(handle); return err; } mz_zip_reader_unzip_cd(reader); return MZ_OK; } int32_t mz_zip_reader_open_file(void *handle, const char *path) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; mz_zip_reader_close(handle); reader->file_stream = mz_stream_os_create(); if (!reader->file_stream) return MZ_MEM_ERROR; reader->buffered_stream = mz_stream_buffered_create(); if (!reader->buffered_stream) { mz_stream_os_delete(&reader->file_stream); return MZ_MEM_ERROR; } reader->split_stream = mz_stream_split_create(); if (!reader->split_stream) { mz_stream_os_delete(&reader->file_stream); mz_stream_buffered_delete(&reader->buffered_stream); return MZ_MEM_ERROR; } mz_stream_set_base(reader->buffered_stream, reader->file_stream); mz_stream_set_base(reader->split_stream, reader->buffered_stream); err = mz_stream_open(reader->split_stream, path, MZ_OPEN_MODE_READ); if (err == MZ_OK) err = mz_zip_reader_open(handle, reader->split_stream); return err; } int32_t mz_zip_reader_open_file_in_memory(void *handle, const char *path) { mz_zip_reader *reader = (mz_zip_reader *)handle; void *file_stream = NULL; int64_t file_size = 0; int32_t err = 0; mz_zip_reader_close(handle); file_stream = mz_stream_os_create(); if (!file_stream) return MZ_MEM_ERROR; err = mz_stream_os_open(file_stream, path, MZ_OPEN_MODE_READ); if (err != MZ_OK) { mz_stream_os_delete(&file_stream); mz_zip_reader_close(handle); return err; } mz_stream_os_seek(file_stream, 0, MZ_SEEK_END); file_size = mz_stream_os_tell(file_stream); mz_stream_os_seek(file_stream, 0, MZ_SEEK_SET); reader->mem_stream = mz_stream_mem_create(); if ((file_size <= 0) || (file_size > UINT32_MAX) || (!reader->mem_stream)) { /* Memory size is too large or too small */ mz_stream_os_close(file_stream); mz_stream_os_delete(&file_stream); mz_zip_reader_close(handle); return MZ_MEM_ERROR; } mz_stream_mem_set_grow_size(reader->mem_stream, (int32_t)file_size); mz_stream_mem_open(reader->mem_stream, NULL, MZ_OPEN_MODE_CREATE); err = mz_stream_copy(reader->mem_stream, file_stream, (int32_t)file_size); mz_stream_os_close(file_stream); mz_stream_os_delete(&file_stream); if (err == MZ_OK) err = mz_zip_reader_open(handle, reader->mem_stream); if (err != MZ_OK) mz_zip_reader_close(handle); return err; } int32_t mz_zip_reader_open_buffer(void *handle, uint8_t *buf, int32_t len, uint8_t copy) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; mz_zip_reader_close(handle); reader->mem_stream = mz_stream_mem_create(); if (!reader->mem_stream) return MZ_MEM_ERROR; if (copy) { mz_stream_mem_set_grow_size(reader->mem_stream, len); mz_stream_mem_open(reader->mem_stream, NULL, MZ_OPEN_MODE_CREATE); mz_stream_mem_write(reader->mem_stream, buf, len); mz_stream_mem_seek(reader->mem_stream, 0, MZ_SEEK_SET); } else { mz_stream_mem_open(reader->mem_stream, NULL, MZ_OPEN_MODE_READ); mz_stream_mem_set_buffer(reader->mem_stream, buf, len); } if (err == MZ_OK) err = mz_zip_reader_open(handle, reader->mem_stream); return err; } int32_t mz_zip_reader_close(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; if (reader->zip_handle) { err = mz_zip_close(reader->zip_handle); mz_zip_delete(&reader->zip_handle); } if (reader->split_stream) { mz_stream_split_close(reader->split_stream); mz_stream_split_delete(&reader->split_stream); } if (reader->buffered_stream) mz_stream_buffered_delete(&reader->buffered_stream); if (reader->file_stream) mz_stream_os_delete(&reader->file_stream); if (reader->mem_stream) { mz_stream_close(reader->mem_stream); mz_stream_delete(&reader->mem_stream); } return err; } /***************************************************************************/ int32_t mz_zip_reader_unzip_cd(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; mz_zip_file *cd_info = NULL; void *cd_mem_stream = NULL; void *new_cd_stream = NULL; void *file_extra_stream = NULL; uint64_t number_entry = 0; int32_t err = MZ_OK; err = mz_zip_reader_goto_first_entry(handle); if (err != MZ_OK) return err; err = mz_zip_reader_entry_get_info(handle, &cd_info); if (err != MZ_OK) return err; if (strcmp(cd_info->filename, MZ_ZIP_CD_FILENAME) != 0) return mz_zip_reader_goto_first_entry(handle); err = mz_zip_reader_entry_open(handle); if (err != MZ_OK) return err; file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(file_extra_stream, (void *)cd_info->extrafield, cd_info->extrafield_size); err = mz_zip_extrafield_find(file_extra_stream, MZ_ZIP_EXTENSION_CDCD, INT32_MAX, NULL); if (err == MZ_OK) err = mz_stream_read_uint64(file_extra_stream, &number_entry); mz_stream_mem_delete(&file_extra_stream); if (err != MZ_OK) return err; mz_zip_get_cd_mem_stream(reader->zip_handle, &cd_mem_stream); if (mz_stream_mem_is_open(cd_mem_stream) != MZ_OK) mz_stream_mem_open(cd_mem_stream, NULL, MZ_OPEN_MODE_CREATE); err = mz_stream_seek(cd_mem_stream, 0, MZ_SEEK_SET); if (err == MZ_OK) err = mz_stream_copy_stream(cd_mem_stream, NULL, handle, mz_zip_reader_entry_read, (int32_t)cd_info->uncompressed_size); if (err == MZ_OK) { reader->cd_zipped = 1; mz_zip_set_cd_stream(reader->zip_handle, 0, cd_mem_stream); mz_zip_set_number_entry(reader->zip_handle, number_entry); err = mz_zip_reader_goto_first_entry(handle); } reader->cd_verified = reader->entry_verified; mz_stream_mem_delete(&new_cd_stream); return err; } /***************************************************************************/ static int32_t mz_zip_reader_locate_entry_cb(void *handle, void *userdata, mz_zip_file *file_info) { mz_zip_reader *reader = (mz_zip_reader *)userdata; int32_t result = 0; MZ_UNUSED(handle); result = mz_path_compare_wc(file_info->filename, reader->pattern, reader->pattern_ignore_case); return result; } int32_t mz_zip_reader_goto_first_entry(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; if (mz_zip_reader_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (mz_zip_entry_is_open(reader->zip_handle) == MZ_OK) mz_zip_reader_entry_close(handle); if (!reader->pattern) err = mz_zip_goto_first_entry(reader->zip_handle); else err = mz_zip_locate_first_entry(reader->zip_handle, reader, mz_zip_reader_locate_entry_cb); reader->file_info = NULL; if (err == MZ_OK) err = mz_zip_entry_get_info(reader->zip_handle, &reader->file_info); return err; } int32_t mz_zip_reader_goto_next_entry(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; if (mz_zip_reader_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (mz_zip_entry_is_open(reader->zip_handle) == MZ_OK) mz_zip_reader_entry_close(handle); if (!reader->pattern) err = mz_zip_goto_next_entry(reader->zip_handle); else err = mz_zip_locate_next_entry(reader->zip_handle, reader, mz_zip_reader_locate_entry_cb); reader->file_info = NULL; if (err == MZ_OK) err = mz_zip_entry_get_info(reader->zip_handle, &reader->file_info); return err; } int32_t mz_zip_reader_locate_entry(void *handle, const char *filename, uint8_t ignore_case) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; if (mz_zip_entry_is_open(reader->zip_handle) == MZ_OK) mz_zip_reader_entry_close(handle); err = mz_zip_locate_entry(reader->zip_handle, filename, ignore_case); reader->file_info = NULL; if (err == MZ_OK) err = mz_zip_entry_get_info(reader->zip_handle, &reader->file_info); return err; } /***************************************************************************/ int32_t mz_zip_reader_entry_open(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; const char *password = NULL; char password_buf[120]; reader->entry_verified = 0; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info) return MZ_PARAM_ERROR; /* If the entry isn't open for reading, open it */ if (mz_zip_entry_is_open(reader->zip_handle) == MZ_OK) return MZ_OK; password = reader->password; /* Check if we need a password and ask for it if we need to */ if (!password && reader->password_cb && (reader->file_info->flag & MZ_ZIP_FLAG_ENCRYPTED)) { reader->password_cb(handle, reader->password_userdata, reader->file_info, password_buf, sizeof(password_buf)); password = password_buf; } err = mz_zip_entry_read_open(reader->zip_handle, reader->raw, password); #ifndef MZ_ZIP_NO_CRYPTO if (err != MZ_OK) return err; if (mz_zip_reader_entry_get_first_hash(handle, &reader->hash_algorithm, &reader->hash_digest_size) == MZ_OK) { reader->hash = mz_crypt_sha_create(); if (!reader->hash) return MZ_MEM_ERROR; if (reader->hash_algorithm == MZ_HASH_SHA1) err = mz_crypt_sha_set_algorithm(reader->hash, MZ_HASH_SHA1); else if (reader->hash_algorithm == MZ_HASH_SHA256) err = mz_crypt_sha_set_algorithm(reader->hash, MZ_HASH_SHA256); else err = MZ_SUPPORT_ERROR; if (err == MZ_OK) mz_crypt_sha_begin(reader->hash); } else if (reader->sign_required && !reader->cd_verified) err = MZ_SIGN_ERROR; #endif return err; } int32_t mz_zip_reader_entry_close(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; int32_t err_close = MZ_OK; #ifndef MZ_ZIP_NO_CRYPTO int32_t err_hash = MZ_OK; uint8_t computed_hash[MZ_HASH_MAX_SIZE]; uint8_t expected_hash[MZ_HASH_MAX_SIZE]; if (reader->hash) { mz_crypt_sha_end(reader->hash, computed_hash, sizeof(computed_hash)); mz_crypt_sha_delete(&reader->hash); err_hash = mz_zip_reader_entry_get_hash(handle, reader->hash_algorithm, expected_hash, reader->hash_digest_size); if (err_hash == MZ_OK) { /* Verify expected hash against computed hash */ if (memcmp(computed_hash, expected_hash, reader->hash_digest_size) != 0) err = MZ_CRC_ERROR; } } #endif err_close = mz_zip_entry_close(reader->zip_handle); if (err == MZ_OK) err = err_close; return err; } int32_t mz_zip_reader_entry_read(void *handle, void *buf, int32_t len) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t read = 0; read = mz_zip_entry_read(reader->zip_handle, buf, len); #ifndef MZ_ZIP_NO_CRYPTO if (read > 0 && reader->hash) mz_crypt_sha_update(reader->hash, buf, read); #endif return read; } int32_t mz_zip_reader_entry_get_hash(void *handle, uint16_t algorithm, uint8_t *digest, int32_t digest_size) { mz_zip_reader *reader = (mz_zip_reader *)handle; void *file_extra_stream = NULL; int32_t err = MZ_OK; int32_t return_err = MZ_EXIST_ERROR; uint16_t cur_algorithm = 0; uint16_t cur_digest_size = 0; file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(file_extra_stream, (void *)reader->file_info->extrafield, reader->file_info->extrafield_size); do { err = mz_zip_extrafield_find(file_extra_stream, MZ_ZIP_EXTENSION_HASH, INT32_MAX, NULL); if (err != MZ_OK) break; err = mz_stream_read_uint16(file_extra_stream, &cur_algorithm); if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &cur_digest_size); if ((err == MZ_OK) && (cur_algorithm == algorithm) && (cur_digest_size <= digest_size) && (cur_digest_size <= MZ_HASH_MAX_SIZE)) { /* Read hash digest */ if (mz_stream_read(file_extra_stream, digest, digest_size) == cur_digest_size) return_err = MZ_OK; break; } else { err = mz_stream_seek(file_extra_stream, cur_digest_size, MZ_SEEK_CUR); } } while (err == MZ_OK); mz_stream_mem_delete(&file_extra_stream); return return_err; } int32_t mz_zip_reader_entry_get_first_hash(void *handle, uint16_t *algorithm, uint16_t *digest_size) { mz_zip_reader *reader = (mz_zip_reader *)handle; void *file_extra_stream = NULL; int32_t err = MZ_OK; uint16_t cur_algorithm = 0; uint16_t cur_digest_size = 0; if (!reader || !algorithm) return MZ_PARAM_ERROR; file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(file_extra_stream, (void *)reader->file_info->extrafield, reader->file_info->extrafield_size); err = mz_zip_extrafield_find(file_extra_stream, MZ_ZIP_EXTENSION_HASH, INT32_MAX, NULL); if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &cur_algorithm); if (err == MZ_OK) err = mz_stream_read_uint16(file_extra_stream, &cur_digest_size); if (algorithm) *algorithm = cur_algorithm; if (digest_size) *digest_size = cur_digest_size; mz_stream_mem_delete(&file_extra_stream); return err; } int32_t mz_zip_reader_entry_get_info(void *handle, mz_zip_file **file_info) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; if (!file_info || mz_zip_reader_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; *file_info = reader->file_info; if (!*file_info) return MZ_EXIST_ERROR; return err; } int32_t mz_zip_reader_entry_is_dir(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (mz_zip_reader_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; return mz_zip_entry_is_dir(reader->zip_handle); } int32_t mz_zip_reader_entry_save_process(void *handle, void *stream, mz_stream_write_cb write_cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; int32_t read = 0; int32_t written = 0; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info || !write_cb) return MZ_PARAM_ERROR; /* If the entry isn't open for reading, open it */ if (mz_zip_entry_is_open(reader->zip_handle) != MZ_OK) err = mz_zip_reader_entry_open(handle); if (err != MZ_OK) return err; /* Unzip entry in zip file */ read = mz_zip_reader_entry_read(handle, reader->buffer, sizeof(reader->buffer)); if (read == 0) { /* If we are done close the entry */ err = mz_zip_reader_entry_close(handle); if (err != MZ_OK) return err; return MZ_END_OF_STREAM; } if (read > 0) { /* Write the data to the specified stream */ written = write_cb(stream, reader->buffer, read); if (written != read) return MZ_WRITE_ERROR; } return read; } int32_t mz_zip_reader_entry_save(void *handle, void *stream, mz_stream_write_cb write_cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; uint64_t current_time = 0; uint64_t update_time = 0; int64_t current_pos = 0; int64_t update_pos = 0; int32_t err = MZ_OK; int32_t written = 0; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info) return MZ_PARAM_ERROR; /* Update the progress at the beginning */ if (reader->progress_cb) reader->progress_cb(handle, reader->progress_userdata, reader->file_info, current_pos); /* Write data to stream until done */ while (err == MZ_OK) { written = mz_zip_reader_entry_save_process(handle, stream, write_cb); if (written == MZ_END_OF_STREAM) break; if (written > 0) current_pos += written; if (written < 0) err = written; /* Update progress if enough time have passed */ current_time = mz_os_ms_time(); if ((current_time - update_time) > reader->progress_cb_interval_ms) { if (reader->progress_cb) reader->progress_cb(handle, reader->progress_userdata, reader->file_info, current_pos); update_pos = current_pos; update_time = current_time; } } /* Update the progress at the end */ if (reader->progress_cb && update_pos != current_pos) reader->progress_cb(handle, reader->progress_userdata, reader->file_info, current_pos); return err; } int32_t mz_zip_reader_entry_save_file(void *handle, const char *path) { mz_zip_reader *reader = (mz_zip_reader *)handle; void *stream = NULL; uint32_t target_attrib = 0; int32_t err_attrib = 0; int32_t err = MZ_OK; int32_t err_cb = MZ_OK; size_t path_length = 0; char *pathwfs = NULL; char *directory = NULL; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info || !path) return MZ_PARAM_ERROR; path_length = strlen(path); /* Convert to forward slashes for unix which doesn't like backslashes */ pathwfs = (char *)calloc(path_length + 1, sizeof(char)); if (!pathwfs) return MZ_MEM_ERROR; strncat(pathwfs, path, path_length); mz_path_convert_slashes(pathwfs, MZ_PATH_SLASH_UNIX); if (reader->entry_cb) reader->entry_cb(handle, reader->entry_userdata, reader->file_info, pathwfs); directory = (char *)calloc(path_length + 1, sizeof(char)); if (!directory) return MZ_MEM_ERROR; strncat(directory, pathwfs, path_length); mz_path_remove_filename(directory); /* If it is a directory entry then create a directory instead of writing file */ if ((mz_zip_entry_is_dir(reader->zip_handle) == MZ_OK) && (mz_zip_entry_is_symlink(reader->zip_handle) != MZ_OK)) { err = mz_dir_make(directory); goto save_cleanup; } /* Check if file exists and ask if we want to overwrite */ if (reader->overwrite_cb && mz_os_file_exists(pathwfs) == MZ_OK) { err_cb = reader->overwrite_cb(handle, reader->overwrite_userdata, reader->file_info, pathwfs); if (err_cb != MZ_OK) goto save_cleanup; /* We want to overwrite the file so we delete the existing one */ mz_os_unlink(pathwfs); } /* If symbolic link then properly construct destination path and link path */ if ((mz_zip_entry_is_symlink(reader->zip_handle) == MZ_OK) && (mz_path_has_slash(pathwfs) == MZ_OK)) { mz_path_remove_slash(pathwfs); mz_path_remove_filename(directory); } /* Create the output directory if it doesn't already exist */ if (mz_os_is_dir(directory) != MZ_OK) { err = mz_dir_make(directory); if (err != MZ_OK) goto save_cleanup; } /* If it is a symbolic link then create symbolic link instead of writing file */ if (mz_zip_entry_is_symlink(reader->zip_handle) == MZ_OK) { if (reader->file_info->linkname && *reader->file_info->linkname != 0) { /* Create symbolic link from UNIX1 extrafield */ err = mz_os_make_symlink(pathwfs, reader->file_info->linkname); } else if (reader->file_info->uncompressed_size < UINT16_MAX) { /* Create symbolic link from zip entry contents */ stream = mz_stream_mem_create(); if (!stream) { err = MZ_MEM_ERROR; goto save_cleanup; } err = mz_stream_mem_open(stream, NULL, MZ_OPEN_MODE_CREATE); if (err == MZ_OK) err = mz_zip_reader_entry_save(handle, stream, mz_stream_write); if (err == MZ_OK) err = mz_stream_write_uint8(stream, 0); if (err == MZ_OK) { const char *linkname = NULL; if (mz_stream_mem_get_buffer(stream, (const void **)&linkname) == MZ_OK) err = mz_os_make_symlink(pathwfs, linkname); } mz_stream_mem_close(stream); mz_stream_mem_delete(&stream); } /* Don't check return value because we aren't validating symbolic link target */ goto save_cleanup; } /* Create the file on disk so we can save to it */ stream = mz_stream_os_create(); if (!stream) { err = MZ_MEM_ERROR; goto save_cleanup; } err = mz_stream_os_open(stream, pathwfs, MZ_OPEN_MODE_CREATE); if (err == MZ_OK) err = mz_zip_reader_entry_save(handle, stream, mz_stream_write); mz_stream_close(stream); mz_stream_delete(&stream); if (err == MZ_OK) { /* Set the time of the file that has been created */ mz_os_set_file_date(pathwfs, reader->file_info->modified_date, reader->file_info->accessed_date, reader->file_info->creation_date); } if (err == MZ_OK) { /* Set file attributes for the correct system */ err_attrib = mz_zip_attrib_convert(MZ_HOST_SYSTEM(reader->file_info->version_madeby), reader->file_info->external_fa, MZ_VERSION_MADEBY_HOST_SYSTEM, &target_attrib); if (err_attrib == MZ_OK) mz_os_set_file_attribs(pathwfs, target_attrib); } save_cleanup: free(pathwfs); free(directory); return err; } int32_t mz_zip_reader_entry_save_buffer(void *handle, void *buf, int32_t len) { mz_zip_reader *reader = (mz_zip_reader *)handle; void *mem_stream = NULL; int32_t err = MZ_OK; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info || reader->file_info->uncompressed_size > INT32_MAX) return MZ_PARAM_ERROR; if (len != (int32_t)reader->file_info->uncompressed_size) return MZ_BUF_ERROR; /* Create a memory stream backed by our buffer and save to it */ mem_stream = mz_stream_mem_create(); if (!mem_stream) return MZ_MEM_ERROR; mz_stream_mem_set_buffer(mem_stream, buf, len); err = mz_stream_mem_open(mem_stream, NULL, MZ_OPEN_MODE_READ); if (err == MZ_OK) err = mz_zip_reader_entry_save(handle, mem_stream, mz_stream_mem_write); mz_stream_mem_delete(&mem_stream); return err; } int32_t mz_zip_reader_entry_save_buffer_length(void *handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!reader->file_info || reader->file_info->uncompressed_size > INT32_MAX) return MZ_PARAM_ERROR; /* Get the maximum size required for the save buffer */ return (int32_t)reader->file_info->uncompressed_size; } /***************************************************************************/ int32_t mz_zip_reader_save_all(void *handle, const char *destination_dir) { mz_zip_reader *reader = (mz_zip_reader *)handle; int32_t err = MZ_OK; int32_t utf8_name_size = 0; int32_t resolved_name_size = 0; char *utf8_string = NULL; char *path = NULL; char *utf8_name = NULL; char *resolved_name = NULL; err = mz_zip_reader_goto_first_entry(handle); if (err == MZ_END_OF_LIST) return err; while (err == MZ_OK) { /* Assume 4 bytes per character needed + 1 for terminating null */ utf8_name_size = reader->file_info->filename_size * 4 + 1; resolved_name_size = utf8_name_size; if (destination_dir) { /* +1 is for the "/" separator */ resolved_name_size += (int)strlen(destination_dir) + 1; } if (!path) { path = (char *)malloc(resolved_name_size); utf8_name = (char *)malloc(utf8_name_size); resolved_name = (char *)malloc(resolved_name_size); } else { path = (char *)realloc(path, resolved_name_size); utf8_name = (char *)realloc(utf8_name, utf8_name_size); resolved_name = (char *)realloc(resolved_name, resolved_name_size); } if (!path || !utf8_name || !resolved_name) { err = MZ_MEM_ERROR; goto save_all_cleanup; } /* Construct output path */ path[0] = 0; strncpy(utf8_name, reader->file_info->filename, utf8_name_size - 1); utf8_name[utf8_name_size - 1] = 0; if ((reader->encoding > 0) && (reader->file_info->flag & MZ_ZIP_FLAG_UTF8) == 0) { utf8_string = mz_os_utf8_string_create(reader->file_info->filename, reader->encoding); if (utf8_string) { strncpy(utf8_name, (char *)utf8_string, utf8_name_size - 1); utf8_name[utf8_name_size - 1] = 0; mz_os_utf8_string_delete(&utf8_string); } } err = mz_path_resolve(utf8_name, resolved_name, resolved_name_size); if (err != MZ_OK) break; if (destination_dir) mz_path_combine(path, destination_dir, resolved_name_size); mz_path_combine(path, resolved_name, resolved_name_size); /* Save file to disk */ err = mz_zip_reader_entry_save_file(handle, path); if (err == MZ_OK) err = mz_zip_reader_goto_next_entry(handle); } if (err == MZ_END_OF_LIST) err = MZ_OK; save_all_cleanup: free(path); free(utf8_name); free(resolved_name); return err; } /***************************************************************************/ void mz_zip_reader_set_pattern(void *handle, const char *pattern, uint8_t ignore_case) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->pattern = pattern; reader->pattern_ignore_case = ignore_case; } void mz_zip_reader_set_password(void *handle, const char *password) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->password = password; } void mz_zip_reader_set_raw(void *handle, uint8_t raw) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->raw = raw; } int32_t mz_zip_reader_get_raw(void *handle, uint8_t *raw) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (!raw) return MZ_PARAM_ERROR; *raw = reader->raw; return MZ_OK; } int32_t mz_zip_reader_get_zip_cd(void *handle, uint8_t *zip_cd) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (!zip_cd) return MZ_PARAM_ERROR; *zip_cd = reader->cd_zipped; return MZ_OK; } int32_t mz_zip_reader_get_comment(void *handle, const char **comment) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (!comment) return MZ_PARAM_ERROR; return mz_zip_get_comment(reader->zip_handle, comment); } int32_t mz_zip_reader_set_recover(void *handle, uint8_t recover) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (!reader) return MZ_PARAM_ERROR; reader->recover = recover; return MZ_OK; } void mz_zip_reader_set_encoding(void *handle, int32_t encoding) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->encoding = encoding; } void mz_zip_reader_set_overwrite_cb(void *handle, void *userdata, mz_zip_reader_overwrite_cb cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->overwrite_cb = cb; reader->overwrite_userdata = userdata; } void mz_zip_reader_set_password_cb(void *handle, void *userdata, mz_zip_reader_password_cb cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->password_cb = cb; reader->password_userdata = userdata; } void mz_zip_reader_set_progress_cb(void *handle, void *userdata, mz_zip_reader_progress_cb cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->progress_cb = cb; reader->progress_userdata = userdata; } void mz_zip_reader_set_progress_interval(void *handle, uint32_t milliseconds) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->progress_cb_interval_ms = milliseconds; } void mz_zip_reader_set_entry_cb(void *handle, void *userdata, mz_zip_reader_entry_cb cb) { mz_zip_reader *reader = (mz_zip_reader *)handle; reader->entry_cb = cb; reader->entry_userdata = userdata; } int32_t mz_zip_reader_get_zip_handle(void *handle, void **zip_handle) { mz_zip_reader *reader = (mz_zip_reader *)handle; if (!zip_handle) return MZ_PARAM_ERROR; *zip_handle = reader->zip_handle; if (!*zip_handle) return MZ_EXIST_ERROR; return MZ_OK; } /***************************************************************************/ void *mz_zip_reader_create(void) { mz_zip_reader *reader = (mz_zip_reader *)calloc(1, sizeof(mz_zip_reader)); if (reader) { reader->recover = 1; reader->progress_cb_interval_ms = MZ_DEFAULT_PROGRESS_INTERVAL; } return reader; } void mz_zip_reader_delete(void **handle) { mz_zip_reader *reader = NULL; if (!handle) return; reader = (mz_zip_reader *)*handle; if (reader) { mz_zip_reader_close(reader); free(reader); } *handle = NULL; } /***************************************************************************/ typedef struct mz_zip_writer_s { void *zip_handle; void *file_stream; void *buffered_stream; void *split_stream; void *hash; uint16_t hash_algorithm; void *mem_stream; void *file_extra_stream; mz_zip_file file_info; void *overwrite_userdata; mz_zip_writer_overwrite_cb overwrite_cb; void *password_userdata; mz_zip_writer_password_cb password_cb; void *progress_userdata; mz_zip_writer_progress_cb progress_cb; uint32_t progress_cb_interval_ms; void *entry_userdata; mz_zip_writer_entry_cb entry_cb; const char *password; const char *comment; uint8_t *cert_data; int32_t cert_data_size; const char *cert_pwd; uint16_t compress_method; int16_t compress_level; uint8_t follow_links; uint8_t store_links; uint8_t zip_cd; uint8_t aes; uint8_t raw; uint8_t buffer[UINT16_MAX]; } mz_zip_writer; /***************************************************************************/ int32_t mz_zip_writer_zip_cd(void *handle) { mz_zip_writer *writer = (mz_zip_writer *)handle; mz_zip_file cd_file; uint64_t number_entry = 0; int64_t cd_mem_length = 0; int32_t err = MZ_OK; int32_t extrafield_size = 0; void *file_extra_stream = NULL; void *cd_mem_stream = NULL; memset(&cd_file, 0, sizeof(cd_file)); mz_zip_get_number_entry(writer->zip_handle, &number_entry); mz_zip_get_cd_mem_stream(writer->zip_handle, &cd_mem_stream); mz_stream_seek(cd_mem_stream, 0, MZ_SEEK_END); cd_mem_length = (uint32_t)mz_stream_tell(cd_mem_stream); mz_stream_seek(cd_mem_stream, 0, MZ_SEEK_SET); cd_file.filename = MZ_ZIP_CD_FILENAME; cd_file.modified_date = time(NULL); cd_file.version_madeby = MZ_VERSION_MADEBY; cd_file.compression_method = writer->compress_method; cd_file.uncompressed_size = (int32_t)cd_mem_length; cd_file.flag = MZ_ZIP_FLAG_UTF8; if (writer->password) cd_file.flag |= MZ_ZIP_FLAG_ENCRYPTED; file_extra_stream = mz_stream_mem_create(); if (!file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_open(file_extra_stream, NULL, MZ_OPEN_MODE_CREATE); mz_zip_extrafield_write(file_extra_stream, MZ_ZIP_EXTENSION_CDCD, 8); mz_stream_write_uint64(file_extra_stream, number_entry); mz_stream_mem_get_buffer(file_extra_stream, (const void **)&cd_file.extrafield); mz_stream_mem_get_buffer_length(file_extra_stream, &extrafield_size); cd_file.extrafield_size = (uint16_t)extrafield_size; err = mz_zip_writer_entry_open(handle, &cd_file); if (err == MZ_OK) { mz_stream_copy_stream(handle, mz_zip_writer_entry_write, cd_mem_stream, NULL, (int32_t)cd_mem_length); mz_stream_seek(cd_mem_stream, 0, MZ_SEEK_SET); mz_stream_mem_set_buffer_limit(cd_mem_stream, 0); err = mz_zip_writer_entry_close(writer); } mz_stream_mem_delete(&file_extra_stream); return err; } /***************************************************************************/ int32_t mz_zip_writer_is_open(void *handle) { mz_zip_writer *writer = (mz_zip_writer *)handle; if (!writer || !writer->zip_handle) return MZ_PARAM_ERROR; return MZ_OK; } static int32_t mz_zip_writer_open_int(void *handle, void *stream, int32_t mode) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t err = MZ_OK; writer->zip_handle = mz_zip_create(); if (writer->zip_handle == NULL) return MZ_MEM_ERROR; err = mz_zip_open(writer->zip_handle, stream, mode); if (err != MZ_OK) { mz_zip_writer_close(handle); return err; } return MZ_OK; } int32_t mz_zip_writer_open(void *handle, void *stream, uint8_t append) { int32_t mode = MZ_OPEN_MODE_WRITE; if (append) { mode |= MZ_OPEN_MODE_APPEND; } else { mode |= MZ_OPEN_MODE_CREATE; } return mz_zip_writer_open_int(handle, stream, mode); } int32_t mz_zip_writer_open_file(void *handle, const char *path, int64_t disk_size, uint8_t append) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t mode = MZ_OPEN_MODE_READWRITE; int32_t err = MZ_OK; int32_t err_cb = 0; char directory[320]; mz_zip_writer_close(handle); if (mz_os_file_exists(path) != MZ_OK) { /* If the file doesn't exist, we don't append file */ mode |= MZ_OPEN_MODE_CREATE; /* Create destination directory if it doesn't already exist */ if (strchr(path, '/') || strrchr(path, '\\')) { strncpy(directory, path, sizeof(directory) - 1); directory[sizeof(directory) - 1] = 0; mz_path_remove_filename(directory); if (mz_os_file_exists(directory) != MZ_OK) mz_dir_make(directory); } } else if (append) { mode |= MZ_OPEN_MODE_APPEND; } else { if (writer->overwrite_cb) err_cb = writer->overwrite_cb(handle, writer->overwrite_userdata, path); if (err_cb == MZ_INTERNAL_ERROR) return err; if (err_cb == MZ_OK) mode |= MZ_OPEN_MODE_CREATE; else mode |= MZ_OPEN_MODE_APPEND; } writer->file_stream = mz_stream_os_create(); if (!writer->file_stream) return MZ_MEM_ERROR; writer->buffered_stream = mz_stream_buffered_create(); if (!writer->buffered_stream) { mz_stream_os_delete(&writer->file_stream); return MZ_MEM_ERROR; } writer->split_stream = mz_stream_split_create(); if (!writer->split_stream) { mz_stream_buffered_delete(&writer->buffered_stream); mz_stream_os_delete(&writer->file_stream); return MZ_MEM_ERROR; } mz_stream_set_base(writer->buffered_stream, writer->file_stream); mz_stream_set_base(writer->split_stream, writer->buffered_stream); mz_stream_split_set_prop_int64(writer->split_stream, MZ_STREAM_PROP_DISK_SIZE, disk_size); err = mz_stream_open(writer->split_stream, path, mode); if (err == MZ_OK) err = mz_zip_writer_open_int(handle, writer->split_stream, mode); return err; } int32_t mz_zip_writer_open_file_in_memory(void *handle, const char *path) { mz_zip_writer *writer = (mz_zip_writer *)handle; void *file_stream = NULL; int64_t file_size = 0; int32_t err = 0; mz_zip_writer_close(handle); file_stream = mz_stream_os_create(); if (!file_stream) return MZ_MEM_ERROR; err = mz_stream_os_open(file_stream, path, MZ_OPEN_MODE_READ); if (err != MZ_OK) { mz_stream_os_delete(&file_stream); mz_zip_writer_close(handle); return err; } mz_stream_os_seek(file_stream, 0, MZ_SEEK_END); file_size = mz_stream_os_tell(file_stream); mz_stream_os_seek(file_stream, 0, MZ_SEEK_SET); writer->mem_stream = mz_stream_mem_create(); if ((file_size <= 0) || (file_size > UINT32_MAX) || (!writer->mem_stream)) { /* Memory size is too large or too small */ mz_stream_os_close(file_stream); mz_stream_os_delete(&file_stream); mz_zip_writer_close(handle); return MZ_MEM_ERROR; } mz_stream_mem_set_grow_size(writer->mem_stream, (int32_t)file_size); mz_stream_mem_open(writer->mem_stream, NULL, MZ_OPEN_MODE_CREATE); err = mz_stream_copy(writer->mem_stream, file_stream, (int32_t)file_size); mz_stream_os_close(file_stream); mz_stream_os_delete(&file_stream); if (err == MZ_OK) err = mz_zip_writer_open(handle, writer->mem_stream, 1); if (err != MZ_OK) mz_zip_writer_close(handle); return err; } int32_t mz_zip_writer_close(void *handle) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t err = MZ_OK; if (writer->zip_handle) { mz_zip_set_version_madeby(writer->zip_handle, MZ_VERSION_MADEBY); if (writer->comment) mz_zip_set_comment(writer->zip_handle, writer->comment); if (writer->zip_cd) mz_zip_writer_zip_cd(writer); err = mz_zip_close(writer->zip_handle); mz_zip_delete(&writer->zip_handle); } if (writer->split_stream) { mz_stream_split_close(writer->split_stream); mz_stream_split_delete(&writer->split_stream); } if (writer->buffered_stream) mz_stream_buffered_delete(&writer->buffered_stream); if (writer->file_stream) mz_stream_os_delete(&writer->file_stream); if (writer->mem_stream) { mz_stream_mem_close(writer->mem_stream); mz_stream_mem_delete(&writer->mem_stream); } return err; } /***************************************************************************/ int32_t mz_zip_writer_entry_open(void *handle, mz_zip_file *file_info) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t err = MZ_OK; const char *password = NULL; char password_buf[120]; /* Copy file info to access data upon close */ memcpy(&writer->file_info, file_info, sizeof(mz_zip_file)); if (writer->entry_cb) writer->entry_cb(handle, writer->entry_userdata, &writer->file_info); password = writer->password; /* Check if we need a password and ask for it if we need to */ if (!password && writer->password_cb && (writer->file_info.flag & MZ_ZIP_FLAG_ENCRYPTED)) { writer->password_cb(handle, writer->password_userdata, &writer->file_info, password_buf, sizeof(password_buf)); password = password_buf; } #ifndef MZ_ZIP_NO_CRYPTO if (mz_zip_attrib_is_dir(writer->file_info.external_fa, writer->file_info.version_madeby) != MZ_OK) { /* Start calculating hash */ writer->hash = mz_crypt_sha_create(); writer->hash_algorithm = MZ_HASH_SHA256; if (!writer->hash) return MZ_MEM_ERROR; err = mz_crypt_sha_set_algorithm(writer->hash, writer->hash_algorithm); if (err != MZ_OK) { writer->hash_algorithm = MZ_HASH_SHA1; err = mz_crypt_sha_set_algorithm(writer->hash, writer->hash_algorithm); } mz_crypt_sha_begin(writer->hash); } #endif /* Open entry in zip */ err = mz_zip_entry_write_open(writer->zip_handle, &writer->file_info, writer->compress_level, writer->raw, password); return err; } int32_t mz_zip_writer_entry_close(void *handle) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t err = MZ_OK; #ifndef MZ_ZIP_NO_CRYPTO const uint8_t *extrafield = NULL; int32_t extrafield_size = 0; int16_t field_length_hash = 0; uint8_t hash_digest[MZ_HASH_MAX_SIZE]; if (writer->hash) { uint16_t hash_digest_size = 0; switch (writer->hash_algorithm) { case MZ_HASH_SHA1: hash_digest_size = MZ_HASH_SHA1_SIZE; break; case MZ_HASH_SHA256: hash_digest_size = MZ_HASH_SHA256_SIZE; break; default: return MZ_PARAM_ERROR; } mz_crypt_sha_end(writer->hash, hash_digest, hash_digest_size); mz_crypt_sha_delete(&writer->hash); /* Copy extrafield so we can append our own fields before close */ writer->file_extra_stream = mz_stream_mem_create(); if (!writer->file_extra_stream) return MZ_MEM_ERROR; mz_stream_mem_open(writer->file_extra_stream, NULL, MZ_OPEN_MODE_CREATE); /* Write digest to extrafield */ field_length_hash = 4 + hash_digest_size; err = mz_zip_extrafield_write(writer->file_extra_stream, MZ_ZIP_EXTENSION_HASH, field_length_hash); if (err == MZ_OK) err = mz_stream_write_uint16(writer->file_extra_stream, writer->hash_algorithm); if (err == MZ_OK) err = mz_stream_write_uint16(writer->file_extra_stream, hash_digest_size); if (err == MZ_OK) { if (mz_stream_write(writer->file_extra_stream, hash_digest, hash_digest_size) != hash_digest_size) err = MZ_WRITE_ERROR; } if ((writer->file_info.extrafield) && (writer->file_info.extrafield_size > 0)) mz_stream_mem_write(writer->file_extra_stream, writer->file_info.extrafield, writer->file_info.extrafield_size); /* Update extra field for central directory after adding extra fields */ mz_stream_mem_get_buffer(writer->file_extra_stream, (const void **)&extrafield); mz_stream_mem_get_buffer_length(writer->file_extra_stream, &extrafield_size); mz_zip_entry_set_extrafield(writer->zip_handle, extrafield, (uint16_t)extrafield_size); } #endif if (err == MZ_OK) { if (writer->raw) err = mz_zip_entry_close_raw(writer->zip_handle, writer->file_info.uncompressed_size, writer->file_info.crc); else err = mz_zip_entry_close(writer->zip_handle); } if (writer->file_extra_stream) mz_stream_mem_delete(&writer->file_extra_stream); return err; } int32_t mz_zip_writer_entry_write(void *handle, const void *buf, int32_t len) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t written = 0; written = mz_zip_entry_write(writer->zip_handle, buf, len); #ifndef MZ_ZIP_NO_CRYPTO if (written > 0 && writer->hash) mz_crypt_sha_update(writer->hash, buf, written); #endif return written; } /***************************************************************************/ int32_t mz_zip_writer_add_process(void *handle, void *stream, mz_stream_read_cb read_cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t read = 0; int32_t written = 0; int32_t err = MZ_OK; if (mz_zip_writer_is_open(writer) != MZ_OK) return MZ_PARAM_ERROR; /* If the entry isn't open for writing, open it */ if (mz_zip_entry_is_open(writer->zip_handle) != MZ_OK) return MZ_PARAM_ERROR; if (!read_cb) return MZ_PARAM_ERROR; read = read_cb(stream, writer->buffer, sizeof(writer->buffer)); if (read == 0) return MZ_END_OF_STREAM; if (read < 0) { err = read; return err; } written = mz_zip_writer_entry_write(handle, writer->buffer, read); if (written != read) return MZ_WRITE_ERROR; return written; } int32_t mz_zip_writer_add(void *handle, void *stream, mz_stream_read_cb read_cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; uint64_t current_time = 0; uint64_t update_time = 0; int64_t current_pos = 0; int64_t update_pos = 0; int32_t err = MZ_OK; int32_t written = 0; /* Update the progress at the beginning */ if (writer->progress_cb) writer->progress_cb(handle, writer->progress_userdata, &writer->file_info, current_pos); /* Write data to stream until done */ while (err == MZ_OK) { written = mz_zip_writer_add_process(handle, stream, read_cb); if (written == MZ_END_OF_STREAM) break; if (written > 0) current_pos += written; if (written < 0) err = written; /* Update progress if enough time have passed */ current_time = mz_os_ms_time(); if ((current_time - update_time) > writer->progress_cb_interval_ms) { if (writer->progress_cb) writer->progress_cb(handle, writer->progress_userdata, &writer->file_info, current_pos); update_pos = current_pos; update_time = current_time; } } /* Update the progress at the end */ if (writer->progress_cb && update_pos != current_pos) writer->progress_cb(handle, writer->progress_userdata, &writer->file_info, current_pos); return err; } int32_t mz_zip_writer_add_info(void *handle, void *stream, mz_stream_read_cb read_cb, mz_zip_file *file_info) { mz_zip_writer *writer = (mz_zip_writer *)handle; int32_t err = MZ_OK; if (mz_zip_writer_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (!file_info) return MZ_PARAM_ERROR; /* Add to zip */ err = mz_zip_writer_entry_open(handle, file_info); if (err != MZ_OK) return err; if (stream) { if (mz_zip_attrib_is_dir(writer->file_info.external_fa, writer->file_info.version_madeby) != MZ_OK) { err = mz_zip_writer_add(handle, stream, read_cb); if (err != MZ_OK) return err; } } err = mz_zip_writer_entry_close(handle); return err; } int32_t mz_zip_writer_add_buffer(void *handle, void *buf, int32_t len, mz_zip_file *file_info) { void *mem_stream = NULL; int32_t err = MZ_OK; if (mz_zip_writer_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (!buf) return MZ_PARAM_ERROR; /* Create a memory stream backed by our buffer and add from it */ mem_stream = mz_stream_mem_create(); if (!mem_stream) return MZ_STREAM_ERROR; mz_stream_mem_set_buffer(mem_stream, buf, len); err = mz_stream_mem_open(mem_stream, NULL, MZ_OPEN_MODE_READ); if (err == MZ_OK) err = mz_zip_writer_add_info(handle, mem_stream, mz_stream_mem_read, file_info); mz_stream_mem_delete(&mem_stream); return err; } int32_t mz_zip_writer_add_file(void *handle, const char *path, const char *filename_in_zip) { mz_zip_writer *writer = (mz_zip_writer *)handle; mz_zip_file file_info; uint32_t target_attrib = 0; uint32_t src_attrib = 0; int32_t err = MZ_OK; uint8_t src_sys = 0; void *stream = NULL; char link_path[1024]; const char *filename = filename_in_zip; if (mz_zip_writer_is_open(handle) != MZ_OK) return MZ_PARAM_ERROR; if (!path) return MZ_PARAM_ERROR; if (!filename) { err = mz_path_get_filename(path, &filename); if (err != MZ_OK) return err; } memset(&file_info, 0, sizeof(file_info)); /* The path name saved, should not include a leading slash. */ /* If it did, windows/xp and dynazip couldn't read the zip file. */ while (filename[0] == '\\' || filename[0] == '/') filename += 1; /* Get information about the file on disk so we can store it in zip */ file_info.version_madeby = MZ_VERSION_MADEBY; file_info.compression_method = writer->compress_method; file_info.filename = filename; file_info.uncompressed_size = mz_os_get_file_size(path); file_info.flag = MZ_ZIP_FLAG_UTF8; if (writer->zip_cd) file_info.flag |= MZ_ZIP_FLAG_MASK_LOCAL_INFO; if (writer->aes) file_info.aes_version = MZ_AES_VERSION; mz_os_get_file_date(path, &file_info.modified_date, &file_info.accessed_date, &file_info.creation_date); mz_os_get_file_attribs(path, &src_attrib); src_sys = MZ_HOST_SYSTEM(file_info.version_madeby); if ((src_sys != MZ_HOST_SYSTEM_MSDOS) && (src_sys != MZ_HOST_SYSTEM_WINDOWS_NTFS)) { /* High bytes are OS specific attributes, low byte is always DOS attributes */ if (mz_zip_attrib_convert(src_sys, src_attrib, MZ_HOST_SYSTEM_MSDOS, &target_attrib) == MZ_OK) file_info.external_fa = target_attrib; file_info.external_fa |= (src_attrib << 16); } else { file_info.external_fa = src_attrib; } if (writer->store_links && mz_os_is_symlink(path) == MZ_OK) { err = mz_os_read_symlink(path, link_path, sizeof(link_path)); if (err == MZ_OK) file_info.linkname = link_path; } else if (mz_os_is_dir(path) != MZ_OK) { stream = mz_stream_os_create(); if (!stream) return MZ_STREAM_ERROR; err = mz_stream_os_open(stream, path, MZ_OPEN_MODE_READ); } if (err == MZ_OK) err = mz_zip_writer_add_info(handle, stream, mz_stream_read, &file_info); if (stream) { mz_stream_close(stream); mz_stream_delete(&stream); } return err; } int32_t mz_zip_writer_add_path(void *handle, const char *path, const char *root_path, uint8_t include_path, uint8_t recursive) { mz_zip_writer *writer = (mz_zip_writer *)handle; DIR *dir = NULL; struct dirent *entry = NULL; int32_t err = MZ_OK; int16_t is_dir = 0; const char *filename = NULL; const char *filenameinzip = path; char *wildcard_ptr = NULL; char full_path[1024]; char path_dir[1024]; if (strrchr(path, '*')) { strncpy(path_dir, path, sizeof(path_dir) - 1); path_dir[sizeof(path_dir) - 1] = 0; mz_path_remove_filename(path_dir); wildcard_ptr = path_dir + strlen(path_dir) + 1; root_path = path = path_dir; } else { if (mz_os_is_dir(path) == MZ_OK) is_dir = 1; /* Construct the filename that our file will be stored in the zip as */ if (!root_path) root_path = path; /* Should the file be stored with any path info at all? */ if (!include_path) { if (!is_dir && root_path == path) { if (mz_path_get_filename(filenameinzip, &filename) == MZ_OK) filenameinzip = filename; } else { filenameinzip += strlen(root_path); } } if (!writer->store_links && !writer->follow_links) { if (mz_os_is_symlink(path) == MZ_OK) return err; } if (*filenameinzip != 0) err = mz_zip_writer_add_file(handle, path, filenameinzip); if (!is_dir) return err; if (writer->store_links) { if (mz_os_is_symlink(path) == MZ_OK) return err; } } dir = mz_os_open_dir(path); if (!dir) return MZ_EXIST_ERROR; while ((entry = mz_os_read_dir(dir))) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; full_path[0] = 0; mz_path_combine(full_path, path, sizeof(full_path)); mz_path_combine(full_path, entry->d_name, sizeof(full_path)); if (!recursive && mz_os_is_dir(full_path) == MZ_OK) continue; if ((wildcard_ptr) && (mz_path_compare_wc(entry->d_name, wildcard_ptr, 1) != MZ_OK)) continue; err = mz_zip_writer_add_path(handle, full_path, root_path, include_path, recursive); if (err != MZ_OK) break; } mz_os_close_dir(dir); return err; } int32_t mz_zip_writer_copy_from_reader(void *handle, void *reader) { mz_zip_writer *writer = (mz_zip_writer *)handle; mz_zip_file *file_info = NULL; int64_t compressed_size = 0; int64_t uncompressed_size = 0; uint32_t crc32 = 0; int32_t err = MZ_OK; uint8_t original_raw = 0; void *reader_zip_handle = NULL; void *writer_zip_handle = NULL; if (mz_zip_reader_is_open(reader) != MZ_OK) return MZ_PARAM_ERROR; if (mz_zip_writer_is_open(writer) != MZ_OK) return MZ_PARAM_ERROR; err = mz_zip_reader_entry_get_info(reader, &file_info); if (err != MZ_OK) return err; mz_zip_reader_get_zip_handle(reader, &reader_zip_handle); mz_zip_writer_get_zip_handle(writer, &writer_zip_handle); /* Open entry for raw reading */ err = mz_zip_entry_read_open(reader_zip_handle, 1, NULL); if (err == MZ_OK) { /* Write entry raw, save original raw value */ original_raw = writer->raw; writer->raw = 1; err = mz_zip_writer_entry_open(writer, file_info); if ((err == MZ_OK) && (mz_zip_attrib_is_dir(writer->file_info.external_fa, writer->file_info.version_madeby) != MZ_OK)) { err = mz_zip_writer_add(writer, reader_zip_handle, mz_zip_entry_read); } if (err == MZ_OK) { err = mz_zip_entry_read_close(reader_zip_handle, &crc32, &compressed_size, &uncompressed_size); if (err == MZ_OK) err = mz_zip_entry_write_close(writer_zip_handle, crc32, compressed_size, uncompressed_size); } if (mz_zip_entry_is_open(reader_zip_handle) == MZ_OK) mz_zip_entry_close(reader_zip_handle); if (mz_zip_entry_is_open(writer_zip_handle) == MZ_OK) mz_zip_entry_close(writer_zip_handle); #ifndef MZ_ZIP_NO_CRYPTO mz_crypt_sha_delete(&writer->hash); #endif writer->raw = original_raw; } return err; } /***************************************************************************/ void mz_zip_writer_set_password(void *handle, const char *password) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->password = password; } void mz_zip_writer_set_comment(void *handle, const char *comment) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->comment = comment; } void mz_zip_writer_set_raw(void *handle, uint8_t raw) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->raw = raw; } int32_t mz_zip_writer_get_raw(void *handle, uint8_t *raw) { mz_zip_writer *writer = (mz_zip_writer *)handle; if (!raw) return MZ_PARAM_ERROR; *raw = writer->raw; return MZ_OK; } void mz_zip_writer_set_aes(void *handle, uint8_t aes) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->aes = aes; } void mz_zip_writer_set_compress_method(void *handle, uint16_t compress_method) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->compress_method = compress_method; } void mz_zip_writer_set_compress_level(void *handle, int16_t compress_level) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->compress_level = compress_level; } void mz_zip_writer_set_follow_links(void *handle, uint8_t follow_links) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->follow_links = follow_links; } void mz_zip_writer_set_store_links(void *handle, uint8_t store_links) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->store_links = store_links; } void mz_zip_writer_set_zip_cd(void *handle, uint8_t zip_cd) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->zip_cd = zip_cd; } int32_t mz_zip_writer_set_certificate(void *handle, const char *cert_path, const char *cert_pwd) { mz_zip_writer *writer = (mz_zip_writer *)handle; void *cert_stream = NULL; uint8_t *cert_data = NULL; int32_t cert_data_size = 0; int32_t err = MZ_OK; if (!cert_path) return MZ_PARAM_ERROR; cert_data_size = (int32_t)mz_os_get_file_size(cert_path); if (cert_data_size == 0) return MZ_PARAM_ERROR; if (writer->cert_data) { free(writer->cert_data); writer->cert_data = NULL; } cert_data = (uint8_t *)malloc(cert_data_size); /* Read pkcs12 certificate from disk */ cert_stream = mz_stream_os_create(); if (!cert_stream) return MZ_MEM_ERROR; err = mz_stream_os_open(cert_stream, cert_path, MZ_OPEN_MODE_READ); if (err == MZ_OK) { if (mz_stream_os_read(cert_stream, cert_data, cert_data_size) != cert_data_size) err = MZ_READ_ERROR; mz_stream_os_close(cert_stream); } mz_stream_os_delete(&cert_stream); if (err == MZ_OK) { writer->cert_data = cert_data; writer->cert_data_size = cert_data_size; writer->cert_pwd = cert_pwd; } else { free(cert_data); } return err; } void mz_zip_writer_set_overwrite_cb(void *handle, void *userdata, mz_zip_writer_overwrite_cb cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->overwrite_cb = cb; writer->overwrite_userdata = userdata; } void mz_zip_writer_set_password_cb(void *handle, void *userdata, mz_zip_writer_password_cb cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->password_cb = cb; writer->password_userdata = userdata; } void mz_zip_writer_set_progress_cb(void *handle, void *userdata, mz_zip_writer_progress_cb cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->progress_cb = cb; writer->progress_userdata = userdata; } void mz_zip_writer_set_progress_interval(void *handle, uint32_t milliseconds) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->progress_cb_interval_ms = milliseconds; } void mz_zip_writer_set_entry_cb(void *handle, void *userdata, mz_zip_writer_entry_cb cb) { mz_zip_writer *writer = (mz_zip_writer *)handle; writer->entry_cb = cb; writer->entry_userdata = userdata; } int32_t mz_zip_writer_get_zip_handle(void *handle, void **zip_handle) { mz_zip_writer *writer = (mz_zip_writer *)handle; if (!zip_handle) return MZ_PARAM_ERROR; *zip_handle = writer->zip_handle; if (!*zip_handle) return MZ_EXIST_ERROR; return MZ_OK; } /***************************************************************************/ void *mz_zip_writer_create(void) { mz_zip_writer *writer = (mz_zip_writer *)calloc(1, sizeof(mz_zip_writer)); if (writer) { #if defined(HAVE_WZAES) writer->aes = 1; #endif #if defined(HAVE_ZLIB) || defined(HAVE_LIBCOMP) writer->compress_method = MZ_COMPRESS_METHOD_DEFLATE; #elif defined(HAVE_BZIP2) writer->compress_method = MZ_COMPRESS_METHOD_BZIP2; #elif defined(HAVE_LZMA) writer->compress_method = MZ_COMPRESS_METHOD_LZMA; #else writer->compress_method = MZ_COMPRESS_METHOD_STORE; #endif writer->compress_level = MZ_COMPRESS_LEVEL_BEST; writer->progress_cb_interval_ms = MZ_DEFAULT_PROGRESS_INTERVAL; } return writer; } void mz_zip_writer_delete(void **handle) { mz_zip_writer *writer = NULL; if (!handle) return; writer = (mz_zip_writer *)*handle; if (writer) { mz_zip_writer_close(writer); if (writer->cert_data) free(writer->cert_data); writer->cert_data = NULL; writer->cert_data_size = 0; free(writer); } *handle = NULL; } /***************************************************************************/ sight-23.1.0/3rd-party/minizip/mz_zip_rw.h000066400000000000000000000263451450532053500204240ustar00rootroot00000000000000/* mz_zip_rw.h -- Zip reader/writer part of the minizip-ng project Copyright (C) Nathan Moinvaziri https://github.com/zlib-ng/minizip-ng This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_ZIP_RW_H #define MZ_ZIP_RW_H #ifdef __cplusplus extern "C" { #endif /***************************************************************************/ typedef int32_t (*mz_zip_reader_overwrite_cb)(void *handle, void *userdata, mz_zip_file *file_info, const char *path); typedef int32_t (*mz_zip_reader_password_cb)(void *handle, void *userdata, mz_zip_file *file_info, char *password, int32_t max_password); typedef int32_t (*mz_zip_reader_progress_cb)(void *handle, void *userdata, mz_zip_file *file_info, int64_t position); typedef int32_t (*mz_zip_reader_entry_cb)(void *handle, void *userdata, mz_zip_file *file_info, const char *path); /***************************************************************************/ int32_t mz_zip_reader_is_open(void *handle); /* Checks to see if the zip file is open */ int32_t mz_zip_reader_open(void *handle, void *stream); /* Opens zip file from stream */ int32_t mz_zip_reader_open_file(void *handle, const char *path); /* Opens zip file from a file path */ int32_t mz_zip_reader_open_file_in_memory(void *handle, const char *path); /* Opens zip file from a file path into memory for faster access */ int32_t mz_zip_reader_open_buffer(void *handle, uint8_t *buf, int32_t len, uint8_t copy); /* Opens zip file from memory buffer */ int32_t mz_zip_reader_close(void *handle); /* Closes the zip file */ /***************************************************************************/ int32_t mz_zip_reader_unzip_cd(void *handle); /* Unzip the central directory */ /***************************************************************************/ int32_t mz_zip_reader_goto_first_entry(void *handle); /* Goto the first entry in the zip file that matches the pattern */ int32_t mz_zip_reader_goto_next_entry(void *handle); /* Goto the next entry in the zip file that matches the pattern */ int32_t mz_zip_reader_locate_entry(void *handle, const char *filename, uint8_t ignore_case); /* Locates an entry by filename */ int32_t mz_zip_reader_entry_open(void *handle); /* Opens an entry for reading */ int32_t mz_zip_reader_entry_close(void *handle); /* Closes an entry */ int32_t mz_zip_reader_entry_read(void *handle, void *buf, int32_t len); /* Reads and entry after being opened */ int32_t mz_zip_reader_entry_get_hash(void *handle, uint16_t algorithm, uint8_t *digest, int32_t digest_size); /* Gets a hash algorithm from the entry's extra field */ int32_t mz_zip_reader_entry_get_first_hash(void *handle, uint16_t *algorithm, uint16_t *digest_size); /* Gets the most secure hash algorithm from the entry's extra field */ int32_t mz_zip_reader_entry_get_info(void *handle, mz_zip_file **file_info); /* Gets the current entry file info */ int32_t mz_zip_reader_entry_is_dir(void *handle); /* Gets the current entry is a directory */ int32_t mz_zip_reader_entry_save(void *handle, void *stream, mz_stream_write_cb write_cb); /* Save the current entry to a stream */ int32_t mz_zip_reader_entry_save_process(void *handle, void *stream, mz_stream_write_cb write_cb); /* Saves a portion of the current entry to a stream callback */ int32_t mz_zip_reader_entry_save_file(void *handle, const char *path); /* Save the current entry to a file */ int32_t mz_zip_reader_entry_save_buffer(void *handle, void *buf, int32_t len); /* Save the current entry to a memory buffer */ int32_t mz_zip_reader_entry_save_buffer_length(void *handle); /* Gets the length of the buffer required to save */ /***************************************************************************/ int32_t mz_zip_reader_save_all(void *handle, const char *destination_dir); /* Save all files into a directory */ /***************************************************************************/ void mz_zip_reader_set_pattern(void *handle, const char *pattern, uint8_t ignore_case); /* Sets the match pattern for entries in the zip file, if null all entries are matched */ void mz_zip_reader_set_password(void *handle, const char *password); /* Sets the password required for extraction */ void mz_zip_reader_set_raw(void *handle, uint8_t raw); /* Sets whether or not it should save the entry raw */ int32_t mz_zip_reader_get_raw(void *handle, uint8_t *raw); /* Gets whether or not it should save the entry raw */ int32_t mz_zip_reader_get_zip_cd(void *handle, uint8_t *zip_cd); /* Gets whether or not the archive has a zipped central directory */ int32_t mz_zip_reader_get_comment(void *handle, const char **comment); /* Gets the comment for the central directory */ int32_t mz_zip_reader_set_recover(void *handle, uint8_t recover); /* Sets the ability to recover the central dir by reading local file headers */ void mz_zip_reader_set_encoding(void *handle, int32_t encoding); /* Sets whether or not it should support a special character encoding in zip file names. */ void mz_zip_reader_set_overwrite_cb(void *handle, void *userdata, mz_zip_reader_overwrite_cb cb); /* Callback for what to do when a file is being overwritten */ void mz_zip_reader_set_password_cb(void *handle, void *userdata, mz_zip_reader_password_cb cb); /* Callback for when a password is required and hasn't been set */ void mz_zip_reader_set_progress_cb(void *handle, void *userdata, mz_zip_reader_progress_cb cb); /* Callback for extraction progress */ void mz_zip_reader_set_progress_interval(void *handle, uint32_t milliseconds); /* Let at least milliseconds pass between calls to progress callback */ void mz_zip_reader_set_entry_cb(void *handle, void *userdata, mz_zip_reader_entry_cb cb); /* Callback for zip file entries */ int32_t mz_zip_reader_get_zip_handle(void *handle, void **zip_handle); /* Gets the underlying zip instance handle */ void* mz_zip_reader_create(void); /* Create new instance of zip reader */ void mz_zip_reader_delete(void **handle); /* Delete instance of zip reader */ /***************************************************************************/ typedef int32_t (*mz_zip_writer_overwrite_cb)(void *handle, void *userdata, const char *path); typedef int32_t (*mz_zip_writer_password_cb)(void *handle, void *userdata, mz_zip_file *file_info, char *password, int32_t max_password); typedef int32_t (*mz_zip_writer_progress_cb)(void *handle, void *userdata, mz_zip_file *file_info, int64_t position); typedef int32_t (*mz_zip_writer_entry_cb)(void *handle, void *userdata, mz_zip_file *file_info); /***************************************************************************/ int32_t mz_zip_writer_is_open(void *handle); /* Checks to see if the zip file is open */ int32_t mz_zip_writer_open(void *handle, void *stream, uint8_t append); /* Opens zip file from stream */ int32_t mz_zip_writer_open_file(void *handle, const char *path, int64_t disk_size, uint8_t append); /* Opens zip file from a file path */ int32_t mz_zip_writer_open_file_in_memory(void *handle, const char *path); /* Opens zip file from a file path into memory for faster access */ int32_t mz_zip_writer_close(void *handle); /* Closes the zip file */ /***************************************************************************/ int32_t mz_zip_writer_entry_open(void *handle, mz_zip_file *file_info); /* Opens an entry in the zip file for writing */ int32_t mz_zip_writer_entry_close(void *handle); /* Closes entry in zip file */ int32_t mz_zip_writer_entry_write(void *handle, const void *buf, int32_t len); /* Writes data into entry for zip */ /***************************************************************************/ int32_t mz_zip_writer_add(void *handle, void *stream, mz_stream_read_cb read_cb); /* Writes all data to the currently open entry in the zip */ int32_t mz_zip_writer_add_process(void *handle, void *stream, mz_stream_read_cb read_cb); /* Writes a portion of data to the currently open entry in the zip */ int32_t mz_zip_writer_add_info(void *handle, void *stream, mz_stream_read_cb read_cb, mz_zip_file *file_info); /* Adds an entry to the zip based on the info */ int32_t mz_zip_writer_add_buffer(void *handle, void *buf, int32_t len, mz_zip_file *file_info); /* Adds an entry to the zip with a memory buffer */ int32_t mz_zip_writer_add_file(void *handle, const char *path, const char *filename_in_zip); /* Adds an entry to the zip from a file */ int32_t mz_zip_writer_add_path(void *handle, const char *path, const char *root_path, uint8_t include_path, uint8_t recursive); /* Enumerates a directory or pattern and adds entries to the zip */ int32_t mz_zip_writer_copy_from_reader(void *handle, void *reader); /* Adds an entry from a zip reader instance */ /***************************************************************************/ void mz_zip_writer_set_password(void *handle, const char *password); /* Password to use for encrypting files in the zip */ void mz_zip_writer_set_comment(void *handle, const char *comment); /* Comment to use for the archive */ void mz_zip_writer_set_raw(void *handle, uint8_t raw); /* Sets whether or not we should write the entry raw */ int32_t mz_zip_writer_get_raw(void *handle, uint8_t *raw); /* Gets whether or not we should write the entry raw */ void mz_zip_writer_set_aes(void *handle, uint8_t aes); /* Use aes encryption when adding files in zip */ void mz_zip_writer_set_compress_method(void *handle, uint16_t compress_method); /* Sets the compression method when adding files in zip */ void mz_zip_writer_set_compress_level(void *handle, int16_t compress_level); /* Sets the compression level when adding files in zip */ void mz_zip_writer_set_follow_links(void *handle, uint8_t follow_links); /* Follow symbolic links when traversing directories and files to add */ void mz_zip_writer_set_store_links(void *handle, uint8_t store_links); /* Store symbolic links in zip file */ void mz_zip_writer_set_zip_cd(void *handle, uint8_t zip_cd); /* Sets whether or not central directory should be zipped */ int32_t mz_zip_writer_set_certificate(void *handle, const char *cert_path, const char *cert_pwd); /* Sets the certificate and timestamp url to use for signing when adding files in zip */ void mz_zip_writer_set_overwrite_cb(void *handle, void *userdata, mz_zip_writer_overwrite_cb cb); /* Callback for what to do when zip file already exists */ void mz_zip_writer_set_password_cb(void *handle, void *userdata, mz_zip_writer_password_cb cb); /* Callback for ask if a password is required for adding */ void mz_zip_writer_set_progress_cb(void *handle, void *userdata, mz_zip_writer_progress_cb cb); /* Callback for compression progress */ void mz_zip_writer_set_progress_interval(void *handle, uint32_t milliseconds); /* Let at least milliseconds pass between calls to progress callback */ void mz_zip_writer_set_entry_cb(void *handle, void *userdata, mz_zip_writer_entry_cb cb); /* Callback for zip file entries */ int32_t mz_zip_writer_get_zip_handle(void *handle, void **zip_handle); /* Gets the underlying zip handle */ void* mz_zip_writer_create(void); /* Create new instance of zip writer */ void mz_zip_writer_delete(void **handle); /* Delete instance of zip writer */ /***************************************************************************/ #ifdef __cplusplus } #endif #endif sight-23.1.0/3rd-party/minizip/unzip.h000066400000000000000000000004601450532053500175370ustar00rootroot00000000000000/* unzip.h -- Compatibility layer shim part of the minizip-ng project This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_COMPAT_UNZIP #define MZ_COMPAT_UNZIP #include "mz_compat.h" #endif sight-23.1.0/3rd-party/minizip/zip.h000066400000000000000000000004521450532053500171750ustar00rootroot00000000000000/* zip.h -- Compatibility layer shim part of the minizip-ng project This program is distributed under the terms of the same license as zlib. See the accompanying LICENSE file for the full text of the license. */ #ifndef MZ_COMPAT_ZIP #define MZ_COMPAT_ZIP #include "mz_compat.h" #endif sight-23.1.0/CHANGELOG.md000066400000000000000000011516301450532053500145350ustar00rootroot00000000000000# sight 23.1.0 ## New features: ### io *Filters dicom series by sop class.* Use the new `module`::io::dicom::SReader``configuration: `sopFilter="1.2.840.10008.5.1.4.1.1.2"` -or- call `sight::io::dicom::Reader::setFilters({sight::data::dicom::sop::Keyword::CTImageStorage})` *Add the Spatial Fiducials IOD read/write feature.* These changes add the Spatial Fiducials IOD read/write feature to the existing DICOM reader/writer. ### ui *Predefined camera enhancement, cardinalLayout area maximization and accordion menu fix.* also: - add a modifyLayout slot for custom layouting actions - SAction can now trigger custom "parameter_t" signals - Remove various unused constants which were breaking clang build - Make the animation to take render time into account. This makes the RPM speed somewhat constant. - Bad size for non button widget in accordion menu *Add a slider to modify transfer function opacity.* ### viz *Allow disabling predefined camera animation.* *Allow moving landmarks from selected groups outside edit mode.* `sight::module::viz::scene3dQt`::adaptor::SLandmarks``has been improved to support a `MOVE` mode when not in `EDIT` mode. The `MOVE` mode is controlled by `enableMoveMode()`, `disableMoveMode()`, `toggleMoveMode()` and `changeMoveMode(bool)` slots. The move can be restricted to specific groups when `modify="groups"` adaptor configuration is used, by setting a list of group in a new parameter of the `configureLandmarks()`. `configureLandmarks()` takes now a `sight::viz::scene3d`::LandmarksConfiguration``structure, which is shared by signals, reducing the risk of typo and unwanted API modification. ## Enhancement: ### io *Update minizip to 4.0.1.* ### ui *Improve SSequencer appearance.* This improves a bit the appearance of SSequencer and above all, make it more customizable. The buttons and the fonts size can now be adjusted as well. ExActivities was also fixed. *Add the possibility to only allow moving landmarks from a given group.* We added the possibility to allow moving landmarks only for a given group. It adds the configuration key `modify` for `sight::modules::viz::scene3DQt`::adaptor::SLandmarks``with the possible values `all` (the default, which allows to modify all landmarks, ignoring the current group) and `group` (which allows to modify only the landmarks belonging to the current group). *Allow modifying the displayed columns in the series selector widget.* Add a new configuration in `module`::io::dicom::SReader``like: `displayedColumns="PatientID,Modality,Description,Date,Time,BodyPart,PatientPosition"` to configure the displayed columns *Password must be strong enough.* *Add contextual mode and menu for fiducials.* These changes introduce an editing mode for landmarks and distance. Landmarks and distances are now immutable by default, their respecting editing mode must be on in order to be created, removed, moved and renamed. Now, in order to remove a landmark or a distance, one must click on it while the editing mode is on and then click on the bin button which appears. In order to rename a landmark, one can click on the label and directly edit it. Note that, right now, the landmark groups have names, not individual landmarks; therefore, to rename a landmark will actually modify the name of its group. ### viz *Add option to disable validation through double click for SShapeExtruder.* *Add other slice lines on negato 2D views.* *Update landmark/distance adaptors to work on data::Series.* ## Bug fixes: ### build *Fix clang-15 build.* ### core *Add missing copy operators in FiducialsSeries.* ### viz *Display of 2D image in a 3D scene.* *Store the VR clipping matrix in local instead of world.* This makes this transform more portable, for instance when the image is moved/registered between the time the clipping is made and the image is rendered. *Respect the number of samples set in SVolumeRender config.* # sight 23.0.0 ## Bug fixes: ### build *Fix nvcc configuration.* *Make build compatible with CUDA.* *Protect from target coverage redefinition.* *Build with gcc 12.* *Provide a project or an application version number for xml.* We fixed and enhanced the way to specify version numbers that can be used in XML configuration: * the `PROJECT_VERSION` variable is now correctly filled and matches the global project version number specified in the CMake `project()` macro. * a new variable `_VERSION` is now defined for each application, that matches the version used in the packaging, deduced from git tags. If a matching git tag does not exist, it fallback to the latest global tag. *Clang-15 support and warning fixes.* ### ci *Try to avoid crashes when a service test fails.* *Increase timeout for tests.* *Fix Linux build jobs not outputting test reports.* *Fix GUI tests crashing because of dangling pointers.* ### core *Parsing of "channel", "uid" pair for dedicated notifications channels.* *Error in sync test.* *Add PB missing enums.* *Start deferred service if its objects are present or optional.* *Crash if getMultiFrameGroupSequence is not found.* Safe return if `getMultiFrameGroupSequence` doesn't exist in current series. *Random crash in SSynchroniser.* The `SSynchronizer`::synchronize``function should be run on a separate worker thread. Otherwise, stopping it properly while it runs will never be possible. By doing that, we introduce an implicit synchronisation when we stop the worker thread, which joins and thus waits for `SSynchronizer`::synchronize``to finish. So we even don't need a more sophisticated synchronisation mechanism with mutexes, condition variables, etc... However, we discovered three other issues: * some data objects in the unit-tests were destroyed before the synchronizer service. We modified those unit tests accordingly, * a deadlock could occur when a slot is destroyed during the asynchronous emission of a signal it is connected to. Now, we ensure the destruction occurs after the emission of the signal, * a crash could occur when a timer is destroyed before its callback is called. *Data XML parsers execution policy.* Data-specific XML parsers are executed whenever an object is created in an XML configuration. We discovered they were also executed with referenced objects, which could lead to objects overwritten with defaults. This happened for instance with transfer functions. We no longer execute the parsers in these cases. On the other side, objects created in activities do not benefit from this mechanism. This means that after this first change, an activity having a transfer function as a requirement with `create="true"` would create an empty transfer function. Many services do not handle that correctly. It turns out to be desirable to also allow specifying initial object configuration for requirements. Example from the unit test, which set the value "dummy string" to the requirement `string`: ```xml TestBuilderObjectParser ObjectParser Desc Test1 Icon Test1 dummy string ``` *Mistmatch beween malloc and delete in Demangler.* *Ensure that removed frame data are removed and not saved with GDCM writer.* ### io *Prevent SReader to lose its configuraiton on start/stop.* session`::Sreader`forgets its configuration at stop and start. Prevent this when the dialog policy is NEVER, because it means that the file-to-read path is only specified in configuration, and should not be forgotten. *Add openJpg support for dicom writer.* Some dicom tests writing fail because of an internal mismatch in dicom/nvJpeg2000/openJpeg. To summarize, for strongly randomized images, nvpeg2000 fails. This has been fixed in the 0.7 version of nvjpeg, used on linux, but not presently on windows. So, when writing the dicom in a ut on windows, nvJpeg2000 is detected, used, fails, and a backup is used to openJpeg. However, gdcm, the dicom writing lib, uses openJpeg intrinsecly, and does not support an the external use of openjpeg (bug ! ) which lead,s in the present case to a fail of the nvjpeg2000 backup system. As a result, some tests fail on windows. To fix this, a support of dicom writing in onpenjpeg has been added, to make syure that the dicom is writen in any cases *Add tests and many fixes, optimizations and cleanup for bitmap reader/writer.* - add read - write tests - ensure unsupported pixel format / type will throw an exception - support endianness correctly (libpng) - cleanup and code factorization - add some tests - ensure to throw an exception if nvjpeg2000 is asked for dicom and library is not found at runtime *Prevent ssynchronizer double lock.* Prevent SSynchronizer to synchronize in the update in legacy mode. There is a dedicated worker for that. This avoids a dead lock in legacy mode. *Ensure the parent path is created in io::session::SWriter.* *Correct SSynchronizer test random fail.* The SSynchronizer copy from the TL to the output vars did a scoped lock, while the buffer was used outside of it. This lead to concurent access and test fail. The scope has been enhanced to cover the whole copy method from the tl to the output var. ### test *Fix GUI test not working on subprojects with Ctest.* GUI tests didn't work using CTest on subprojects on Linux because of a bug in the `exec_gui_tests.sh` script. ### ui *Fix bugs with Accordion Menu.* *Enhance negato slider with window level.* We improved the negatoscope view to allow the bottom slider to tweak the transfer function window. Before that, it was only possible to do it with a right-click mouse move. *Replace INFO logging by DEBUG in SStatus.* *Preferences no longer reset when app version changes.* A regression caused the application preferences to be dependent on the commit ref. This fixes the behaviour. *Resize overlay layout according to its children.* *Transparent notifications with NVidia prime.* *Typo in SNotifier.* *Remove useless "SRecurrentSignal".* *Notification popups doesn't move down when stacked.* *Fully export class when derived from QObject.* This allows to use the class as a QObject outside its library and avoid strange missing symbols on windows. *Fix non-linear sliders value changing too much when scrolling.* Up to now, the non-linear sliders did too big step, going from maximum to minimum. This has been enhanced to do more progressive changes in non-linear sliders. *Non-linear slider wrong min/max values when changing values in SParameters.* These changes fix the wrong min/max values displayed for a non-linear slider in SParameters. This was because the rangeChanged signal was sent with the wrong values, those from the internal slider, rather than those from the non-linear slider. *First call IGuiContainer visibility slots when hide/show SSignalButton.* Call first `IGuiContainer` enable/disable and setVisibility slots in SSignalButton. This fix the bug where is SSignalButton was hiden in a SView, it was impossible to show it again. *Fix labels being cut off in SParameters with the touch-friendly style.* When the touch-friendly style is applied, the labels are cut off in SParameters if there isn't enough space. These changes fix that by applying a negative margin to the labels. *Remove the close callback of notification and force close at stopping of SNotifier.* ### viz *Compute clipping planes on each rendering frame.* *Crash when switching an activity when a notification is shown.* *Make SCamera calibrate safer.* The SCamera adaptor requires a calibration step. This calibration can be provided through an input to the service (CameraSet, cameraCalibration). However, for virtual camera in classical 3Dscene, no calibration is provided, and the calibration is computed based on the viewport size. This set is only called at the service start, and, if the viewport is hidden, or deffined with visibility=false, its height and with are null or negativ. This leads to an error which stops the application in debug. Add a calibration verification checK. If the calibration fails in SCamera, it stops the updating. If the updating is called and the calibration has not been done, it is calibrated again. *Correct several update issues with the 3D widget.* *Shape extruder does not work with touchscreen.* When using shape extruder on a volume in a 3D scene, and using a mousse, all works fine. However, on the same machine, same volume, same extrusion path, when doing it with the touchscreen the extrusion takes ages, and freezes the application. This has been fixed by the way events are handled. shape extrusion should work perfectly on both touchscreen and mousse actions. *Fix event managment for touch.* * Remove `GestureRecognizer`, `EventFilter`, `GestureFilter` as we rely on default Qt one for Pinch and Pan. * Remove Tap and long Tap, as they are no more used, but it should be easy to add them back, if needed. * Use synthesized mouse event from Qt gesture, and synthesize the one missing (in SNegato2DCamera) * Use float version of device pixel ratio to manage correctly fractional scaling (like 1.5 \* full HD) *Use resize event informations to set aspect ratio.* The aspect ratio could be broken on some initialisation paths. Also, fixed the missing label SAxis when the axis are disabled. *Touch event for landmarks.* *Update of transfer function widget when image is updated.* *Display of landmarks and distance over volume rendering.* *Correct SLine visibility.* The SLine 3D adaptor is displayed everytime that the line length is changed, even if its visibility is set to hidden. To fix this, the rendering mechanism has been upgraded to display it only when it is set to visible. ## Enhancement: ### build *Add sanitizer support.* Using the CMake option `SIGHT_SANITIZE="sanitizer(s)"` like in `cmake .... -DSIGHT_SANITIZE="thread" ....` The string is passed to the compiler with the option `-fsanitize=xxx`. Launching the result binaries will execute instrumented code that will check things like concurrent access, memory leak, address uses, etc. One an error is found, the code is stopped with an exception and a meaningful message is printed on the console. ### ci *Be more permissive.* *Cache sight-data.* *Disable gdb to speed-up coverage build.* *Fix caching with clang.* *Use a shared linux runner for build jobs.* *Use direct dependencies between jobs.* *Use merge-requests pipelines.* ### core *Tag output synchronized images with timestamps in SSynchronizer.* *Add blocker support for IContainer::scoped_emit.* The scope emiter is a shortlived object which watches a IContainer object, and, once destroyed (scope variable destroyed) sends all the appropriate signals regarding what happend to the IContainer (add/remove/changed...). However, in some cases, we might want to make use of a scope_emiter, though want to prevent it from sending a specific signal. This is added here, through a block method which can be called ``` const auto scoped_emitter = container->scoped_emit(); scoped_emitter->block(this->slot(IService::slots::UPDATE)); container->push_back(object1); container->erase(object2); container->push_back(object3); ``` In this case, the update will not be sent from the container. *Support start/stop slots connections in XML configurations.* The `AppConfigManager` has been modified to support the connection of `start` and `stop` slots. A service started by the trigger of a signal will be automatically stopped. ``` service1/computed service2/start service1/failed service2/stop ``` This deprecates the service `SStarter` that was used as an alternative so far. ### io *Add some accessors for serialization.* - keep the file path of the original DICOM file - getter for archive file path - getter for the default (de)serializer function which allow us to call them in a custom (de)serializer - fix a typo / coding style normalization - update unit tests *Forward the grabbing fps in IGrabber/SGrabberProxy.* For performance and quality evaluation, it is useful to forward a real-time frame-grabbing frame rate. A signal is added in the grabber proxy to forward the fps from the grabbers which support this functionality. Connect ```GRABBER_PROXY_SRC/fpsChanged``` to get the fps when it is updated. *Add NvJPEG2K backend when saving multiframes in DICOM.* ### test *Update MacroSaver from change to ITest::getProfilePath.* These changes reflect the changes of GUI test API to the MacroSaver. The main change is the support for the helper API that the code generated by MacroSaver will now use. ### ui *Reflect changes of presets in the TF editor.* The transfer function selector now updates the list of transfer functions properly when it changes. *Make toolbar button icons bigger in touch-friendly apps.* Some issues with touch-friendly apps were fixed: * The toolbar buttons are now bigger in touch-friendly apps by default (48\*48 instead of 32\*32) * When using SStatus with form = circle, the circles are now actually circular for any size * The slider groove is now bigger in touch-friendly apps to make it easier to use *Change Play/Pause/Stop shortcut.* Changes the controls.xml config Play/Pause/Stop shortcuts to config parameters. Space is the default value for play/pause and "s" for stop, though they can be changed in the configuration. This allows apps to use the space shortcut for their own usage. *Add swapp support from single volume view to 3/4 view with negatos.* The classical volume view in sightviewer is a single 3D scene with the volume. It is possible to go to a view with 4 scenes, with the 3D volume view on the top left, and the negato in all 3 directions in the other corner. It is presently not possible to simply make one of the negato in full screen. To make this possible, a SEvent service is added, to catch the different events, and forward a particular one. Once added to the configuration it is used to catch double click, and hide/show the different scenes. This makes it a lot easier to change the view, and go back. To keep the classical button functionality, the IAction api has been enhanced to support toogleVisibility. *Add grabber optimize channel to controls.xml configuration.* *Prevent SVideo crash on empty image update.* When providing an empty image (size (0,0,0) ) to a SVideo service, the service does not filter and forwards it to the textureManager which tests it and generates an error in particular in debug mode (ASSERT). However empty images are often used as default ones, and this leads to various difficulties. Here, an if(size\[0\] == 0 || size\[1\] == 0) test is added on the SVideo updating and return when it fails. *Use Qt layout instead of multiple 3D viewports in SightViewer.* ### viz *Improve distance measurement tool with a click and drag movement.* The distance measurement tool had some limitations. In particular, at the creation, the initial process was : - click on add distance: a distance is created at the ends (0,0) and (width, height) of the image - drag-drop the created distance ends to the location you want to measure This was too tedious. The new behaviour is : - click on add Distance: enter a dedicated mode - click on the starting point you want to measure - drag to the end - drop, the distance is ready. During your measurement, the distance is automatically updated on the screen, allowing you to visualise what you measure, and the distance between the starting point and present location. SightViewer has been updated to support the new tool and to have the negato2D and 3D interacting when the distance is created and measured. *Make Qt overlays compatible with the 3D scene.* The Ogre Qt widget has been heavily reworked. This was motivated by the need to have Qt widgets as an overlay. To make this possible, we chose to let Qt make the OpenGL compositing of the whole application. However, this required us to make a part of the composition ourselves. It was no longer possible to use a classic `Ogre`::RenderWindow``because, at some point, it will end up trying to handle its own final back buffer, while we want to render in the FBO managed by Qt. Thus, `Ogre`::RenderWindow``was banned in favour of `Ogre::RenderTarget`. This implied other significant changes to handle viewport resizes with listeners. Other changes were brought along this rework: - SightViewer XML configuration has been heavily reworked to use shared configurations. Three new configurations are now available in `sight::config::viz::scene3D` to display a single negatoscope, a 3D scene and four-split views with a 3D scene and 3 negatoscopes. - Layer transparency: if not specified, then the OIT is disabled (you still have transparency, but it is order dependent). This ensures that most render layers do not use an expensive transparency technique if it is not required. If you need OIT, `Default` is the best setting and is an alias for `HybridTransparency` - The Ogre Overlay was removed because it was hard to make it compatible with the new rendering setup. On top of that, it seems pretty irrelevant to keep two systems to do the same thing. The services that used it, like `sight::module::viz::scene3d`::adaptor::SText``have been switched to Qt. - In GUI tests, it is now possible to address the views using a `wid` in `SView` - `SImageExtruder` can now take an optional transform matrix, in the case where the image is moved in the scene (registration for instance) *Add reset layer camera slot.* The reset camera slot is connected, on the SRender service, to all layouts of the service. However, when several layouts are present, it can be expected to reset only a given layout's camera. To do this, a dedicated slot is created at the service configuration. The slot name contains the layoutId, and call the resetCameraCoordinates which is specified for the layoutId provided in parameter. *Use an additional mask for volume rendering extrusion.* This introduces a mask in the volume rendering, that is used to mark cropped regions instead of marking these regions with a special intensity value. This solves the problem of the computation of the gradient on the edges of these cropped regions and also provides smoother edges. A few extra changes were brought on the way: new toolbar icons for the cropping tool, cleaned properly the extrusions when a new image is loaded. *Add default tf loading option in TransferFunctionWidget.* The transferFunction editor widget (and windows) don't zllow to freely specify the a folder with f to pre-load, and the default tfs are always present. Add two optional parameters to the configs allowing loading pre-registered tf through the path attribute of STransferFunction. Add support to empty path (default value in the config) in the STransferFunction service. Changes the TransferFunctionWidgetCfg and TransferFunctionWindowsCfg config id to fetch new standards (sight::config::viz::scene2d::TransferFunctionWidgetCfg) *Enable binary alpha mixed rendering.* Binary-transparent surface objects are now rendered properly with volume rendering. *Add point selection feature on SLandmarks.* The SLandmark service is a graphical widget which handles the Landmarks, which can be seen as a vector of points. It has a feature to send the coordinates of the current selected point through a signal. This mechanism is enhanced, to treat a newly created point as a selected one. In addition, the selected point are outputed in a ```sight`::data::Point````variable in addition to the signal, to make it possible to treat it as a classical sight data. closes 1040 *Correct SLIne and SText.* Make SText input autoconnect to true Make SLine use getOrCreateTransformNode to get its transform Node *Add an optional transfer function presets list.* This adds the ability to specify an optional preset of transfer functions. ## New features: ### ci *Add a custom CMake command to run gcovr.* This reduces redundancy across project and make it easier to use. ### core *Introduce SMultiConfigController.* The present config launcher allows starting a given XML configuration. SMultiConfigController allows running a configuration selected between a set of configs that share the same parameters. Somehow, it creates a simple interface, where each "subconfig" is an implementation. This can have many applications, in particular in device handling, and will help to make smaller and more generic XML configurations. *Add API support for fiducials.* We introduced a new class, `FiducialsSeries`, representing a "Spatial Fiducials" DICOM IOD. `ImageSeries` and `ModelSeries` can both have a `FiducialSeries`. Some modifications were done in `SeriesImpl` in order to add support to sequences of sequences with more than one element. *Ssequencer / slandmarks fixes and enhancements.* - Application::exit() can now be synchronous and exit immediatly - SLandmarks: make "configureLandmarks()" a slot - SLandmarks: allow to limit the number of landmarks - SLandmarks: remove also landmarks no more in the data`::Landmarks`when update() is called - crash when clicking on ok without selecting a DICOM series - show number of frame in the series description - SSequencer: add a validate "next" that doesn't enable next activity - SSequencer: reset requirement that are no more valid - SSequencer: refresh validity on previous and next activities when calling checkNext() - cleanup - use const_lock whenever possible *Allow per-frame private DICOM attributes.* *Allow log relocation.* Add a `relocate_log()` that does exactly what its name suggests. Optionally, it also relocates the previous log files. Additionally: * the log singleton is now really a singleton * `sightlog` can now be launched outside "Sight", which is needed for external unit test * we have now access to all "binaries" paths from repositories (IE Sight/bin, XXXX/bin, ...the directories that contain executables like `sightrun` and `sightlog`) * changing the password while using encrypted logs, will indeed also relocate the previous logs, with the new password. This is useful when you plan to submit the logs for analysis and don't want to remember all passwords you used during the work session. * ..and some gcc-12 warnings have also been fixed. * add also a special environment variable (try with `export SIGHT_LEGACY_COMPRESSION=1`) that force legacy zip deflate algorithm for all compression operation, instead of zstd. This allows to open archives (logs, sessions, ...) with plain old third party archiver. * Force non-empty password. Empty password means "no password", which makes things ambiguous and complicated. *A better temporary directory / file.* - RAII to ensure the file / directory is deleted - Convenient conversion / utilities operator - Thread safe / process safe - path lenght is minimized - globally safer ### io *Allow to configure the baseFolder via a slot in IWriter.* *Allow to configure and override the transfer syntax used to write Enhanced US Volume.* Also: * 10% increase of nvjpeg2000 writing performance (avoiding unnecessary copy) * fix a huge memory leak while using nvjpeg2000 for DICOM writing * add profiling test for transfer syntax * allow using TempDir as a simple RAII directory cleaner * fix many memory leaks: * [valgrind_before.log](/sight/sight/uploads/7fd81924e7cdd842494917b0c09a3b11/valgrind_before.log) * [valgrind.log](/sight/sight/uploads/b84702ee5646b42910dfa3d8f679fb3d/valgrind.log) * fix a possible crash when the window is resized while not yet ready *Forward folder of loaded session as a signal.* *Add a new tool to extract data from an archive.* These changes introduce a new tool, ArchiveExtractor, to extract archives generated by Sight applications. It was designed specifically for opening archive from a real-world application, but it should be generalist enough to allow extract archives from any Sight application, as long as they're salted archives, as they aren't supported by ArchiveExtractor. This application needed a new module, module::io::zip::SExtract, which asks the user for the input file and the output path and eventually the password if needed. *Implement bitmap readers.* A reader and a service that allows fast bitmap reading were added. Some code has been refactored and factorized with the bitmap writers and some bugs have been fixed: - Image generator / randomizer that can now be called in one step, for all image formats and pixel type. - nvjpeg2000 flaw mitigation: fallback to openJPEG if the encoded file is bigger than source instead of failing - Reader / writer code factorization and cleanup ### test *Add backtrace generation mechanism for GUI tests.* These changes add helper methods to ease the creation of GUI tests. Some helpers, such as `helper`::Button``or `helper::Field`, operates at the component level, while some others, such as `helper::VideoControls`, operates at the level of a Sight XML config. Most helper methods use a `Select` helper class to get the components they operate on. For example, one can use `Select::fromDialog("fileNameEdit")` to get the component named "fileNameEdit" inside the currently displayed dialog window. Select has an implicit constructor which take a string, which will select a component within the main window, which is the most common use case. In addition, Select has two setters, `withTimeout` and `withCondition` which allows to set, respectively, a specific timeout to wait for the component to show up, and a condition for it to meet. A new GUI test was added for SightCalibrator, which is VideoControls. It checks whether SightCalibrator's video controls work correctly (and, incidentally, check that helper`::VideoControls`works). ### ui *Add accordion menus.* A new accordion menu is now available in tool bars by enclosing buttons in the `` tag. The toolbar in SightViewer was modified so that extrusion-related buttons are shown only if the extruder is activated and distance-related buttons are shown only if the distance mode is activated. The extrusion and distance modes are mutually exclusive, if buttons related to extrusion are shown, buttons related to distance are hidden, and vice versa. *Notification enhancements.* - The API has been updated, the code is no more part of `IService`, but has been moved to a new interface `INotifier`. The services that need to send notifications should now inherit from that new interface. The name of the notification method and the corresponding signal has not changed (`notify()` and `notified`), but the signature now uses a `Notification` structure, instead of only the type and the message string. For compatibility and for convenience, a `notify()` with the same parameters as before is available - Notifications can now have individual duration, that can be "infinite". The notification will then be "permanent" and will only be closed by a double click. The duration can be set within the `Notification` structure, a parameter of the new `notify()` - Notifications can now be "channeled", meaning they can be reused, shared and even closed by several services who share the same "channel" keys. The channel name is also passed in the `Notification` structure, but can also be mapped from XML configuration: ```xml ``` - Many bug fixes / small enhancement: - Changing position can now be done dynamically (useful for channels), without waiting that all previous notification to be closed to have a correct placement - Use a button to display long text instead of single click (which disallowed closing them !) - Fixed long text truncation - Race conditions / various crashes fixes. *Add a Speed Dial button.* These changes add a Speed Dial button, which displays a list of other buttons when clicked with an animation. The actual "buttons" can be any kind of QWidget, typically QPushButton, but it can also be more exotic widgets such as QOpenGLWidget. It also adds SIconSpeedDial, which is a service which allows to create a Speed Dial with a list of actions. It is the most simple and typical use case of the Speed Dial and can serve as a reference. *Create buttonbar widget for SParam enum.* The SParameter supports enums, though they are not simple to use, in terms of xml and ui. A new enum display will be added, corresponding to a bar, with buttons, image and text which allow to select a specific value. It should have the features of enumSParam, with icons and labels. The unselected options are gray, while the selected one is in full color. Gui test are added, to check this feature, and a sample is added in SParameter. *Provide a view that can be overlayed on 3D scenes.* A new `OverlayLayoutManager` is introduced, allowing the addition of overlays to a widget. Here is an example of use: ```xml ``` In OverlayLayoutManager, we define a list of views. The first view is the background widget, typically a 3D scene. The other ones are overlays, we can define properties such as ``x``, ``y``, ``width``, ``height`` to indicate where the overlay should be drawn and what its size should be. By default, ``x`` and ``y`` are the offset from the left and the top respectively, however, if they are negative, then it is the offset from the right and the bottom respectively. By default, they are absolute sizes in pixels, however, if ``%`` is appended, then it is relative to the size of the parent widget. *Add a optional forward / backward button for slider.* *Allow selecting absolute positions in negato sliders.* *Makes password dialog customizable.* Small modifications were brought to allow displaying an image and a custom message for the password dialog used in preferences. Basically, it is just a couple of parameters for module_ui_base: ```cmake module_param( module_ui_base PARAM_LIST preferences_password_dialog_title preferences_password_dialog_message preferences_password_dialog_icon PARAM_VALUES "Password required" " Please enter your password: " "sight::module::ui::qt/rename.png" ) ``` *Add Preferences::ignoreFilesystem method.* *Make toolbar hideable.* Enhance the IToolBarLayoutManager with a setVisible(bool isVisible) method Get the toggleViewAction QAction from the toolbar in the ToolBarLayoutManager and store it Set the toggleViewAction check state and trigger it when isVisible is called Add slots in the IToolBar to hide/show/setVisibility add toolbar hide/show to tuto14 *Add non-linear sliders for SParameters.* A new widget for `type=enum` parameters in SParameters is introduced, `slider`. This will use the new NonLinearSlider widget. ### viz *Create a pre-defined camera interactor.* New camera interactor SPredefinedCamera that takes multiple "point-of-view" in configuration. We can navigate through each point-of-view, the camera will go from one to another using a smooth animation. Mouse track (rotation only) can be disable, if enable you can rotate the camera arround a fixing point, but will be reset at next point of view. An optional "initial" matrix can also be set, if so camera will first use this matrix and then move to configured point-of-view according to this new position. This matrix can be updated in real time to get a "GPS-like" camera tracking an object. Others changes: * remove requestRender from Window,now only interactors should decide when trigger a render * add requestRender in ClippingBoxInteractor *Allow to specify the view distance of the landmark.* ...and many fixes on SLandmarks and one in is_less and is_greater. *Allows to use SCamera with orthographic projection.* # sight 22.1.0 ## New features: ### core *Add a function profiling utility.* - fix Warning C4244 - windows pch off support ### io *Add a DICOM Enhanced-US volume writer.* The current Dicom Series writer has been updated to call a specialized writer when the SOP class is [Enhanced US Volume](https://dicom.nema.org/dicom/2013/output/chtml/part03/sect_A.59.html). The new writer is for now minimalist and maybe not 100% DICOM compliant yet, as it requires, nor checks for mandatory tags to operate. However, all frames of a data`::ImageSeries`(on the Z axis) are saved losslessly in jpeg2000, and Series API allows writing/reading per-frame `Image Position Patient/Volume`, `Image Orientation Patient/Volume`, and `Frame Acquisition Date Time`. Even if the writer doesn't ensure other mandatory tags are present, it is still possible (and desirable) to write them using the Series API with the generated tag name/sop class from sight`::data::dicom::Tag`and sight::data::dicom::SopClass. Note however that the current API is limited to simple attributes, not the one located in a frame sequence like in `Shared Functional Groups Sequence`. Some adaptations are required (the same as \`Image Position Patient…). This part will be updated later when needed. *Use correct gdcm attributes for US volume.* - ImagePositionVolume, ImageOrientationVolume, FrameAcquisitionDateTime DICOM attribute are now stored into sequence element when using Enhenced US Volume, as before for CT/MR. - DICOM Tags, SOPClasses, Modules definitions are generated from official documentation using python code. This allows friendlier operations (no need to remember exact tag values, or SOP uids). - Unit tests have been updated to match changes and use generated DICOM tags, SOPClasses. - Some bugs with equality operator have been corrected *Allow forwarding grabber long running jobs.* *Add optimize slot to IGrabber/SGrabberProxy.* *Allow specifying a target camera in SGrabberProxy.* *Nvjpeg writer implementation.* A "fast" 2D image writer (sight::io::bitmap::Writer) and its associated service (sight::module::io::bitmap::SWriter) have been implemented. The writer uses NVidia CUDA accelerated JPEG / JPEG2000 encoding library: nvJPEG, if support has been compiled in and if a suitable GPU has been found. Alternatively, libjpeg-turbo, openJPEG, libtiff or libPNG can be used as CPU fallback. The performance should be better than VTK or even OpenCV because of direct API calls and avoided unneeded buffer copy. > :warning: VTK SImageWriter support for 2D bitmap format has been removed. The support was anyway bugged as the image were saved upsode down. > > also added: > - fix on `LocationDialog::getCurrentSelection()` that erased the first char to return an extension from a wildcard filter. Now there is a `ILocationDialog::getSelectedExtensions()` that returns a vector of extension, in case there are more than one extension from a filter. > - some small fix for high dpi displays in the GUI tester code. *Add zoom capability in video grabbers.* We added the possibility to zoom on videos. Some hardware devices offers this possibility, so it is better to use this instead of zooming in the visualization pipeline. ## Enhancement: ### build *Use /Z7 in all cases and enable ccache for windows.* ### ci *Enable debug optimized build for GUI tester.* Our GUI tester is very slow in the coverage build. We enabled optimizations for the tester code, especially for the image comparison functions, hoping that this will decrease the number of false positives. *Increase test timeout on test coverage.* ### core *Add private tag support.* *Lower the test epsilon to be a bit more tolerant.* *Add strict mode to require matrix presence in SFrameMatrixSynchronizer.* *Add a simple function to set the location of series instances.* A function was added to set both the position and orientation of a series instance at once, passing a `sight::data::Matrix4`. Besides this, `sight::data::Matrix4` has been modernized. ### filter *Make SFrameMatrix synchroniser delay specific for each timeline.* add a vector for the framesTl and one for the matrixTl to store the delay. The delay is applied at the synchronization, and the frame/matrix picked is in the past regarding the most recent data, from an amount of delay. The timelines are associated through their index. ### io *Un-pause grabber on successive startCamera calls.* *Skip camera restart when already started.* ### test *Enhance global test code coverage.* Many tests were added, especially for the most used services in our applications, that were untested so far. *Add external project gui test support.* - rename the gui test core folder to testCore -change the ITest profile path handling, by geting the full path, and not using "getWorkingDir()". It will be up to the GUI tests to provide the full profile path. - add the profile modules. The clasicall sightrun looks for the modules situated relatively to the profile path. This allows to load automatically the project modules; This will be done in the ITest too, at the test setup() -add -B bundlesPath in the cppunit_main. Similarly to classical applications, the -B argument allows specifying additional bundles path. This will be handled in the unit test too. - change test templates to add external libs path in the PATH variable and bundles path - in the eventHandling, verify that the event catched is a testEvent, and do nothing if it is not one. -install exec_gui_test and copy it in sight-projects build bin dir *Improve operator== tests for Data Objects.* ### ui *Use unique slot to configure Grabbers.* * rename some slots from SParameter from "set" to "update" for clarity * also add a vector of string as part of the parameter_t variant to be able to update all values of enum widget *Emit signal with value and key from SPreferenceConfiguration.* The signal, called `preferenceChanged`, has the same signature as the signal `SParameter::parameterChanged`. This simplifies the API when the service needs to listen to a parameter that can be changed from preference or/and from a`SParameter`. An example of usage is shown in ExSParameter. *Use a 3 columns layout for SParameters.* These changes modify SParameters layout to use a 3 columns system instead of the current 6 columns system, to improve the usability of the second and third spinboxes. In addition, the labels of the parameters now can wrap if they are too wide, and a bug where the second and third spinboxes wouldn't be disabled if the depend is disabled is also fixed. *Apply SParameters' stylesheet globally.* These changes apply the stylesheet from https://git.ircad.fr/sight/sight/-/merge_requests/795 globally. It can be enabled by setting the `"touch_friendly"` application option to `"true"` at configure time. *Add a generic signal/slot parameter type.* *Improve hitboxes for Q*SpinBox controls.* *Rename toolbar.xml to controls.xml and add more signals.* => add some out signals => disconnect fileConfigured with video play => add documentation ### viz *Add slot in SShapeExtruder to replace right click.* These changes add a slot called "cancelLastClick" to cancel the last click in the shape extruder. This allows to replace the right click in context where it isn't available, such as in a touchscreen context. In addition, this adds a button in SightViewer which triggers this slot when clicked. *Adapt default transfer function to a reference image.* The default transfer function can now be adapted to the image pixel type, especially for ultrasound images. The `data`::Image``no longer holds a default transfer function. To get a default transfer function, you have to use `sight`::module::ui::qt::image::STransferFunction``and specify a reference image as input. This is no issue if you don't want the transfer function selector in the user interface. You can register the service in an invisible view. You can have a look at `Tuto07GenericScene` for instance. Also, some bugs were fixed in SNegato2DCamera for the computation of the viewport of the axial view. *Add gestures to scene 3D.* These changes will allow to use gestures on the 3D scene. It allows in particular to pinch fingers to zoom and to long tap to place a landmark. Simple taps and pan gestures should intuitively map to mouse clicks and mouse drags. ## Refactor: ### build *Use built-in CMake PCH functions.* ### core *Introduce SSynchronizer to replace all frame/matrices sync services.* This refactors fundamentally the synchronization between frames and matrices, by bringing a single service SSynchronization that replaces all the previous ones: `SFrameMatrixSynchronizer`, `SMatrixSynchronizer`, `SMatrixTLSynchronizer` and `SFrameUpdater`. It is much more versatile to answer all the different use cases and his behaviour is well tested. *Inherit data::Activity from data::Composite.* *Separate service public and private API.* We reduced the size of the public API of the IService interface, which is undoubtedly the most used in Sight. First, the data management responsibility has been moved to the IHasData interface and now holds the getters and setters for inputs, in/outs and outputs. Secondly, a significant part of the implementation of IService methods has been moved to a pimpl in service`::detail::Service`and service::detail::ServiceConnection. The AppConfigManager was moved in the detail namespace as well, so now the public API only exposes IAppConfigManager. This refactor also finishes the migration of data::ptr. Now the objects of services are only held in data::ptr, the former input, inout and output maps of IService were removed, which simplifies a lot the code. This also implies that services can no longer specify any data in the XML configuration that is not declared as data::ptr. In this repository, only two services relied on the old behaviour SConfigController and SConfigLauncher. The migration consisted in using a single declared group of objects (data::ptr_vector) instead of multiple undeclared objects. Changes were brought in all XML configurations. Last, the ObjectService registry refactor was also finished. Its role has been reduced because we no longer rely on it to store the relationship between services and objects. This responsibility is filled by the services themselves. So now, this registry only holds a global list of registered services. It has been renamed accordingly. Doing so, the sight`::service::registry`namespace was removed, and the only other class that was there, sight`::service::registry::Proxy`was moved to sight::core::com::Proxy. Indeed, it has actually no dependency at all on services and is generic enough to be in the core`::com`namespace. *Deprecate IService::getConfigTree().* *Remove ConfigurationElement totally.* *Remove AppManager and Qml apps based on it.* *Replace ConfigurationElement in IService.* *Replace ConfigurationElement in all service configurations.* ### io *Create a widget & window configuration for pacs selector.* * the widget config is called by the windows config * widget can be used if the pacs selector should be integrated in a existing window *Create macros `SIGHT_REGISTER_SERIALIZER` to ease the serialization's function registration for each data.* ### viz *Simplify layer configuration for scene3d adaptors.* The scene3d adaptors no longer specify their layer. Instead, it is implicitly declared in the `SRender` configuration by putting the adaptors as children of the layers tags. ```xml ``` *Store transfer function as 2D Nx1x1 texture.* ## Bug fixes: ### build *Update dependency URLs.* *Use relative paths in launcher installed scripts.* *Only install header files when necessary.* This prevents rebuilding a child repository each time sight is installed. To achieve this, a custom target was added to generate the library headers without `*_API` macros in the build folder, and then copy these at install. Previously, we modified the files directly in the install folders, which led to always modify the timestamp of the headers, thus triggering the rebuild. ### ci *Use 'fetch' strategy instead of none on Windows.* On Windows, we do not have docker runners. Thus the build folders are reused between jobs. GIT_STRATEGY='none' is faster but does not provide the clean stage that is performed with 'clone' and 'fetch'. Because of this, we may end up with artifacts from previous jobs in the deploy stages. To overcome this, we use the 'fetch' strategy. It is useless to get the sources, but, this gives us the clean stage which is impossible to do in a build script. See https://gitlab.com/gitlab-org/gitlab/-/issues/17103 *Doxygen deployment.* ### io *Use new bitmap writer for screenshots.* *Ensure serializer register is unique.* *Make loop great again.* reset the timelines when reading process reached the end and is in loop mode add loop mode (slot + config + mechanism) in SMatricesReader make SMatricesReader pause system similar to SFrameGrabber one *Serialize & deserialize correctly empty objects.* - Data::Mesh * do not resize if mesh has no points / cells * Add VTK_EMPTY_CELLS in switch case - Data::Array * do not resize if deseralized array is empty - Data`::Image`/ ImageSeries * initialize Image windowCenter and windowWidth to empty vectors - Data::TransfertFunction * mistake in operator== * also test pieces vector * implementation of operator != - Misc * Remove Graph, Node, Edge, Port, ReconstructionTraits, ROITraits Data * Use operator== to compare all data in sessionTest ### test *Handle external modules properly in test bat and bin.* *Improve LoadDicom GUI test sensitiveness.* ### ui *Fix password management for preferences.* * restore BadPassword exception * changed inputDialog to return value and a boolean to know if user canceled it * allow closing sight if user cancel or if wrong password have been entered 3 times * updated ExActivities plugin configuration to force encryption and to exit on password error * "once" passwod policy configuration has been changed to "global": "global" which means the global password will be used, if set, otherwise or if wrong, it will be asked to the user * "default" configuration has been removed. User should simply not set any configuration if they want the default to apply *Add a slot in SLandmarks scene 3d adaptor to take care of landmarks' group renaming.* *Replace delete by deleteLater in QtContainer class.* To get rid of the deletion order we use deleteLater() function on the m_container QPointer. *Destroy the GUI elements in the reverse order in IGuiContainer.* ### viz *Use a read lock on the image when possible in SNegato2DCamera.* When receiving the resize event, we may end up with a deadlock if the image is already locked in writing. This may happen for instance with a writer that uses a progress bar. *Switch current drawable when swiching OpenGL context.* # sight 22.0.0 ## Enhancement: ### build *Update VCPKG.* VCPKG packages has been rebuilt, and the hash has been changed. All dependency packages have kept the same version number, so it is unlikely that a change of behavior occurs. *Remove libxml2 from the core public interface.* *Upgrade code to support C++20, and use some new features.* * Build with C++20 standard * Update the code to fix the following deprecations: * implicit capture of ‘this’ via ‘\[=\]’ is deprecated in C++20 (see [reference](https://www.nextptr.com/tutorial/ta1430524603/capture-this-in-lambda-expression-timeline-of-change) ) * Replace usage of `boost`::ublas``by glm (the current version does not build with C++20, Debian is shipped with an old version of boost...) * Use a new vcpkg build with a patched ITK version for C++20, and thus some minor adjustments because of new package versions (DCMTK and openCV for instance) * Use std`::ranges`algorithms in some places just for fun :heart_eyes: *Update VCPKG packages.* ### ci *Disable debug dialog on Windows on the CI.* When a unit test fails with an assertion failure in Windows Debug, a debug dialog will appear. This is useless in the CI, where physical access is required to view the dialog and know where is the problem. These changes remedy this, by disabling debug dialog and printing messages in the console when the environment variable DISABLE_ABORT_DIALOG is set. *Disable thread information from GDB in the CI.* *Use Sheldon's Clang-tidy hook for lint job.* Now that Clang-tidy is added as a hook for Sheldon, we can use it instead of using Clang-tidy directly, to reduce code redundancy. *Check whether packaged applications are executable.* Existing testing to prevent regressions isn't sufficient, as experience has shown. The packaged applications will now be tested automatically in the CI: SightViewer and SightCalibrator will be installed, and then executed in order to check if they start successfully or crash because of missing dependencies or various errors during installation. Also, all examples, tutorials and utilities will be launched to verify, at least, that they can start and stop. *Add Clang-Tidy to the CI.* *Add some metrics.* This shows the number of warnings and deprecated declarations in the merge request metrics reports. ### core *Create the log in user cache directory by default.* Default log file path, when nothing is specified with --log-output in the user "cache" directory, which is given by $XDG_CACHE_HOME on Linux or simply $APPDATA on Windows. As a fallback, the default temporary directory is used. In both cases, the path is suffixed with ./sight/. The final path is also displayed on the console. > VTK.log and Ogre.log has been taken into account... Some (light) adjustment and cleanup have also been made in core`::tools::Os`to manage "cache" directory and return a std`::filesystem::path`instead of a std::string. this could be a possible breaking change as you may have to call std::filesystem::path::string() when calling getUserConfigDir() (already fixed in this MR). getUserDataDir() name is misleading. Since it returns XDG_CONFIG_HOME it should be called getUserConfigDir(). It was hard to not change this in this MR for me, so it was done.... And last but not least, a small "fix" in PreferencesTest to clean correctly the user config directory after the test pass. I come through it while changing the getUserDataDir() returned type to std::filesystem::path *Remove hard-coded label value to generate mesh.* provide a from input the value to generate mesh and implements the unit tests for the codes. *Enable usage of lamba functions in slots.* It is now possible to use lambda functions in slots. For instance, this declares a slot making the sum of two integers : ```cpp auto slotSum = core::com::newSlot( [](int a, int b){ return a + b;} ); ``` *Improve camera resolution selection.* The camera service selection now provides a new setting `` allowing to automate the choice of the resolution. The value can be `min/max/WxH/preferences/prompt`. - `min`: the minimum resolution is automatically chosen. - `max`: the maximum resolution is automatically chosen. - `WxH`: the exact resolution is set (for instance 1280x720). Beware because if the device does not support the resolution, an error message will be displayed and the camera will not be available. - `preferences`: default value, the dialog is shown on the first time and then the choice is stored in the preferences of the application. This choice will then be used each time. An extra button is displayed next to the camera selector to change the resolution later. - `prompt`: former behavior which makes the resolution dialog to always prompt. *Add initializer_list constructor support for KeyConnectionsMap.* A new constructor was added to KeyConnectionsMap allowing to shorten the implementation of `IService::GetAutoConnections()`. For instance : ```cpp IService`::KeyConnectionsMap`SSample::getAutoConnections() const override { return { {"data1", data::Object::s_MODIFIED_SIG, s_UPDATE_SLOT}, {"data2", data::Object::s_MODIFIED_SIG, s_UPDATE_SLOT} }; } ``` instead of : ```cpp IService`::KeyConnectionsMap`getAutoConnections() const override { KeyConnectionsMap connections; connections.push("data1", data::Object::s_MODIFIED_SIG, s_UPDATE_SLOT); connections.push("data2", data::Object::s_MODIFIED_SIG, s_UPDATE_SLOT); return connections; } ``` The previous declaration is still possible. Few implementations were changed as example. *Secure library loading when upgrading sight version.* When executing sight in build tree, we may load the wrong version of libraries when upgrading. Now, we use the ."so" symlink first to be less sensitive to version change. ### geometry *Remove charuco related codes.* ### io *Add optional receive timeout on igtl server.* * when using the timeout receive fonction aren't blocking * also remove client from vector when disconnected ### navigation *Download openvslam vocabulary only when SOpenvslam starts.* * create a function to donwload file using curl in io_http library * minors fixes on SOpenvslam, SFrustum & SFrustumList to match latest updates ### test *Add tests for the HiResTimer class.* *Improve geometry::data::Mesh::transform unit-test.* The unit test for `geometry`::data::Mesh::transform``was pretty weak, as the test was mostly the same code as the tested code. The method is now tested with a hardcoded small mesh which is transformed, with all combinations of types possible (only points, point and point normals, point and cell normals, point and all normals). ### ui *Add an optional scroll bar for SParameters.* A `scrollable` property was implemented in `SParameters`, which adds a scroll bar to the right of the widgets. *Add a new signal to notify if the next activity is ready.* Two signals were renamed in `sight::module::ui::qt::SSequencer`: - `enabledNext()` -> hasNext() - `enabledPrevious()` -> hasPrevious() One signal was added, which is triggered when the next activity is enabled (all requirements are satisfied): - `nextEnabled()` *Simplify notification API by using single signal & slot.* * One signal "notified" in IService containing the type & the message * One slot "pop" in SNotifier reading type & message and displaying the corresponding notification popup *Move the modal transfer function editor in the right panel in SightViewer.* ### viz *Add pixel values in 2D negatoscopes.* We added the ability to pick pixel values in 2D negatoscopes, in the same way than it was already done in 3D negatoscopes. *Use image GPU resource sharing in all adaptors.* *Speedup the tf upload by 40x.* *Set SNegato2D adaptor transformable.* *Merge ExOgreRGBDStream and ExRealSense together.* The ExOgreRGBDStream sample was somehow useless since the only RGBD camera we do support is the IntelRealsense, which is demonstrated in ExRealSense. We added a missing feature from ExOgreRGBDStream into ExRealSense, the transfer function editor. The sample was also modernized a bit and debug optimizations were enabled in some modules to keep good performances in this build type. *Merge SAxis and SScaleValues together.* *Enlarge the viewport shutter to contain histogram and tf values.* ## Bug fixes: ### build *Fix various CPPCheck warnings / errors.* *Change windows export handling on lib with QT in the name.* *Small fixes to support gcc / libstdc++ 12.* *Configuration issues with GLM.* Since GLMConfig.cmake is correct on Windows and buggy on Ubuntu, we use a different approach depending on the platform: * Use the old-ish system with `target_include_directories` on Linux * Use `glmConfig.cmake` on Windows (but everywhere this time) *Clang-tidy warnings.* Here is the complete list: - readability-duplicate-include - readability-container-data-pointer - cppcoreguidelines-virtual-class-destructor - cert-err33-c - readability-identifier-naming - cppcoreguidelines-pro-type-cstyle-cast - clang-analyzer-core.NonNullParamChecker - clang-analyzer-core.NullDereference - clang-analyzer-core.CallAndMessage - cppcoreguidelines-non-private-member-variables-in-classes - google-explicit-constructor,hicpp-explicit-conversions - bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp - modernize-use-using - cppcoreguidelines-macro-usage - bugprone-macro-parentheses - hicpp-exception-baseclass - clang-analyzer-security.insecureAPI.strcpy - bugprone-too-small-loop-variable - bugprone-inaccurate-erase - cert-flp30-c - bugprone-incorrect-roundings - bugprone-suspicious-include - google-build-explicit-make-pair - google-global-names-in-headers - readability-redundant-control-flow - bugprone-throw-keyword-missing - readability-static-definition-in-anonymous-namespace - readability-string-compare - hicpp-move-const-arg,performance-move-const-arg - cppcoreguidelines-interfaces-global-init - readability-misleading-indentation - cert-err09-cpp,cert-err61-cpp,misc-throw-by-value-catch-by-reference - bugprone-parent-virtual-call - modernize-redundant-void-arg - misc-unused-using-decls - performance-inefficient-algorithm - modernize-make-unique - readability-suspicious-call-argument - bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions - bugprone-undefined-memory-manipulation - google-readability-function-size,hicpp-function-size,readability-function-size - readability-container-size-empty - bugprone-integer-division - readability-use-anyofallof - cppcoreguidelines-slicing - modernize-raw-string-literal - performance-unnecessary-copy-initialization - boost-use-to-string - readability-redundant-smartptr-get - hicpp-use-emplace,modernize-use-emplace - cert-msc32-c,cert-msc51-cpp - cppcoreguidelines-pro-type-const-cast - hicpp-multiway-paths-covered - performance-inefficient-vector-operation - cert-err34-c - performance-faster-string-find - clang-analyzer-optin.cplusplus.VirtualCall - readability-isolate-declaration - readability-qualified-auto,llvm-qualified-auto - clang-analyzer-deadcode.DeadStores - google-build-using-namespace - readability-delete-null-pointer - bugprone-implicit-widening-of-multiplication-result - misc-unused-alias-decls - readability-uppercase-literal-suffix - bugprone-branch-clone - performance-inefficient-string-concatenation - bugprone-misplaced-widening-cast - cppcoreguidelines-no-malloc,hicpp-no-malloc - performance-no-automatic-move - performance-for-range-copy - modernize-loop-convert - readability-inconsistent-declaration-parameter-name - modernize-avoid-bind - bugprone-forward-declaration-namespace - modernize-make-shared - performance-trivially-destructible - cert-dcl21-cpp - modernize-use-transparent-functors - readability-implicit-bool-conversion - cppcoreguidelines-init-variables - hicpp-noexcept-move,performance-noexcept-move-constructor - modernize-pass-by-value - hicpp-named-parameter,readability-named-parameter - google-runtime-int - hicpp-use-equals-delete,modernize-use-equals-delete - cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator - cert-oop54-cpp - readability-simplify-boolean-expr - modify .clang-tidy configuration file - bugprone-sizeof-container - llvm-else-after-return,readability-else-after-return - hicpp-use-auto,modernize-use-auto - cppcoreguidelines-pro-type-member-init,hicpp-member-init - cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays - hicpp-deprecated-headers,modernize-deprecated-headers - hicpp-use-equals-default,modernize-use-equals-default - readability-redundant-string-init - readability-redundant-member-init - modernize-use-default-member-init - hicpp-use-nullptr,modernize-use-nullptr - cppcoreguidelines-prefer-member-initializer - readability-avoid-const-params-in-decls - llvm-namespace-comment - modernize-return-braced-init-list - readability-const-return-type - modernize-use-nodiscard - readability-make-member-function-const - readability-convert-member-functions-to-static,readability-static-accessed-through-instance - modernize-concat-nested-namespaces - hicpp-use-override,modernize-use-override - cert-dcl58-cpp *Small corrections on filter_image to build with ITK5.* * disable spheroidExtraction * Add missing components *Move Ogre plugins next to the Ogre libraries.* *Remove warnings in modules.* These changes remove warnings in Sight modules. These warnings were mostly harmless, but could hide potentially harmful problems. *Remove warnings in libraries.* These changes remove all compile warnings in Sight libraries. These warnings were mostly harmless but could hide potentially harmful problems. *Correct windows application packaging.* *Forward script arguments when using privilege escalation on Windows.* ### ci *Windows SDK package made relocatable.* Sight windows SDK package is now relocatable. All mentions of the build tree are removed with careful usage of CMake. A test has been added to the CI to prevent any regression. *Reorder plugins loading in Tuto01DataServiceBasicCpp to avoid crash at exit.* *Migrate artifacts download to nextcloud.* *Remove redundant coverage report in Sight config.* ### core *Detection of runtime library folder.* *Reset the count before resetting BufferObject to avoid lock count assert at buffer destruction.* Resetting the counter in the destructor **BEFORE** resetting BufferObject shared pointer is required ! Otherwise, the lock count assert in the destruction of the buffer, in `BufferManager::::unregisterBufferImpl()` will be triggered. Also remove hack in SDistorsion service. *Parsing of transfer function data in XML.* The transfer function data can be initialized directly in XML configurations. Because of a regression, the parsing was broken and caused a crash at start. *Really disable SIGHT_DEFAULT_PASSWORD when not set by user.* *Consider multi arch folders in runtime directory detection.* *Use priorities to unload modules loaded after profile start.* Priorities are now used to unload all modules, even those loaded after the initial start of the profile. This allows notably to unload `appXml` first, and then modules like `module::viz::scene3d`. To achieve this, the start and priority properties are now set directly in the `plugin.xml`. The priority is read at runtime when parsing modules. It is used both to start and to stop modules. Some code cleanup was performed, which led for instance to remove the over-designed Starter and Stopper classes. This part of the profile management should be clearer now. The sorting of modules in the generation of the `profile.xml` is _de facto_ no longer necessary and has thus been removed to simplify the code. *Set the log output in the main of unit-tests.* The redirection of the log into `fwTest.log` is performed by a singleton in sight::core::utest. We link with this library in coreTest, but we do not use any symbol from it. Thus the linker strips it and so in the end, we do not initialize the log output. To fix this, we simply initialize it in the main file of unit tests. *Prevent race condition in serviceTest.* *Prevent race condition when adding a new id.* ### geometry *Update intrinsic parameters in SPoseFrom2d.* When intrinsic parameters, such as the resolution of the camera, change, the computation of the 2D pose did not take this into account and used the parameters set at start. Now we listen the changes of the parameters and update accordingly. ### io *Use a patched ITK header when using clang + Ubuntu 22.04 support.* - update sight-deps and use Ubuntu 22.04 image - vtk mesher has been fixed upstream *Overwrite the seriesDB in the ITK reader, make *.nii the default.* *Add patched version of buggy igtl functions.* * Add a modify version of igtlSocket.h header, included first it allows public access to socket descriptor (needed for a proper closing function) * Patched version of createServer to call patched version of bindSocket() * bindSocket: remove need to define VTK_HAVE_SO_REUSEADDR to add SO_REUSEADDR option in socket *Throw exception for common socket error (timeout, ...).* * INetwork will now throw exceptions if timeout, network error, or size mismatching of received data instead of returning a nullptr of igtl::MessageBase. * Create unit test to test server/client communication *Do not restore the UUID of objects when deserializing.* Restoring the UUID of objects implies that a serialized object is really unique. Thus if you read a file containing a object twice, you expect to have only on object in memory. This is definitely not the behavior we want, we expect the object to be duplicated each time it is read, with its own UUID. ### navigation *Remove vocabulary download from cmake.* Since the download is now performed at runtime in C++ ### test *Change float comparison equality strictness of copies.* ### ui *Deadlock when exporting transfer function.* Because SWriter`::update`locks data and so does the function before calling this, a deadlock occurred. *Allow to use subtoolbars in toolbars.* This fixes two bugs preventing from using sub toolbars in toolbars: * parsing error in `` tag attribute in the toolbar config * wrong alignment used in child toolbars *Block signal when enum parameter is updated in SParameter.* * also look in both item text and data as fallback to find value of enum *Initialize the type selection combobox with the right value.* *SNegato2D Camera crash when a single frame is provided.* *Run appXml code on the main worker thread.* This fixes a regression caused by the removal of the second initialisation stage of `IPlugin`. All `initialize()` functions, notably the one from AppXml, were called from the Qt event loop. The function loading the stylesheet is posted just before on this Qt event loop, which implies it is called before the initialisation of `AppXml`. With the removal of `initialize()`, the `start` function of `AppXml` was called directly from the main thread, before the start of the Qt event loop. Thus, the function loading the stylesheet was executed after the start of the application, causing rendering issues. It seems safer anyway to keep the previous behaviour. So, `AppXml` was slightly modified to execute the start of the application on the Qt event loop. *Various issues when loading meshes in SightViewer.* - random crash when the camera is not reset - reset the camera when a model is loaded in SightViewer - enable the hide/show model when a model is loaded - do not enable the image buttons when a model is loaded ### viz *Display of images with 32 bits integer pixel format.* This restores partially the behavior prior to 1353d895 that converts 32 bits integer images into 16 bits images when uploading them on the GPU. This fixes a regression that prevents from reading all 32 bits integer DICOMs. *Avoid deadlock in viz::scene3d::IParameter with textures.* *Invert Plane constructor param to fit SNegato usage.* *Out of bounds writing in function transfer.* An error was introduced that could fill one pixel too many, causing a crash when deleting the transfer function, potentially when exiting the application on Windows. *Add a workaround for NVidia Prime to solve a deadlock with several 3D scenes.* *Blend transfer function pieces proportionally to their opacity.* *Do not allow to move TF points outside the viewport.* *Do not reset the opacity when changing the color of a TF point.* *Change Ogre plugin location.* Ogre needs to locate its plugin at the start, in a similar way as Qt does. Over the years, we had different strategies to locate them which always fails in the end in some corner cases. Well, I finally propose to use the exact same strategy as we do for Qt, which is to locate the core Ogre library and then use a relative filesystem path from there. It has proved to be a winning strategy with Qt. ## New features: ### core *Forward SParameters signals from SGrabberProxy and IGrabber.* *Remove SeriesDB, Activity and Camera are stored in separated set.* - rename ActivitySeries to Activity - rename CameraSeries to CameraSet - rework deep/shallow copy to use full inheritance and to copy parent class - change ImageSeries inheritance to Series and Image - remove Patient, Study, Equipment data object and use GDCM to store DICOM attributes *Add generic container classes.* #### Description Implements a generic templated data container class, aka `IContainer`, that allows code factorization from all containers. STL API from the corresponding STL container classes is exposed and the inherited containers, such `Composite` and `Vector` can be seen as a real `std`::vector``and `std`::map``from outside (which they indeed are !), while keeping to be data objects, that can be used in XML, that can be serialized, etc.. Since it is a part of https://git.ircad.fr/sight/sight/-/issues/862, some containers (`ActivitySet`, `CameraSet`, `SeriesSet`) have been also implemented. Although not used yet, you can still take a look at them, as `CameraSet` uses a more complex `std::vector>` while `ActivitySet` and `SeriesSet` use a [Boost Multi-index](https://www.boost.org/doc/libs/1_79_0/libs/multi_index/doc/index.html), which allows to define a `set` which is sequenced like a `vector`. ##### Usage The best open `Composite` or `Vector` and `IContainerTest` code, but basically, all you have to do if you need a specific data object container class, is to inherits from `sight::data::IContainer`, with `XXX` being your STL container type (or boost STL compatible container, like Multi-index !). As an example: ```c++ #include "data/IContainer.hpp" class DATA_CLASS_API Vector final : public IContainer > { ... }; ``` You can then use it like a real std::vector: ```c++ auto vector = sight::data::Vector::New(); // 99.9% of STL API is available vector.reserve(2) vector.push_back(sight::data::Integer::New(1)); vector.push_back(vector.front()) vector[1] = sight::data::Integer::New(2) ... // Initializer list / assignment operators vector = {sight::data::Integer::New(1), sight::data::Integer::New(2), sight::data::Integer::New(3)}; // iterators are supported for(const auto& element ; *vector) { std`::cout`<< element->getValue() << std::endl; } ``` ##### ScoppedEmitter There is also a generic `ScopedEmitter` which replace various "helpers", that were used to send signals when adding / removing objects in the container. It uses RAII mechanism to send the right signals when it is deleted. To use them, simply call the generic `scoped_emit()` function form a container to get a `ScopedEmitter` instance, and perform operation on the container. The ScopedEmitter will take a snapshot of the content and compare it with the current container upon destruction. Signals will be fired if elements have been added or removed or changed (in case of a map like container). Short example: ```c++ auto composite = sight::data::Composite::New(); { auto scoped_emitter = composite->scoped_emit(); // Now modification to `composite` will be notified to whatever is connected to `composite` signals composite->insert({"beast", sight::data::Integer::New(666)}); ... // Signals are sent when notifier is destroyed, like outside this scope... } ``` ##### Advanced usage ###### Writing specific code for specific container Sometimes, it is useful to know if an object is a container and if yes, from which kind it is. Some template matching functions have been added to `core/tools/compare.hpp`: ```c++ #include template void my_function(const T& truc) { ... if constexpr(core::tools::is_map_like::value) { truc.insert({"maman", value}); } else if constexpr(core::tools::is_container::value) { truc.insert(value); } else { .... } } ``` ###### Generic container without inheriting from `IContainer` If you don't want the `IContainer` inheritance because you don't want to be a `sight::data::Object`, but still want to act like a `XXX`, you could inherit directly from `ContainerWrapper`: ```c++ class MySimpleContainer : public ContainerWrapper> { ... }; MySimpleContainer a; a.insert("Le petit chaton bleu est très malade."); ... ``` ### io *Add requestSettings slot to grabber interfaces.* *New DICOM reader implementaion.* A new DICOM reader has been implemented to take use of the shared DICOM context, allowing to have access to all DICOM properties from the original DICOM files. The new reader is also able to read DICOM IMAGE files that were not well-supported, most notably: * All Ultrasound Images IOD (Enhanced US Volume, Ultrasound Image, Ultrasound Multi-Frame Image) * RGB Image with YBR color space (used in jpeg image) * Encapsulated transfer syntax * Unusual planar configuration (r1r2r3...g1g2g3...b1b2b3 instead of r1g1b1r2g2b2r3g3b3...) * Monochrome 1 image Few bugs have also been corrected, and some enhancement has been done: * Allows selecting the series to read in case there are more than one series found * Huge speedup: 4x faster reading * 2x less memory used * Fixed many bugs in the Series selection dialog: * crash with date/time on anonymized data (which contained unusual dates) * wrong data displayed * wrong data selected * added utf-8 / internationalization support (yes Ren**é** is now displayed correctly, and far east patient are no more a number of squares) * Thread management of GUI stuff like cursors, DICOM logger dialog, etc.... * some tests were added (and also US data on sight-data) *Update IWriter interface to automate data output.* * Automate the output of data using Preferences and Series for the SFrameWriter, SVideoWriter and SMatrixWriter services *Refactor io itk services and add nifti support.* Global refactor of the itk io services and libs. * add of the nifti support in the lib and in the modules * refactor the lib existing read/write files to fit the global sight io naming * refactor the services, to make a single SImageReader/SImageWriter which switch depending on the extension * refactor the services, to have reader/writer which go together * add unit-test * add itk reader in sightviewer images series loader ### test *Add a macro saver to generate GUI test skeletons.* GUI testing is now possible, but creating GUI tests still isn't that simple, especially to get the graphic components to interact with. MacroSaver will generate a GUI test skeleton compatible with GuiTester to save that hassle. To use MacroSaver, one must call sightrun with the `--macro` flag, the generated tests will be available once the application is closed as the files "GuiTest.cpp" and "GuiTest.hpp". *Add a GUI test library and GUI tests.* An automated GUI test library built on top of QTest was introduced. This library can wait and get graphic components, interact with them by emulating mouse and keyboard events and check if assertions are true. In order for the graphic components to be fetched more easily, components got objectNames, so they can be easily found using `QObject::findChild()`. Additionally, the tests will test the 3D rendering, by creating snapshots and comparing them with reference images using 6 different methods (pixel by pixel, mean square error, cosine of the matrices, histogram, Spearman's correlation,...). When a test fail, it will take a screenshot of the screen, to help in troubleshooting, especially when it runs on an non-desktop environment, such as the CI. Last, first UI tests were introduced for SightViewer and SightCalibrator. ### ui *Add standard embeddable video toolbar.* *Allow to programmatically set enum values in SParameters.* ### viz *Introduce GPU resource sharing.* GPU resource sharing is introduced, with the first application to textures and transfer functions. From the user point of view, we provide a new class `sight::viz::scene3d`::Texture``and we extended the existing class `sight::viz::scene3d`::TransferFunction``in order to allow GPU resource sharing. These classes only allocate Ogre resources (and thus GPU memory) when the Id of the source object changes. In addition, they "cache" the update of these resources. Thus now, when we have, for instance, 3 negato adaptors on the same image, there is only one `Ogre`::Texture``created, and only one `Ogre`::Texture``updated when the `sight`::data::Image``is modified (and similarly for the transfer functions). *Allow applications to add Ogre plugins from CMake.* We added the possibility to enable Ogre plugins from CMake `module_param(module_viz_scene3d ...)` calls. ## Refactor: ### build *Use a single PCH with only external dependencies.* To solve the issues described in #948, we now provide a single PCH file. It only contains 3rd part libraries headers. The list was extracted from the previous pchServices recursive list, by removing all sight headers. It is also built in a second version for the targets that use optimized debug builds. During tests, we realized the build timings remain stable and even outperform sometimes the previous approach. On Clang, we also took the opportunity to use a new feature that speedups PCH builds: http://llunak.blogspot.com/2021/04/clang-precompiled-headers-and-improving.html. The gain was measured at 10%. ### core *Rename oldish macros.* *Replace EConfigurationElement with boost::property_tree::ptree in all unit tests.* *Remove visibility and transparency signals on images.* The visibility and transparency of images are now handled in a simpler way, following the MVC pattern: - the image is the model - the view is the adaptor (`SNegato2D`, etc...) - the controller is the widget (`SParameters`, `SAction`, etc...) The view does not control the state and only applies what the controller requests. This implied the following changes: - Removed s_TRANSPARENCY_MODIFIED_SIG and s_VISIBILITY_MODIFIED_SIG fields from `data::image` - Removed all associated code, including the old service `module::ui::qt::image::ImageTransparency` *Simplify core::tools::Type and massive core::tools cleaning.* `core`::tools::Type``was simplified for easier use. First, it was moved to the root of the library, so it is now `core::Type`. Then, it simply contains a single enum attribute that sets the supported type. All methods of the class use an internal map to answer to the capabilities of the type (size, signed, name, etc...) instead of storing them in each type instance. Some extra cleaning was also done. `core`::tools::Type``is a very old piece of code, previous to C++11 and was linked to some pieces of dead code. Many features it used to bring are now done easily with post C++11 code. The dispatcher, for instance, used exclusively for ITK filters, relied on `type_info` just because of the use of a deprecated ITK function to get the image type. With the new function, this is no longer necessary, so a large amount of code dealing with `type_info` was removed. *No longer use xml profile in utest, remove initialize state in IPlugin.* ### ui *Deprecated SSlotCaller in favor of SAction.* *Use new signals and slots of IAction everywhere.* *Harmonize IAction signals and slots.* *Remove deprecated services, functions and config.* `ui`::viz::SAddPoint``is removed in favor of `module::geometry::SManagePointList`, `IAction::getActiveStateValue()` is removed in favor of `IAction`::inverted``and `ISlideViewBuilder` `align` and `size` configuration attributes are removed in favor of `halign/valign` and `width/height`. ### viz *Remove transfer function merge copy in the data.* We faced multiple floating precisions issues when merging the pieces of a transfer function. To avoid that, we removed the pre-merge phase of the pieces and we actually merge directly when sampling. *Simplify transfer function management.* This is a major rework of the transfer function data. Now the transfer function is a real piecewise function. Each piece stored in the object can be individually edited and thus is serialized. Pieces can be accessed and edited independently thanks to the `pieces()` function that returns a vector of `TransferFunctionData`. When the pieces are modified, the function `mergePieces()` must be called to mix the pieces together. This implies that the duplicated `sight`::module::ui::qt::SMultipleTF``and `sight::module::viz::scene2d`::SMultipleTF``are removed in favor of `sight`::module::ui::qt::STransferFunction``and `sight::module::viz::scene2d::STransferFunction`. On top of that, the former TF "pool" is no longer exposed anywhere in the services interfaces, thus from the XML. `sight`::module::ui::qt::STransferFunction``handles this "pool", renamed as "presets", internally. Other changes were brought: - `sight::data::TransferFunction::mergePieces()` implies the removal of `sight`::module::data::SMergeTF``service. It also brings a functional change, the pieces of the transfer function is performed with an average of colors instead of a strict additive blending. - It is no longer possible to move a transfer function piece outside the range of the viewport (bug fix request in the comments of this ticket). - Adjusting the window in the negatoscope is now reflected properly in the transfer function editor (partially fixes https://git.ircad.fr/sight/sight/-/issues/847) - Moved and renamed `TransferFunctionManager` from `scene3d` to `scene2D::TransferFunctionWindow`. *Include TransferFunctionManager from TransferFunctionManagerWindow.* *Merge SHistogram, SHistogramCursor and SHistogramValue together.* Since we removed SCurveHistogram, there was no good reason to keep those three adaptors separately. Doing that, we improved the computation speed of the image histogram by a factor of 10. Computing the histogram is now so fast that it is useless to have a dedicated data for it. We removed all the ecosystem around it and the only service that uses it so far, the SHistogram adaptor, computes the histogram dynamically. On top of that, this allows to change the bins width dynamically which is very handy. We also added an axis for the image histogram that can scale with the graph. This required a refactor of the usage of the viewport in the 2D scene. Now the scene no longer holds a viewport, but can only update its viewing rect through a dedicated function available to the adaptors. The adaptors that do use the viewport now all explicitly declare it, with the correct access type (in or inout). Last, we scale the transfer function viewport range automatically from image min and max intensities. Many warnings were fixed along, notably because of the coexistence of float and double variables. The floating point precision was set to double everywhere to comply with Qt API. *Remove irrelevant SCurvedHistogram service, use SHistogram instead.* # sight 21.1.0 ## Refactor: ### build *Apply cmake-linter rules.* ### core *Remove last bits of data reflection based on camp.* Data reflection based on the camp library was definitely removed from _Sight_. It consisted in removing the files used to declare data reflection and all files that used camp. Most usages of data reflection was removed in previous merge requests, like serialisation. However, some last services still used data reflection and were modified accordingly: #### module::ui::qt::model::SModelSeriesList This service displays reconstructions in a tree widget. It used data reflection to display any model series attribute. However practically, it was only used to display the organ names, structures types and volumes. Those three possibilities were hard-coded instead. #### module::ui::qt::series::SViewer `SViewer` shows a preview of data. Normally, it takes input data, but a similar mechanism was in place to allow data extraction like in activities. This was a bit over-designed and practically only used to extract images from image series. The image preview activity was thus modified to extract the image with the new `SGetImage` service. #### module::data::SCopy The most annoying service was `SCopy`. Like `SExtractObj`, it was capable of using a path camp to copy sub-objects. It was used abusively in SightViewer, probably to avoid deferred objects. This was bad since model series and images are present multiple times in memory. Nevertheless, this could not be changed easily. Two new services needed to be written. - `module`::data::SGetVector`:`very similar to `SGetSeries`, it allows to extract elements of a `sight::data::Vector`. - `module`::ui::qt::series::SSelectDialog`:`the intent of this service is to pop-up a dialog to let the user pick a series. Indeed in SightViewer, we may load several series, but only the first one is displayed. So for instance, if we read a CT-scan with 3 different blood times, we can only display the first one. This service also resolves the problem of the type of output. It allows to output the result to different objects according to their type: image or model. With the constraint of time for the incoming release, this service is proposed in the state of a draft. It does not prompt the dialog yet, instead, it takes the first element. This allows at least to keep the same level of functionality in SightViewer. It will be finalized in Sight 22.0 *Remove oldish SPushObject and SPushField, rename SObjFromSlot.* We are very close to finish the rework we started years ago about clarifying object selection services. - `SPushObject` and `SPushField` were outdated, and can be replaced easily by the `SManage` service. So we simply removed them. - `SObjFromSlot` does not have a meaningful name. It is renamed as `SSelectObject` and no longer inherits from the also meaningless `IUpdaterSrv` interface, but rather from `IController`. *Simplify workers management.* Firstly, this was an intent to add a function to unregister workers, but in the end, this is a complete rework simplification of the `ActiveWorkers` registry. Here is a summary of the changes. No longer exposes the ActiveWorkers registry publicly. The only interest would be to have multiple registries... Mmm really? I don't think that's useful. So then if there is only one registry, as a user, I don't care that this is a singleton, I even don't care there is a registry at all. I just want to add and remove workers, right? Now, people are supposed to add and remove the workers themselves. There is no more "global" cleaning method (formerly `cleanRegistry()` ). Symmetry for the win. The initialisation phase has changed, which is somehow a breaking and important change. **So please read the following carefully**. Formerly, no default worker is created by default. It was created either by calling `initRegistry()` (instantiating a `workerAsio` or by calling `setDefaultWorker` (in concrete use cases, either a `workerAsio` or a `workerQt`). In most apps (all Qt apps of course), services, and unit tests, a worker was created. But in rare cases, no worker was set, which implies async functions such as `IService::start()`, `IService::stop()`, etc... were in fact executed synchronously. With this MR, a `workerAsio` is created at the start and set as the default worker. If someones (actually only Qt Apps) want to set a different worker (the `WorkerQt`), it can call `setDefaultWorker()` and the default worker will thus be changed. The initial worker will be removed, but the function will raise an exception to avoid early slots registration with this worker. In clear, `setDefaultWorker()` is intended to be called at the very beginning of an application and only once. Even clearer, this is going to be called only once by the main Qt and Qml plugins. So actually, no one bothers, whereas before, everyone writing a unit-test or an executable app would have to think about it and call it. Last a `resetDefaultWorker()` had to be implemented, just because QApp doesn't like to be destroyed during static variables cleaning, after the main exits. So this `resetDefaultWorker()` is actually called twice symmetrically with `setDefaultWorker()` in the main Qt and Qml plugins. *Merge fieldHelper into helper/MedicalImage.* * all functions are now static and class is replaced by namespace MedicalImage * unused functions was removed * unit test of MedicalImage was improved to test all helpers methods * Update services to use only integer values instead of pointers for slice indexes *Rename all getNumberOf*() functions to num*().* *Clean old deprecated array API.* *Clean old deprecated image API.* *Modernize mesh API.* ### io *Remove module::io::atoms and replace it by module::io::session counterpart.* All of module`::io::atoms`has been removed and replaced by module`::io::session`counterpart. `Patch` and `Filter` features of atoms have also been removed. io`::session`has been upgraded to support simple JSON on filesystem serialization. Additionally, a new preference system, using Boost property tree, has been implemented: # Preference The class is thread safe and use RAII mechanism to load and store data from and to the preference file. In a service, the basic usage would be: ``` c++ try { // Load Preferences preferences; std`::string`filename = preferences.get("debug.filename"); int level = preferences.get("debug.level"); ... // Save Preferences preferences; preferences.put("debug.filename", "log.txt"); preferences.put("debug.level", 2); } catch(const ui::base::PreferencesDisabled&) { // Nothing to do.. } ``` Which will be translated into: ``` json debug: filename: "log.txt" level: 2 ``` ## Configuration The configuration is done by static functions: - set_enabled: Enable or disable preference management as a whoole. All functions, including constructor will throw `PreferencesDisabled` exception if used while "disabled" - set_password: Set an harcoded password to be used. It enables defacto the encryption - set_password_policy: Defines how and when a password is asked. @see sight`::core::crypto::PasswordKeeper::PasswordPolicy`for possible values. > `NEVER` will never display any message box, but if a password has been set, the resulting preference file will still be encrypted. An `BadPassword` exception will be thrown instead of diplaying a message box, asking to renter the password. - set_encryption_policy: Define when the preferences file is encrypted: @see sight`::core::crypto::PasswordKeeper::EncryptionPolicy`for possible values. > `FORCE` will encrypt the file, even if no password is given. In this case a pseudo random password is used, which can be guessed if someone has access to the code. Another option is to use an harcoded password AND EncryptionPolicy::SALTED - Module Configuration: All the above can be configured through the module ui_base parameters (@see sight::module::ui::base::Plugin) The preferences are enabled by default, without encryption. An example of configuration would be: ``` cmake moduleParam( module_ui_base PARAM_LIST preferences_enabled preferences_password_policy preferences_encryption_policy preferences_password PARAM_VALUES true once salted a_bad_hardcoded_password ) ``` # Simple JSON serialization on filesystem It is now possible to use `SReader` and `SWriter` to serialize a data object into a single JSON file (until the serializer class also store additional files like for Mesh or Image object). ## SReader This is achieved withe the `archive` configuration node and its `format` attribute: - `filesystem`: Reads files from the filesystem. - `archive`: Reads files from an session archive. - `default`: uses the builtin default behavior which is `archive` ### XML sample configuration: ```xml ``` ## SWriter This is achieved withe the `archive` configuration node and its `format` attribute: - `filesystem`: Use the filesystem to store files. - `compatible`: Store files in a ZIP archive, with old deflate algorithm - `optimized`: Store files in a ZIP archive, with zstd algorithm - `default`: uses the builtin default behavior which is "optimized" ### XML sample configuration: ```xml ``` ### ui *Remove obsolete SSlider, superseded by SParameters.* ## Bug fixes: ### build *Fix application package.* * CMake configuration has been modified to ensure that sightlog binaries are always shipped with Sight, even when building a standalone application. * Ogre plugins install was not done because of a regression introduced when fixing Qml plugins install. * use the .bat instead of .exe to launch app in .lnk *Add tighter security in get_default_password access.* Add if def security around the get_default_password Export the SIGHT_DEFAULT_PASSWORD var from sight *Improve application version in package name.* *Allow to link with io_igtl from a child project.* *Prevent whole rebuild each time with CMake >= 3.20.* This was caused by the new CMake policy CMP0116 about the usage of the DEPFILE argument of add_custom_command. Since we did not succeed to use the NEW behavior yet, we switch back, temporarily, to the OLD behavior. *Qml applications on Windows.* Several fixes were brought to fix sight applications using qml on Windows: - determine qml plugin path at runtime instead of build time. We use the same strategy for Qt plugins. - install qml plugins correctly when building an installer - port deprecated QtQuick1 stuff to QtQuick2 *Enable warning as errors on sight_core.* Warnings as errors were enabled but sight_core, but this library first builds an object library. The flags were not passed to it. This has been fixed and some warnings were fixed as well. ### ci *Fix sheldon license date check.* - only build on Ubuntu 21.10 - fix code coverage html/xml report generation ### core *Replace assertion when slice index field doesn't exists.* `getSliceIndex` returns a std`::optional`that needs to be tested to know if field is present or not. *Object registration is overriden by XML configuration.* Previously, there was no data prerequisite in a service. One can declare any data in the XML configuration of a service, and use it at runtime with getters. So basically you could configure a service with any data. It was even possible to change the access type dynamically. Sight 21.0 enforced a prior declaration of data with `sight::data::ptr`. They allow specifying the key name, access type, as well as the auto-connect and the optional attributes. Normally, only declared data this way should be used in services. However, for back compatibility purposes (especially for the very specific `SConfigController` and `SConfigLauncher` services), it is still possible to register data just from the XML configuration. We discovered that this is actually buggy and the XML configuration overrides the `sight`::data::ptr``declaration. So it is for instance possible to declare input data and finally configure it as an inout. We also realized that the default auto-connect and optional attributes values were not respected with an XML configuration. The actual default values were those of the XML parser. This merge request first fixes the override of the data declaration with the XML configuration. It also fixes the XML parser to use the default auto-connect and optional attributes values declared in each service type. This required some extra work on group objects. Indeed, we used to have a minimum and a maximum number of objects. These were actually not really used, and developers misused this feature most of the time. They configured `sight`::data::ptr_vector``with the same signature as `sight`::data::ptr``which led to implicitly converting a true boolean meaning "optional data", in an integer meaning "at least one object". Thus the intent of the developer was actually the opposite of the actual result. The maximum number of objects was never used in real cases and was in fact introduced to solve an internal issue with non-XML apps. This was not a real need for the developer. In the end, `sight`::data::ptr_vector``now shares the same signature than `sight::data::ptr`. It is still possible to configure in the XML the auto-connect and optional on each member of the group, but this time the default value will be the one declared in the `sight`::data::ptr_vector``declaration. Last, fixing all of this highlighted some misconfiguration in a few services. These were corrected accordingly. *Update old "3DSimpleConfig2" by "3DSimpleConfig".* * ExDicomSegmentation & ExDump impacted *Remove dead lock and init mesh celltype properly.* *Attributes arrays not reallocatted on pushPoint and pushCell.* *Load of dynamic libraries when only versioned files are present.* On a regular Linux system, libraries are installed with the version in the extension, like libsight_core.so.21.0. The symlink without the version in the extension is only present if the development package is installed. Thus we can not rely on this symlink to load the library like we did since Sight 21.0. This commit switches back to the old way, looking for a file name that matches the library name. A cache has been added to avoid the cost of iterating over all library files each time. *Correct needle calibration.* Correct point pivot based nbeedle calibration algorithm fix header to allow include in external project misc: update coding style *Optimize data::iterator::ImageIterator.* *Check if service UID is used in signal/slot before collecting UID for parameter replace.* * parse also menuItem sid="..." attribute before collecting UID for replacements *Remove useless return after throwing exception.* *Use sight_core module path to determine the runtime dir.* *Speed-up image copy in SFrameMatrixSynchronizer.* The image copy using the image iterator is slow as hell in debug, making some applications unusable. This was replaced by a simple std::memcpy. *Add sight namespace to profiling macros.* ### doc *Update README to match Sight 21.0 changes.* ### geometry *Workarround to get rid of bufferObject assert still locked.* Force destruction of original buffer object of output image after the unlock of input & output image, doing this avoid the assert of bufferObject still locked. *Don't shift 2d points on when computing RMSE on calibration.* * Add option in SSolvePnP to shift points or not (default off) * Replace quad mesh plane.vtk by triangular mesh plane.vtp ### io *Replace deprecated OFIterator in favor of OFListIterator.* This deprecated container is removed in recent dcmtk versions. *Remove deprecated VTK types.* These types were deprecated and unused a long time ago. They are removed in latest VTK releases. *Extension() getter function in reader/writer made const.* ### test *Fix ui_qt_test not executing offscreen.* ### ui *Reduce lock scope to avoid a deadlock.* *Remove all deprecated QSignalMapper.* ### viz *Do not snap landmark onto slice plane in 2D negatoscopes.* Landmarks can now be moved properly as before with drag & drop. An extra correction was made to not snap the landmark onto the image plane in the 2D negatoscope views. This led to weird behavior when you adjust the position of the landmarks in two different orthogonal views. The landmark always snaps to the image plane, thus giving the effect of "jumping" in the other view, and preventing from adjusting the position finely. *Replace getTransformNode by a pure getter.* `getTransformNode` was ambiguous since it return the transform node if existing or creates it if it doesn't. This behaviour is kept but function was rennamed into `getOrCreateTransformNode`. A pure getter was also created `getTransformNode()` to return the transform node pointer or nullptr if it doesn't exists. Add small unit test to test ITransformable functions All adaptors was updated to call either `getOrCreateTransformNode` or `getTransformNode` regarding the case (creation of the node of getting the pointer). This fixes the crash due to Ogre exception "Node already exists" when trying to get a deleted node. *Move orientation marker when splitting views.* The orientation marker in the 3D view of SightViewer remained on the bottom right corner of the view when splitting views. Now it keeps attached to the 3D view. *Remove extra space in R2VB program preprocessor definitions.* Remove extra space in R2VB program preprocessor definitions. Sadly, this prevented the preprocessor defines of the R2VB geometry programs to be parsed properly, thus causing rendering issues. *Crash in Ogre resources loading.* The list containing the Ogre resources paths was not allocated properly. *Set texture unit state after changing a material template.* ## Enhancement: ### build *Update vcpkg pakage hashes to match last build.* *Add some flags for better performance and debugging.* *Default to warnings as errors.* *Forbid link with a module.* ### ci *Make the code coverage percentage more precise.* *Use shared scripts to deploy, add SightCalibrator deployment.* *Remove Ubuntu 20.10 Release target, replace it with Ubuntu 21.04 Debug.* ### core *Remove redundant internal lock in the Timeline object.* We removed internal locks in timeline functions. Now, we assume that all timeline objects are accessed by a lock() in the caller. *Return const pointer when using getters on const data.* Many getters in data returns shared_pointer, even if the data was const the returned pointer wasn't and underlying data was still modifiable. This has been changed to provide const getters that returns const pointer, and non const getter to returns simple shared_pointer. Doing so leads to some changes in part of the code that uses const data (usualy input data) * Use of const_cast as been restricted to 3 cases: * When moving buffer to ITK or VTK * SReconstruction when moving the pointer to data`::Material`to an internal SMesh adaptor. * SGetImage, since ImageSeries input is const, when doing a setOutput (non const) with series->getImage, a const_cast is needed to discard const qualifier. * Changing from inout to input access: * SMesh: mesh is now a const input. * Use const shared_pointer when possible *Simplify image fields initialisation, remove unused fields.* - `MedicalImageSrv` was simply removed. - Instead, `data::helper::MedicalImage::check*()` functions are called when reading or creating an image. An image is "always" a medical image, but this does not hurt to have extra fields for non-medical images. - `checkLandmarks()` was removed, the point list is now always present. - The following used fields were removed: slices count, comment, label. *Make dispalyCalibrationInfo more scalable.* *Remove obsolete atoms lib.* ### io *Move csv reader from io::dicom to io::base.* ### ui *Enable HiDPI scaling on Qt apps.* *Move notification stack up/down when oldest notification is closed.* *Add option to "read more..." when notification message exceeds maximum allowed characters.* *Upgrade default confirmation message on action.* *Add fullpath option for camera selection in Scamera.* style: apply sheldon style: apply review suggestion style: correct variable name style: apply coding style style: apply coding style style: correct comment ### viz *Make viz::scene3d::vr great again.* #### Description `viz::scene3D`::vr``has many feature that either don't work as intended or do not work at all. This is mainly due to bad service-library interactions and subtle bugs / flaws in some methods. Because of that, using this namespace as a base for subclasses requires substantial efforts to workaround those bugs / design problems. #### Changes ##### Library **Volume renderer:** - `IVolumeRenderer`::update``has been introduced to solve the problem of the initial issue (calls to virtual function from constructor). This member is `public` and `virtual`, and `override`n in `RayTracingVolumeRenderer`. - Shader source file is now specified upon construction. - As `RayTracingVolumeRenderer`::initEntryPoints``must only be called once, there is now a check it has not been called before. - New `struct`s wrapping attributes. - `createRayTracingMaterial` is now `updateRayTracingMaterial`, and does not take any parameter. - Some functions were renamed to something explaining what they actually do. - Some integer values are now `unsigned` in order to ease some asserts. **Volume rendering techniques:** - RAM leaks and follow the changes in the volume renderer (types). **Data management:** - Before this MR, the image resources was managed by **both** the service and the library. This is not the case anymore. The service now knows *almost* nothing about the data. Consequently, what was `weak_ptr` previously in the library are now `shared_ptr` or even `unique_ptr`. - The following are now set upon construction: - Raytracing fragment shader source file, - Ambient occlusion parameters, - Preintegration parameters, - Shadows parameters, - SAT parameters, - There used to be duplicated attributes in the service and the library, which represented the same flags but where not updated simultaneously. This is not the case anymore. Actually, this was the main cause of - #756, #791 and #792). ##### Module - Reported changes in the library (argument type changes, etc.) - New `struct`s wrapping attributes (config, etc.). *Improve flat shading by using fragment shader computed normals.* Flat shading may often be broken if point normals are shared between faces. To overcome this, we chose to compute normals in the fragment shader using eye position derivatives. Doing so, the outdated and never used Gouraud shading mode was removed. This removes a shader combination, which makes maintenance easier. ## New features: ### build *Forbid module linking, even for tests.* - Add a special verification step to forbid linking with a module. - Rename `fw_cppunit_test` to `fw_test`. *Allow privilege escalation on Windows.* *Allow to override the downloading of dependencies.* *Debian package build prevents networking access.* ### ci *Enable unit-tests report.* To output unit-tests results in JUnit format will allow us to see the results of the unit-tests in the GitLab web interface. *Attach gdb to running test to have a core file.* *Add code coverage to unit tests and Ubuntu 21.10 support in CI.* ### core *Remove sub-object extraction from activities.* Now, when defining a requirement in an activity, there is no need to define a corresponding `AppConfig` parameter to "replace" it with the corresponding key. In short, the same key is used for the requirement and the parameter, and there is no need to give a complicated object "path": - Before: ```xml ... ``` - After: ```xml ... ``` ##### Limitation However, this simplification implies some limitations: 1. The key must match for both requirement and `AppConfig` parameter. There is no way to "replace" them on the fly like before. We really believe this is fine as the ability to have a different name only complicate both xml (you need to specify the "mapping") and C++ code, with no real added value. 2. As we can only access to the "required" object, we cannot "walk" through the object hierarchy and extract sub-objects. For example, it is no more possible to have an `Image` as `AppConfig` parameter which is extracted from a required `ImageSeries`. This can be easily adapted with the use of the new extraction services (`SGetImage`, `SGetMesh`, ...) in `AppConfig` code. *New service sight::module::data::SGetCamera.* This new service extracts cameras and extrinsic matrices from a camera series. *New service sight::module::data::SGetSeries.* This service can be used to extract one or several series from a seriesDB. The XML configuration is fairly simple: ```xml ``` where: - seriesDB is a `sight::data::SeriesDB` - series group data are `sight::data::Series` *Remove core::data::ObjectLock.* - remove core`::data::ObjectLock`call and use straight locked_ptr in place. - rename all "dump" lock() (lock(), bufferLock(), lock_buffer(), ...) to dump_lock() to avoid confusion with "mutex" locks. - factorize dump_lock() call in IBuffered.hpp. - remove one deprecated TimeLine construct. *Implement SGetImage Service.* *Add == operators for all data object.* #### Description Now a data object of the same type can be compared using == like: ```c++ std::shared_ptr image1 = ...; std::shared_ptr image2 = ...; if(*image1 == *image2) { ... } ``` Floating point values are compared using a scaled epsilon (which gives result similar to [ULP](https://en.wikipedia.org/wiki/Unit_in_the_last_place) comparison). NaN, infinite values are also taken into account. Templated helpers `core::tools::is_equal()` have been added to ease comparison with containers, pointers and floating point values. *Encrypted log.* #### Description Our logging system is based on [boost::log](https://www.boost.org/doc/libs/1_77_0/libs/log/doc/html/index.html), which works fine, but doesn't provide a way to secure the content of the log file. We choose to use [minizip-ng](https://github.com/zlib-ng/minizip-ng) with built-in AES encryption as the backend to store the log and continue to use boost log as the frontend. We have also improved password management, to allow encryption to be used even without providing a password. The minizip backend runs in a separate and detached child process, so it will always produce a valid zip archive even if the parent process crashes. #### Additions / Changes ##### CMake - Enable log encryption support with new CMake build options: `SIGHT_ENABLE_ENCRYPTED_LOG` (OFF by default) - Allow to specify a default hardcoded (but obfuscated) password at compile time, set by `SIGHT_DEFAULT_PASSWORD` CMake definition. ##### Password management Password management has been reworked a bit to factorize and unify behaviors. ###### `SIGHT_DEFAULT_PASSWORD` It will be used when required (log encryption, preferences, session, ..) by default, until overwritten by user when an input dialog asking the user for a password is shown. It allows to use encryption, without having to ask user for a password. BTW, this is **less** secure, as the password is still hardcoded, even if obfuscated in the binary. ###### User password An input dialog asking for a password will be shown when: - the log is encrypted and no `SIGHT_DEFAULT_PASSWORD` is set **or** if `sightrun` is launched with `--ask-password` argument. - for preferences, if the appropriate `password` and `encryption` `policy` is set in module `ui_base` configuration (take a look at `libs/ui/base/Preferences.hpp`). - for session files, if the appropriate `password` and `encryption` `policy` is set in SReader and SWriter service configuration (take a look at `modules/io/session/SReader.hpp` and `modules/io/session/SWriter.hpp`). In all case, the entered password will be kept (obfuscated) in memory, allowing to only ask the password once, until, of course, it is explicitly configured to not do so. ### Sightlog logger (utils/sightlog/src/sightlog.cpp) It is a simple standalone application that read stuff from standard input and write them in a [minizip-ng](https://github.com/zlib-ng/minizip-ng) archive or a raw log file. Alternatively, it can also decrypt the real log from a log archive, which can be useful if a human need to read it back. The logger is started as a standalone detached child process by `Sight` which ensure the integrity of the log archive, even if `Sight` crashes. If `SIGHT_DEFAULT_PASSWORD` password has been used, it is also embedded inside `sightlog` binary, and it should not be necessary to use `-p` option. ###### sightlog usage ``` Sightlog logger options: -h [ --help ] Display this help message. -v [ --version ] Display the version of the program. -i [ --input ] arg Log archive to extract. -p [ --password ] arg Password to use for encryption and decryption. -a [ --ask-password ] Show a popup to enter the password. -d [ --directory ] arg Output directory when extracting a log archive. ``` For example to extract the log file from archive `/home/bozo/sight/bin/sight.log.0.zip` protected with password `w34r3th3B3st` in directory /home/bozo/logs and we can use: ```bash ./sightlog -i /home/bozo/sight/bin/sight.log.0.zip -d /home/bozo/logs -p "w34r3th3B3st" ``` ##### String "obfuscator" (libs/core/core/crypto/obfuscated_string.hpp) Allows to define a string literal that will not appears in "clear" text in the final binary. Useful for defining an "hardcoded" password, without being to simple to find and read. This is of course not as secure as a real password entered by a real user. ##### SpyLogger class - Doxygen comments.. - New method `start_logger()` and `start_encrypted_logger` which starts `sightlog` child process. - New unit tests `EncryptedLogTest` - The file paths in the log file are now trimmed again to not show the full path, but the minimal one to be able to locate a source file: (/home/bozo_the_clown/work/src/sight45/.../.../libs/core/core/spyLog.hpp -> libs/core/core/spyLog.hpp) *Add an image parser to allow basic initialisation in xml.* ### io *Allow custom serializers for any object, even when defined outside sight.* ### ui *Delete sequencer data when going backward.* Add an option to remove all the data generated when going backward with the sequencer. ### viz *Update slice indexes when a landmarks is double clicked.* Update SNegato3d & SNegato2d to move slices to the selected landmark. * SLandmarks send world position when double clicked (new signal) * SNegato3d, SNegato2d listens through a slot if slices indexes needs to be updated regarding a world position (new slot). * Conversion between world coordinates and slice index as been implemented in scene3d`::Utils`and a unit test has been added. Update adaptor`::SLandmarks`to handle double clicks on landmarks and also send the current world coordinates of the point *Use the mouse wheel to scroll through slices in the negatoscope.* Before the mouse wheel event was used to zoom in/out the image, it now allows to scroll the slices, like in other software. The Shift key speeds up scrolling. You can still zoom in/out the image with the mouse wheel, but with the Ctrl key pressed. *Add optional name to SAxis adaptor.* # sight 21.0.0 ## Bug fixes: ### build *Use project_name in variable exported by sight_generate_components_list.* Do not export SIGHT_COMPONENTS in sight_generate_components_list cmake function, use instead COMPONENTS. This avoids variable collision when using sight in subprojects, since SIGHT_COMPONENTS is exported by sightConfig.cmake. *Sight-project installation error due to sight version.* To fix the main problem, SOVERSION is no longer defined for executable targets. That simply prevents from creating these useless versioned binaries. On top of that, several other fixes were brought: * the version attribute of the `project()` CMake command is used instead of redefining a custom `SIGHT_VERSION` variable, * code cleaning was done around this, notably to rename `FWPROJECT_NAME` into `SIGHT_TARGET`, which is more correct with the usage of this variable, * dependencies computing now browses `OBJECT` libraries targets, like `io_session_obj` (fixes `Tuto01Basic` packaging for instance where `sight_io_vtk` library was missing), * dependencies computing now handles cross-repositories dependencies (fixes some child projects packaging), * components ordering was included in a higher-level function `sight_generate_component_list()` for a simpler use outside *Sight*. *Tests are relatives to last cmake project call.* * Use `${CMAKE_BINARY_DIR}` instead of `${PROJECT_BINARY_DIR}` to force executable to be produced in ./bin folder. * Also testing if safe-svfb-run isn't already copied in ./bin * early return in CppUnitConfig.cmake if CppUnit is already FOUND. *Configure child projects fails.* To fix the problem, we no longer export PCH targets and we no longer export modules .lib. On top of the initial problem, we also always build `utest`, `utestData`, and `module_utest` instead of only building them when `SIGHT_BUILD_TESTS` is `ON`. Child projects may need them even if unit tests were not built in Sight. *Generate sight component list.* CMake components in SIGHT_COMPONENTS variable are now ordered automatically according to their dependencies. It will ease the burden to manually maintain the list. *Explicit relative path in installted imported target library symlinks.* When we install packages in child repositories, we copy the necessary dependencies from Sight, for instance, the libraries. On Linux, we also need to recreate the library symlinks. This was done with absolute paths, which makes packages not relocatable. This fix just creates relative symlinks instead. *Fix package generation.* This brings back the package generation with CPack. Both Linux and Windows are functional. Sight can be packaged as a whole (similar to the former "SDK mode") in `tar.zst` (Linux) or in `.zip` (Windows). Any application or executable target can be packaged in `tar.zst` (Linux) or in `.exe` installer (Windows). The CI has been updated to always build the Sight and SightViewer packages on both platforms. However, the deployment on [Owncloud](https://owncloud.ircad.fr/index.php/apps/files/?dir=/IRCAD%20-%20Open/Binaries&fileid=894807) is only done on dev and master branch, or on any branch manually. On the dev branch, the package version number is replaced by `-latest`, so that it corresponds to a "latest" build. This prevents us from having to clean our archive folder too frequently since the packages will be erased at each upload. *Readd missing component io_session.* *Add missing component for sight-dependent project configurations.* *Makes the flag WARNING_AS_ERRORS effective.* *Add SMatricesReader export in the plugin.xml.* *Export Qt find_package in ui_qt.* Moves `find_package(Qt5 ...)` to Dependencies.cmake to be exported when using imported target `sight::ui_qt` *Geometry_eigen export.* Export also the `find_package(Eigen3 QUIET REQUIRED)` for the target geometry_eigen. *Move cppunit_main in cmake/build folder.* Fix the build of unit test on external projects. * `cppunit_main.cpp` has been moved from `cmake/cppunit` to `cmake/build` folder. * `FindOpenNI2.cmake `has been removed * `fw*.cmake` files has been removed, contents was added in `cmake/build/macros.cmake` file in order to be retrieved from outside. *Install executable shell scripts.* Install missing templates files for executable target ### ci *Small typo in SightViewer package name.* *Use sed for regex replacement of dev packages.* *Launch unit tests properly on Linux.* The code with `flock` was wrong, and the test was not executed. The initial code was restored, which should be safe. Also, there was another specific bug with `viz_scene3d` test. It crashed after destroying the first `Ogre::Root`. Indeed we chose to create and destroy it after each test. This problem is thus independent of the display number of `xvfb-run` since it does succeed to create an OpenGL context once but somehow fails to create a second. We assumed `xvfb-run` might be buggy regarding this initialization code. As a workaround, we create and destroy the `Ogre`::Root``only once thanks to a new module `sight::module::viz::scene3d::test`. Last, several tests in serviceTest were fixed. ### core *Broken library path on external projects when using '.local' in installation paths.* The deduction of the library path failed when share was already present in the main module path. The problem already occurred with module paths themselves, so the regex is now shared between these two places. *Tuto01DataServiceBasicCpp launch.* The source image loaded at start in Tuto01DataServiceBasicCpp was changed with the one used in Tuto02DataServiceBasic. This fixes the launch of this tutorial. *Add case to replace uids for slide views.* When launching a config, we substitute all `by` attributes with uids. We missed a case to handle slide views when attaching a widget. *Add an extra LD_LIBRARY_PATH for intermediate sight projects.* This fixes the inclusion of more than 2 sight projects. *Fix XML configuration parsing (#3).* Fix the parsing of objects containing sub-object (like Composite) or values (like String). Also fix the parsing of service with an external configuration ("config" tag in the XML service definition). *Make material resource file handling project independent.* Make `resources.cfg` path treatment independent of the working dir. Indeed, the present behavior uses the working dir for the absolute path generation. However, as this is done inside sight code, the prefix corresponds to the sight install path, and not the loading module-specific path. As a result, files that are not installed in the sight install dir can not be loaded. It is safer to rely on the module name, and get its specific path. *ExActivities fails to launch.* This fixes the parsing of a service configuration when a config extension was used (`config=` attribute). *Harmonize autoConnect booleans config parsing.* This merge requests changes all: - `autoConnect="yes|no"` into `autoConnect="true|false"` - `optional="yes|no"` into `optional="true|false"` *FwServicesTest randomly fails.* The last failing test was keyGroupTest. The problem was actually quite simple, the autoconnection with a swapped object is done after the swap. Thus, we have to wait for the object to finish the swap sequence before sending a modified signal from the data. Before we waited for the object to be present in the object map, but this is not sufficient since this only tells the object is registered, and the registration occurs before the swap. *Restore MSVC build.* Windows support is back! Third-part libraries are now built with vcpkg instead of Conan. We found out that vcpkg packages are much more stable and most of all, coherency is ensured between packages. Few fixes were brought to support the newest version of these libraries. Indeed they are often more recent than Ubuntu packages. Doing this, the GitLab CI/CD scripts were updated to use Powershell instead of cmd, as recommended by GitLab. *Remove TransferFunctionManagerWindow include from sightViewer plugin.xml.* *Several runtime errors after sight 21.0 upgrade.* ### doc *Rewriting doc of CardinalLayoutManagerBase.* ### io *DicomXplorer crashes when display mesh preview.* This MR fixes a crash upon selecting mesh in `dicomXplorer`. The problem was simply that old configurations used in this software were deleted. **It does not display the mesh in an activity.** It simply fixes the crash and re-enables the preview. *VTK readers doesn't handle color array properly.* When converting from vtk to sight mesh format, we check if color array named "Colors" exists in polydata in order to copy vertex or cells colors. When using PLY reader from VTK (maybe other format too) color array is named "RGB" or "RGBA". We also added a workaround to fix color rendering of first cell on Ogre 3d. Otherwise, mesh can appear black at first render. *Igtl client is not thread safe.* Make io_igtl`::Client`thread safe at connect / disconnect. OpenIgtLink socket class isn't thread safe at connection due to internal function calls (details in #736). *Dicom readers does not have the good scale along the z axis.* *Tuto02DataServiceBasic cannot load sample data.* Tuto02DataServiceBasic loads an image at start, but path to the image was hard-coded (`../../data/patient1.vtk`). A sample image was provided in the resource folder to the tutorial and loaded at startup. *Jpeg Writer (ITK) causes the application to crash upon usage.* ITK jpeg image writer has been replaced by vtk image writer service when saving snapshots in sightviewer. In addition, the image number of component in the vtk image writer service has been updated, as well as the lock systems. *Remove VTK warnings when reading meshes.* Redirect VTK messages (warnings/errors) in a VTK.log file. *Activities saving failed.* Saving activities was blocked due to extra "::" in the plugin.xml of ioActivity. *Add some Dependencies.cmake.* To build our current projects with sight 21.0, we needed to add missing `Dependencies.cmake` files, otherwise people would have to find the necessary `find_package`commands to run first. Besides this, an unrelated change has been made to reenable the load of extra bundle paths. This is needed when you depend on more than two repositories. ### test *ServiceTest randomly fails.* This fixes two tests in the `serviceTest` suite. Basically, it is just about waiting for the correct condition before testing the result. ### ui *Preferences path is broken.* The application name in the preferences file path is deduced from the profile name attribute. During the generation, this property was not generated properly. This fixes it. *Floating buttons are frozen when moving underlying main window.* ### viz *Dialog deadlock with 'always' render mode and GTK.* This removes the 'always' render mode in `viz::scene3d::SRender`, which is useless and may cause deadlocks with pop-up dialogs. *Default SRender transparency mode is broken.* Set the default transparency to `HybridTransparency`. (SightViewer's transparency has been set to default instead of `DepthPeeling`) *Cropbox reset freezes SightViewer.* We avoid a deadlock in `SVolumeRender::updateClippingBox()` by unlocking the clipping matrix data before calling the interaction callback. *SightViewer crashes at start.* In `SVideo`, the SceneManager was used to get the viewport. The correct way to retrieve is to get it through the layer. ## New features: ### build *Ubuntu 21.04 support.* ### core *Implement SessionWriter and SessionReader and many other things.* This is the foundation of the new serialization mechanism. ### New "crypto" package in `libs/core/crypto` * `secure_string`: a std`::basic_string`implementation with a custom `secure` allocator which erase used memory on de-allocation. This class is mostly used to store sensitive data like password. * `SHA256`: computes SHA256 cryptographic hashes * `Base64`: encode/decode to/from base64 strings * `AES256`: encrypt/decrypt to/from strings using AES with 256 bits key. * Unit tests in `libs/core/core/test/api/crypto/CryptoTest.xxx` ### New `ArchiveReader` and `ArchiveWriter` classes in `libs/io/zip` * Fixed some nasty bugs on ressource deallocation with WriteZipArchive / ReadZipArchive: Handle from files opened inside archive were not closed * Implements some thread safety measures: Due to minizip implementation, to avoid strange corruption problems, an archive could only be opened either in `read` or in `write` mode. In the same way, only one file in a archive should be opened at once. With old classes, no restrictions was applied, Yolo mode by default. * Allows to specify, as the zip format allows us to do, one compression method, one compression level, and one encryption key by file. This let us, for example, adapt the compression level, when the stored file is already strongly compressed, like for a mp4 file. * Use RAII mechanism to close file handle inside archive, global zip handle, etc. It means that opening the same archive, the same file inside an archive in the same scope, or even simply when the ostream/istream is alive, will dead lock (it's a feature, not a bug...) * Unit tests in `libs/io/zip/test/tu/ArchiveTest.xxx` ### Refactor UUID Not planned, but since `core::tools::Object::getUUID()` was not `const`, it requires some attention. Basically, only the generator has been kept in `core`::tools::UUID``and all code went in `core::tools::Object`. * Removed double mutex, strange double indirection, etc.. while retaining most of the feature (especially the `lazy` getter/generator, which a really doubt it is useful, but I did not Benchmarked it, so I decided to keep it) * `core::tools::Object::getUUID()` is now const at the operation doesn't modify external and even internal class state. * Unit tests in `libs/core/core/test/api/tools/UUIDTest.xxx` ### Implementation of SessionWriter, SessionReader, ... All in `libs/io/session` #### New `PasswordKeeper` password management system Designed to hold passwords, in the case you don't want the user to retype every 3 seconds its password. * Replace the less secure and more `handcrafted` solution in `libs/ui/base/preferences/helper.xxx` * Store the password in an AES256 encrypted `secure_string`. The key is computed in a deterministic way (no surprise), but should not be so easy to guess. Once the password is no more needed, or when the application quit, it will be erased from memory. * Allows to store a "global" password along several "instance" passwords. * `libs/ui/base/preferences/helper.xxx` has been a bit refactored to use the new `PasswordKeeper` * No need to say, a password should never be serialized on disk or in a database. Use only password hash for that. * Unit tests in `libs/io/session/test/tu/PasswordKeeperTest.xxx` #### New `SessionWriter` It's an implementation of a base::reader::IObjectWriter. It's purpose is to be used in a service to "write" an object to a session archive. It is the public API interface for writing a session archive. Basic usage would be something like: ```cpp auto sessionWriter = io::session::SessionWriter::New(); sessionWriter->setObject(myActivitySeries); sessionWriter->setFile("session.zip"); sessionWriter->setPassword("123") sessionWriter->write(); ``` #### New `SessionReader` It's an implementation of a base::reader::IObjectReader. It's purpose is to be used in a service to "read" an object from a session archive. It is the public API interface for reading a session archive. Basic usage would be something like: ```cpp auto sessionReader = io::session::SessionReader::New(); sessionReader->setFile("session.zip"); sessionReader->setPassword("123") sessionWriter->read(); auto myActivitySeries = sessionReader->getObject(); ``` > You may have noticed the slight change in classical `IObjectReader` API usage. It is no more needed to guess, before reading, the type of object to deserialize. Instead of "setting" and empty object, we simply "get" it back, once the "read" done #### New `SessionSerializer` This class contains the the main serialization algorithm. It also contains a specialized serializer (one for each kind of data object) registry, so it can delegate specific serialization tasks. The serialization is done on two medium: one boost ptree and, for big binary file, directly into the archive. The final ptree will also be stored in the archive as the index.json. The algorithm is really straightforward, not to say "basic": 1. Extract the UUID of the input object and the class name. 1. With the UUID, look into an object cache. If the object is already serialized, put a reference on the current ptree node, and stop. 1. With the classname, find a suitable serializer and call it. The specific serializer will update the current ptree node and maybe store binary file to the archive. 1. The serializer from step (3) will eventually return also a list of "children" object (this is the case for composite objects). Recall recursively the step (1) on them. 1. If the object contains `fields`, recall recursively the step (1) on them. > this MR text will be my base for README.md which I will write once everything are reviewed. Don't panic if you don't see it now, a new MR will be issued later. #### New `SessionDeserializer` This class is the counterpart of `SessionSerializer`. Instead of a specialized serializer registry, we have a specialized deserializer registry. The algorithm is a bit more complex, but still straightforward: 1. Extract the UUID and the class name of the current object stored in the ptree index. 1. With the UUID, look into an object cache. If the object is already deserialized return it, and stop. 1. With the UUID, look into the global UUID object registry. Use it to avoid unneeded object instantiation. It also allow us to safely deserialize children which have direct reference on parent objects. 1. With the classname, find a suitable deserializer. 1. First, deserialize the child objects by recalling recursively the step (1) on them. 1. Deserialize current object, passing the deserialized child objects from step (5) 1. If the object contains `fields`, recall recursively the step (1) on them. #### Specific object serializer/deserializer For now, only a very small subset is implemented. This subset should however cover most cases encountered while writing a serializer for a new kind of data object: * ActivitySeries\[De\]serializer: * Demonstrate how to serialize object with a child `Composite` reference and how to use another serializer to mange inheritance (with `Series`). * Composite\[De\]serializer * Equipment\[De\]serializer * Generic\[De\]serializer: * Demonstrate how to serialize "generic" object (Integer, Float, Boolean,String) * Mesh\[De\]serializer * Demonstrate how to serialize big binary data to archive * Patient\[De\]serializer * Demonstrate how to encrypt sensitive data, regardless of the encryption status of the archive * Series\[De\]serializer * String\[De\]serializer * This serialize String to and from Base64. Since boost ptree have serious flaws with strings with special characters in it, encoding to base64 is a suitable workaround, but still a bit overkill.. * Study\[De\]serializer #### Unit tests all in `libs/io/session/test/tu/SessionTest.hpp` *Promotes code from internal to open-source.* * Create `SRecurrentSignal` service in modules/ui/base/com. This service emits a signal at a defined frequency. * Create `Mesh` lib in libs/geometry/vtk and the corresponding unit test. This library computes the center of mass of a mesh using vtk. ### graphics *Add a material transparency editor.* A new service `SMaterialOpacityEditor` was added, which allows tweaking the opacity of a `sight`::data::Mesh``via `sight`::data::Material``with a slider. *Quad mesh integration in fwRenderQt3D.* ### io *Drop in replacement for SReader and SWriter to serialize an application session.* ### Main feature Two services `sight`::module::io::session::SReader``and `sight`::module::io::session::SWriter``were implemented. They read/write a root data object from/to a session file on a filesystem. The session file is indeed a standard "ZIP" archive, while the compression algorithm for files inside the session archive is ZSTD. A standard archive reader could open a session file, if it is able to handle ZIP archive with ZSTD compression. The archive can be password protected using AES256 algorithm and the compression level is set individually, depending of the type of data to serialize. The service configuration includes specifying the file extension and the password policy for encryption. Configuration example: ```xml ``` The dialog policy specifies when the open dialog is shown: * **never**: never show the open dialog * **once**: show only once, store the location as long as the service is started * **always**: always show the location dialog * **default**: default behavior, which is "always" The password policy defines if we should protect the session file using a password and when to ask for it: * **never**: a password will never be asked and the session file will never be encrypted. * **once**: a password will be asked only once and stored in the memory for subsequent uses. The session file will be encrypted. * **always**: a password will always be asked. The session file will be encrypted. * **default**: uses the builtin default behavior which is "never". The encryption policy defines if we uses the password as is or with salt. It can also be used to encrypt without password: * **password**: Use the given password for encryption. * **salted**: Use the given password with salt for encryption. * **forced**: Force encryption with a pseudo random hidden password (if no password are provided). * **default**: uses the builtin default behavior which is "password". ### General improvement: * `ExActivities` has been modified to use the new session services instead of atoms * new `TemporaryFile` class in `core::tools::System` that uses RAII to delete the associated file as soon as the `TemporaryFile` class is destroyed. * `core::tools::System::RobustRename()` now have an optional parameter to force renaming, even if the target already exists (it will be first deleted) * `ui::base::Cursor` improvement: `BusyCursor`, `WaitCursor`, `CrossCursor` classes that use RAII to restore back "default" cursor, even if an exception occurs * `ui`::xxx::dialog::InputDialog``improvement: add a "bullet" mode for password field. * `ui`::xxx::dialog::MessageDialog``improvement: add a "retry" button. *Serialize most objects.* The serialization is done through two classes: SessionSerializer, SessionsDeserializer, and many .hpp with two functions: `serialize()` and `deserialize`, depending of the type of data object to serialize. For example, the serializers for meshes and images are coded respectively in `Mesh.hpp` and `Image.hpp`. They are good samples to demonstrate how it is possible to use a well known format to serialize objects. The Sight images / meshes are converted into VTK format using Sight helpers and are then saved with the now "standard" VTK way using `vtkXMLImageDataWriter` for image and `vtkXMLPolyDataWriter` for meshes. As a side notes, since the files are stored in a zstd compressed zip file, and since VTK doesn't provide any way to use an output streams, the VTK writers are configured as such (image and mesh are equivalent): ```cpp vtkWriter->SetCompressorTypeToNone(); vtkWriter->SetDataModeToBinary(); vtkWriter->WriteToOutputStringOn(); vtkWriter->SetInputData(vtkImage); ``` This allow us to compress only one time and use fast zstd. Since the compression level can be set independently, some test need to be done to find the best efficiency. For now it is the "default" mode that is used, but better compression ratio at the expense of compression speed (not decompression!) is also possible. The drawback for using `WriteToOutputStringOn()` is that the complete data need to be written in memory before being able to serialize it. Shame on VTK for not providing an easy way to use c++ streams... Most serializers are far more simple as we only write/read values into a Boost property tree, a bit like before, but without the complexity of "atoms" tree. The version management is also quite simple, we write a integer in the tree and read it back. It is up to the user to add the `if(version < 666)...` ## Enhancement: ### build *Enable support of PCH in unit tests.* Sight CMake targets of type TEST now build with precompiled headers, which speed-ups a bit the global build time. ### core *Wrap notification signal emission in a function.* Wraps emission of "notification" signals into `IService`::notify``with an enum class NotificationType (SUCCESS, INFO, FAILURE) and the message. *Add helper function to ease error handling in boost::property_tree.* This adds a new function to ease error handling in `boost::property_tree`. ```cpp core::runtime::get_ptree_value(config, "test.true", false); // returns true core::runtime::get_ptree_value(config, "test.yes", false); // throws core::runtime::get_ptree_value(config, "test.foo", false); // returns false core::runtime::get_ptree_value(config, "test.foo", true); // returns true core::runtime::get_ptree_value(config, "test.true", 42); // throws because it implicitly request an integer ``` *Move TransferFunctionManagerWindow configuration to config folder.* - Move `TransferFunctionManagerWindow.xml` to `configs/viz/scene3d`. - Add a link in `sightViewer` application to use it. ### doc *Add a README.md for each target.* We now provide a short documentation file for each target. The goal of this file is to give an overview of the content of the library or the module to the developer. It is complementary with the doxygen and sight-doc but it should not overlap with them. ### graphics *Support keeping the original image size and bilinear filtering in SVideo.* * Add support for switching between nearest and bilinear filtering for the texture * Add support to scale or not the image to the size of the viewport ### io *Make realsense support optional.* *Add missing description for pdf writer label.* add description in plugin.xml of modules/io/document ### ui *Send value when released slider in SParameters.* Adds an option to emit value of SParameter sliders only when releasing the slider, this avoids multiple sending when moving the slider. *Add option to fix the size of QToolButton on a toolbar.* Adds an option on Toolbar layout to resize buttons to the wider one. This ensures to keep same size between each button and fix some glitches when larger button was hide / show. ### viz *Enhance tracked us display.* - change UsUltrasoundMesh default us format, and allow xml configuration of this format - add SMatrixViewer significant number for display ## Refactor: ### build *Remove obsolete activities.* The following activities were removed: - blendActivity - registrationActivity - 3DVisualizationActivity - volumeRenderingActivity Only 2DVisualization is kept, and renamed to `sight::activity::viz::negato`. Indeed some configurations of this activity are used in other activities and in **dicomxplorer**. The following activities were fixed: - DicomPacsReader - DicomPacsWriter - DicomFiltering - DicomWebReader - DicomWebWriter Also, the loading of DICOM images from the filesystem or a PACS in SightViewer should also be fixed. ### core *Use data::ptr everywhere.* This is the final merge request that generalizes the usage of data`::ptr`instead of IService::get*/getLocked*/getWeak*. The deprecated `DynamicType` class was also removed, which really helps to clear the build log from many warnings. Last, Ogre runtime deprecation warnings were also processed, which implied to refactor a bit the material and shader code. *Move remaining misplaced files.* - Move several services interfaces from `sight::service`: - `IGrabber` -> io - `IRGBDGrabber` -> io - `ICalibration` -> geometry_vision - Rename `IOperator` as `IFilter` to match the new naming scheme and avoid synonyms - `IParametersService` is renamed into `IHasParameters`, moved in `ui_base` and is no longer a service. Thus any specialized service can inherit this interface using multiple inheritances. - Rename `pchServices/pchServicesOmp` into `pchService/pchServiceOmp` (we have used the singular everywhere for `service`) - Renamed and moved `sight`::module::ui::dicom::SSeriesDBMerger``into `sight::module::ui::series::SPushSelection`, since it pushes a selection (vector) of series into a `SeriesDB`. - Removed duplicated `module`::geometry::generator::SUltrasoundMesh``and moved `module`::geometry::generator::SNeedle``into the same module than the duplicate of `SUltrasoundMesh`, i.e. in `module::filter::mesh::generator`. *New pointer types to manage data in services.* Two new pointer types are introduced, which the only aim is to be used as service class members: - `sight`::data::ptr`:`single data - `sight`::data::ptr_vector`:`group of data For instance, they can be declared this way in a class declaration: ```cpp class STest : public IService { ... private: data::ptr m_input {this, "image"}; data::ptr_vector m_inoutGroup {this, "meshes", true, 2}; data::ptr m_output {this, "genericOutput", false, true}; }; ``` `this` must be passed as the first argument, with a class instance inheriting from `IHasData`. So far, only `IService` inherits from this interface, but other cases might appear later. It is used to register the pointers in the OSR and get/set their content automatically, mainly with the `AppManager` (Xml based and C++ based). This prevents calling `registerObject()` for each data in the service constructor (it was almost never done because this only breaks C++-based apps, but normally it should have been done everywhere). Actually, this registration method was removed from the public interface of `IService` so you can no longer call it and there is no risk of conflict. All occurrences were refactored to use these new pointer types. To retrieve the data, it is simple as using a `data::mt::weak_ptr`, so you can simply call ```cpp auto input = m_input.lock(); // returns a data::mt::locked_ptr const auto data = *input; // returns a data::Image& const auto data_shared = input.get_shared(); // returns a data::Image::csptr // Access data in a group using indexes for(int i = 0; i < m_inoutGroup.size(); ++i) { auto data = m_inoutGroup[i].lock(); ... } // Access data in a group using for range loop - this gives access to the underlying map, // that's why '.second' should be specified, while '.first' gives the index for(const auto& data : m_inoutGroup) { auto data = data.second.lock(); ... } // Alternative using structured binding for(const auto&[index, data] : m_inoutGroup) { auto lockedData = data.lock(); ... } ``` *Booleans attributes configuration parsing.* Harmonize XML configuration of services code by replacing the use of "yes"/"no" with "true"/"false". *Replace getPathDifference() by std::filesystem::relative().* *Reorganize all targets and rework the build system.* Sight 21.0 brings a major update on the naming scheme. We renamed almost every target, according a new naming scheme, and we reduced drastically the scope of categories we use to sort targets. Many targets were merged together. We lost some modularity but we gained in simplicity. Also the build system was partially rewritten. Now it relies only on standard CMakeLists.txt, and no longer on our custom Properties.cmake. We no longer support injecting external repositories into a Sight build. To build other repositories, we use what we called before the SDK mode, which is actually the classic way to link some code to another in C++. Last we introduced a global `sight`::``namespace, which is also reflected on the filesystem. This makes extensibility easier by avoiding naming conflicts. # sight 20.3.0 ## New features: ### core *Add services for echography navigation and simulation.* Add various services that help to build applications based on echography. * create `cvSegmentation` module * add `SUltrasoundImage`: segments an ultrasound image from an echography video * move `SColourImageMasking` service from `colourSegmentation` module * add several services in `maths`: * `SMatrixList`: manages a list of matrices * `STransformLandMark`: applies a matrix transform to a landmark * `STransformPickedPoint`: applies a matrix transform to a picked point in a scene * `SPointToLandmarkDistance`: compute the distance between a point and a landmark * `SPointToLandmarkVector`: compute a direction vector between a point and a landmark * create `opUltrasound` module * `SUltrasoundMesh`: generates a 3D mesh to display an echographic plane in a 3D scene ### graphics *Add adaptor to show the patient orientation in Ogre scenes.* * Add a new SOrientationMarker Ogre adaptor service, that allows to display a mesh showing the orientation of the scene at the bottom right of the screen (equivalent to the VTK SOrientationMarker) * Use SOrientationMarker service in OgreViewer *Synchronize 2D negatos when picking.* * Synchronize 2D negatos when cliking on the image. * Add a parameter in `SVoxelPicker` to enable the update of image slices indexes. Send ``::fwData::Image::s_SLICE_INDEX_MODIFIED_SIG``with the picked indexes. *Allow to delete the last extruded mesh.* Add a slot to delete the last mesh generated by SShapeExtruder. ### ui *Allow to delete series from the selection view from a button.* ## Bug fixes: ### core *Fix SLandmarks by setting an optional input for the key "matrix".* *Save preferences when they are changed.* Save preferences when updated from GUI. *OgreViewer doesn't read properly json with modelSeries.* Connects seriesDB modified signal to the extractImage/Mesh update slots in OgreViewer app. *FwServicesTest randomly fails.* Fix the fwServices`::ut::LockTest::testDumpLock`by adapting the test to asynchronous unlocking. In real world application, the bug should not be present, although the randomly failing test are annoying. ### doc *Update licenses.* ### graphics *Default visibility of modelSeries adaptor is not taken into account.* Take into account default visibility in `visuOgreAdaptor::SModelSeries`. *Mesh normals aren't computed each time.* Compute normals each time a mesh is updated (if mesh has no normals). Before it was only computed if mesh needs a reallocation (number of vertices greater than the previous mesh). ### io *Mesh attributes created after getInput aren't locked.* Some attributes of ``::fwData::Mesh``may be created later (aka after the New()), like points/cells normals/colors/texture coordinates. But this can lead to some unpredicted unlock issues on internal arrays of `::fwData::Mesh`, when using new RAII methods like `getLockedInput` if the mesh hasn't point normals when getting the locked input the corresponding array will not be locked (because it will be equal to nullptr), so if you want to set normals afterwards the corresponding array will still be in an unlocked state. We now initialize all attributes (colors/normals/texture) at mesh creation. A binary mask corresponding to which attributes are currently used in mesh can be checked. We don't rely anymore on the `nullptr` of internal arrays. We also modify mesh iterator to remove the lock it performs, so we need systematically call `mesh->lock()` to lock internal array only if we don't use RAII methods (`getLocked*`) from services. Along with previous modifications, we also modify internal structure of CellsData arrays, previously we store `std::uint64_t` values, we change values to `std::uint32_t` much more adaptable on both 32bits and 64bits systems. To deal with all previous modifications we also updated data mesh version (version 4), fwData version (V15) & arData version (V17AR). We provide structural patches to load/save previous version of data. Some of our unit test has also be updated to handle all previous modifications. This could break the API. ### ui *Fix visuOgre/SNegato3D::setvisible() freeze in ExRegistration.* *Adaptor SLandmarks deadlock.* *Show distances button in OgreViewer bugs.* ### vision *Fix SNeedleGenerator colors.* ## Enhancement: ### core *Add boolean record slot to SFrameWriter.* Add boolean `record` slot to SFrameWriter and SVideoWriter *Improve SPreferencesConfiguration to prevent setting wrong parameters.* ### graphics *Allow to interact with Ogre landmarks.* Allow mouse interaction on Ogre landmarks *Add default visibility configuration for SLandmarks adaptor.* Adds a tag to configure default visibility in `SLandmarks`. Enables the possibility to hide the adaptor by default in the xml configuration. *Add default visibility configuration for SNegato2D.* Uses the tag from IAdaptor to configure default visibility in `SNegato2D`. Enables the possibility to hide the adaptor by default in the xml configuration ### io *Use igtl::serverSocket to get real port number.* Allow the use of port 0, setting port = 0 will ask socket to find the first available port number. Thus we need to modify the way the port is stored in igtlNetwork::Server, and use igtl`::ServerSocker::GetServerPort`to have the real port number. *Make igtlProtocol::MessageFactory extendable from other libraries.* Make the MessageFactory public, to be used from outside of `igtlProtocol`. This is helpful to registrar new type of IGTL Messages that are not necessary implemented in `igtlProtocol` library. ## Refactor: ### core *Add services for ITK and VTK operator modules.* ### graphics *Move all material to fwRenderOgre and deprecate the `material` module.* *Remove all usage of the deprecated API in Ogre modules and libraries.* * Remove deprecated functions in Ogre libs/modules. * Use the new RAII system in Ogre modules. ### io *Remove videoOrbbec.* * Remove videoOrbbec from sources. # sight 20.2.0 ## New features: ### graphics *Add a new picker to really pick the current slice image.* - When using an Ogre picker on a medical image, the picked position does not correspond to a voxel position of the image. In fact, the Ogre negato display the image between \[0;size\] and the picker needs to pick between \[0;size\]. *Add Qt3D SMaterial adaptor.* Implement qt3d material service: * `::fwRenderQt3D`::data::Material``object handling a qt3d material * `::fwRenderQt3D`::techniques::Lighting``object handling a qt3d technique with shader programs to compute lighting mode and rendering options such as point/line/surface rendering or normals visualization * `::fwRenderQt3D`::SMaterial``adaptor used to create a qt3d material from sight data and attach it to the render service ### io *Read tfp TF from directory with ::uiTF::SMultipleTF.* *Add setNotifyInterval method to the Grabber interface.* Adds an option in the videoQt Player to change the notifyInterval option. This is useful to require frame through "setPosition". *Add birth date request field for PACS query editor.* ### ui *Allow to manage opacity of the TF in TF editors.* Allow to manage a whole TF opacity at the same time from the TF editor. ## Refactor: ### core *SpyLog rework.* SpyLog has been unnecessarily complex for a long time. In this rework, we propose to: - deprecate the loglevel `TRACE`. Only `SLM_TRACE_FUNC()` remains, but its occurrences should never be committed. - deprecate `OSLM_*` macros in favor of `SLM_*` macros, which now take stringstreams as input (no performance penalty) - all loglevels are now always compiled, which means that the big bloat of `SPYLOG_*` CMake variables were removed. - occurrences of `OSLM_*` macros were replaced by `SLM_*` macros - occurrences of `O?SLM_TRACE*` macros were removed or replaced by higher levels logging macros - the default displayed log level is now `WARN` - the path of files displayed in the output was shortened to keep the minimum information needed: namespace(s), source fil *Deprecate configureWithIHM.* Deprecate `configureWithIHM` and use `openLocationDialog`, backward compatibility is kept until sight 22.0 *Deprecate *dataReg modules and move *dataCamp content to *data.* This deprecates the usage of dataReg and arDataReg modules, which were so far mandatory as `REQUIREMENTS` for any XML configuration using data. This was done in several steps: 1. a function was added in `fwRuntime` to allow the loading of any regular shared library (we could only load libraries from modules before). 2. `AppConfigManager` was modified to guess the library name when parsing configuration, and load the library accordingly 3. `dataReg` and `arDataReg` were emptied from the hacky symbols, and deprecated 4. the only real useful code, i.e. the XML data parsers from `dataReg` were moved to `fwServices`, so that we can remove the whole module later. 5. `dataReg` and `arDataReg` were replaced by `fwData`, `fwMedData` and `arData` in `Properties.cmake` files 6. `dataReg` and `arDataReg` were removed from all `plugin.xml` requirements. 7. all `*DataCamp` libraries were deprecated and most of their content imported in the corresponding `*Data` libraries. They were linked in an application thanks to the dataReg modules and hacky symbols. I could have loaded the modules manually like data libraries but I think it is simpler to gather everything related to a data into a single library. There is no real use case in my mind where we want only the data without any introspection. And we do not need to plan for a coexisting alternative to perform the introspection, we are anyway too tight with Camp. This is not a breaking change and it is still possible to keep the deprecated modules. ### graphics *Deprecate VTK.* * Deprecates VTk generic scene * Updates all samples to use Ogre * Cleans all sample files (xml/hpp/cpp/cmake) * Fixes some errors in our samples * Adds a new module `visuBasic` for basic generics scenes * Rename samples ### io *Deprecate VLC.* Deprecation of `videoVLC` since VLC package will no longer be available with new conan system (sight 21.0). ### vision *Deprecate the bundle.* Deprecate the bundle `uiHandEye` ## Enhancement: ### core *Complete meshFunction baricentric API.* Add a method `isInsideTetrahedron( const ::glm::dvec4 barycentricCoord);` in the MeshFunction. *Add [[nodiscard]] attribute for weak/shared_ptr::lock().* Adds `[[nodiscard]]` attributes in weak_ptr and shared_ptr lock() function. This avoids using lock() as lock function and force user to use returned lock_ptr object *Update conan.cmake file to v0.15".* Update conan.cmake file to v0.15. ### graphics *Improve scene resetting.* ### io *Increase the DICOM services log level.* Add detailed logs for our communications with the PACS. *Improve PACS research fields.* * Make research fields of ioPacs case insensitive. * Improve date research. * Avoid to read unreadable modalities with the series puller. *Execute PACS queries from a worker.* ``::ioPacs::SeriesPuller``now retrieves series in a worker to avoid the app to freeze. *Improve ioPacs queries.* Adds a PACS series selection to `OgreViewer`. * `SPacsConfigurationEditor`: send notifications. * `NotificationDialog`: use the height of the notification instead of the width for computation. * `SSelector`: remove margin. * `SNegato2D` and `SNegato3D`: avoid a division by 0. * `Utils`: sometime the default texture as the same size than the image, so there is never initialized. ### ui *Rename bad named functions.* * Deprecated `::fwGui::dialog::MessageDialog::showNotificationDialog()` and propose a new `::fwGui::dialog::MessageDialog::show()` * Deprecated `::fwGui::dialog::NotificationDialog::showNotificationDialog()` and propose a new `::fwGui::dialog::NotificationDialog::show()` * Renamed all occurrences. ## Bug fixes: ### build *Add deps between targets and their PCH for Unix Makefiles.* This fixes errors when building using the Unix Makefiles generator and multiple processes. ### core *Load library is broken when launching activity using wizard.* Adds `loadLibrary` method in `new.cpp` file in order to load libraries before starting `AppConfigManager` or `ActivityWizard` ### io *Cannot save json on mounted disk.* Create a custom `rename` function that will first try a `std`::filesystem::rename``and then fallback to a basic copy-remove scenario. Using this avoid the `Invalid cross-device link` error, when saving a json(z) file on a another disk/volume. *Tf names without extension are not saved.* ### ui *Enable the current activity of the sequencer if no data are required.* * Enable the current activity of the sequencer if it's needed. * Avoid double start of the config launcher. *The TF editor suppresses points.* ### vision *Display left and right view vertically.* Until a better fix, display left and right camera vertically in extrinsic calibration. Doing this provide a better width view of video. # sight 20.1.0 ## Bug fixes: ### build *Remove ".sh" extension from launcher scripts.* Both build and install targets are impacted. Adds `.bin` extension to executable target such as utilities/tests or fwlauncher to distinguish executable targets from shell scripts launcher *Ninja install issue on linux.* Test if the install directory ( `CMAKE_INSTALL_PREFIX`) is empty, if not print a warning at configure time. ### ci *Build on master branch on Windows.* Fix quoting of branch name while cloning ### core *Crashes when closing OgreViewer.* OgreViewer crash at closing, this crash happens because the action `openSeriesDBAct` is working on a thread. Now we wait until services are properly stopped after `service->stop()` in XXRegistrar class. *Replace misleading error logs in SlotBase.* When trying to call/run a slot, an error log was displayed if the signatures don't match, but it is allowed to call a slot with less parameters. Now, an improved information message is displayed if the slot cannot be launched with the given parameters, then we try to call the slot removing the last parameter. The error is only raised if the slot cannot be called without parameter. ### graphics *Fix screen selection for Ogre scene.* Enable the full screen of Ogre scene on the right monitor. For more informations: https://stackoverflow.com/questions/3203095/display-window-full-screen-on-secondary-monitor-using-qt. *Slice outline colors are inverted between axial and sagittal in OgreViewer.* Use blue outline color for Ogre's sagittal view, and red outline color the axial one. ### io *Change the overwrite method when saving using ioAtoms.* Change the overwrite method of `ioAtoms::SWriter`. Previously, when a file was overwritten, it was deleted then saved. But if the saving failed, the old one was still deleted. Now, the file is saved with a temporary name, then the old one is deleted and the temporary name is renamed with the real one. *Realsense doesn't work on latest 5.4 linux kernel.* Update the version of librealsense package to latest (2.35.2). This fix issue of using realsense camera on linux kernel > 5.3 *Remove useless requirement in ogreConfig.* Remove `ioVTK` module from `ogreConfig`. No reader, writer or selector was used in the configurations. *Change realsense camera timestamp to milliseconds.* Correct the Realsense grabber timestamp from microseconds to milliseconds *Allow to re-start reading a csv without re-selecting the file path.* Update 'SMatricesReader' to properly close the file stream when calling `stopReading` slot and clear the timeline. Properly stop the worker to avoid a crash when closing the application. Also remove the default delay of 1s when using one shot mode. *Remove hard-coded codec and only offer mp4 as extension available in SVideoWriter.* * Limits extension selection to only `.mp4` for now. * Limits FOURCC codec to `avc1`. This codec is also linked to the `.mp4` extension. *Fix a crash with OpenCV grabber.* - Start/stop the worker of OpenCV grabber when service start/stop ### ui *Notifications crashes when no active window was found.* Avoid crash of app when notifications were displayed without active window (focus lost). If no active window is found, print an error message and discard the current notification. *Prevent dead lock when opening organ manager.* Block Qt signals in SModelSeriesList when changing the state of the "hide all organs" checkbox. ## Enhancement: ### ci *Re-enable slow tests and remove ITKRegistrationTest.* ### core *Add empty constructor to Array iterator.* * Add empty constructor to Array BaseIterator, to make it compatible with std::minmax_element ### doc *Improve IService doxygen about output management.* Describe how to properly remove the service's outputs and why and when we should do it. Add a check when the service is unregistered and destroyed to verify if it owns an output that will also be destroyed (if the output pointer is only maintained by this service). Currently only an error log is displayed, but it may be replaced by an assert later. Other services may work on this object but didn't maintained the pointer (they used a weak pointer). *Update the screenshots in README.md.* Update README.md with more up-to-date screenshots/animations ### graphics *Use ogre to display videos in ARCalibration.* * Use Ogre for `ARCalibration`. * Properly clean ogre resources before root deletion. *Manage default visibility of `SNegato3D` from XML configuration.* Call `setVisible` method at the end of the starting method. ### io *Improve ioPacs module.* * Improves connection/disconnection management. * Improves the UI and request forms. * Use new disconnection method of dcmtk. * Fills new `medData` attributes. ### ui *Add goTo channel in ActivityLauncher.* Add `goToChannel`in `ActivityLauncher.xml` in order to call `goTo` slot from an activity. *Replace Ircad and Ihu logos by the unique Ircad/Ihu logo in the sequencer view.* Modify ActivityLauncher configuration to replace Ircad and Ihu logos by the new version of Ircad/Ihu logo. *Improve assert messages in fwGui.* Add as much information as possible in the assertion messages: service uid, why the error occurs, ... *Add check/uncheck slot in SSignalButton.* These two new slots allow to easily check/uncheck the button without using a boolean parameter. They can be connected to a SSlotCaller or any signal. Update TutoGui to show an example with these two new slots. *Allow to delete all reconstructions or one from a right click.* - Allow to delete all reconstructions from `SModelSeriesList` - Delete specific reconstruction from a right click. *Improve Qt sequencer colors management.* Allow to manage more colors in the Qt sequencer. ## New features: ### core *Implements copy for mesh iterators.* Implement `operator=()` and `operator==()` on mesh iterator's internal structs (PointInfo and CellInfo). It allows to use `std`::copy``(or other std algorithms) with Mesh iterators. Update Mesh unit tests to check using `std::copy`, `std`::equal``and `std::fill`. ### graphics *Add new experimental Qt3D renderer.* A new experimental renderer based on Qt3D has been integrated, providing basic support for mesh visualization. Three samples are provided to show how Qt3D could be integrated into a classic XML application, a pure c++ application or a QML application: * TutoSceneQt3D * TutoSceneQt3DCpp * TutoSceneQt3DQml The following classes and services have been introduced: * `::fwRenderQt3D`::GenericScene``object handling a qt3d scene * `::fwRenderQt3D`::FrameGraph``object to attach to a GenericScene, allowing to define custom qt3d framegraphs * `::fwRenderQt3D`::SRender``service used to define a GenericScene object within Sight context and attach adaptors to it * `::fwRenderQt3D`::Mesh``object creating a mesh from sight data using qt3d geometry renderer * `::fwRenderQt3D`::IAdaptor``class providing base functionalities for Qt3D adaptors. * `::visuQt3DAdaptor`::SMesh``adaptor used to create a qt3d mesh from sight data and attach it to the render service *Improve Ogre's SLandmarks for 2D scenes.* Improve Ogre resources management in '::visuOgreAdaptor::SLandmark' and display the landmarks in 2D negato scenes only on the slice of the landmark. *Add Ircad-IHU logo overlay in Ogre Scene.* - 8 positions are supported: left-top, left-center, left-bottom, center-top, center-bottom, right-top, right-center and right-bottom. ### io *Allow to save and load multiple TF with TF editor.* * Add new buttons to export and import a TF pool to `SMultipleTF` * Use the new API in `SMultipleTF`. ## Refactor: ### core *Manage pixel format in FrameTL.* Manage pixel formats: Gray Scale, RGB, BGR, RGBA and BGRA. Now, to initialize the frame timeline, the format must be specified, the previous initialization method (with number of components)is deprecated. Also improve the unit tests to check timeline initialization and copy. Update `SFrameMatrixSynchronizer`: use the new pixel format to initialize the image, but still support the old API when the format is undefined. Also use the new service's API with locked and weak pointers. ### graphics *Rename the layer "depth" to "order".* Replace `depth` attribute of Ogre layer by `order`. ### ui *Factorize visibility slots in Ogre3D renderer.* - Factorise `updateVisibility`, `toggleVisibility`, `show` and `hide`. `setVisible` is the only method to reimplement in subclasses. # sight 20.0.0 ## Bug fixes: ### .gitlab *Improve sheldon stage.* Use sheldon and build the project on the merge result instead of the working branche. *Improve sheldon stage.* ### activities *Split bundle to separate gui services from core services.* Separate service using Qt Widget from other services in order to use generic service with a Qml application, because Qt widgets cannot be instantiated in a Qml application. A new bundle `uiActivitiesQt` was created where `SCreateActivity` and `SActivityLauncher` has been moved. The old `SCreateActivity` and `SActivityLauncher` services has been kept in activities but set as deprecated. A fatal would be raised if you use them in a Qml application. `ENABLE_QML_APPLICATION` variable has been added in the main CMakeList to define if there is a Qml application that will be launched. It is temporary because we need to keep the old API until sight 21.0 and allow to remove the dependency to Qt Widgets in activities bundle. ### ActivityLauncher *Fix reader/writer configuration.* Fix the reader and writer configurations used by `ActivityLauncher` config: use the configuration given in parameters instead of the default one. ### AppConfig *Fix XML variable regex.* The regex is used to know if the xml attribute contains a variable (`${...}`). But in a few cases, for example in signal/slot connections, the variable is followed by other chars. For these cases, the regex should not be limited to `${...}`but to `${...}....`. The unit tests have been updated to check this error. ### AppConfigManager *Fix useless variable.* Remove wrong `#ifdef` around `FwCoreNotUsedMacro(ret);` ### Array *Implement missing copy constructor in Array iterator.* Implement copy constructor for const iterator and assignment operator. ### build *Fix build on linux with gcc7 in release mode.* - fixed sheldon coding style and define in fwCom - fixed unused variable (release mode) in fwServices ### CalibrationInfoReader *Wrong image channel order.* * Convert to the sight's default color format when reading calibration inputs. * Sort the calibration input by their filename. * Update the related tests. ### CI *Disable slow tests until they all pass.* *Sheldon-mr job doesn't work.* According to #402, the sheldon-mr job seems to fail when merge commit are present in-between dev and the current mr branch. Here the `git merge-base` function has been replaced by a diff of revision list between the MR branch and dev, and then keep the oldest common ancestor. **Explanations** * `git rev-list --first-parent origin/${CI_COMMIT_REF_NAME}`: revision list of the MR branch * `git rev-list --first-parent origin/dev`: revision list of dev (/!\\ we need to check is there is a limitation on number) * `diff -u <(git rev-list --first-parent origin/${CI_COMMIT_REF_NAME}) <(git rev-list --first-parent dev)` : basic diff between the two list * `| sed -ne 's/^ //p'`: removes the diff line ("+" "-", etc), to keep only the common revisions * `| head -1`: keep the first form common revisions. This is, indeed, a bit over-complicated, and can be simplified by a simple merge on the CI side, and then run sheldon, but this avoid any potential merge conflicts checking beforehand. *Use CI_JOB_TOKEN when cloning sight-data.* ### CMake *Disable RelWithDebInfo build type.* *Resolve Qt plugins path in SDK mode.* Do not install the qt.conf from our Conan package that points to a bad plugin location. This overrides the location set in `WorkerQt.cpp`, preventing Qt application built with the SDK from launching. Besides this, I also fixed file permissions of installed files (executable were not actually executable) and I corrected a warning at the end of a CMake run because of a wrong usage of `PARENT_SCOPE` in the macro `generic_install()`. *Resolve missing export when using SDK mode.* The systematic build of the object library broke the SDK build, because the export was missing for the object library. However, this means users would have to link for instance against `fwCore_SHARED_LIB` instead of `fwCore` which is the object library. This is counter-intuitive and really not desirable. We chose to invert the logic. `fwCore` is now the shared library and `fwCore_obj` is the object library. This solves the problem for external users but not for sight developers who would need to modify all `CMakeLists.txt` to link fwCore_obj with 3rd party libraries instead of fwCore. We found a middle-ground by building the object library **only** when the variable GENERATE_OBJECT_LIB is set. This variable was set for `fwRuntime` to enable the build of `fwRuntimeDetailTest`. Its `CMakeLists.txt` was last modified to link against `fwRuntime_obj` instead of `fwRuntime`. On top of that, some corrections were made because of the rework of `fwRuntime` and the usage of `std::filesystem`. *Conan cmake script not correctly downloaded.* - Add check hash of `conan.cmake` file for: * avoid downloading if the file already exists and is valid * download the file if it's corrupted *Add cmake 3.17.0 support.* Add cmake 3.17.0 support *Fix the plugin config command.* Include the appropriate headers in generated `registerService` files. *Strip cmake compilation flags on Windows.* Avoids cmake adding a space at the end of compilation flags *Fix executable installer.* This enables the packaging of executable programs under windows. By the way, the call of generic_install() is now done automatically for all APP and EXECUTABLE targets, thus enabling packaging automatically. A warning is displayed if the macro is called in the CMakeLists.txt of the application. ### conan-deps *Update hybrid_marker_tracker version.* Update hybrid_marker_tracker library version that fixes memory leak. ### ConfigLauncher *Add existing deferred objects to configuration.* * Notify xml sub-configurations that optional objects already exist. * Deprecate `IAppConfigManager`. * Improve the documentation of modified classes. ### dataReg *Add missing include to compile with latest VS2019 16.6.0.* ### Dispatcher *Fix wrong mapping for uint8 type.* `isMapping` method is used by Dispatcher to find the right type for calling template functor. ### doxygen *Doxygen uses the correct README.md to generate the main page.* Update Doxyfile to fix the path of the main README.md. Now the doxygen is generated using the main README file as the main page. ### ExIgtl *Add auto-connections INetworkSender.* * Add missing auto-connections method in INetworkSender * Fix ExIgtl example * Add JetBrains IDEs (CLion) project folder in git ignore file ### ExImageMix *Fix image voxel information.* Remove the useless hack that skipped some events in VTK picker interactor, so the information was not up-to-date. ### ExSimpleARCVOgre *Add missing module_ui_media bundle.* This solves the crash of ExSimpleARCVOgre at start. The bundle module_ui_media was missing. ### fwData/Image *Deep copy.* * Fixes an assert raised in debug when the image is locked and deep copied. * Don't let the data array expire. * Add a test to ensure this doesn't happen again. * Fix ExDump. ### fwGdcmIOTest *Test fails.* Fixes fwGdcmIOTest by using correct type when setting Tags Values. * ConsultingPhysicianName is a list * Patient Size/Weight/MassIndex are double * Attributes was missing when copying a Study ### fwGuiQt *Allow notifications to work with ogre scenes.* Fixes notifications for app that used Ogre scenes. Moves the dialog according to the parent. ### fwLauncher *Allow to exit when receiving signals.* - Use regular exit() to stop program execution when receiving SIGINT, SIGTERM, SIGQUIT signals. ### fwMath *Use glm vector when computing barycenters and fix mistake.* * Replace all `fwVec3` structure by `::glm::dvec3`, along with glm maths functions. * Fix mistake in dot product when computing barycentric coordinates. * Update unit-test ### fwRenderOgre *Fix query flags and ray mask.* * Sets all pickable adaptors query flags to a default value ('::Ogre::SceneManager::ENTITY_TYPE_MASK'). * Sets pickers query mask to a default value ('::Ogre::SceneManager::ENTITY_TYPE_MASK'). * Query flags on adaptors are now sets, (previously, they was added). * Updates documentations on updated files. It allows pickers to pick all adaptors by default. This can be adjusted in xml by modifying the query mask of the picker, and the query flags of adaptors ### fwVtkIO *Fix warnings (as error) when building with Clang.* ### gitlab *Improve sheldon stage.* Fix the build on dev, master and tags ### HybridMarkerTracking *Fix tracking issues with strong distortion.* Removing re-definition of member variable and undistort displayed image allows to correctly re-project tracking position on videos with strong distortions. ### IActivitySequencer *Retrieve more data on update.* The sequencer allows to store all data related to all activities in a member called `requirements`. When the sequencer checks an activity for the first time, it'll create it and add all it's needed data that already exist in the `requirement` list into the activity composite. If we have two activities `A1` and `A2`, `A1` needs an image called `CT` and `A2` needs the same image, and also a matrix `MA` created by `A1`. You launch A1 after adding its needed data in the wizard (`CT`), at this time, the sequencer stores `CT` in its `requirements` list. So A1 is open, the sequencer will check if needed data for A2 have been loaded (Allows to enable a button in the view). To do that, `A2` is created and the sequencer adds the `CT` into the composite of `A2`, but `MA` is missing, nothing is launched. Now `A1` has created the matrix `MA` and asks the sequencer to open the next activity, `A2`. The sequencer checks needed data, but `A2` is created, and the sequencer only updates data that are contained in the composite of `A2`. * These modifications allow to update data and also to add potential new data generated by a previous activity (`IActivitySequencer::getActivity`). * Now, before checking a next activity, the sequencer stores data of the current one (the current one has maybe created a new data). * `IActivitySequencer`::parseActivities``returns the last valid activity. Before modifications, the next one was launched. ### Image *Fix the iterator when using a different type than the image.* The image iterator is now computed based on the format of the iterator instead of using the image type. You can now use Iterator on int16 image. It can be useful to fill the image with zeros. You can also parse int32 image with int64 iterator to gain performance. `SLM_WARN` have been added when you use an iterator on a different type. ### ioDcmtk *Fix the series DB reader and the CI last modification time of file.* ### ioIGTL *Fix the module loading on windows.* - Moves the module `ioNetwork` to SrcLib, it only contains interface. Furthermore some modules like `ioIGTL` links with it, and link between modules are prohibited. ### ioVTK *Vtk Mesh readers and writers only support VTK Legacy files format.* Add more Mesh format in VTK readers/writers. * VTK Polydata (\*.vtp) * Wavefront OBJ (\*.obj) * Stereo lithography format (\*.stl) * Polygonal File Format (\*.ply) This was added to improve compatibility with other VTK software (paraview for example), it seems that the \*.vtk format is a legacy format and we should use \*.vtp when dealing with polydata (our ::fwData::Mesh). **Note:** when using OBJ/PLY/STL format you may loose some informations (point normals/point color/...), often it saves only global geometry of the data (points, edges, ...). ### IParameter *Add missing makeCurrent in IParameter.* Add missing `makeCurrent` in `fwRenderOgre/IParameter` ### ModelSeries *Add const in model series helper.* Update `::fwMedDataTools::ModelSeries`to add const on shared pointer parameters. It allows to call the helper with const sptr. ### OgreVolumeRendering *Fix the ambient occlusion.* * Fix a crash in `SummedAreaTable` due to bad storage (when `m sat Size[0]` is 256, the old `std:uint8_t` stores 0). * Fix a crash when the software is closed. ### openVSlamIOTest *Add missing dependencies for link.* This adds ffmpeg and Qt as explicit dependencies. There is clearly a bug in the OpenCV target but until this is fixed upstream, we can use this solution. ### openvslamTracker *Do not download the vocabulary file each time.* Check the file hash to prevent it to be downloaded on each CMake configuring step. ### RayTracingVolumeRenderer *Correctly blend the volume with the scene behind it.* * Fix alpha blending between the volume and the scene behind it. * Fix z-fighting between the negato picking widget and the negato plane when OIT is enabled. * Fix z-fighting between the volume and the negato planes. ### SActivitySequencer *Qml import path is not properly defined.* Check if a `qml` folder exist on the application root folder (for installed application) and use the conan path otherwise. ### SArucoTracker *Doesn't display marker if image components < 4.* Test the number of components of the input image before doing OpenCV conversion. With this modification we can now handle both 3 and 4 components images. ### SCalibrationInfoReader *Don't convert the image if loading failed.* Fix a crash when loading a folder containing files not readable as images. ### SeriesDBReader *Skip structured report and improve the activity data view.* When you load a DICOM folder that contains a `SR` modality with the reader ``::vtk`Gdcm`::Series`FBReader`, it throws an exception. Now it's skipped with a message. The activity data view is also improved in this MR. ### SFrameMatrixSynchronizer *Use new image API.* * Fix the issue when the number of components are not properly reset (#423) * Add a missing write lock on matrices. * Use the new image API ### SFrameWriter *Add missing else statement.* ### Sight *Fail to compile with Clang.* This adds the AES flag for Clang, allowing to build fwZip successfully. Initially, the MR was opened to fix this issue but actually many targets failed to compile with Clang, thus other minor fixes are included. ### SMatricesReader *Fix default path.* Fix the default path in `::ioTimeline::SMatricesReader`. The default path must be a folder, so we use the parent path of the selected file to set the default reader path. It allows to re-open the file dialog in the same folder. ### SMatrixWriter *Add fixed floating point format and set float precision.* Set floating precision fixed to 7 digits. ### SMesh *Fix recursive read lock.* Update ``::visuOgreAdaptor::SMesh``to remove a read lock in an internal method and only call it in the slots. It fixes a random freeze when starting the adaptor in a large application. *Fix auto reset in mesh adaptor.* Fix auto reset camera in `::visuOgreAdaptor::SMesh`: * call auto reset when the vertices are modified * call request render when the adaptor is started ### SNegato2DCamera *Modify camera position in function of the image.* Modify the AutoReset camera method to reset the camera position in function of the image and not the world position. If there is other adaptors than SNegato2D, the scene will be autoreset with the position of the image. It avoids some strange scaling due to other adaptors. ### SNegato3D *Properly use the ITransformable interface.* Properly use the ITransformable interface in SNegato3D. ### spylog *Reduce usage of FW_DEPRECATED Macro.* Small cleanup of usage of `FW_DEPRECATED` macros. * Macros was removed from widely used functions * keyword `[[deprecated]]` was added where it was missing ### SText *Fix text configuration.* The `text` configuration was wrong when parsing xml file. ### STransferFunction *Avoid assert when icons path are not initialized.* - Fix crash when icons path are not initialized in `StransferFunction` service. - When icons path were not defined, we have this assert: `Assertion 'path.is_relative()' failed. Path should be relative` ### STransform *Remove or add the node instead of change the visibility.* Show or hide the transform node directly impact attached entities and services like `::visuOgreAdaptor::SMesh`, that can't manage its visibility since STransform change it any time. Now, the node is just removed or added from/to its parent to avoid a visibility error. ### STransformEditor *Add missing lock.* Add missing mutex lock in `uiVisuQt::STransformEditor` ### SVector *Fix the visibility update of SVector.* * Add two slots to show and hide the vector ### SVideoWriter *Computes video framerate.* * Removes the default framerate value hardcoded to 30 fps in SVideoWriter * Computes framerate using the timestamps of the first frames in the timeline ### SVolumeRender *Fix usage of transfer functions.* * Create a new service `uiTF`::STransferFunction``instead of `uiTF`::TransferFunctionEditor``(it also fix the swapping method and lock data). * Improve the TF usage in `visuOgreAdaptor::SVolumeRender`. * Set the sampling rate at starting of `visuOgreAdaptor::SVolumeRender`. * Fix the `GridProxyGeometry` by avoid uniforms sharing between programs. * Fix the `makeCurrent` method. *Fix a crash with the volume render.* *Double lock when updating the volume sampling.* ### test *IoVTKTest randomly crashes.* Fix ioVTKTest random crash. Sometimes writer doesn't load the reconstructions in the same order than the reader saved it. We need to force writer to load file in a specific order: * prefix reconstruction filename by its index in reconstructionDB (like "0_Liver") * sort filenames by alphabetical order, using the previous prefixed index, to ensure that reconstructions are loaded in the same order than the generated ones. * add messages in CPPUNIT assert marco to help to find failing tests. ### TutoTrianConverterCtrl *Console application cannot be launched with parameters.* Forward arguments of .bat/.sh scripts to fwLauncher. ### videoVLC *Fix VLC plugins dir.* * use current working path to find VLC plugins folder in `videoVLC` for installed applications * fix cmake install target for apps using libvlc: * on Windows (with MSVC2019) VLC is now manually installed to avoid `fatal error LNK1328: missing string table` in fixup_bundle * on linux vlc plugins path is now analysed by the fixup_bundle script to find required dependencies * update VLC conan package to the version 3.0.6-r5 ### visuOgreAdaptor *Properly generate the r2vb in SMesh.* ### visuOgreQt *Intel mesa regressions.* * Fix regressions when using intel mesa GPU following the context handling MR (!249) * Handle buffer swapping manually instead of relying on ogre. *Remove unused variables.* * Fixes a warning on the CI preventing sight from building. * Removes an unused parameter in `visuOgreQt::Window`. *Always force rendering when the window is exposed.* * Fix the call to `renderNow` in `visuOgreQt/Window` * Request render when changing visibility parameters in `ExSimpleARCVOgre` *Send mouse modifiers as keyboard events.* * Take mouse modifiers into account for mouse events. * This is a quick fix and should be refactored later on. ## Documentation: ### fwData *Improve doxygen of Image, Mesh and Array.* * add examples, fix some mistakes. * improve `Image::at(x, y, z, c)` to add the component parameter, it allows to retrieves the value of an element of a image with components ### README *Remove broken install links.* Remove broken links pointing to old documentation pages. ### visuOgreQt *Clean the bundle.* Cleans the `visuOgreQt` bundle. ## Refactor: ### Boost *Replace boost use by C++17 new features.* Replace usage of Boost by **standard library** versions of: - `boost::filesystem` - `boost::make_unique` - `boost::any` - `boost`::assign``(most of them, some were left because of specific boost containers such as bimaps) Also, `fwQtTest` failed a lot during testing, so a fix has been proposed. It should no longer fail now. ### CMake *Rename THOROUGH_DEBUG option.* Rename `THOROUGH_DEBUG` into `SIGHT_ENABLE_FULL_DEBUG` ### deprecated *Remove last remaining deprecated classes and methods for sight 20.0.* * Remove deprecated class Bookmarks * Remove deprecated class AttachmentSeries and the associated reader and converter class (atom patches have been kept to support the loading of old data). * it implies the increment of MedicalData version to V14 and V16AR * Remove the stop of the worker in its destructor * it implies to properly stop the workers before to clear the worker registry (::fwThread::ActiveWorkers). In fact, the workers should be stopped by the classes that created them, but as the API to remove a worker from the registry does not exist, it will be done in #521. * it also implies to stop manually the workers used in the unit tests and not managed by the registry *Remove the use of deprecated Image, Mesh and Array API.* * Remove the last remaining usage of the deprecated API of Image, Array and Mesh outside of fwData and fwDataTools: add a `2` after get/setSize, get/setOrigin, get/SetSpacing. * Fix dump lock on Image and Array iterators: lock must be called before accessing the buffer. * Improve the documentation about the dump lock. *Use new Image, Mesh and Array API.* Refactor some services and libraries to use new Image, Mesh and Array API: * refactor `igtlProtocol` library to use new API * refactor `fwCommand` library to use new API * remove useless helpers includes * fix MeshIterator: set 'operator=()' as virtual and remove redundant cast ### filetree *Rename root folders.* All root folders were renamed, and first of all, Bundles into modules. We also chose to stick to lower-case only and so we renamed all existing folders to their lower counterpart. Besides this SrcLib was shortened into libs and Utilities in utils. Here was the old file tree: | Apps | Bundles | CMake | fwlauncher | Samples \ Examples | PoC | Tutorials | SrcLib | Utilities And here is the new one: | apps | cmake | fwlauncher | libs | modules | samples \ examples | poc | tutorials | utils ### fwData *Clean fwData and fwTest with new API of Image, Mesh and Array.* * Update `config.hpp.in` to add `_DEPRECATED_CLASS_API`, it allows to set the `deprecated` attribute on a class (display a compilation warning). * Update `fwTest` and `fwData` libraries to remove the dependency to `fwDataTools` * Clean `fwDataTools` to remove the use of deprecated helpers, but the helpers are still here. * fix SImagesBlend adaptor: fix size, spacing and origin comparison *Use new Image, Mesh and Array API in uiXXX Bundles.* * Use new Image, Mesh and Array API in uiXXX bundles * Improve `ioVTK` and `fwVTKIO` unit tests * Fix `fwTest` Image generator (number of components was not properly set) * Fix `::fwData::Image`, add a missing const on `getPixelAsString` method *Improve the API of `::fwData::Array`.* Simplifies Array API by moving the methods from the helper to the data itself: * deprecate `::fwDataTools::helper::Array` * integrate the useful methods from the helper to `::fwData::Array` * deprecate the component attribute * add `Iterator` and `ConstIterator` to iterate through the array buffer ### fwDataTools *Use the new Mesh API.* * Refactor Mesh iterator to access values on a const variable. * Use the new Mesh API in ``::fwDataTools::Mesh``to compute normals and improve unit tests. * Also fix the normals: when the cell contains more than 3 points, only the last 3 points were used to compute the normal. * Improve Image ans Array documentation. ### fwRenderOgre *Use the new API for Mesh, Image and Array.* Refactor `fwRenderOgre` and `uiVisuOgre` to use new Image, Array and Mesh API. *Clean the module_ui_media folder.* Sorts glsl, metarial and compostior. ### fwRuntime *Remove usage of deprecated methods.* * This removes the usage of all deprecated methods by !282 * This removes the usage of the term `bundle` in local variables, private functions, comments. *Rename 'Bundle' into 'Module'".* The first intent of this MR is to rename the term 'Bundle' into 'Module'. As stated in #404, 'Bundle' is not a term widely spread in software for the meaning we give to it. More often, software use either the term 'Module' or 'Plugin'. Late in summer 2019, we decided to choose 'Module'. However we did not want that change to be a breaking change. So as usual, during two major versions, 'Bundle' and 'Module' terms are likely to coexist and the old API should be deprecated but maintained. Most code mentioning 'Bundle' lies in `fwRuntime`. I realized a lot of code present in that library was never used outside. It would have been useless to double every method and class for non-public code. I've been keeping saying we do not clearly separate public and private API in our libraries. I decided so to try to achieve that in fwRuntime. After doing this, the only deprecation of the public API will be faster. To separate the private and the public API in _Sight_ **libraries**, I propose to add `detail` folders both in `include` and `src` folders. Symbols in `detail` folders will be hidden/not exported, thus reducing the size of the shared library and speeding up debugging (when doing this at a large scale of course). This has many advantages in terms of readability of code, maintenance (like this deprecation), etc... However, one drawback is that since symbols are not exported, it was no longer possible to unit-test private classes and methods. To overcome this, I propose to compile libraries in two steps. One `OBJECT_LIBRARY`, then the usual `SHARED_LIBRARY`, that uses the previous as input of course. This way, the unit-test can build directly with the `OBJECT_LIBRARY` (so the precompiled .obj) directly, removing the need of export, and allowing the test of private classes and methods. **But**, this was not that simple. In our tests that are often more functional tests than unit-tests, we face two issues: - we have circular dependencies between libraries, so the test may try to link against both the OBJECT_LIBRARY and the SHARED_LIBRARY, causing awful runtime errors, - we use lots of static singletons to register types, factories, etc... The same singleton may be instanced both in the OBJECT_LIBRARY and the SHARED_LIBRARY, ending up with a duplicate and not a singleton. The first issue can be tackled, I tried at some point, but it was quite hard, especially as soon as we load modules. The second is even harder sometimes. At the end I chose an alternative. I propose to split tests in two. One for the public API (ex: `fwRuntimeTest`) and one for the implementation (ex: `fwRuntimeImplTest`). The implementation test should be much more minimal and should not require many dependencies, thus reducing the possibility of these two problems to occur. At least that's my hope. :candle: ### fwServices *Remove the old API from fwServices.* Remove all the deprecated methods from IService and its associated helpers and registries. Remove IService default object. **Note**: the default auto-connection on the first service's object to the 'modified' signal is removed. Check your log to know if your auto-connections are connect. ### guiQt *Improve SParameters.* * Fix a bad call to `m_illum`. * Allow to avoid the automatic update of `SParameters`. * Add option in `SParameters` to hide the reset button. ### Image *Improve the API of ::fwData::Image.* Improve the API of `::fwData::Image`: * Add the pixel format information: GRAY_SCALE, RGB, RGBA, BGR, BGRA * Add an iterator for the different formats * the format involve the number of components * Prevent to use more than 3 dimensions: the size, spacing and origin are defined in a `std::array` * 4D images are no longer allowed * The ``::fwData::Array``is no longer accessible from the image * Update Dispatcher to use ``::fwTools::Type``instead of ``::fwTools::DynamicType``and deprecate DynamicType. * **Most** of the old API is still supported with deprecated warning: * the new getter/setter for size, origin and spacing are temporary post-fixed by `2` (ex: getSize2()) * Increase the version of Medical Data to serialize the image format (V12, V14AR, V16RD) * Update `WARNINGS_AS_ERRORS` macro to allow deprecated warnings. Example: ```cpp `::fwData::Image::sptr`img = ::fwData::Image::New(); img->resize({1920, 1080}, ::fwTools::Type::s_UINT8, ::fwData::Image::PixelFormat::RGBA); typedef `::fwData::Image::RGBAIteration`RGBAIteration; auto lock = img->lock(); // to prevent buffer dumping auto iter = img->begin(); const auto iterEnd = img->end(); for (; iter != iterEnd; ++iter) { iter->r = static_cast(rand()%256); iter->g = static_cast(rand()%256); iter->b = static_cast(rand()%256); iter->a = static_cast(rand()%256); } ``` ### IO *Use the new Image, Mesh and Array API.* - Use the new Image, Array and Mesh API in readers and writers. - Fix Mesh iterators to properly access the values, even if the variable is const. - Update Image to add the missing API for lazy readers : it requires access to the buffer object to read streams. *Use the new Image, Mesh and Array API.* - Refactor fwVtkIO, fwItkIO, igtlProtocol and associated bundles to use the new Image, Mesh and Array API. - Fix Image iterator: the end of the const iterator was not correct. - Improve mesh iterator to allow point and cell colors with 3 components (RGB). ### iterator *Improve iterator to access values.* - Update Image and Array iterators to allow to access values on const iterators. - Refactor Image iterator to remove complicated format and only use simple struct. - removed warnings when getting an iterator on a type different from the array type. It allows to iterate through a multiple value structure at the same time. Now, to iterate through an Array or an Image, you can use a struct like: ```cpp struct RGBA{ std::uint8t r; std::uint8t g; std::uint8t b; std::uint8t a; } ``` Then: ```cpp `::fwData::Image::sptr`image = ::fwData::Image::New(); image->resize(125, 125, 12, ::fwTools::Type::s_UINT8, ::fwData::Image::RGBA); auto itr = image->begin< RGBA >(); const auto itrEnd = image->end< RGBA >(); for (; itr != itrEnd ; ++itr) { itr->r = 12.0; itr->g = 12.0; itr->b = 12.0; itr->a = 12.0; } ``` ### module_ui_media *Fuse all module_ui_media bundles.* * Deprecate `arMedia` bundle. * Copy all `arMedia` content into `module_ui_media`. * Fixes xml files that used these bundles. ### Mesh *Improve the API of ::fwData::Mesh.* Refactor the mesh API: - deprecate the access to the points, cells and other arrays - rename allocate method to reserve - allow to allocate the color, normal and texture arrays in the same reserve method - add resize method to allocate the memory and set the number of points and cells - add iterator to iterate through the points and cells **Allocation**: The two methods `reserve()` and `resize()` allow to allocate the mesh arrays. The difference between the two methods is that resize modify the number of points and cells. - `pushPoint()` and `pushCell()` methods allow to add new points or cells, it increments the number of points and allocate the memory if needed. - `setPoint()` and `setCell()` methods allow to change the value in a given index. Example with `resize()`, `setPoint()` and `setCell()`: ```cpp `::fwData::Mesh::sptr`mesh = ::fwData::Mesh::New(); mesh->resize(NB_POINTS, NB_CELLS, CELL_TYPE, EXTRA_ARRAY); const auto lock = mesh->lock(); for (size_t i = 0; i < NB_POINTS; ++i) { const std::uint8_t val = static_cast(i); const std::array< ::fwData::Mesh::ColorValueType, 4> color = {val, val, val, val}; const float floatVal = static_cast(i); const std::array< ::fwData::Mesh::NormalValueType, 3> normal = {floatVal, floatVal, floatVal}; const std::array< ::fwData::Mesh::TexCoordValueType, 2> texCoords = {floatVal, floatVal}; const size_t value = 3*i; mesh->setPoint(i, static_cast(value), static_cast(value+1), static_cast(value+2)); mesh->setPointColor(i, color); mesh->setPointNormal(i, normal); mesh->setPointTexCoord(i, texCoords); } for (size_t i = 0; i < NB_CELLS; ++i) { mesh->setCell(i, i, i+1, i+2); const std::array< ::fwData::Mesh::ColorValueType, 4> color = {val, val, val, val}; const float floatVal = static_cast(i); const std::array< ::fwData::Mesh::NormalValueType, 3> normal = {floatVal, floatVal, floatVal}; const std::array< ::fwData::Mesh::TexCoordValueType, 2> texCoords = {floatVal, floatVal}; const size_t value = 3*i; mesh->setCellColor(i, color); mesh->setCellNormal(i, normal); mesh->setCellTexCoord(i, texCoords); } ``` Example with `reseve()`, `pushPoint()` and `pushCell()` ```cpp `::fwData::Mesh::sptr`mesh = ::fwData::Mesh::New(); mesh->reserve(NB_POINTS, NB_CELLS, CELL_TYPE, EXTRA_ARRAY); const auto lock = mesh->lock(); for (size_t i = 0; i < NB_POINTS; ++i) { const std::uint8_t val = static_cast(i); const std::array< ::fwData::Mesh::ColorValueType, 4> color = {val, val, val, val}; const float floatVal = static_cast(i); const std::array< ::fwData::Mesh::NormalValueType, 3> normal = {floatVal, floatVal, floatVal}; const std::array< ::fwData::Mesh::TexCoordValueType, 2> texCoords = {floatVal, floatVal}; const size_t value = 3*i; const size_t value = 3*i; const auto id = mesh->pushPoint(static_cast(value), static_cast(value+1), static_cast(value+2)); mesh->setPointColor(id, color); mesh->setPointNormal(id, normal); mesh->setPointTexCoord(id, texCoords); } for (size_t i = 0; i < NB_CELLS; ++i) { const auto id = mesh->pushCell(i, i+1, i+2); const `::fwData::Mesh::ColorValueType`val = static_cast< `::fwData::Mesh::ColorValueType`>(i); const std::array< ::fwData::Mesh::ColorValueType, 4> color = {val, val, val, val}; const float floatVal = static_cast(i); const std::array< ::fwData::Mesh::NormalValueType, 3> normal = {floatVal, floatVal, floatVal}; const std::array< ::fwData::Mesh::TexCoordValueType, 2> texCoords = {floatVal, floatVal}; const size_t value = 3*i; mesh->setCellColor(id, color); mesh->setCellNormal(id, normal); mesh->setCellTexCoord(id, texCoords); } ``` **Iterators** To access the mesh points and cells, you should uses the following iterators: - `::fwData::iterator::PointIterator:`to iterate through mesh points - `::fwData::iterator::ConstPointIterator:`to iterate through mesh points read-only - `::fwData::iterator::CellIterator:`to iterate through mesh cells - `::fwData::iterator::ConstCellIterator:`to iterate through mesh cells read-only Example to iterate through points: ```cpp `::fwData::Mesh::sptr`mesh = ::fwData::Mesh::New(); mesh->resize(25, 33, ::fwData::Mesh::TRIANGLE); auto iter = mesh->begin< `::fwData::iterator::PointIterator`>(); const auto iterEnd = mesh->end< `::fwData::iterator::PointIterator`>(); float p[3] = {12.f, 16.f, 18.f}; for (; iter != iterEnd; ++iter) { iter->point->x = p[0]; iter->point->y = p[1]; iter->point->z = p[2]; } ``` Example to iterate through cells: ```cpp `::fwData::Mesh::sptr`mesh = ::fwData::Mesh::New(); mesh->resize(25, 33, ::fwData::Mesh::TRIANGLE); auto iter = mesh->begin< `::fwData::iterator::ConstCellIterator`>(); const auto endItr = mesh->end< `::fwData::iterator::ConstCellIterator`>(); auto itrPt = mesh->begin< `::fwData::iterator::ConstPointIterator`>(); float p[3]; for(; iter != endItr; ++iter) { const auto nbPoints = iter->nbPoints; for(size_t i = 0 ; i < nbPoints ; ++i) { auto pIdx = static_cast< `::fwData::iterator::ConstCellIterator::difference_type`>(iter->pointIdx[i]); `::fwData::iterator::ConstPointIterator`pointItr(itrPt + pIdx); p[0] = pointItr->point->x; p[1] = pointItr->point->y; p[2] = pointItr->point->z; } } ``` `pushCell()` and `setCell()` may not be very efficient, you can use `CellIterator` to define the cell. But take care to properly define all the cell attribute. Example of defining cells using iterators ```cpp `::fwData::Mesh::sptr`mesh = ::fwData::Mesh::New(); mesh->resize(25, 33, ::fwData::Mesh::QUAD); auto it = mesh->begin< `::fwData::iterator::CellIterator`>(); const auto itEnd = mesh->end< `::fwData::iterator::CellIterator`>(); const auto cellType = ::fwData::Mesh::QUAD; const size_t nbPointPerCell = 4; size_t count = 0; for (; it != itEnd; ++it) { // define the cell type and cell offset (*it->type) = cellType; (*it->offset) = nbPointPerCell*count; // /!\ define the next offset to be able to iterate through point indices if (it != itEnd-1) { (*(it+1)->offset) = nbPointPerCell*(count+1); } // define the point indices for (size_t i = 0; i < 4; ++i) { `::fwData::Mesh::CellValueType`ptIdx = val; it->pointIdx[i] = ptIdx; } } ``` ### MeshIterator *Cast cell type into CellType enum instead of using std::uint8_t.* When iterating through mesh cells, the iterator return the type as a CellType enum instead of a std::uint8_t. It allow to avoid a static_cast to compare the type to the enum. ### OgreViewer *Recreate the whole application.* * Cleans `visuOgreAdaptor`. * Cleans the documentations of all adaptors and fix it for some of them. * Draws border of negatos and allow to enable/disable them from the xml. * Creates a new `OgreViewer`. * Adds a missing documentation in `LineLayoutManagerBase`. * Creates a xml color parser. * Fixes the fragment info adaptor by listening the viewport instead of the layer. * Improves the slide view builder ### RayTracingVolumeRenderer *Separate ray marching, sampling, compositing, and lighting code.* * Simplifies the volume ray tracing shader to make it more understandable. * Reduces macro definition combinations. ### resource *Fuse all module_ui_media bundles.* * Adds `arMedia` and `module_ui_media` into a folder `resource`. * Adds a new bundle `flatIcon` with flat theme icons. ### SNegato2DCamera *Improve 2D negato interactions.* * Add a new adaptor to replace the `Negato2D` interactor style. * Precisely zoom on a voxel using the mouse cursor. * Deprecate `::visuOgreAdaptor::SInteractorStyle`. * Update OgreViewer to use the new adaptor. * Decouple camera management from the negato adaptor. * Fix interactors to work within a viewport smaller than the whole render window. * Fix the camera's aspect ratio when the viewport width and height ratios are not the same. ### STrackballCamera *Move the trackball interaction to a new adaptor.* * Decouples the trackball interactor from the layer. * Moves trackball interactions to a new service. * Makes 'fixed' interactions the default. * Deprecate parts of the `SInteractorStyle`. ### Tuto *Use new API of Image, Mesh and Array.* Refactor some services and libraries to use new Image, Mesh and Array API: * Refactor Tuto14 and Tuto16 specific algorithms to use the new API * Refactor `scene` to use new API and remove some warnings * Refactor `visuVTKAdaptor` to use new API * Refactor `itkRegistrationOp` library to use new API ### video *Video use new data api.* Refactor some services and libraries to use new Image, Mesh and Array API: * Refactor `videoCalibration` * Refactor trackers, frame grabbers * Refactor `cvIO`: conversion between openCV and sight ### visuVTKAdaptor *Use the new Image, Mesh and Array API.* * update `fwDataTools` to remove the last uses of the deprecated API except the helpers * refactor `visuVTKAdaptor` `vtkSimpleNegato`and `vtkSimpleMesh` to remove the deprecated API * refactor `opImageFilter` and the associated library to remove the deprecated API * fix `::scene2D`::SComputeHistogram``due to a missing include and remove the deprecated API * fix ``::fwRenderOgre::Utils``due to a missing include and remove the deprecated API for the image conversion ### VRWidgetsInteractor *Move the clipping interaction to a separate class.* * Refactors vr widget interaction. Splits `VRWidgetsInteractor` into `TrackballInteractor` and `ClippingBoxInteractor` and deprecates it. * Adds right mouse button interaction to the trackball. * Renames `VRWidget` to `ClippingBox`. ## New features: ### ActivityLauncher *Update the activityLauncher configuration to change icons paths and readers configuration.* Allow to customize the activity wizard used by the sequencer. You can use different icons and/or define the readers to use. * Add a parameter in ActivityLauncher configuration `WIZARD_CONFIG` to define the custom configuration. * Update ExActivities sample to customize the wizard. ### ARCalibration *Load calibration input image folders.* * Add a service to load image folders with calibration inputs. * Move the detection method to the `calibration3d` library. *Live reprojection for intrinsic calibration.* * Compute the reprojection error for each new frame following the calibration. * Display the reprojected points and the reprojection error. * Display the detected points. * Add the ability to undistort the video images once the calibration is computed. * Modify SSolvePnP to always update the camera parameters. ### build *Embed PDB file when installing Sight in debug mode on Windows platform.* Add `install(FILES $ DESTINATION ${CMAKE_INSTALL_BINDIR}/${FW_INSTALL_PATH_SUFFIX} OPTIONAL)` ### ci *Build sight-sdk-sample with the SDK.* * Refactor a bit linux release and debug jobs to build in SDK mode and install/package the SDK. The SDK is an artifact of the job and passed to other dependent jobs * Add jobs that use the SDK artifact and unpack and use it to build sight-sample-sdk * The SDK artifact can be used to manually deploy the SDK on artifactory *Use LFS repo for sight-data.* This replaces the usage of sight-data with a new repository with LFS support. This speed-ups the download time because git LFS can parallelize batch downloads. This is particularly useful for the CI: - Previously we used `curl` to retrieve the archive then `tar` to decompress the archive, **the whole process took around 170s**. - The new `git clone` commands, **this takes only 45s**. For some ci tasks like deploying issues and merge requests templates, we will use `GIT_LFS_SKIP_SMUDGE=1` which allows to skip completely the download of binaries. *Remove macos support.* * remove macos jobs in gitlab-ci script * add warning message to inform users that macos is no longer supported ### cmake *Conan update and compilation flag sharing.* * Update ogre to patched version 1.12.2 ** Match shader input/ouput attribute names in vertex/geometry/fragment shaders. ** Fix varying parsing for the volume proxy bricks shaders. ** Replace the deprecated scene node iterator. ** Remove the debug plugin configuration on windows. ** Explicitly convert quaternions to matrices. ** Fix normal rendering. * Add Visual studio 2019 support with conan package available on artifactory. All conan packages have been updated * Share "optimized" debug compiler flags across all conan package and Sight. Some previous work on array API (and in many place in our code or our dependencies) showed very bad performance in debug. To mitigate this, we want to use optimized debug build with `-Og -g` (unix) or `/Ox /Oy- /Ob1 /Z7 /MDd` (windows) which will effectively make the speed almost reach release build, while being "debuggable". The drawbacks are: ** the build will take a bit longer (max 10% longer on gcc/clang, 30% on MSVC) ** some lines may be "optimized" out ** we loose /RTC1 on windows To allow "full" debugging on Sight, we plan to add a special option to use regular flags. A new option `THOROUGH_DEBUG` has been added to allow full debugging without optimization, if needed. On windows it also add /sdl /RTC1 which performs additional security checks. Also be sure to have the latest version of conan and that you use the latest `settings.yml` on Windows or macOS (sometimes there is a `settings.yml.new` and you need to rename it `settings.yml`). On Linux, Sight automatically download an updated `settings.yml`, but you can still update conan. To update conan: `pip3 install --upgrade conan` *C++17 support.* This updates our Sight build to support C++17 standard. Some modifications were also needed from some of our dependencies: - Camp (patched upstream) - ITK (updated to 5.0.1) - Flann (imported patch from upstream) - Sofa (updated to 19.06.01 and patched locally) ### conan *Update Qt, PCL, Opencv & Eigen.* *Update conan package to support CUDA 7.5 arch.* This is mainly for supporting correctly NVIDIA RTX GPU ### conan-deps *Support Visual compiler 16 for Visual Studio 2019.* Now Sight can be compiled with the latest Visual compiler 16 provided with Visual Studio 2019. ### core *Use RAII mechanism and weak_prt / shared_ptr pattern to protect fwData against race condition and memory dumping.* Three class has been added: `weak_ptr`, `locked_ptr`, `shared_ptr`. Each of them will "store" the pointer to the real data object, but in a different manner and with a different way to access it. You will receive a `weak_ptr` when calling `IServices::getWeak[Input|Inout|Output]()` and a a `locked_ptr` when calling `IServices::getLocked[Input|Inout|Output]()` weak_ptr will use a hidden `std`::weak_ptr``to hold the real data, but it can only be accessed by "locking" it through a `locked_ptr`. `locked_ptr` will hold a `std::shared_ptr`, but also a mutex lock to guard against concurrent access and a buffer lock to prevent dumping on disk when the data object have an array object. RAII mechanism will ensure that everything is unlocked once the `locked_ptr` is destroyed. The underlying lock mutex will be a **write** mutex locker if the pointer is **NOT const**, a **read** mutex locker if the pointer **is const**. Using an `Input` will anyway force you to have const pointer, forcing you to use a **read** mutex locker. You can simply get the original data object through a std`::shared_ptr`by calling `locked_ptr::getShared()` *Simplifies macros in fwCore and enables WARNINGS_AS_ERRORS in some core libs.* * Warnings in Sight core was mainly due to the call of macro with fewer parameters than required. * We have now a macro `fwCoreClassMacro` with three versions: * fwCoreClassMacro(_class); * fwCoreClassMacro(_class, _parentClass); * fwCoreClassMacro(_class, _parentClass, _factory); * The macro `fwCoreServiceClassDefinitionsMacro` used in services has been simplified and replaced by `fwCoreServiceMacro(_class, _parentClass);` * All old deprecated macros have been placed in the `macros-legacy.hpp` file (still included by `macros.hpp` for now - until **Sight 22.0**) * List of new projects that no longer generate warnings during compilation (new cmake option `WARNINGS_AS_ERRORS` enabled): * arData * arDataTest * fwCom * fwComTest * fwCore * fwCoreTest * fwData * fwDataTest * fwMedData * fwMedDataTest * fwRuntime * fwRuntimeTest * fwServices * fwServicesTest * fwTools * fwToolsTest * fwRenderOgre * fwRenderOgreTest ### ctrlPicking *Add a new bundle for picking operation services.* * merge `::uiVisuOgre::SAddPoint`, ``::echoSimulation::STransformPickedPoint``and ``::uiMeasurement::SManageLandmarks``into `::ctrlPicking::SManagePoint` * Allow to have a maximum number of points in a pointlist via `::opPicking::SAddPoint`. * Allow to avoid points to be removed in `::ctrlPicking::SManagePoint`. * Deprecate `::uiVisuOgre::SAddPoint`. * Deprecate `::uiMeasurement::SManageLandmarks`. ### debian *Build sight on Debian-med.* Added several patches to build sight on Debian-med * fix launcher library path * fix version getter: in debian workflow, Sight version should be passed from the build parameters and not from the git repository * do not install conan deps since we use system libraries * add missing copy constructor for fwData`::ImageIterator`(new warning in gcc9) * fix support of VTK 7 * remove redundant move in return statement in fwCom \[-Werror=redundant-move\] * fix build flag for project using system lib * add a new debian gitlab-ci build job * fix the source path of dcmtk scp config file ### ExActivitiesQml *Implement activities for Qml applications.* Create a Qml sample to launch activities: `ExActivitiesQml` * Create base class for activity launcher and sequencer service to share the code between qml and qt services. * Move qml style from `guiQml` to `style` bundles, it is required because some bundles require it and we don't want to start guiQml bundle before them. * Improve `AppManager` to manage input parameters and to generate unique identifier * Create an Qml object `ActivityLauncher` to help launching activities in a Qml application ### flatdark *Update flatdark.qss to add style for persia.* Modify `flatdark.qss` to add specific style for `Persia` application. ### fwData *Allow locked_ptr to work with nullptr.* - If a data is optional, it can be null. But the AppConfig manager try to get a locked_ptr of the data, and the locked_ptr try to lock a nullptr, so an exception is thrown. Now, locked_ptr allows nullptr. - Fix a crash when clicking on `Reinitialize` or `Delete` in the Volume TF editor. *Get/set a 4x4 Matrix from TranformationMatrix3D.* - Add new functions to get/set a TransformationMatrix3D from/to a 4x4 Matrix (array of array). This ensure the row major order and avoid linear to 2d conversions before setting coefficients. ### fwGui *Manage more gui aspects.* * Manage label of SCamera. * Remove a "pading" warning in flatdark.qss. * Add tooltips on button in the WindowLevel. * Change the color of disabled QLabel. * Allow to set the size of each borders in layouts, and manage spacing between widget in the same layout. * Fix the icons aliasing in the wizard. * Fix the opacity in `fwGuiQt` *Manage inverse actions.* Handle the inverse actions behavior. When the inverse is set, it means that the behavior of toolbar button (or menu item) is inverted. It is like if it's internal state return false when it is checked and true when unchecked. *Add parameter to specify the tool button style in ToolBar.* Enable to display the text beside or under the icons in a toolBar. ### fwGuiQt *Allow to set a background color on toolbars, menus and layouts.* ### fwPreferences *Add password management capabilities.* This MR allow to specify a password, retrieve it from memory (it is stored in a scrambled form) and compare its sha256 hash to the one stored in preferences. This password is then used by SWriter and SReader to write and read encrypted data. The code rely on fwPreferences helper and should be accessible from anywhere as static variable is used to hold the password in memory. This functions should be thread safe. ### fwRenderOgre *Simplify fullscreen toggling.* * Make fullscreen toggling easier and more efficient. * Add slots to enable/disable fullscreen on the render service. * Add an action service to select a screen for fullscreen rendering. * Add a shortcut to return to windowed mode. * Fix bundle linking in `uiVisuOgre`. *Configurable viewports.* * Configure viewports for each layer. * Refactor the overlay system to enable overlays per viewport (layer). * Fix adaptors to render text using the new overlay system. *Allow pickers to pick both side of meshes.* Take into account the culling mode of entities for the picking. It allows to know which sides of the triangle to pick. See Sight/sight#373 ### fwRenderOgre/Text *Crisp font rendering.* * Improve font rendering by taking into account the dpi and rendering text at the font size. * Update the dpi on text objects when switching to a screen with a different DPI. * Handle vertical alignment for texts. * Update all adaptors to use this new font rendering method. ### fwServices *Raise an exception when IService::getLockedInput() return a NULL locked_ptr.* Throw an exception when `IService::getLockedXXX()` retrieve a NULL data object. ### fwZip *Add "encryption" support when reading and writing jsonz archives.* - add encryption and update internal minizip to version "1.2". ### gui *Add notification popups in sight applications.* * Notification can be displayed at 7 fixed positions (from top-left to bottom right including top & bottom centers). * 3 Types of notifications: INFO, SUCCESS, FAILURE (background color changes). * Notifications appears / disappears with a fade-in/out effect on opacity. * Two ways of displaying notifications: * Centralized by the new `SNotifier` service: * Using new IService signals `infoNotified`, `successNotified` and `failureNotified` connected to SNotifier slots `popInfo`, `popSuccess`, `popfailure`. * `SNotifier` can queue multiple notifications, if queue is full the oldest one is removed. * `SNotifier` handles also position of the notification per application/config (ex: always at TOP_RIGHT). * Or notification can be displayed by calling directly `::fwGui::NotificationDialog::show()`, loosing the advantages of the centralized system (position, queue, ...). * Add `ExNotifications` sample & `SDisplayTestNotification` service to test and to show how it can work. ### ImageSeries *Add more attributes to our medical data.* * Adds more attributes to our medical data folder. * Creates patch related to these data. * Add tests related to these new data versions. ### MeshFunctions *Add function to convert point coordinates to barycentric one in tetrahedron.* Add functions and test to convert a points coordinates to barycentric coordinates to its barycentric coordinate inside of a tetrahedron. Add corresponding unit test. *Add function to convert world coordinates to barycentric.* * Add functions and test to convert from world coordinates to barycentric coordinates if a point belongs to a triangle. * Add corresponding unit test. ### MeshPickerInteractor *New service for mesh picking interactions.* ### OpenVSlam *Integrate OpenVSLAM in sight.* * openvslamIO is a library that contains some conversion classes & functions in order to easily convert from/to sight to/from openvslam structures. OpenvslamIO is unit tested. * openvslamTracker contains SOpenvslam service to interface with openvslam process * start/stop/pause/resume tracking * Get camera pose for each frames given to the service * Get the map as a `::fwData::Mesh`pointcloud * Save/Load the map. * Save Trajectories as .txt files (matrix or vector/quaternions format). * ExOpenvslam is an example that show all possibilities that offer the openvlsam integration in sight. **Note**: this is a preliminary integration so for now openvslam runs only on linux and with monocular perspectives cameras (very classical models). ### SActivitySequencer *Add new editor to display an activity stepper.* The list of the activities are displayed in a toolbar, the buttons are enabled only if the activity can be launched (if all its parameters are present). The sequencer uses the data from the previously launched activity to create the current one. Create a new `ActivityLauncher` configuration to simplify the launch of an activity sequencer. Improve `ExActivities` sample to use `ActivitySequencer` configuration and add volume rendering activity ### SAxis *Add a configurable marker.* Add a configurable marker on `visuOgreAdaptor::SAxis` ### SFrameMatrixSynchronizer *Add new signals to be consistent with SMatrixTLSynchronizer.* - Add slots to be compatible with the behaviour of `SMatrixTLSynchronizer` in order to connect with a `SStatus` service. The `ExStereoARCV` example is updated to show its usage. - The configuration of `SMatrixTLSynchronizer` is updated to take into account the wish to send the status of some matrices in timelines in `SMatrixSynchronizer`. - Now, it's possible to add the tag `sendStatus` in a ``. - In this way, if you have multiple timelines and multiple matrices, you can choose which one you want to send its status like: ```xml ``` ### SImage *Add editor to display an image.* Create an editor ``::guiQt::editor::SImage``to display an image in a view. ### SImageMultiDistance *Improve interactions and resources management.* * Fixe `::visuOgreadaptor::SImageMultiDistance`. * Add auto-snap on distances. * Update distance on multiple scene. * Improve resources management. * Use our new interactor API. ### SLight *Manage point light.* * Adds point light in addition of directional light. * Allows to manage point light position with `SLightEditor`. * Fixes the specular color computation in `Lighting.glsl`. * Allows to manage ambient color of materials in a new service `SOrganMaterialEditor`. * Deprecates the service `OrganMaterialEditor`. ### SMesh *Add default visibility configuration.* * Add default visibility state in configuration of a mesh. * Add a usage example of this feature in `ExSimpleARCVOgre` ### SMultipleTF *Add new adaptor to manage TF composite.* Creates a new adaptor to display a composite of TF and interact with them. The following actions are available: * Left mouse click: selects a new current TF or move the current clicked TF point. * Left mouse double click: adds a new TF point to the current TF or open a color dialog to change the current clicked TF point. * Middle mouse click: adjusts the transfer function window/level by moving the mouse left/right and up/down respectively. * Right mouse click: remove the current clicked TF point or open a context menu to manage multiple actions which are 'delete', 'add ramp', 'clamp' or 'linear'. ### SNegato2D *Take the slide position into account.* * Take into account the slice position to have the right picking information. * Retrieve the viewport size in the event method for `SNegato2D`. ### SParameters *Manage dependencies.* Adds dependencies system on `SParameters`. ### SPointList *Add slots to update and toggle visibility.* * Add a `toggleVisibility` slot in `SPointList` * Implement this feature in `ExOpenvslam` ### SPreferencesConfiguration *Add the possibility to specify a file in the preferences.* ### SRGBDImageMasking *New service to perform depth image masking.* ### SSeriesSignal *Listen the modified signal.* ### SSquare *Deferred position update and mouse interaction toggling.* - Implement deferred position update, via the "autoRefresh" xml attribute - Allow to enable/disable mouse interaction, via the "interaction" xml attribute ### SsquareAdaptor *Add slots on scene2d SSquare.* Add a slot to the scene2D Ssquare adaptor which allows the change the configuration parameters of the square. This will allow the movement of the square by changing the values of `X` and `Y` on the widget slider. ### STextStatus *Add input string.* Add an input ``::fwData::String``and display it. ### Stransform *Check if the matrix is null.* Check if the given matrix of `visuOgreAdaptor`::STransform``is null to avoid a computation error with Ogre's nodes. ### style *Add QLabel error style.* Add a style in the qss to make a QLabel red and bold for errors. *Add service and preference to switch from one theme to another.* - Selected style is saved in preference file (if it exists), and then reloaded when you re-launch the app. ### SVector *Add parameter to configure the vector visibility on start.* Add `visible` parameter in `SVector` configuration to manage the visibility of the vector on start. ### SVideo *Add update visibility on SVideo Ogre adaptor.* Add a `updateVisibility` slot in `visuOgreAdaptor::SVideo` ### SVolumeRender *Buffer the input image in a background thread.* * Add a new option to load input images into textures in another thread. * Add a new worker type able to handle graphical resources in parallel. ### Tuto06Filter *Update the tutorial to follow the API changes (fwData and RAII).* * Improve Tuto06Filter documentation according to sight-doc. * Use new service API in SThreshold * Remove useless dump locks in SThreshold * Use SSlotCaller action instead of calling the operator service in the menu * Add some comments ### ui *Improve gui aesthetic.* * Improve the background management in 'fwGuiQt'. * Disable parameters in 'uiMeasurement::SLandmarks' instead of hide them. * Allow to configure the style of 'SActivityWizard'. * Properly use the 'hideActions' mode on toolbars. * Properly set bounding boxes on 'visuOgreAdaptor::SAxis'. * Add a flatdark theme. ### uiMeasurementQT *Allow to remove landmarks with SLandmarks.* * Allows to add or remove landmarks from picking information with the service 'uiMeasurementQt::editor::SLandmarks'. * Updates the documentation. ### visuOgreAdaptor *Improve the negato camera.* Compute the camera ratio relatively to the viewport size *Add a punch tool to the volume rendering.* Adds a punch tool, a new adaptor to creates extruded meshes from a lasso tools, and a service to remove image voxels that are in meshes. * The service `SShapeExtruder` works as follows: * The drawn shape is stored as a points list belonging to a 2D plane in the near of the camera, and a second one is stored in the far of the camera. * Once the shape is closed, a triangulation is done on the two points list with a constrained Bowyer-Watson algorithm. * Then, for each segment of the shape, two triangles are created between the segment at the near plane and the far plane. *New adaptor to output renderTarget as an image.* Add a new adaptor `SFragmentsInfo` that takes informations of the configured layer like, informations can be color, depth or primitive ID. Some minors updates are also pushed in this MR: 1. SMaterial can now be configured with a `representationMode` (SURFACE/POINT/EDGE/WIREFRAME). 1. Add new conversion function in `fwRenderOgre`::helper::Camera``to convert from screen space to NDC or viewspace. deprecates the old ones. *Directional light editing.* Adds a visual feedback to light adaptors. *Allow to manage TF windowing with SNegato2DCamera.* * Add TF windowing management with SNegato2DCamera. * Fix a configuring error from SPicker. *Add new adaptors to resize a viewport.* * Add a new compositor to draw borders in viewports. * Add an adaptor to resize viewports *Interact with the 3D negato.* * Add the same interactions on the negato as in VTK * Add a priority to the image interactors * Add the ability to cancel interactions * Deprecate the old selection interactor API *Add a new adaptor to display a vector.* Add `SVector`, a new adaptor that displays a vector. ### visuOgreQt *Properly compute cameras aspect ratio.* If an Ogre layer has a ratio different of 1:1, the camera aspect ratio of the layer is badly computed. It's due to the resize event that retrieves the wrong viewport ratio. *Use qt to create the OpenGL contexts for ogre.* * Add a new class to create OpenGL contexts for ogre. * Move the offscreen rendering manager to `visuOgreQt` and instantiate it through a factory. * Fix material management for the VR widgets. ## Performances: ### videoCalibration *Speedup chessboard detection.* * Add a scaling factor to the input to run the detection algorithm on a downscaled image. * Const-overload `::cvIO::moveToCV`. * Add a new preference parameter to configure the scaling in ARCalibration. # sight 19.0.0 ## Bug fixes: ### qml *Use of a QML Engine to recreate dialog and apply a new style.* * fwQt has been change to add a callback function that is called to create the application using QApplication or QGuiApplication. * created libraries: * guiQml: start all services needed for a Qml Application and contain element to customise Material style. * fwGuiQml: contain all visual Component for Qml, like dialogs. * guiQml * Plugin: call getQtWorker to setup services and launch the Application. Then set the style to Material. * Material.qml: Singleton to set the color of the theme globally in each Window. * qmldir: regroup all Control.qml in rc to override the theme from QtQuick.Controls and QtQuick.Controls.Material * fwGuiQml * model: regroup ListModel and TableModel that are generic model to use inside Qml * dialog: recreate all Qt dialog in Qml ### vlc *Conan package depends on testing dependencies.* Update VLC to 3.0.6-r2 to depends from Qt and FFMpeg of the testing branch. ### fwServicesTest *Increase timeout in fwTestWaitMacro.* - The timeout of `fwTestWaitMacro` was increased to give more time when the runner is heavily loaded. - An optional parameter to specify the duration of the timeout was added. This is useful when we want for instance a shorter duration when we want to verify that a condition did not occurred. ### SWriter *Automatically parse file name when saving an activity.* * Extension is added automatically if no extension is provided in filename * if an extension is provided in filename it will overwrite extension selected in dialog, a error pop if extension is unknown. ### SHybridMarkerTracker *Update hybrid_marker_track to version 1.1 to improve tracking speed.* ### fwRenderOgre *Use std::isinf() instead of isinf() from math.h.* ### fwRenderOgre *Remove Courier.ttf font file, not allowed for redistribution.* The font `Courier.ttf` was removed from `fwRenderOgre` and replaced by `DejaVuSans.ttf`, which was already present in the bundle `material`. `Courier.ttf` was only used for the unit-tests, so the test was modified to reflect this change. ### VRRender *Activities creation crash.* Add parameters `APP_NAME` and `PROGRESS_CHANNEL` in `SActivityLauncher` service in VRRender `sdb.xml`. Modify `SActivityWizard` to check if no tab was created because the selected activity did not have any input parameters. ### ExSolvePnP *Crash due to wrong data inout key name.* This MR fixes the issue Sight/sight#354. It edits the INOUT key name for the meshReader service in ExSolvePnP ### calibration *Add missing locks in SSolvePnP and SChessBoardDetector.* Without these locks, it is possible to find a configuration where the objects are used in the same time and the application crashed. ### CMake *Set policy CMP0072 to NEW to avoid warning about findOpenGL on Linux.* Please refer to `cmake --help-policy CMP0072` for details ### VideoRealSense *Only set the output when the first frame has been grabbed.* - Wait until the first frame has been grabbed to set the output. Doing so, prevent the use of an allocated but randomly filled buffer to be processed by other services, thus making them crash. See #333 for detail. - Additionally, the pause mode has been fixed to not consume all cpu power. ### VRRender *Crash at exit.* This prevents VRRender to crash when exiting in all DICOM related activities. Actually the crash occurred in the ioDicom plugin destruction. The usual linking hack, preventing the linker to strip symbols, consists in instancing one of the class of the bundle. It was placed in the destructor which is a bad idea because it creates an allocation of an UUID while the application is being destroyed. ### SSolvePnP *Add missing locks.* Without these locks, it is possible to find a configuration where the objects are used in the same time and the application crashed. ### TutoEditorQml *Fix the crash when the application is launched.* - The `startService` in `onServiceCreated()` is removed. `AppManager` base class has been updated to automatically start the services when they are added (if `startServices()` has been called once). ### core *Add missing readlock.* Some read locks are missing in central services like SCopy. Adding them may lead to slower but better, safer code ### SShaderParameter *Force parameter update when the update slot is called.* - Reset the dirty flag when calling the update. Not doing so prevented textures from being updated when modified. ### cmake *Check CMAKE_BUILD_TYPE value.* * on Windows, if the user doesn't specify a value for 'CMAKE_BUILD_TYPE', it's automatically initialized to 'Debug' after 'project()' cmake command. * it's annoying because if we wanted to build in release, we have to clean the cmake cache and define `CMAKE_BUILD_TYPE` to `Release` (just redefining `CMAKE_BUILD_TYPE` isn't enough and is "dangerous") * so now, we check `CMAKE_BUILD_TYPE` before cmake command 'project()', and if the user forgets to define `CMAKE_BUILD_TYPE` before configuring, configuration is stopped and display an error message ### RayTracingVolumeRenderer *Allow to work with derived classes.* ### visuOgreAdaptor *Missing color buffer when rendering point billboards.* Add a new material to handle the case when the rendered mesh has no color buffer ### SFrameUpdater *Change image dimension to 2D.* Modify image creation in SFrameUpdater to change dimension from 3D to 2D ### visuOgreQt *Fix crash in ogreResize().* - Add a test to check if the ogre render windows is initialized before using it in the `ogreResize()` method ### visuOgreAdaptor *Properly release resources.* Releases Ogre texture properly ### ogre *Fix infinite loop and graphic corruption in ogre shader code.* - Fix infinite loop and graphic corruption in ogre shader code by replacing a 'for' loop with its 'reverse' equivalent. It is very strange, and looks like a glsl compiler bug, but the workaround seems to work. - Some missing `makeCurrent()` were added ### visuOgreQt *Fix hidpi mode for various mouse event.* - Computes correctly the mouse and window coordinate by taking into account HiDPI (retina) display, on each events, instead of only once. This should fix problems when switching display with a different resolution. Still a manual resize may be needed to force relayouting and thus to have correct size computation. ### SGrabberProxy *Remove spaces when parsing camera Type Tags.* ### fwRenderOgre *Prevent alpha from leaking onto the rendering window.* * Disable alpha writing when blending layers with the background. * Fix the transparent widget bug. ### SAxis *Fix the SAxis node visibility.* `SAxis` visibility is defined by changing the visibility of its node, which can be used by other adapters. The visibility is now sets with another method. ### fwVTKQml *Fix QML Tutos with VTK Scene.* The vtk OpenGLRenderWindow was changed from an external to a generic one which handle his own OpenGL context. So in each render at the beginning we init the state of the OpenGL by calling OpenGLInitState. QVTKOpenGLWidget was changed by QVTKOpenGLNativeWidget because in the code source of VTK it was written: `QVTKOpenGLNativeWidget is intended to be a replacement for QVTKWidget when using Qt 5`. ### fwCore *Fix HisResClockTest::getTimeTest.* We use now the `std::chrono::high_resolution_clock::now()` instead of `std::chrono::system_clock::now()`. Although it may be different, especially on macos where system_clock tends to go too fast (!!!), it seems that on most platform it is indeed the same. This need to be validated on a long test period, and may require a revert.. ### OgreVolumeRendering *Pepper artifacts when the clipping box exceeds the image size.* Clamp clipping box coordinates to not exceed the volume size to fix some artifacts when the user sets a clipping box bigger than the rendered image. ### fwServices *Crash when swapping the inputs of stopped services.* ### Qml *Set conan Qt/Qml directory in QML_IMPORT_PATH".* Allow to use QtCreator to edit Qml files with the qt package from conan. ### ARCalibration *Reverse the model pointlist coordinates.* Reverse x and y coordinates on the calibration model according to openCV tutorial (https://docs.opencv.org/3.4/d4/d94/tutorial_camera_calibration.html). It does not seem to change the result. ### AppManager *Fix auto-start services in AppManager.* Fixes `AppManager` to start automatically services when all associated objects are available. ### OgreVolumeRendering *Fix proxy geometry generation.* A bug occurs when the volume rendering display a tiny image (like a 10\*10). ### visuOgreAdaptor *Fix camera ratio in Ogre SFrustumList.* Camera ratio was wrong in `visuOgreAdaptor`::SFrustumList``because it's not the same than `visuOgreAdaptor::SFrustum`. Now, Both adaptors have the same behavior and display the frustum at the same size and the same place. ### videoVLC *Vlc SFrameGrabber continuously pushing while paused.* ### AppConfigTest *Add a missing wait condition in startStopTest.* ### fwDataTest *Fix MTLockTest random failure.* The test was not written correctly. This could lead to race conditions. We rewrote it in the following way. The test try to lock the data to write two different string sequences in a `fwData::String`. It launches two asynchronous methods that lock the data to write, wait 2 ms between each char insertion and wait 5ms after the unlock. Then, it ensures that the letters from the two sequences are not mixed in the string. ### ObjectService *Add missing mutex.* There was a missing mutex lock in ObjectService::unregisterServiceOutput(). This should solves the random fail in AppConfigTest::startStopTest(), and possibly other random failures in the rest of the tests. ### ARCalibration *Fix extrinsic calibration synchronisation.* Now, we ensure that the chessboard is detected in the two cameras before adding the calibration information. It prevents a wrong synchronization of the calibration information. By the way, an action was also added in the extrinsic view to save the calibration images. Fixes #292 ### fwDicomIOFilter *Limit memory usage of fwDicomIOFilterTest & fwDcmtkIOTest.* This replaces the usage of deepCopy in two Dcmtk filters. We used to copy the whole DicomSeries and then remove the internal buffer. This is both inefficient and memory expensive. We propose here to use shallowCopy() instead, which does not copy the buffer. The container is still cleared out, but only the pointers, so the source buffer is not destroyed. ### Ogre *Set the origin of the SNegato2D to a corner.* The origin of the `::visuOgreAdaptor::SNegato2D` representation is moved on the lower left corner of the image. This change is necessary because the distance system (which was designed for the VTK backend) returns values from the lower left corner of the image. To get this working properly with Ogre, we need to change the origin that currently lies in the middle of the image. The method used to change the orientation of the negato was also modified accordingly. ### videoRealSense *Fix grabber to properly update the cameraSeries.* Prevent to add multiple times the same camera in the cameraSeries when the `startCamera` method is called by checking if the cameraSeries is calibrated. Fix ExRealSense configuration to set the proper parameters for the service. ### unit-tests *Fix random failures.* - **fwServicesTest**: add missing wait. Also, one second might not be enough when the system is under heavy load, so the waiting time has been increased to 2500ms instead of 1000ms. Remember this is just the worst case and usually the function returns in a shorter time. - **ioAtomsTest**: this divides the test image size by 2 and reduces the number of reconstructions from 15 to 5 in the test model series. This should help a bit to reduce the execution time, see results below. - **igtlProtocolTest**: actually fix a lot of the mesh conversion code. It crashed randomly, but only because the UTest was very poor. If done properly, it should have shown how bad the code was, since apart from positions and cells copy, all the rest of the array copies were broken. - **All tests**: - when destroying a worker, we may ask it to join twice the thread if someone else is calling `stop()`. On top of that, hen stopping a worker, we decide whether we need to join the thread by testing the state of the io_service. However this does not seem to be a reliable way, so we now test the thread state itself, - when launching two unit-tests in parallel, they may stop at the same time. Both processes will try to remove temporary folders simultaneously, so we must handle failures properly with exceptions, - use temporary folders for writing instead of folders in the build tree, - last, we realized it is a bad practice to rely on stopping a worker with the auto-destruction (i.e. using shared pointers), because this could lead the `std`::thread``to be destroyed from its own execution scope. So we deprecated the call of `stop()` in the `WorkerAsio` and now we advise people to call `stop()` from the callee thread (most often the main thread). All of this solves a lot of random errors when launching all unit-tests. We can also launch unit-tests in parallel now, making the CI jobs faster. ### SDK *Remove relative paths in 3rd part libraries.* All paths relative to the build host should now be removed from the include and library paths. The absolute paths are stripped away. Some cleaning has also been done to include only the needed modules for VTK and PCL. ### qml *VisuVTKAdaptor crashes when using QML.* Registers imageSeries and tf objects in the SImageSeries constructor. ### Qml *Fix SIOSelector when using Qml.* Change the `AccessType` of the registered object from INPUT to INOUT when we are in writer_mode. ### Ogre *Correct GLSL shaders compile errors on Intel chipsets.* ### SGrabberProxy *Fix SGrabberProxy configuration selection.* ### SScan *Convert point cloud positions to millimeter.* RealSense camera return the point cloud in meters, but we need a point cloud in millimeters. Thus we convert point positions to millimeter (multiply the values by 1000). We also add a test if the camera is already started to avoid a crash. ## New features: ### calibrationActivity *Improve widget layout.* * Display all widgets other than the scenes in a panel on the left side. * Fix the naming convention for service uids. ### cmake *Add option to build a project with warnings as errors.* * Added a cmake option `WARNINGS_AS_ERRORS` in sight to build a project in warning as error (`/Wx` on MSVC or `-Werror` on gcc/clang) * Removed warning in sight project `fwlauncher` * Enabled option `WARNINGS_AS_ERRORS` in `fwlauncher` project * Changed warning level to `w4` on Windows (to see unreferenced local variable) ### cmake *Improve package version number generation.* * Added cmake helper script `get_git_rev.cmake` (from [sight-deps](https://git.ircad.fr/Sight/sight-deps/blob/dev/cmake/utils/get_git_rev.cmake)) to find git tags, branch name, version... * Updated cmake script to generate a SDK filename using the latest tag (or git revision, see command [git describe --tags](https://git-scm.com/docs/git-describe)) * Updated cmake script to add Sight version in app packages ### cmake *Add warning for links between bundles.* Add a test in CMakeLists.txt to display a warning message if there are links between bundles ### fwRenderOgre *Add a depth technique to the VR.* Add a new technique to the volume rendering in order to display the depth of the volume. * RayTracedVolumeDepth_FP: new fragment shader that displays the volume depth. * OffScreenWindowInteractor: fix the rendering by calling the specific target instead of all targets. Remove a double connection in `::visuOgreAdaptor::SInteractorStyle`. ### CMake *Allow utilities to be launched from Visual Studio.* Generate the `vcxproj.user` for utilities. ### OgreDynamicImageTest *Speed-up copyNegatoImage() and updateImage().* - Improve copyNegatoImage using parallel omp ### videoRealSense *Align pointcloud on RGB frame for AR.* Align streams to the desired frame coordinate system (Depth, Infrared, Color). This allow us to have each stream in the same coordinate system, no need to apply transforms in xml configurations. New option is available trough ExRealSense: "Align frames to"; this allow user to choose target coordinate frame where all frames should be align to. Add "visible" option in configuration of `::visuOgreAdaptor::SPointList` ### SHybridMarkerTracker *Extract tag position and orientation in camera.* * Modify `SHybridMarkerTracker` to extract tag position and orientation and take into account an `::arData::Camera`. * Configuration file was replaced by parameters that could be set through `SParameters`. ### hybridMarkerTracker *Add service to track cylindrical hybrid marker.* - Add SHybridMarkerTracker service for tracking a cylindrical hybrid marker - Add associated ExHybridMarkerTracker example ### visuOgreAdaptor *Addition of a distance measurement editor.* - Addition of a distance measurement adaptor in the Ogre 2D negato. You can create a new distance, remove a specific distance or hide/show the distance. ### visuOgreAdaptor *Support landmarks visibility.* Added landmark visibility support in `::visuOgreAdaptor::SLandmarks` ### conan *Update all package to allow sharing of C flags.* - The goal of this code is to share C flags across all our conan packages to ensure compatible code generation as some compiler settings can lead to strange bugs, hard to debug (especially floating point mode like `-mfpmath=sse`, please see the associated issue https://git.ircad.fr/Sight/sight/issues/188). - We choose to write the flags and compiler settings inside a python file packaged as a conan package (https://git.ircad.fr/conan/conan-common/tree/stable/1.0.0). For now, you will have acces to: - `get_[c,cxx]_flags()`, `get_[c,cxx]_flags_[release,debug,relwithdebinfo]()`, `get_cuda_version()`, `get_cuda_arch()` and some utility functions for conanfile.py like `fix_conan_path(conanfile, root, wildcard)` which allows to fix path in .cmake files. ### SFrameMatrixSynchronizer *Handle time shift delay.* Handle synchronization issues in our application by applying a time shift value. ### fwRenderOgre *Update `MeshPickerInteractor` to send `PickingInfo` over signals.* Send ``::fwDataTools::PickingInfo``with `MeshPickerInteractor`to be more generic. ### SLandmarks *Configurable text size.* Use an xml configuration to set the text size of `::visuOgreAdaptor::SLandmarks`. ### visuOgreAdaptor *Addition of a dashed line SLine.* Ability to draw a dashed line and choose the distance between the dots. Configuration is done in XML (SLine service) ### videoRealSense *Implement the record and playback from realsense library.* Adding record/playback functionalities in ::videoRealSense::SScan. * Record function can records all streams synchronously in one file in rosbag format (.bag) * Playback function can replay recording and emulate a realsense device (filters can be applied, and camera parameters are the same as the real device). Also add color on Ogre's SPointList adaptor. ### visuOgreAdaptor *Adaptor displaying text.* Display text along the borders or in the center of an OGRE window. ### videoRealSense *Add filters on depth frame.* Allow to filter the depth frame with the three filters provided by the RealSense SDK: spacial, temporal and hole filling. The filters can be enabled and configured with a `SParameter`. The three filters are: * **Spatial Edge-Preserving filter**: it performs a series of 1D horizontal and vertical passes or iterations, to enhance the smoothness of the reconstructed data. * **Temporal filter**: it is intended to improve the depth data persistency by manipulating per-pixel values based on previous frames. The filter performs a single pass on the data, adjusting the depth values while also updating the tracking history. In cases where the pixel data is missing or invalid the filter uses a user-defined persistency mode to decide whether the missing value should be rectified with stored data. Note that due to its reliance on historic data the filter may introduce visible blurring/smearing artifacts, and therefore is best-suited for static scenes. * **Holes Filling filter**: the filter implements several methods to rectify missing data in the resulting image. The filter obtains the four immediate pixel "neighbors" (up, down ,left, right), and selects one of them according to a user-defined rule. Update `ExRealSense` to add widgets to change the filters parameters. Add a service configuration in ARCalibration to play the RealSense infrared frame without the emitter. Fix `SPointCloudFromDepthMap` to emit less signals. It emitted 'modified' signal on the mesh on each update which was causing the entire refresh of the VTK mesh (very slow). But only the vertex and the point colors are modified, so now, only 'vertexModified' and 'pointColorModied' signal are emitted. ### Conan *Update many conan packages.* Update conan package to more up-to-date versions and refactor sight a bit: * boost --> 1.69 * eigen --> 3.3.7 * Qt --> 5.12.2 * pcl -->1.9.1 * vtk --> 8.2.0 * itk --> 4.13.2 * opencv --> 3.4.5 * ogre --> 1.11.5 * glm --> 0.9.9.5 * gdcm --> 2.8.9 * dcmtk --> 3.6.4 * odil --> 0.10.0 * cryptopp --> 8.1 * bullet --> 2.88 Details: * **boost** related ### fwIO *Implement a fail/success notification on all readers and writers.* Adds a new member status boolean to `IReader` and `IWriter`and all of their inherited implementations. The following implementation of those interfaces have been modified : Readers : * ioAtoms/SReader * ioCalibration/SOpenCVReader * ioData/SAttachmentSeriesReader * ioData/STrianMeshReader * ioData/TransformationMatrix3DReaderService * ioDcmtk/SSeriesDBReader * ioGdcm/SDicomSeriesDBReader * ioGdcm/SSeriesDBReader * ioITK/InrImageReaderService * ioITK/SInrSeriesDBReader * ioITK/SImageReader * ioVTK/SModelSeriesReader * ioVTK/SSeriesDBReader * ioVTKGdcm/SSeriesDBLazyReader * ioVTKGdcm/SSeriesDBReader Writers : * ioAtoms/SWriter * ioCalibration/SCalibrationImagesWriter * ioCalibration/SOpenCVWriter * ioData/MeshWriterService * ioData/TransformationMatrix3DWriterService (great name btw). * ioGdcm/SDicomSeriesWriter * ioGdcm/SSeriesDBWriter * ioGdcm/SSurfaceSegmentationWriter * ioITK/InrImageWriterService * ioITK/JpgImageWriterService * ioITK/SJpgImageSeriesWriter * ioITK/SImageSeriesWriter * ioQt/SPdfWriter * ioVTK/SImageSeriesWriter * ioVTK/SImageWriter * ioVTK/SMeshWriter * ioVTK/SModelSeriesObjWriter * ioVTK/SModelSeriesWriter * ioVTKGdcm/SImageSeriesWriter The following implementation of those interfaces have **not** been modified : Note: by default we consider that a non modified reader always return success... Readers: * ioTimeline/SMatricesRead : this service is to complex for a simple muggle like me. * ioZMQ/SAtomNetworkReader : one of those that do a bit more than reading... :rolling_eyes: * ioZMQ/SImageNetworkReader : same here Writers: * ioTimeline/SMatrixWriter : see above * ioZMQ/SAtomNetworkWriter : idem * ioZMQ/SImageNetworkWriter : idem * videoOpenCV/SFrameWriter : not the actual behaviour we expect. ### videoVLC *Implement RTP video streaming with libvlc.* - Adds a new service ̀SFrameStreamer in the videoVLC bundle. Which allows to stream frames pushed into a FrameTL. - Adds a new sample ExVLCVideoStreaming that grabs and streams a given video (either passed through a file or directly a stream). - Adds and increments videoVLC conan package version dependency. ### conan *Stores all used versions of conan packages in a single file.* To simplify the process, all versions packages of conan are now merged into a simple conan-deps.cmake file ### GUI *Add tooltips on views.* A tooltip can now be set on any view of a cardinal or a line layout manager, optionally of course : ```xml ``` If the editor inside the view already has a tooltip, it will be not be overridden by this configuration, thus we do not break the existing tooltips. ### gitlab-ci *Check the compilation with SPYLOG_LEVEL=trace.* Update gitlab-ci to compile debug configuration with SPYLOG_LEVEL=trace to check wrong log message. Fix a wrong debug message. ### SGrabberProxy *Forward IGrabber's signals.* ### FrameLayoutManager *Add visibility parameter.* ### opencv *Use our own ffmpeg and rework opencv dependencies.* ### calibration *Write calibration input images to a folder.* Adds a feature to write calibration input images to a folder. This can be useful for debugging or to compare our results with those of third-party programs. Calibration info image writer. ### CI *Add a new stage to build CI on linux to build the sdk.* Besides this this also embeds some fixes for the sdk packaging on windows. ### test *Use always slow tests skipping.* Resolve "ease CI for slow test" ### fwTest *Add a template version of randomizeArray.* Add a template version of randomizeArray in fwTest generators. It is useful for floating arrays because with the existing method some 'nan' values could appear, and the comparison of 'nan' return always false. ### TutoSimpleAR *Promote ExSimpleARCV into a real tutorial.* ExSimpleARCV is promoted to a real tutorial named TutoSimpleAR. The configuration has been cleaned a bit, comments have been added everywhere and the sample data are now downloaded at configuration time to help the beginners. This sample is also a demonstration of the new design to synchronize AR rendering efficiently. As most of the tutorials, it is documented in the official documentation. ## Refactor: ### deprecated *Remove deprecated code related to sight 19.0.* * Remove deprecated methods in `fwDcmtkIO` * Remove outdated and unused bundle `uiNetwork` ### SActivitySequencer *Emit a signal when the activity requires additional data.* The service emits a signal 'dataRequired' if the activity can not be launch because some data are missing. It allows to connect it to a SActivityWizard to select new data. ### conan *Remove sight-deps support, conan is used by default.* Conan is now the official way to retrieve 3rd party libraries in Sight. Since it would be a pain to keep maintaining both sight-deps and Conan together, we agreed to skip the normal deprecation phase. * Remove option `USE_CONAN` in sight and make it the default. * Clean all parts of the build system that refer to `EXTERNAL_LIBRARIES`. * Remove support of Eclipse project ### fwPreferences *Add getValue helper.* The method `getPreferenceKey(...)` returns associated value saved in the preferences (if delimited with the character `%`) or simply returns the variable. This helper is defined (copied/pasted) 12 times in Sight. To avoid this, we have centralized all these versions in `fwPreferences` with the new method `getValue(const std::string& var, const char delimiter = '%')`. ### deprecated *Remove deprecated code related to sight 19.0.* ### trackingCalibration *Remove hand-eye reprojection service.* SChessboardReprojection was unused in sight. Remove the hand-eye reprojection service ### videoCalibration *Rewrite chessboard detection.* Modifies the SChessboardDetection service to take images as inputs instead of timelines. Makes synchronization easier. ### RayTracedVolume_FP.glsl *Remove IDVR referencies.* ## Performances: ### fwVtkIO *Improve mesh conversion.* The methods updating the mesh points, normals and texture to VTK were very slow, checking the allocated memory on each value. It is replaced by using the `SetArray()` methods with a copy of the data mesh array. This increases the speed from ~23ms to ~0.7ms for the point color update. # sight 18.1.0 ## New features: ### MarkedSphereHandleRepresentation *Add ComputeInteractionState method.* ### videoRealSense *Update realsense grabber:.* - grab also pointcloud - live loading of presets (in /rc/presets) - enable/disable IR emitter - switch between color/infrared frame - live modification of min/max range - speed-up the grabbing function - brand-new ExRealSense using Ogre backend Resolve "Output pointcloud from realsense grabber" ### ci *Add ci-jobs to build sight on windows and macos.* - Add some jobs to build sight on Linux, Macos and Windows - Launch unit-test - Use ccache to reduce build time Resolve "Add windows and macos as gitlab CI target" ### CMake *Add source packaging with CPack.* It is now possible to create a source package for a specific application. To do so, you have to: - Choose an app you'd like to package. (e.g. VRRender, OgreViewer,...) This needs to be an **installable** app make sure it calls `generic_install` in its `CMakeLists.txt` - Set it (and only it) as the `PROJECTS_TO_BUILD` in your cmake config. - Run cmake `cmake .` - Build the source archive, if building with ninja you can run `ninja package_source` else run `cpack --config CPackSourceConfig.cmake` - Retrieve the source archive (e.g. VRRender-0.9-Source.tar.gz if you chose VRRender). ## Some results A source package example : [PoCRegistration-0.1-Source.tar.gz](/uploads/a4fdd05b1681b7f01c1c553903f0f072/PoCRegistration-0.1-Source.tar.gz) ## Additional tests to run This should better be tested on all platforms. - [x] Windows - [ ] ~~macOS~~ :arrow\_right: won't work see #248 - [x] GNU/Linux ### SDecomposeMatrix *New service to decompose a matrix and associated tutorial.* Add a new service to decompose a matrix into a rotation matrix, a translation matrix and a scale matrix. Add a new sample using this service. ### TabLayoutManagerBase *Add a border option.* - add also Parameters_Gray.svg icon. Resolve "Improve GUI esthetic" ### SParameters *Add new index based enumeration slot.* Add a slot which changes enumeration state based on the index and not on the label. ### video *Add slot that plays or pauses according to current state.* - Add new slot to IGrabber that plays or pauses. - Add two state booleans on IGrabber. - Add declaration to start, stop and pause on IGrabber. - Add parent call to all derived grabbers for start, stop, pause. ### conan *Find conan packages associated with installed cuda version.* - Use conan option 'cuda' to find package associated with cuda version installed on the machine - Available cuda versions: "9.2", "10.0", "None" ### SFlip *Add service to flip images.* - Add a service to flip images in the three main axes (can handle up to 3D images) - Implement the SFlip service in Tuto06Filter ### vscode *Add vs code generator.* - add VS Code support to build and debug Sight - to use VSCode with sight: run CMake configure with option SIGHT_GENERATE_VSCODE_WS, and open the workspace file "sight.code-workspace" (in build dir) ### conan *Add linuxmint19 support.* - Support new settings 'os.distro' in cmake-conan script into sight for linux. - Available values in your packages for settings 'os.distro' are: - linuxmint18 - linuxmint19 ### idvr *Draw the IDVR's depth lines from the outside of the countersink.* ### visuOgreAdaptor::SPointList *Addition of a labeled point list.* If the option "displayLabel" is set to true on the XML configuration, it will add a label on a point when the point is created. You can also choose the character height and the color of the label on the XML configuration. ### PoCMergePointcloud *Add a new PoC to merge pointclouds from 2 RGBD Cameras (Orbbec astras).* Move opDepthMap & depthMapOp from internal repository to opensource. Resolve "Sample to merge two RGBD Cameras" ### Calibration *Export extrinsic matrix in .trf format.* Resolve "Export extrinsic matrix in .trf in calibration activity" ### OGRE *Configure stereo cameras using camera series.* - Computes each projection matrix using intrinsic and extrinsic calibrations ### Ogre *Improve stereo rendering management.* - Adds an action to enable/disable stereo in an ogre layer. - Refactors the stereo mode to be handled by the core compositor. - Fixes some adaptors that crashed when restarting. ### SImageWriter *Handles timestamps and bitmap images".* ### Player *Add getter of video duration.* Adds a getter for QMediaPlayer::duration() this is useful for knowing how much time is left on your video and especially this ticket for a video timeline editor which basically uses the `::fwVideoQt::Player`to get specific frames at specific positions. ## Bug fixes: ### template.sh *Add quotes in linux sh template (build & install).* Resolve "Wrong bundledir path in application scripts automatically generated by CMake" ### OgreViewer *Correct user interface bugs.* The compositor uniforms are now properly shown in the compositor selector. The application no longer crashes at exit when all lights are removed. ### SMaterial *Use a lookup table to correctly display 16 bits texture.* ### videoOpenCV *Duration calculation & loop mode.* * Correct the duration calculation. * Use total number of frame and current frame index to loop the video. Resolve "OpenCV grabber loop mode & duration" ### guiQt *Copy the styles plugin on install.* Installed and packaged apps looked bad because we forgot to ship the qt styles plugin. ### fwRuntime *Remove windows.h in Library.hpp.* - avoid exposing of windows.h in fwRuntime`::dl::Library`header (via dl::Win32.hpp) - use abstract class fwRuntime`::dl::Native`(as a pointer) in the hpp and instantiate the specific implementation in the cpp - update vlc conan package used in videoVLC to fix problems related to windows.h ### Flipper *Move the implementation to the correct path.* Resolve "Move Flipper.cpp from imageFlipperOp to imageFilterOp" ### videoOrbbec *Allow to use the grabber in RGB mode.* Fixes a crash in videoOrbbec`::SScan`if no depth timeline was given. Now, we can use this grabber to get only the RGB frames. ### ci *Fix job to deploy doxygen on the sight gitlab page.* - Doxygen pages can no longer be deployed on the CI due to an error on the gitlab-ci script. - There is an error because the git configuration has been defined globally for all jobs, and the deployment jobs use a docker image that doesn't contain 'git'. - To fix this, we'll use the same docker image for all linux jobs (DOCKER_ENVDEV_MINT19) ### guiQtTest *Add missing profile.xml and gui requirement.* ### fwDicomIOFilter *Fix unit tests.* ### SStereoToggler *Remove fwServicesRegisterMacro macro.* Fix compilation without PCH by removing the fwServicesRegisterMacro Resolve "Missing header in SStereoToggler.cpp" ### utests *Various fixes for fwJobsTest, fwGdcmIOTest, fwRenderOgreTest, fwThreadTest.* This fixes the following unit tests: - fwJobsTest: The problem was visible on macOS, but other platforms maybe impacted. Testing if the future is valid before waiting did the trick. Also a wrong "+" with a char* and an integer which give also a crash in release, has been replaced with a proper string concatenation - fwGdcmIOTest: The hashing function boost::hash_combine() doesn't always use the same implementation across platforms (!!!). We now use a regular sha1 hashing, a bit slower, but safer - fwRenderOgreTest: Deleting the dummy RenderWindow with destroy() leads to a double delete crash when deleting ogre root node. Using the appropriate Ogre::RenderSystem::destroyRenderWindow() seems to fix the crash - fwThreadTest: Use a workaround to mitigate the callback cost in time computation. This is a workaround because either the test itself is false (and maybe undoable, as unpredictable), either we must change the implementation of TimerAsio to take into account the time taken by the callback. We may look again for https://git.ircad.fr/Sight/sight/tree/fix/TimerAsio, but it is clear this change will have side effect since some code may actually want to wait for the callback to perform before reseting the timer. I guess that playing a video with openCV did fail with the above merge request ### cmake *Use the correct macOS flags to build pch.* Pass the correct macOS flags when compiling pch ### gitignore *Parse also versioned qtcreator cmake preferences files.* Resolve "Update gitignore to include qtcreator's versioned files" ### conan *Quiet conan output.* Update cmake script with conan OUTPUT_QUIET option to have a more quiet conan's output ### GridProxyGeometry *Fix variables declaration.* ### SGrabberProxy *Correct parsing of grabber list and ensure that the list is filled even if no config is set.* Resolve "Empty SGrabberProxy list" ### ci *Update ccache path.* - now ccache use a nfs folder mounted in docker image - previous gitlab-ci cache is not compatible with this system ### SFrameWriter *Use the correct timestamp in image filename.* Use the timeline timestamp instead of the current timestamp when saving frames using videoOpenCV::SFrameWriter ## Refactor: ### Ogre *Remove IDVR from the repository.* This MR removes all IDVR references from OgreViewer. This makes the application simpler, because over time it accumulated too many features. In the same time, we added volume rendering and negatoMPR adaptors to the VTK tab, in order to show the comparison between the two back-ends. OgreViewer has been updated to 0.3. ### ui *Remove deprecated services (ShowLandmark, SaveLandmark, LoadLandmark and DynamicView).* Resolve "Remove deprecated services" ### Bookmarks *Deprecate ::fwTools::Bookmarks.* Add FW_DEPRECATED macro in fwTools`::Bookmarks`and the associated service ctrlSelection::BookmarksSrv. The bookmarks are no longer used and the service still use a deprecated API. ### HiResClock *Un-deprecate getTime* functions.* Resolve "Un-deprecate HiResClock functions" ### videoRealSense *Use the version 2 of the realsense api.* This is a basic implementation of a Grabber for D400 cameras: * parameters such as resolution, fps, ... are set in code * the camera chosen with the videoQt selector is not taken into account by the grabber (Qt doesn't recognize correctly realsense device) * if multiple realsense cameras are plugged-in the grabber will pop a selector dialog * depth pointcloud is not outputted for now ### filterVRRender *Rename filterVRRender to filterUnknownSeries.* `FilterUnknownActivities` filter from `filterUnknownSeries` bundle allows to remove the unknown activities when reading a medical file (.json, .jsonz, .apz, ...) with `::ioAtoms::SReader`. The old filterVRRender bundle is kept for backward compatibility, but will be removed in version 19.0. ### ioGdcm *Remove plugin.xml in ioGdcm.* Remove the plugin.xml file in ioGdcm bundle because it is useless (cmake generates it automatically). Also change the documentation of services. ### uiVisuOgre *Remove obsolete getObjSrvConnections().* ### fwTools *Move shared library path search code and make it generic.* This introduces a new function in `fwTools`::Os``: ```cpp /** * @brief Return the path to a shared library name * The library should have already been loaded before. * @param _libName The name of the shared library, without any 'lib' prefix, 'd' suffix or extension, * i.e. 'jpeg' or 'boost_filesystem'. The function will try to use the appropriate combination according to * the platform and the build type. * @return path to the library on the filesystem * @throw `::fwTools::Exception`if the library could not be found (not loaded for instance) */ FWTOOLS_API `::boost::filesystem::path`getSharedLibraryPath(const std::string& _libName); ``` This function has been used to search for Qt plugins in `WorkerQt.cpp`, where this was originally needed. It can be used in some of our utilities as well. The code is generic and has been unit-tested properly. ### video *Better support of selected device in video grabbers.* * Strongly identify camera when using Qt Selector, and add better support of multiple same model cameras * Refactor CameraDeviceDlg to keep usb order in comboBox * Uniquely identify cameras using a prefix pushed in description. * Grab Webcam with OpenCV is now multiplatform. * Enhance the video support when using OpenNI grabbers. * Add support of multiple connected astra (videoOrbbec) * Use Opencv instead of Qt to grab RGB frame * Grab RGB & Depth frame in same thread (synchronized on depth) * Remove Qt in videoOrbbec * Add Astra utility program to replace over-complicated SScanIR * astraViewer: to view Color/IR and Depth stream * astraRecord3Streams: to display Color + IR + Depth and take a snapshot (! FPS will be very very slow ! ). Resolve "videoOpenni and videoOrbbec SScan don't take into account the selected device" # sight 18.0.0 ## Bug fixes: ### STransform *Check parent node existence before creating it.* ### unit-tests *Look for profile.xml in the source directory.* Instead of looking for a profile.xml in the build directory for the unit-tests, now we look into the source directory. Otherwise, this does not work when CMake is only ran once. Doing this, some missing bundle requirements in unit-tests were fixed. ### CMake *Check if profile exists to enable bundles load on unit-tests.* ### * *Add GL_SILENCE_DEPRECATION definition globally.* Before it was only defined in fwRenderOgre. Resolve "OpenGL is deprecated on MacOS 10.14" ### TutoOgreGenericScene *Update deprecated service key.* This made this application crash. ### install *Remove useless install target.* setpath.bat and .bat are only usable in build dir ### unit-tests *Ensure test data are really free and anonymized.* This anonymize some data used in our unit-tests. ### SMesh *Check if node exists before attaching it to root.* ### DCMTK *Change DCMTK files path on Windows.* ### * *Resolve errors reported by FOSSA.* - Update our license headers to mention Sight and not FW4SPL - Change the license headers to follow [GNU recommendations](https://www.gnu.org/copyleft/lesser.html) - Add IHU Strasbourg copyright - Remove LGPL license headers from minizip files - Remove DCMTK files and copy them at build instead - Add copyrights for MIT licensed files. ### fwVideoQt *Properly close the camera device and deallocate the related resources.* Resolve "ARCalibration crash when stream stops" ### macos *Fix OgreViewer for macOS in debug mode.* ### calibrationActivity *Correct intrinsic editor inputs.* Calibration activity crashes when starting the intrinsic editor because of an input that should be an inout. Merge remote-tracking branch 'origin/fix-calibration-activity-crash-on-start' into dev ### SReprojectionError *Fix indexing of marker points.* ### fwRuntime *Resolve NOMINMAX redefinition.* - NOMINMAX was defined twice (in 'fw-boost.cmake' and in 'fwRuntime/dl/Win32.hpp') - a warning C4005 was displayed each time this file is used ### conan *Update conan packages.* Conan has new packages available, it is necessary to update the versions used by Sight for macos and QML ### ImportanceCompositing_FP *Allow Nsight compiling.* ### SActivityWizard *Fix crash when loading or importing a data.* Fix load and import in SActivityWizard. SIOSelector service must be configured before to associate the output object Id. ### CMake *Use the correct variable for deps without Conan.* We just used the wrong variable... ### visuOgre *Add include file.* ### SCamera *Replace assert by warning when creating cameras.* Allow to use ``::videoQt::editor::SCamera``when we don't know if the input CameraSeries will be initialized or not: the cameras will be generated if the cameraSeries is empty. ### ogre *Fix naming conflicts and double deletes.* ### sight *Set external lib dir in scripts to launch Sight apps.* Scripts used to launch Sight applications are not correct because the variable FW_EXTERNAL_LIBRARIES_DIR is empty. ### fwRenderOgre *Silent deprecated OpenGL warnings on macos.* Resolve "[macos 10.14] OpenGL is deprecated" ### tests *Fix fwServicesTest and fwActivitiesTest.* Fix the broken tests of `fwServicesTest` and `fwActivitiesTest`: - fix the resources path - update the wait macros to test if a service exists. Replace `::fwTools::fwID::getObject(uid)` by `::fwTools::fwID::exist(uid)` because when getObject() is called, an assert is raised: the service pointer expires before it is removed from the ID map. ### CMake *Remove usage of QT_QPA_FONTDIR on Linux.* Usage of **QT_QPA_FONTDIR** is deleted in both build & install scripts since now we build Qt with fontconfig support. ### fwRenderOgre *Move declaration of static const outside the class.* ### Ogre *R2VB objects can't be picked.* This allows quad-based meshes to be picked. Since the quads are triangulated with a geometry shader, it was not that easy to perform. The chosen solution is not very elegant, I added intersection tests on the quads themselves. Testing intersections on the triangulation is harder to perform and on top of that, at the beginning we did not intend to read it from the CPU. ### IDVR *Mesh/countersink interference.* Also brings a few new buttons to the OgreViewer toolbar and fixes the clipping box update. Only works with the Default or the DepthPeeling transparency technique. [Ogre] Fix idvr with mixed rendering ### SPointListRegistration *Test if registered pointList has labels.* Fix SPointListRegistration service when having two pointLists which one has labels and the other one has no labels. Resolve "Fix SPointListRegistration" ### fwDataToolsTest *Glm initialization.* ### CMakeLists *Add a define for aligned storage compatibility with visual 2017.* ### macos *Remove installation script for executable.* Remove installation script for executable for macOS. This script did not work and broke the cmake configuration. It should be rewrite completely. See #131 ### export *Fix export macro in arData and calibrationActivity.* ### cmake *Allow use of relative path for EXTERNAL_LIBRARIES.* Resolve "Cannot use relative path for EXTERNAL_LIBRARIES" ### ogre *Fix relative paths on linux.* material paths are now absolute using predefined variables ### ogre *Add missing makeCurrent() and fix glsl errors.* ### CMakeLists.txt *Fix link errors with vtk libraries.* The PCL discovery was done in the main CMakeLists.txt, thus defining VTK compile definitions for all targets. This led to strange link errors, notably in unit-tests. ## New features: ### conan *Implement a better Conan support, especially on macOS.* - Remove libxml2 and zlib dependencies on macOS - Use DYLD_FALLBACK_LIBRARY_PATH instead of LD_LIBRARY_PATH because it is unsupported in macOS and DYLD_LIBRARY_PATH prevents using ANY system libs. - Remove unneeded activities bundle dependency to gui - Fix application script template generation to use : as path separator instead of ; - Cleanup template script - Add VLC conan package for Windows and macOS, use system for Linux - Add scripts to launch unit tests and utilities with conan packages - bonus: fix ioAtoms and ioITK unit tests (updated object access type) ### doxygen *Generate sight doxygen with Gitlab-CI.* - A new Gitlab-CI job is added to generate and publish Sight Doxygen - Doxygen is built only if sheldon and debug/release build pass - Doxygen is only deployed on the dev branch - Sight doxygen is available on https://sight.pages.ircad.fr/sight ### tutoQml *Use qml and c++ for tuto 08 and 09.* New version of the Tutorial 08 and 09 using qml and c++ (without XML configuration). - fwVTKQml:new library to allow to display a VTK scene in qml - visuVTKQml:new bundle to initialize qml FrameBuffer - uiMedDataQml, uiImageQml, uiReconstructionQml: new bundles containing services inherited from IQmlService and the associated qml files. ### tutoQml *Add basic samples using qml interfaces.* Add new samples to use Qml: - `Tuto01BasicQml`: same as Tuto01Basic but using qml instead of fwGui frame and xml - `TutoGuiQml`: same as TutoGui but using qml instead of fwGui frame and actions - `TutoEditorQml`: sample to explain how to use a IQmlEditor Add a new library `fwQml` that contains helpers to use qml: - IQmlEditor: base class for f4s service associated to qml UI - QmlEngine: to launch qml ui ### tutoCpp *Convert tuto 08 and 09 to use C++.* The new Samples `Tuto08GenericSceneCpp` and `Tuto09MesherWithGenericSceneCpp` are equivalent to the existing samples (same name without 'Cpp') but they doesn't use a XML configuration. All the services are managed in C++ in the application `Plugin` class. The services' configurations are written with `::boost::property::tree`. To achieve this, a new helper : ``::fwServices::AppManager``was added. It simplifies the management of objects/service/connections in an application. ### CMake *Use Conan to build Sight (experimental).* Add conan support in sight: - A temporary conan registry is used for the moment: [Artifactory](http://5.39.78.163:8081/artifactory) - All conan package are available on [gitlab Conan group](https://gitlab.lan.local/conan/) - A new advanced CMake option is available: `USE_CONAN` ### trackingHandEyeActivity *Load and evaluate calibration matrices.* Adds the possibility to load the hand-eye X matrix for evaluation. Once loaded the Z matrix is computed using the current tracked position and camera pose. The camera can than be moved around and the app will display the reprojection and reprojection error. Evaluate external calibrations in the hand-eye activity. ### SLabeledPointList *Implement updateVisibility slot.* - to update visibility of SLabeledPointList, we have to implement updateVisibility slot into SPoint, SPointLabel, SPointList Resolve "Implement updateVisibility slot in SLabeledPointList" ### PointList *Add pointlist management methods.* * Add a slot to clear the pointlist in SMarkerToPoint * Add a slot to manage the visibility of the pointlist in the adaptor SPointList3D ### SRenderStats *Display rendering stats such as FPS in the OGRE overlay.* - Adds a new adaptor to display FPS and triangle count in ogre windows. - Fixes a crash when setting the volume visibility when no image has been loaded. - Removes the option to print stats in a console. ### sslotcaller *Add wait option for synchronized slot calling.* Add a wait option to SSlotCaller that is used to call the slots synchronously. This allows for dependent slots to be called in the right order. ### 21-integration-of-sopticalflow-from-internship-repository *Into dev.* Add a new service that performs optical flow on a video to detect if camera is moving or not. Use the service in a new example called ExDetectCamMotion. SOpticalFlow is designed to only detect if camera is moving not if something happend on video. It can send 2 signals: cameraMoved if motion and cameraRemained if camera is stable. This can be usefull to trigger event when motion or remaining phases are detected, ex: only add calibration image if camera is not moving. ### 124-sort-example-by-topics-and-remove-numbering *Into dev.* Remove numbering of Samples, and add topics folders. Resolve "Sort example by topics and remove numbering" ### CMake *Introduce SDK mode.* After many years, we propose a real build of Sight as a SDK. This allows to: - create a binary package containing Sight binaries, libraries, includes and resources, - include/link a Sight library in a non-Sight application/library, - create a new Sight library, bundle or application outside Sight source and build tree ### .gitignore *Ignore vs2017 cmake project files.* ## Refactor: ### * *Remove "fw4spl" references.* Resolve "Remove all references to "fw4spl"" ### ITransformable *Node managements is now handle by ITransformable.* * Factorise some functions to have a common method into ITransformable. * Set the parent transformation only in STransform (else, two adaptors with the same transform can have two different parents). * Fix the stopping method of SAxis. ### ioIGTL *Modify INetwork and STDataListener to manage timestamps.* - Add receiveObject function in INetwork to return the message timestamp - Add optional timestamp parameter in manageTimeline from STDataListener ### deprecated *Remove 'FW_DEPRECATED' related to 18.0.* Remove the deprecated code associated to the macros `FW_DEPRECATED_xxx(..., "18.0)`. ### MedicalImage *Split to MedicalImage and TransferFunction.* Splits `::fwDataTools::helper::MedicalImageAdaptor`to `::fwDataTools::helper::MedicalImage`and ::fwDataTools::helper::TransferFunction Most of the adaptors used the half of the `::fwDataTools::helper::MedicalImageAdaptor`: one part to manage an fwData`::Image`and the other one to manage fwData::TransferFunction. Resolve "Split `MedicalImageAdaptor` into `MedicalImage` and `TransferFunction`" ### getObjSrvConnections *Replace getObjSrvConnections() by getAutoConnections().* Resolve getObjSrvConnections() errors by implementing getAutoConnection() method. ### fwCore::HiResClock *Use std::chrono inside and deprecate in favor of std::chrono.* ### ogre *Refactor volume ray entries compositors.* - Removes the volume ray entry compositor scripts and generates them instead. It will be a lot easier to add stereo IDVR now. - Moves all programs/materials/compositors used in fwRenderOgre to it. * **:warning: IMPORTANT** Delete share/fwRenderOgre and share/material in your build directory ### cmake *Cmake cleaning.* cleans sight CMake scripts: - removed unused platform - removed racy backward compatibility ### * *Reorganise some folders.* After the big merge with fw4spl-ar, fw4spl-ogre and fw4spl-ext, it was necessary to clean up a bit the folders hierarchy, notably to group related items together. No project is renamed, the projects were only moved or their parent directory was renamed. See sight!2 ## Documentation: ### README.md *Remove all mentions of 'fw4spl'.* # fw4spl 17.2.0 ## New features: ### calDataGenerator *Add an utility program to generate stereo pair of chessboard/charucoboard images.* This can be useful to test calibration algorithms. ### handEyeActivity *Handling a step value in SMatricesReader and SFrameGrabber.* Add a step value in readNext()/readPrevious() slots in SMatricesReader and SFrameGrabber when configured on oneShot mode. This step value can be changed calling a setStep slot, connected with an int SParameter withstep` key. We also needed to add this setStep slot in the SGrabberProxy and IGrabber in order to call it properly when using a SGrabberProxy instead of a SFrameGrabber directly. ### Ogre *Update ogre to 1.11.* This brings a bunch of fixes following API changes. Among them : * default light direction is set to the camera's view direction, was implicitly the case in ogre 1.10 but changed in 1.11 * `Codec_FreeImage` plugin loaded to support common image file formats * plugin config parsing was modified to be able to load multiple plugins * `::Ogre::Affine3` replaces `::Ogre::Matrix4` when we need to decompose a matrix * colour masks are enabled when computing volume ray entry points ## Refactor: ### ut *Replace deprecated methods to register a service.* Replace the `::OSR::registerService(obj, srv)` by `srv->registerInOut(obj, key)` in the unit tests. ### cmake *Remove racy backward compatibility.* ### registerService *Replace deprecated methods to register a service.* Replace the `::OSR::registerService(obj, srv)` by `srv->registerInOut(obj, key)` and use `::fwServices::add(srv)` helper instead of calling directly `Factory ### SVolumeRender *Store clipping matrices the same way VTK does.* Now clipping box transforms are stored in world space instead of texture space. Clipping transforms can be passed from/to VTK that way. Removes the **broken** slice based volume renderer. ### plugins *Remove the freeimage plugin.* ### textures *Convert all png and tga textures to dds.* DDS is supported natively by ogre without the freeimage plugin. The freeimage BinPkg is awful to maintain and should be considered as deprecated from now on. ## Bug fixes: ### glm *Add missing GLM_ENABLE_EXPERIMENTAL define.* Unused glm extensions have been removed ### fwRuntime *Fix memory leaks.* Fix leaks in fwRuntime ### SMaterial *Texture rendering on other formats than 8 bits.* ### IHasServices *Add wait() when stopping services.* - add wait() when stopping services in unregisterService and unregisterServices methods. ### SGrabberProxy *Include/exclude mode wasn't working as expected.* - Improve include/exclude filtering. We can include/exclude a specific service or a specific configuration of a service or both. - Grabbers are now always displayed in same order in selector dialog. - Frame by Frame mode from `::videoOpenCV::SFrameGrabber`has been excluded from calibration ### registrationActivity *Fix all errors in the registration app.* - fix all log errors - remove useless autoConnects # fw4spl 17.1.0 ## Refactor: ### fwServicesTest *Clean unit test and deprecate unused methods.* Add `FW_DEPRECATED` macro for: - swapService(obj, srv) - registerService(obj, service) - getServices(obj) - getServices(obj, type) - fwServices::add(obj, srvType, srvImpl) - fwServices::get(obj) Replace the deprecated methods in the tests by the new ones. Replace C++ configuration by XML file for the tests of AppConfigTest. Keep a few tests on the deprecated methods until the methods are officially removed. ### VRRender *Remove the deprecated logs.* Clean the configurations to remove the deprecated logs: - remove the useless objects and services - use the right key - remove useless autoConnect Update appConfig.xsd to set 'uid' attribute as required for services. Add missing 'getAutoConnections()' in some services from visuVTKAdaptor. ### tutorials *Remove the deprecated logs.* Remove the deprecated log: - clean configurations - remove useless autoConnect - use the right keys in services - remove useless services and object - add getAutoConnections() methods in uiReconstructionQt to replace the default deprecated getObjSrvConnections() from IService - use the new API to register the reader/writer in ::uiTF::TransfertFunctionEditor - remove auto-connection on 'tf' in the vtk adaptors when registering a sub-service ### ObjectService *Support optional output in services.* - if the output is not defined in the XML configuration, the object is not emitted to the configuration. - add a method in IService to check if the object is defined: hasObjectId() - the method getObjectId() throw an exception as described in the doxygen ### SWriter *Set 'data' as input instead of inout.* Set 'data' as input in '::ioAtoms::SWriter' - update RecursiveLock visitor to use const object - add constCast in SWriter before the conversion to atoms ### deprecated *Remove deprecated getObject() in services.* Replace 'getObject()' by 'getInput()' or 'getInout()' and add a deprecated log if the input key is not correct. ### getObject *Remove deprecated getObject().* Replace deprecated `getObject()` by `getInout()` in `::uiCalibration::SIntrinsicEdition` Depreciate some bundles and services: - bundles: ioZMQ, uiZMQ, uiNetwork - services: SProbeMesh and SProbePosition from echoEdSimu ### getObject *Replace the last 'getObject()' by 'getInOut()'.* Replace the last two getObject() by getInout(). They were forgotten in service that already use getInout() for these data, so the deprecated log is useless. ## New features: ### VRRender *Add activity to upload DICOM series via DicomWeb protocol.* New activity that anonymizes and uploads DICOM series onto an Orthanc PACS. ### proxyConnection *Catch exception when the connection failed.* Catch the exception raised when a connection failed between signals/slots defined in the configuration. It displays a error log with the signal/slot information. ### cvIO *Add new conversion function between cv::Mat and f4s matrices.* Convert from/to `::cv::Mat`to ::fwData::TransformationMatrix3D Convert from/to `::cv::Mat`rvec & tvec convention to ::fwData::TransformationMatrix3D Add new unit tests cases. Refactor Calibration code to use new helpers. ### trackedCameraCalibration *Merge activities.* Fuse sense specific activity and rgb activity thanks to SGrabberProxy. ### video *Import VLC, Orbbec and RealSense grabbers.* VLC, Orbbec and RealSense grabbers code is now open and imported into fw4pl-ar, as well as the video filtering. The VLC grabber is convenient especially for RTSP streams. It may also be used as a fallback when the QtMultimedia grabber fails... The Orbbec grabber works for Astra camera and the RealSense brings support for cameras based on Intel sensors. ### fwRenderOgre *Add a helper to convert pixel to view space position.* The function `convertPixelToViewSpace` translates a pixel coordinates to view space coordinates. ### SNegato2D,3D *Use the transparency of the transfer function (optionally).* A new option was added to use the transparency of the transfer function. ### SAxis *Add a label configurable option.* SAxis now has an option `label` that can be set to `true` or `false` to display or hide the axis labels (`true` by default). ### SRender *Add a 'sync' renderMode.* In the following of our recent rework of the synchronization for real-time augmented-reality, this new mode allows to make the Ogre generic scene compatible with the approach. The example ExSimpleARCVOgre was reworked to use the new sync mechanism and proves that this works. ## Documentation: ### eigenTools *Document helper namespace.* ### visuOgreAdaptor *Update some documentation.* The documentation of several adaptors were fixed. ## Bug fixes: ### cmake *Update wildcard to search all external libraries.* Before only .so.* was found. ### pchServicesOmp *Remove clang specific hack about OpenMP.* Remove a clang specific OpenMP hack in our CMake code. ### fwDataCamp *Fix compilation.* Add a missing header in fwDataCamp (Build without PCH) ### plugin_config_command *Support 0 in service or bundle names.* Fix the regex used to generate the service definition in plugin to support zero. ### docset *Fix broken docset generation.* ### boost *Add support of Boost 1.67 on Windows.* Boost >= 1.67 changes the default random provider on Windows to use BCrypt. So a link to system library bcrypt is now required to use Boost::UUID. The changes are compatible with old Boost version. ### ARCalibration *Remove warnings by using seriesDB key instead of series.* Fix series keys to seriesDB used in various configurations because it will be removed in 18.0 version of FW4SPL. ### activitySelector *Remove warnings by using seriesDB key instead of series.* Fix series keys to seriesDB used in various configurations because it will be removed in 18.0 version of FW4SPL. ### beginnerTraining *Fix the training samples.* - fix the documentation for the plugin.xml generation - remove the fwServicesRegisterMacro from the services to let cmake to generate the right one - add getAutoConnections() for tuto03 and tuto04 SStringEditor ### fwRenderOgre *Correct valgrind errors and leaks.* Memory errors were fixed and memory leaks detected by valgrind (memcheck) on the test suite: * One out of bounds in read `fwRenderOgre::helper::Mesh` * Memory leaks on Ogre root destruction ### fwRenderOgre *Missing headers.* ### fwRenderOgre *Remove clang specific hack about OpenMP.* Remove a clang specific OpenMP hack in our CMake code. ### R2VBRenderable *Clear vertex declaration before filling it.* This caused the varying to be duplicated, and thus the program link to fail. ### Mesh *Generate normals each time the mesh is modified.* For triangle based meshes, when we don't have normals, we generate them. The problem was that it was only done on the first update of the mesh. If points were added to the mesh, the corresponding normals were not computed accordingly, thus the normal layer ended to be be shorter than the position layer. This led eventually to crash at some point... # fw4spl 17.0.0 ## Bug fixes: ### VRRender *Do not crash when clicking on the distance button in VR.* The service `::uiMeasurement::editor::Distance` was also cleaned a bit, and the unused configuration option 'placeInScene' was removed. ### docset *Generation on case sensitive systems.* ### SMesh *Lock the input mesh properly in slots.* ### SPoseFrom2d *Trigger modified signal even if nothing is detected.* To keep the processing pipeline updated, we need to keep to trigger the modified signal anytime, like in SArucoTracker. ### videoQt/editor *Properly handle button actions on choose device.* - Use accept() and reject QtDialog slots instead of our own onValidate() and generic close() - In SCamera, check the result of exec dialog window to check if it's canceled and don't continue to configure the camera if so. ### Mesh *Do not compute normals with point based meshes.* We are not supposed to compute normals when displaying a point based mesh only, however the condition testing this was wrong in the code. ### fwRenderOgre *Missing headers.* ### material *Ensure Common.{program,materials} are parsed first.* Depending on your file system, the `Common.program` could be parsed after the `Video.program`, causing it to fail because it needs `TransferFunction_FP`, which lies inside Common.program to be declared first. ### IDVR *Compute the countersink geometry in world space.* We changed the way the MImP IDVR countersink geometry (CSG) is defined/computed: * CSG used to have a fixed viewport radius, it now has a fixed angle and isn't resized when zooming with the camera. * Depth lines now start at the importance zone and are in the same unit as the image's spacing. * The CSG border had to be removed because we couldn't easily adapt it to this new method :crying_cat_face: * Greyscale CSG and modulation are now separate. ### SMesh *Build error with GCC 5.4.0.* ### SAxis *Make the visibility changeable and fix adaptor stop.* ### RayTracingVolumeRenderer *Do not delay the resize of the viewport.* Delaying the resize of the entry points textures broke the auto-stereoscopic rendering. This was introduced recently in 6e2946 but was actually not necessary and did not fix anything. ## New features: ### uiPreferences *Handle floating value in preferences.* SPreferencesConfiguration only handles integer values. - number configuration element is now deprecated it has to be replaced by int - add double configuration element to handle float/double type (min: -1000000.0 max:1000000.0, decimals: 6) ### SSignalShortcut *Create new service to handle shortcuts.* A new SSignalShortcut service in fw4spl has been added. This service allows to map keys or combination of keys to the trigger of a signal. ### dicom *Add dicom_reference in Image and Model Series.* The purpose of this commit is to keep DICOM tags into fw4spl data and use them to create back valid DICOM to save image and/or models. - Added new example ExDicomSegmentation to generate a ImageSeries mask and a ModelSeries - Removed `::boost::filesystem::path`in DicomSeries - Added BufferObject in DicomSeries to store Dicom data - Updated gdcm/dcmtk reader/writer and unit tests - Updated `::opImageFilter::SThreshold`to `::fwServices::IOperator`(used in ExDicomSegmentation) - Updated `::opVTKMesh::SVTKMesher`to `::fwServices::IOperator`(used in ExDicomSegmentation) - Added dicom_reference in ModelSeries and ImageSeries - Added new MedicalData version V11 ### Calibration *Add charuco calibration.* Add ChArUco board calibration in ARCalibration: * New Bundle with services related to Charuco calibration * Brand new utility to generate charuco board. * New activity in ARCalibration * ARCalibration has been updated to version 0.5 * Both standard calibration and charuco calibration displays now reprojection error when calibration (intrinsic and extrinsic) is performed. * videoCalibration Bundles were moved from video folder to calibration folder. ### SPoseFrom2D *Add a points list data containing the corners of the marker model.* SPoseFrom2D now provides an inout data that can be used to retrieve the 3D geometry of the marker model. A mistake was also corrected in hand eye calibration, that called `SOpenCVIntrinsic` instead of `SSolvePnP`. In that case, the camera calibration was overwritten by the first service. Now, it just finds the pose of a chessboard model in the camera only, without calling the camera calibration service (what we really want to). ### MedicalData *Update fw4spl-ar data to V13AR.* - This commit adds a new data version V13AR for AR data - This new V13AR is require to manage new ModelSeries & ImageSeries with Dicom reference (fw4spl!259) ### SLandmarks *Add adaptor to display landmarks.* The new adaptor SLandmarks displays landmarks with Ogre generic scene. ### SLine *Allow length update via a slot.* A `updateLength()` slot was implemented to update of the length of the rendered line. ## Refactor: ### ioAtoms *Find the correct version without an XML parameter.* Improve `::ioAtoms::SReader`and `::ioAtoms::SReader`to find the correct data version without setting an XML parameter, only the 'patcher' tag is required to use the patch system. When no version is defined in SReader and SWriter, the current version of MedicalData defined in fwMDSemanticPatch is used. This version can be overridden by the new method 'setCurrentVersion'. You can still define your own version and context. ### CMakeLists.txt *Add discovery of additional repositories.* Setting the CMake variable ADDITIONAL_PROJECTS was tedious and error-prone. Now we explore the folders at the same level of FW4SPL to find extra repositories. Then a CMake option, set to ON by default, is proposed to enable/disable the repository. This will make CMake configuration phase easier than ever ! ### deprecated *Replace getObject by getInput or getInOut.* - Replace deprecated `getObject()` by `getInput()` or `getInOut()` - Add deprecated log if the key is not correct in the configuration. - Set the services `ExternalDataReaderService`, `SInitNewSeries` and `SSeries` as deprecated - Improve the `FW_DEPRECATED` macros to display the version where the support will be discontinued - Add a new macro `FW_DEPRECATED_KEY(key, access, version)` to define the correct 'in/inout' key. All XML configurations have not been updated, so expect to see more [deprecated] mentions in the log. Please fix your application as required. ### SSeriesDBMerger *Replace getObject.* ### ioAtoms *Find the correct version without an XML parameter.* Override the current version of fwMDSemanticPatch to use the AR version. Clean the useless IO configuration. ### Synchronization *Improve the synchronization for augmented-reality.* We reworked the way we synchronize the video frames and the extracted data in real-time. So far, we have made an extensive use of timelines. First the video grabbers store the frames in timelines. Then we process some algorithms on them and we store all the extracted data (markers, transforms, etc...) in timelines as well. At the end, we rely on ``::videoTools::SFrameMatrixSynchronizer``to pick frames, matrices, etc... at the same timestamp and give these synchronized objects to the renderer, i.e. the generic scene. However this does not work well. First this is very tedious to work with timelines, since we need to create a dedicated C++ class for each kind of data we want to manage. For some big data, like meshes, we never did it because this would consume too much memory. And some services are simply not well coded and work directly on the data instead of timelines, etc... Eventually, the renderer even screws up the synchronization since all updated objects request the rendering to be done. So we propose a different approach here. First we restrict the usage of timelines to synchronize video grabbers together, for instance when you use a camera with multiple sensors or simply several cameras. After that point, all algorithm process the data directly. A new data ``::arData::MarkerMap``is introduced to store a list of markers, since this was the only "data" that only existed in a "timeline" version. To synchronize the results of the algorithms, we propose a new service called `SSignalGate`. This service waits for several signals to be triggered before sending itself a signal, which indicates everyone before is done. This service is typically used to inform the renderer that it must send everything to the GPU right now. To achieve this, we introduced a new rendering mode in `::fwRenderVTK::SRender`. You can try Ex04SimpleARCV which uses the new design, but for now everything is backward compatible. But we strongly encourage to have a look at this very soon and try to port your application to benefit of this improvement. ### SExportWithSeriesDB *Remove getObject.* ### MesherActivity *Refactor CGogn and VTK mesher.* - This commit removed dependency to bundle opVTKMesh in opPOCMesher - CGoGNMesher is now a standard ::fwServices::IOperator - Updated MesherActivity config with new VTK/CGoGN mesher API Refactor MesherActivity ### Interactors *Allow adaptors to be an interactor implementation.* This is a first step in the refactor of interactors. We plan to implement interactors directly instead of using the only one SInteractorStyle that instantiates sub-classes. It is actually more complicated than if the interactor does the job directly. In ARPerfusion, we had to create a new interactor to select regions (ARPerfusion!10). We wanted to implement it as an adaptor, which allows us to test if the design works. So we modify the inheritance to allow adaptors to behave as an interactor directly. Consider this as a temporary step in the migration of interactors, where both solutions are possible. Besides this, there are some changes that might seem unrelated but they were necessary for our new interactor. There is a first fix to allow all kind of meshes to be displayed with a SPointList adaptor. Then there is a second commit to fix the cell color textures, which were not correctly fetched from the texture used to store them. sight-23.1.0/CHANGELOG.txt000066400000000000000000001244621450532053500147560ustar00rootroot00000000000000=== fw4spl_0.9.2.3 ( diff from fw4spl_0.9.2.2 ) 10/09/2014 === * Transplanted from fw4spl_0.10.0: * Removed all services working on deprecated data PatientDB * Removed ARLcore dependency in uiMeasurement : load/save landmarks with ioAtoms * Moved Examples, POC and Training to fw4spl-ext repository * Fixed AppConfig::getUniqueIdentifier() * Fixed wrong warning in PushObjectSrv. * Fixed gui doxygen (menuBar and toolBar) * Removed useless notify in TransferFunctionEditor::initTransferFunctions() * General: * Updated fwAtomsPatch and spyLogger according to Boost 1.54 * Removed author field in doxygen * Fixed Mac OS issue with Qt (QTBUG-32789) * Fixed ProfileRunner for Mac OS * Fixed guiQt, SliceCursor and WindowLevel memory leak * Moved gdcmIO, ioGdcm and ioGdcmQt to FW4SPL-ext * Added CMakeLists * Removed useless SelectedNodeIOUpdater service * Core: * Added getConfigDesc in fwServices * Fixed timer asio one shot * Changed SigSevBacktrace log level to ERROR * Fixed PushObjectSrv * Added 'launched' signal to ConfigActionSrv and SConfigLauncher * Added 'updated' signal on Graph and Node * Optimized Graph route * Added SSignal service * Updated template arguments to manage five parameters in fwCom * Fixed fwRuntime compilation on Linux * Added support of ! operator in seshat path (returns a string pointed by the seshat path if possible, the uid otherwise) * Allowed empty string in XML default value. * Memory dump system * Set default streamFactory when buffer's streamFactory was never explicitly set * Fixed buffer lock and buffer streams * Fixed an issue due to some implementations returning a non-NULL pointer for malloc(0) in buffer allocation * Fixed BufferManager and StructureTraits binding * Added getTemporaryFolder in System * IO: * Fixed fwData::Array initialization in vtkGdcmIO/fwVtkIO SeriesDB reader * Fixed zipped json/xml loading * Updated ioAtoms to be able to overwrite a lazy-loaded file * Added custom extensions ability in ioAtoms * Fixed atom custom extension when using JSON/XML backends * UI: * Added a way to configure button state * Fixed relative URLs in uiGenericQt::action::LaunchBrowserActionService * Updated IOSelector to display config's description if applicable * Fixed compilation of DataInfoFromMsgUpdaterSrv * Updated SExportSeries to use an existing activity description or physician name * Added ability to pass parameters in config * Updated Qt MessageDialog to manage a default button * Added several editors and services to propose a new export config * Set SShowAbout to modal * Tools: * Added fwDataTools::TransformationMatrix3D to manipulate ::fwData::TransformationMatrix3D * Removed useless dimension check for medical images * Added lib fwMedDataTools to manage fwMedData UID * Visu: * Added autoRender option in genericScene * Added ability of hidding cropping box by default in visuVTKVRAdaptor::Volume * Added locks in VTK adaptors * Updated VTK text adaptor to manage Seshat path, text alignment and font size * Added patient name in all generic scene. * Patch system: * Fixed fatal when visiting enum object in ::fwDataCamp::visitor::getObject class. * Added medical workspace filtering for MedicalData V2 context * Added ImageSeries and ActivitySeries to fwStructuralPatch * Added resection patching in MedicalData V2 context * Activities: * Added activity validator concept to fwActivities * Added image properties validator * Added new option for SActivityLauncher to define a default association * Made activity launch cancelable * Added a new validator for authorizing activity launching with several series from the same study * Added seshat path ability in activity launcher * UT: * Fixed several compilation issues (b4be6561e715 and 20ff6c2d0cda) * Fixed working directory * Software: * Updated VRRender activities: * 3DVisualisationActivity * blendActivity * volumeRenderingActivity === fw4spl_0.9.2.2 ( diff from fw4spl_0.9.2.1 ) 20/06/2013 === * Transplanted from fw4spl_0.9.1.4.: * Added a getAttribute() template method on fwAtoms/Object. * fixed on fwAtoms/Object attributes and metaInfos * Added version number on atom (see fwAtoms/Base.hpp) * Updated fwCore::SpyLogger to remove logger global severity. * Updated CompareObjects visitor for BufferObject * Created a new library fwAtomsPatch which contains the base interface to transform atoms from a version to an other into a context. * Added a version generator utility to generate .versions files (files used by the patch system). * Added MedicalData patch system to VRRender * Updated ioAtoms reader(SReader)/writer(SWriter) to use the patch system. * Added version on Atom writers/readers(Hdf5 reader/writer and BoostIO writer/reader). * Added test for getAttribute() template method. * General : * Cleaned fwZip: removed old and deprecated class/API, group minizip classes. * 'MediacalData' object version change to V2 * Updated fwData::Reconstruction to version 2 (some attributes have been removed). * Fixed duplicated extension filename in objWriter. * Added atoms_version and writer_version in TF files (json files) * Patch system : * Create patch to transform atoms object into 'MediacalData' context from version V1 to version V2. * V1 uses the fwData PatientDB, Acquisition, etc. * V2 uses the new Data fwMedData ( ModelSeries, ImageSeries, ...) * Added fwStructuralPatch library which contains structural patches. * Added fwMDContextualPatch library which contains semantic patches. * Added patchMedicalData bundle. * Updated VRRender config to use MedicalData patch system. * Added unit test for fwStructuralPatch * Memory dump system * BufferManager, BufferObject and depending classes has been moved to fwMemory library. BufferObject is not self-sufficient anymore : (Re)Allocation/destruction has been delegated to BufferManager. * Updated BufferManager and BufferObject API to allow “lazy loading” and to improve dumped data access : * A BufferObject may be initialised with a ‘stream factory’, allowing to load data in ‘dumped’ or ‘lazy loaded’ state, i.e. the data will be really loaded when needed (for example when the BufferObject is locked) * When a buffer has been lazy-loaded or dumped by the buffer manager, an internal structure stores information about the dumped state : the filesystem path of the data (if applicable), and the format of this file (if applicable). This can be useful to reuse filesystem data if needed. For example, fwAtomsBoostIO’s writer creates hardlinks to these files when possible. * If a BufferObject user need an access to the data, it is possible to get a stream to it, regardless of and without changing the buffer state. For example, fwAtomsBoostIO’s Writer use this mechanism to copy data from buffers when a BufferObject is not dumped or the dumped file do not have a compatible format for hardlinking. * fwMemory has been made thread-safe : * Buffer management runs in a dedicated thread * BufferManager has an asynchronous API, based on boost::shared_future * Naive factories has been updated to fwCore's one * IO * Added DICOM LazyReader in vtkGdcmIO. * Added VTK/VTI Lazy Image Reader in fwVtkIO. * Added lazy ability to json(z)/xml(z) data Reader in fwAtomsBoostIO. * fwAtomsBoostIO : fixed archive buffer filename and archive's buffers dir name * A new name for each buffer is generated in order to avoid to have several buffer using the same file name. * The postfix -json or -xml has been appended to buffers dir name, to avoid data overwrite when saving to archive in the same place with the same name but with a different base format. * UI * Added an example of asynchronous UI in DumpEditor using QFutureWatcher === fw4spl_0.9.2.1 ( diff from fw4spl_0.9.2.0 ) 23/05/2013 === * Merging * Merge from tag fw4spl_0.9.1.2 * Data : * Removed PatientDB/Patient/Study/Acquisition/Dictionary/DictionaryOrgan data. Removed Acquisition/Patient/PatientDB msgs. * Cleaned fwData::Reconstriction attributes * NewSptr() is depracted, use now only New() * Fixed deep copy bugs (multiple references to the same data, recursive data) and updated all data * Fixed fwMedDataCamp camp introspection for ImageSeries and Series * Moved ActivitySeries camp binding (from fwActivitiesCamp to fwMedDataCamp) * few changes in fwAtoms API : add factory, renamed Map and Sequence const iterators and added typedef, fixed all clone methods * IO : * Removed fwXML and ioXML * Added ImageSeries and ModelSeries writers/readers in vtkIO or itkIO : * read : .vtk, .vti, .mhd, .inr * write : .vtk, .vti, .mhd, .obj, .inr, .jpg * Updated ioGdcm to support fwMedData ( and fix few old problems ) * Updated fwAtomConversion to support several UUID management policies : when you convert an atom to a data, if the uuid object already exists in application, you can abort the process, you can re use the object or you can generate another uuid * Replace specific atoms reader/writer. Added ioAtoms SReader and SWriter services ( these services work on ::fwData::Object and support 'inject' mode). Removed SMedDataReader and SMedDataWriter services. * Fixed fwAtomsBoostIO issue when hiting a cache value stored in a Atoms::Map, added unit tests * General : * Updated fwAtomConversion: getSubObject() throw exceptions or null object if path is not valid ( data introspection ) * Added macro FW_FORWARD_EXCEPTION_IF(ex, cond) * Added ConfigLauncher helper to centralize management of AppConfig * Added new service SConfigLauncher, updated SConfigController * Updated SActivityLauncher to be able to launch directly a standalone activity. * Software : * Update all Tutorial, all Examples and all PoC to support last modifications * Update VRRender : * support last modifications * enable some new readers/writers * add dump functionalities and menus to monitor the app * Updated TransferFunctionEditor to save/load TF with ioAtoms. * TU : * Update io unit tests to check new readers/writers * Added fwData/fwMedData objects generators in fwTest * Updated fwDataTools : removed data generators and comparator replace by fwTest generators and fwDatacam::visitor::CompareObject * Updated fwTest::generator::SeriesDB to be DICOM compliant. === fw4spl_0.9.1.4 ( diff from fw4spl_0.9.1.3 ) 18/06/2013 === * General : * Added a getAttribute() template method on fwAtoms/Object. * fixed on fwAtoms/Object attributes and metaInfos * Added version number on atom (see fwAtoms/Base.hpp) * Updated fwCore::SpyLogger to remove logger global severity. * Updated CompareObjects visitor for BufferObject * Patch system : * Created a new library fwAtomsPatch which contains the base interface to transform atoms from a version to an other into a context. * Added a version generator utility to generate .versions files (files used by the patch system). * Added MedicalData patch system to VRRender * IO : * Updated ioAtoms reader(SReader)/writer(SWriter) to use the patch system. * Added version on Atom writers/readers(Hdf5 reader/writer and BoostIO writer/reader). * TU : * Added test for getAttribute() template method. === fw4spl_0.9.1.3 ( diff from fw4spl_0.9.1.2 ) 02/05/2013 === * Data : * Fixed deep copy bugs (multiple references to the same data, recursive data) and updated all data * IO : * Updated fwAtomConversion to support several UUID management policies: when you convert an atom to a data, if the uuid object already exists in application, you can abort the process, you can re use the object or you can generate another uuid * Replace specific atoms reader/writer. Added ioAtoms SReader and SWriter services ( these services work on ::fwData::Object and support 'inject' mode). Removed SMedDataReader and SMedDataWriter services. * Fixed fwAtomsBoostIO issue when hiting a cache value stored in a Atoms::Map, added unit tests === fw4spl_0.9.1.2 ( diff from fw4spl_0.9.1.1 ) 10/04/2013 === * General : * Fixed bugs in ConfigActionSrv * Added macro FW_FORWARD_EXCEPTION_IF to forward an exception on certain conditions * Added new bundles (monitor, monitorQt) to monitor system * Added new bundle (ctrlMemory) to provide services to dump lock data * Added new service (uiPatientDB::action::AddMedicalWorkspace) to load and merge medical workspaces * Updated VRRender 0.9.5 : add dump functionality, menus to monitor the app, import/export medical workspace * Data introspection : * Moved ::fwAtomConversion::RetrieveObjectVisitor to ::fwDataCamp::visitor::GetObject * Updated fwDataCamp::Object to bind 'isA' method * Added new visitor (RecursiveLock) to lock (mutex) data recursively * Added new visitor (CompareObjects) to compare two data objects * Added exception management and unit tests * Atoms : * Refactoring of fwAtoms : * cleaning, bug fixing, API updating (added const accessors), unit tests * added factory to build atoms * fixed all clone methods * updated atom visitor to not use camp to visit atom * Refactoring of fwAtomConversion : * removed useless visitors * proposed new conversion methods between fwData::Object and fwAtoms::Object * fixed graph conversion * added exception management and unit tests * managed null pointer in atoms * improved numeric conversion * fwData : * Removed deprecated fwData::None * Added tetra cell type for fwData::Mesh * Managed acquisition 'NetID' in deepCopy/shallowCopy * IO : * Added new library fwAtomsBoostIO to read/write atoms using Boost Property Tree. * Added new bundle ioAtoms to provide services for reading/writing medical data using fwAtomsBoostIO. * Managed zip and folder archive in fwZip * Added BufferObject comparison unit test in fwAtomsBoostIO * Managed dumped buffers during saving * Changed dump policy during medical data loading (set to 'barrier' if policy is 'never'). * Added unit tests for fwAtomsBoostIO and ioAtoms * Log : * Improved logs for 'receive' method in ::fwServices::IService * Communication : * Removed deprecated MODIFIED_KEYS event in fwComEd::CompositeMsg === fw4spl_0.9.2.0 from begin of the branch 12/02/2013 === * Data: * Few fwData class are deprecated : PatientDB, Patient, Study, Acquisition * Created a new library fwMedData to store structures for medical data. * Added structures to store Patient, Study, Series and Equipment information. * Added a type of data called Series ::fwMedData::Series. It aggregates information (Patient, Study, Series, Equipment, etc) related to a data set. * Added ImageSeries data (inherit from Series) which stores an image. * Added ModelSeries data (inherit from Series) which stores a set of reconstructions. * Added structure to store a set of ::fwMedData::SeriesDB series. It provides basic STL container API. * All new fwMedData data structures are wrapped with camp. * Added Tetra cell type management for fwData::Mesh ( update vtk adaptor to show it ) * Removed deprecated fwData::None * Core: * Added the concept of activity (fwActivities library). * Added new factory for fwActivities. * Added a default builder for the data ActivitySeries. * Bundle: * Created a bundle 'activity'. It contains * a service ::activity::SLauncherActivity to launch an activity. * Created a new bundle 'uiMedDataQt'. It contains * a service ::uiMedDataQt::SSelctor to show information about medical data. * a service ::uiMedDataQt::SExportSeries to export series to an ::fwMedData::ActivitySeries defined in the service configuration. * a service ::uiMedDataQt::SSeriesViewer to view series stored in a vector ::fwData::Vector. * Created a new bundle 'LeafActivity'. It contains * a configuration which allows to visualize medical image in 2D. * a configuration which allows to visualize a mesh and optionally a medical image in 3D. * a configuration which allows to blend two medical images (its also contains a transfert function editor). * a configuration which allows to visualize a volume rendering of image and optionally a mesh. * Added new service ::scene2D::processing::SComputeHistogram to compute histogram for an image. * Communication: * Removed deprecated MODIFIED_KEYS from fwComEd::CompositeMsg event (and support few libraries which still used it) * Added messages SeriesDBMsg, VectorMsg, ModelSeriesMsg on fwComEd library. * Added helpers for SeriesDBMsg, VectorMsg on fwComEd. * IO: * Added a reader ::vtkGdcmIO::SeriesDBReader, based on VTK and GDCM, for loading a SeriesDB from DICOM files. * Added a reader ::vtkIO::SeriesDBReader, based on VTK, for loading a SeriesDB from VTK polydata or image'.vtk' files. * Added a service ::uiIO::action::SSeriesDBMerger to read SeriesDB and merges it with the current SeriesDB. * Software: * VRRender 0.9.6. * Tests: * Added unit tests for fwActivities and fwMedData libraries. * Added unit tests for ::scene2D::processing::SComputeHistogram service. === fw4spl_0.9.1.1 ( diff from fw4spl_0.9.1.0 ) 07/02/2013 === * Merge : * Merge from tag fw4spl_0.9.0.3 to branch fw4spl_0.9.1 * General : * Modify Appconfig xml syntax. "parameters" appConfig type is now required ( "standard" and "template" type are no longer supported ) * Modify Appconfig xml syntax. Replace xml attribute : implementation to impl, autoComChannel to autoConnect. priority tag is no longer supported ( priority is now relative to connection creation order ) * Update Appconfig xml syntax. Add two new xml elements ( to support signal/slot connection ) : and (see Tuto15Multithread AppConfig to see an example) * Update SwapperSrv to support new connection system. Updated SwapperSrv xml syntax to manage and tag. * Fix VRRender application to support new communication system / new xml appConfig syntax * Fix bundles and libraries to support new communication system * Fix applications to support xml appConfig syntax * Fix JpgImageWriter to save jpg instead of png file * Fix some issues, ex : updated BufferManager counter to be thread-safe, permissions issue when deleting temporary folder, some cppcheck warnings ... * Visu : * Updated vtk adaptors : rename doUpdate(msg) by doReceive(msg) and new communication system. * Multithread and communication : * Cleaning communication system : removed ComChannelService, MessageHandler service... * Added Proxy in fwServices. Proxy is an application singleton that provides communication channels. A channel can be connected to a signal. Slots can be connected to a channel. Connection/disconnection can be dynamic during application life. A channel has a forwarder role. * Update Tuto15Multithread with another sub configurations (other examples) * Updated AppconfigManager to manage connect and proxy xml tags in config and to wait for start/stop/update. * Fix IService methods : start, stop, update and swap return a correct shared future in mono thread * Added abstraction level to fwThread's Worker and Timer, implements a Qt and WxWidget version. Updated Tuto15 with new Timer API * Fix ActiveWorkers registry : clear and reset all ActiveWorkers when app stop * TU : * Added tests for fwGuiQt WorkerQt and TimerQt * Fix some unit tests to support new communication system / new xml appConfig syntax * Change gdcm trace output stream for unit tests === fw4spl_0.9.1.0 ( diff from fw4spl_0.9.0.2 ) 29/11/2012 === * Thread: * Created new fwThread library that provides few tools to execute asynchronous tasks on different threads. * Created fwThread::Worker. This class creates and manages a thread. Thanks to the post method it is possible to execute handlers on. * Created fwThread::TaskHandler. This class encapsulates packaged task and it is used to post easily a task on a worker * Created fwThread::Timer. The Timer class provides single-shot or repetitive timers. A Timer triggers a function once after a delay, or periodically, inside the worker loop. The delay or the period is defined by the duration attribute. * Communication: * Added new fwCom library. This library provides a set of tools dedicated to communication. These communications are based on Signal and slots concept (http://en.wikipedia.org/wiki/Signals_and_slots). fwCom provides the following features : * function and method wrapping * direct slot calling * asynchronous slot calling * ability to work with multiple threads * auto-disconnection of slot and signals * arguments loss between slots and signals * fwCom::Slot is wrappers for a function or a class method that can be attached to a fwThread::Worker. The purpose of this class is to provide synchronous and asynchronous mechanisms for method and function calling. * fwCom::Slots is a structure that contains a mapping between a key and a Slot * fwCom::HasSlots manages a fwCom::Slots * fwCom::Signal allows to perform grouped calls on slots. In this purpose, Signal provides a mechanism to connect slots to itself. * fwCom::Signals is a structure that contains a mapping between a key and a Signal * fwCom::HasSignals manages a fwCom::Signals * The connection of a Slot to a Signal returns a Connection handler. Connection provides a mechanism which allows to temporarily disable a Slot in a Signal. The slot stays connected to the Signal, but it will not be triggered while the Connection is blocked : * Add new xxx.vrdc file that are parsed by a variadic_parser (fwCom/scripts/variadic_parser.py) to generate some hpp/hxx files (manipulation of template). * fwData: * Updated Object to inherit of HasSignal * all objects have a signal objectModifiedSig to emit object modification * fwServices: * IService: * Updated IService to have an associated worker and thus an associated thread * Updated IService to inherit of HasSignal and HasSlots * Updated IService to remove old communication system * Updated IService to rename update(msg) to receive(msg) * Added slots start, stop, receive, update, swap on IService. If these methods (receive excepted) are not call in thread associated to the service, the slot version is called. * Add IService::getObjSrvConnections method to propose signal/slot connections between a service and his associated object * Add new structure ActiveWorkers to register worker in f4s * Added macros for notification: fwServicesNotifyMsgMacro and fwServicesBlockAndNotifyMsgMacro * Modify IEditionService::notify to use this macros. * Log: * Add fwID::getLightId method used for log * Initialized spylog in fwTest, to enable logs within unit tests * Add communication info message, messages are enable if you define COM_LOG when you compiling f4s * Tutorials: * Create new tutorial Tuto15MultithreadCtrl that contains a few multithread examples. === fw4spl_0.9.0.3 ( diff from fw4spl_0.9.0.2 ) 11/12/2012 === * General : * Change default transfert function for Muscles and Skin * Add a new action AnonymisePatient to anonymise selected patient in PDB * Add new organ to dictionary Lymph Node * Fix OrganDictionary (re add World key). Add also few liver segment keys * Fix JpgImageWriter to save jpg instead of png file * Fix crash when using manage organ editor === fw4spl_0.9.0.2 ( diff from fw4spl_0.9.0.1 ) 02/11/2012 === * General: * renamed fwMetaData library to fwAtoms * few fixes, refactoring * Editor: * PatientDBGuiSelectorService: now it is possible to erase an acquisition OR a patient (with key del) * PatientDBGuiSelectorService: image comment edition is now possible from mouse double-clicking on item * Log: * Update application log: check if default log dir is unreachable before create log file === fw4spl_0.9.0.1 ( diff from fw4spl_0.9.0.0 ) 28/09/2012 === * Merge: * Merge from tag fw4spl_0.8.3.6 * General: * /!\ Removed WxWidgets support in f4s apps (preserved in TutoGui) * /!\ Removed old factory in fwTools * Code cleaning: fix compilation, removed unused code, added missing include, removed verbose logging, added missing export * Add new service ::fwServices::SConfigController to manage AppConfig without using an action * Add new introspection tool in fwMetaConversion to find a subOject from an object and a path. * ConfigActionSrvWithKeySendingConfigTemplate uses now data reflection to find tabPrefix and tabInfo * Fixed fwData::factory::New (register attributes on fwData::Object) * Fixed conflicts with python tolower define * Fixed AnonymiseImage (doesn't duplicate images) * Fixed PatientDBGuiSelectorService : doesn't re-set image label if it exists * Fixed opSofa compilation * Updated opsofa : Replaced EulerImplicitSolver by EulerSolver. * Log : * Updated launcher to parse options with boost program options ( added log options, added Bundle dir and runtime directory options ) * IO : * Catched exception in mesh reader service to prevent bad file format error. * Added reader inject mode in IOSelectorService to add an object in a composite * Updated SPatientDBInserter : allows user to enter a comment on image * Data introspection * Added fwCamp Library, this library is used to introspect fwData * Added Mapper for camp unsupported basic types * Added fwData binding in new library fwDataCamp * Added fwTools Buffer Object inplace binding * Added new meta data in new library fwMetaData * Added new library fwMetaConversion to convert fwData <-> fwMetaData Library. * Visu : * Added SDrop service and drag and drop support in GenericScene * Updated NegatoMPR : fixed red cross bug * New multi thread safe factories : * Added new factory for IObjectReader and IObjectWriter and update readers/writers to use it * Updated fwCommand : doesn't need to use factory * Added new factory for fwXML * Added new factory for VtkWindowInteractor and updated visuVTKQt to use it * Added new factory for fwMetaConversion * Added new factory for fwCamp * Added new factory for Gui objects and updated fwGuiQt/fwGuiWx to use new factory === fw4spl_0.8.3.6 ( diff from fw4spl_0.8.3.5 ) 26/09/2012 === * General * Fixed invalid free in fwRenderVTK/vtklogging.cpp * Code cleaning : Removed several warnings, unused file, missing export * Fixed small bug in AppConfigManager when starting and stopping ComChannels * Fixed small bug in fwservice/ObjectMsg.cpp when subject has expired * Added dynamicConfigStartStop attribute configuration in guiQt/editor/DynamicView.cpp * 2D Scene * 2D scene adaptor can now manage sub adaptors * Vector fields * Updated fwData::Image to allow multi-components images * Added VectorField Adaptor example and TutoVectorField === fw4spl_0.9.0.0 ( diff from fw4spl_0.8.3.5 ) 26/07/2012 === * General : * Fixed few compilation warning * Updated uuid generation using boost::uuid * Added Thread helper to be used for unit test * Removed old fwTools::Singleton * Removed unused XMLSubstitute * Removed unused RootManager * Disable _( macro to avoid conflict with boost and replace _( by wxGetTranslation( * Now, it is not possible to create an ::fwData::Object * Log : * Added OSLM _LOG macro * Changed log backend: log4cxx to boost.log * Updated Spylog default configuration * Fixed build errors with new spylog macros (mostly missing ';'). * Moved SpyLog in fwCore::log namespace * Mutex : * Removed old mutex in fwData::Video * replace interprocess mutex by fwCore::mt::Mutex * Added mutex typedef in fwCore * Added helpers to lock fwData::Object for multi-threading * Factories : * Added FactoryRegistry and LazyInstantiator & UT * Updated fwData to use fwCore/util factory registry * Refactoring all data you must have specific constructor * Updated ServiceFactory to use fwCore/util Instanciator and to be thread safe * Refactoring all services constructors/destructor must become public * Added new message factory * Updated ActionNotifyService : used new message factory * Updated ctrlSelection to use new data and message factories * Thread-safe : * Updated fwServices Config to become thread safe * Updated AppConfigParameters to become thread safe. * Updated fwServices AppConfig to become thread safe. * Updated fwID to become thread safe. * Updated UUID to become thread-safe. * Updated IBufferManager to become thread-safe === fw4spl_0.8.3.5 ( diff from fw4spl_0.8.3.4 ) 26/07/2012 === * General : * improved msvc2010 compatibility * Application configuration : * Add new type of app config : parameter, this type of config permits to declare template parameter and his default value. * System manages now new extension point AppConfigParameters * AppXml can use now a paremeter set to launch a config thanks to new extension point AppConfigParameters * Service configuration : * Updated fwRuntime and fwServices to accept boost property tree as configuration objects. The current implementation actually converts ptrees to ConfigurationElement and vice versa, but is fully functional. * Added examples to show how to use a ptree to configure a service from c++. * Added examples to show how to parse a service configuration with a ptree. * Scene 2D : * Fixed bug in scene 2d to manage better composite key removing * Fixed scene 2D adaptor stopping : srv configuration was lost and zvalue was not correct after call swap (stop/start) * Scene 2D adaptor can now manages sub adaptors * Add new adaptor to interact with the viewport in 2D scene (zoom, translation) * Fixed negato adaptor, it was not his job to manage zoom and translation in the view * ARLcore : * ARLcore now use fw4spl pointer * Added unit tests === fw4spl_0.8.3.4 ( diff from fw4spl_0.8.3.3 ) === * General : * Remove some warnings : type conversion, useless exports, ... * Fixed NumericRoundCast (wrong type) and add unit test * Added fwTools::os::getEnv method * Fixed zip file path creation * Updated AppConfig : 'type' attribute is not required anymore in xml files for 'service' tag, but must be consitent with 'implementation' attribute * Data : * Modified the fwData::Camera class adding the skew and distortion coefficients. * UI : * Fixed OrganListEditor when reconstructions are removed * Fixed a crash when a message dialog is shown without icon * WindowLevel now uses floating precision to compute range width * ImageTransparency : fixed focus on visibility checkbox (use QAction to set shortcut) * IO : * Fixed InrPatientDBReader problem, now it is possible to select a folder which contains inr images * Visualization : * Updated NegatoWindowingInteractor to parse TF config * Updated transfer function helper : use image window width/center to create TF * Add config option in Window Level editor to use image grey level tf instead of create new tf * Python : * python management of Image.size .spacing .origin as python list * Added handler for python outputs * Binding Image::deepCopy === fw4spl_0.8.3.3 === * General : * Refactoring of fwService, now an IService work on a fwData::Object (instead of fwTools::Object) * Disabled Qt keyword (avoid conflicts with boost signals and foreach) * Continue adding array lock ( or image/mesh lock helper ) in different libs/bundles * Fixed AppConfig (adaptField if cfg element value is not empty) * Updated temporary folder management * Refactoring of AppConfigManager to be more easily extended * Added ByteSize object and unit tests : this class manages conversion between string and size_t * Updated MenuLayoutManager to allow setting icon for actions in menu * Added new service to substract two images SImagesSubstract * Apps : * Added Ex04ImagesRegistration which subtract two images with itk * Updated Ex02ImageMix with TF selection * Visualization : * Fixed clipping plane visualization on meshes * Fixed ImagesProbeCursor, manage now image origin * Fixed ProbeCursor (problem with view reset) * Fixed shakeNormals when array is null * Updated Volume adaptor to support TF nearest mode * Fixed RemoveDistance action * Fixed ImageMultiDistances adaptor * Fixed PlaneXMLTranslator (compute plane from points) * Data : * Updated Reconstruction, Mesh, Image, and Array API to be compatible with new dump system to maniplate a buffer, you must used Mesh/Image/Array helper (in fwComEd/helper) * Updated Image and Mesh helpers * Removed fwData::Image::setDataArray (keep existing data::Array in Image) * Fixed Array deepCopy (copy array informations if buffer is empty) * Added swap on fwData::Array * Some evolution in ObjectLock : keep object reference, added copy constructor and operator implementation * Updated Array : array is buffer owner on creation * Updated Image, Mesh : not New on array when deepCopy or clear * BufferObject / IBufferManager : * Added documentation * Added swap on fwTools::BufferObject * Added fwTools::Exception on BufferAllocatePolicy allocate/reallocate * Dump management : * Added documentation * Introduced hysteresis offset in fwMemory::policy::ValveDump * Updated fwMemory Policy API : added policy factory, added setParam API on dump policies * Added service : SDumpService will help to configure the dump policy * Fwxml writer does not restore dumped image during serialization, just copy dumped file * Try to hard link raw file instead of copy to serialize patient folder * Fixed barrier limit to max(freeMemory/2, aliveMemory, 512Mo) during serialization * IO : * Updated fwXML FileFormatService system ( is not used in a separated process ) * FileFormatService is now called directly in ArrayXMLTranslator * Updated ImageXMLTranslator and MeshXMLTranslator to use Array::swap method * Fixed ResectionXMLTranslator (read "isValid" element) * Test : * Changed some namespace in different unittest libraries === fw4spl_0.8.3.2 === * General : * Fixed clang/icc compilation * Fixed import fxz (fields in few structures were not managed). * Fixed ImagesBlend Adaptor when there is twice the same image * Fixed selected acquisition index in PatientDBGuiSelectorService * New service SPatientDBInserter (io::IWriter type) that permits to push a structure (patientDB, patient, study, acquisition or image) in a patientDB. If destination pdb is not configured, a dialog box proposes to select a pdb from an active pdb list ( pdb registered in OSR ) * Added helper to compare float/double value with 'epsilon' error margin (fwMath/Comapre.hpp) and Update ImageBlend Adaptor to use it * Inactivated minimized mode (in preference) for frames * Update compression level for raw buffer ( low compression, hight speed ) * Apps : * Added new example Ex01VolumeRendering to show different services that use or manipulate a TF * Added new example Ex03Registration to show a registration between points by using ARLCore. * Transfert function : * Fixed issue with TransferFunctionEditor * Fixed issue with last table color in fwVtkWindowLevelLookupTable * Complete refactoring of TransferFunction adaptor (scene2D) to support now new TF structure ( manage NEAREST interpolation, manage clamping, manage negative window * Support new TF structure for PoC06Scene2DTF * Added TransferFunction helper to create a drawing TF * BufferObject / IBufferManager * Added fwTools::BufferObject : Base class for FW4SPL buffers. Keep a pointer to a buffer and it's allocation policy (new or malloc) without any cleverness about allocating/destroying the buffer. Users of this class needs to take care about allocation and destruction by themselves. BufferObject class has a BufferManager and Locks mechanism, Allowing to trigger special treatments on various events on BufferObjects (allocation, reallocation, destruction, swapping, locking, unlocking) (see doxygen for more information). * Added fwTools::IBufferManager : Provides interface for a buffer manager. A BufferManager is able to hook BufferObjects actions an to change it's behaviors. (see doxygen for more information) * Updated fwData::Array to use fwTools::BufferObject * Added new helper fwdata::ObjectLock : a simple helper to lock specific object, manages : Image, Mesh, Array, Reconstruction and Acquisition. * Removed few critical methods of basic structures (fwData::Array, fwData::Mesh and fwData::Image) according to buffer lock mecanism. These methods are now proposed by helpers (fwComEd::helper::Array, fwComEd::helper::Mesh, fwComEd::helper::Image) and manage buffer lock process. * Support buffer lock process in many helpers/services ( MeshGenerator, vtk conversion, itk conversion, serialization, etc ) * Dump management * Added an implementation of fwTools::IBufferManager with fwMemory::BufferManager : This implementation purpose is to manage memory load, freeing memory and restoring freed buffers as needed. A dump policy is used to trigger memory freeing process. The restore process is always triggers when a lock is requested on a dumped buffer. Available policies : * NeverDump : This policy will never take the initiative to free memory. This is the policy used when no automatic memory management is wanted. Memory will be dumped on demand. * AlwaysDump : This policy will dump buffers as often as possible. As soon as a buffer is released (ie the lock count become zero), it will be dumped. * BarrierDump : This policy defines a memory usage barrier and will try to keep the managed buffers memory usage under this barrier. * ValveDump : This policy is monitoring system memory usage and will trigger memory dump when the amount of system free memory is lower than the minFreeMem parameter. An hysteresis parameter exists to free more memory when the process is triggered. If the free system memory amount is lower than the minFreeMem, this policy will try to reach minFreeMem + hysteresisOffset bytes of free memory. * Updated darwin memory tool : take in account inactive memory as free memory * Activate BarrierDump during fwXML serialization if fwMemory::BufferManager with NeverDump policy is used. === fw4spl_0.8.3.0 === * New field API structure for data : * Remove old field API on fwTools::Object ( impact on all fwData::Object / IService / ObjectMsg / etc ) * Add new field API on fwData::Object * New transfert function structure : * Remove old transfert function structure * Add new transfert function structure : * a transfert function has its own window level * window can be negative or null * transfert function associate a value in double to a RGBA color * Added reimplementation of vtkWindowLevelLookupTable, fwVtkWindowLevelLookupTable ( in fwRenderVTK ) managing negative window and out-of-range value clamp * Method to convert a ::fwData::TransferFunction to vtk lookup table are added in vtkIO::helper::TransfertFunction * It's possible now for negato or volume rendering or window level interactor to work only on a specific transfert function * All image messages concerning window/level or transfer function has been removed, no messages are send directly on the tf * Evolution of ::fwDataTools::helper::MedicalImageAdaptor to provide some helpers to manipulate transfer function in your service * Other : * Add new macros API to generate getter/setter for fwData * fwDataGetSetCRefMacro( Param, Type ) generate : * const Type & getParam() const; * void setParam( const Type & attrParam ); * User must declare Type m_attrParam; * fwDataGetSetSptrMacro( Param, Type ) generate : * Type getParam() const; * void setParam( Type attrParam ); * User must declare Type m_attrParam; * fwData introduces new macro to register data in factory fwDataRegisterMacro ( ex : fwDataRegisterMacro( ::fwData::Image ) ) instead of REGISTER_BINDING_BYCLASSNAME * fwData provides a new factory helper (::fwData::Factory) to build ::fwData::Object, use it instead ::fwTools::Factory to build class of type ::fwData::Object * Support change in fwXML, and thus increment .yaf version (3->4) to support new structures (old yaf version are not compatible) * Move ObjectGenerator/ObjectComparator from fwXML unit test to fwDataTools to merge helper to create and compare data * Moved data visitors from fwData to fwXML * New API and events on ObjectMsg (ADDED/CHANGED/REMOVED FIELDS) * Updated CompositeMsg API ( xxx_FIELDS -> xxx_KEYS ) * New Field helper : as for composite helper, build a message with fields modifications * New Field Manager : Works the same way as the composite helper, but for fields === fw4spl_0.8.2.3 === * General : * Added new helper fwTools::Type to manage different system type * Image structure refactoring * Replaced IBufferDelegate by ::fwData::Array * fwTools::Type to define the image type * Support new image structure in the system * Improve origin image management : reader/writer, visualization 2D/3D/VR, pipeline, registration, resection * Fixed libxml memory management (source of different problems in VRMed) * Updated ImagesBlend adaptor to check if images have the same size, spacing and origin. Show a message dialog if image have not same size, spacing or origin. Added tolerance for spacing and origin comparison * Modified Pulse dialog to work when guiQt is disable * Add new function in class Array to setBuffer with all parameters instead of allocating it * Updated API to convert itk image to or from a fwData image (fwItkIO), updates unit tests * Added CDATA section parsing in xml app configuration ( used by python tuto ) * Clean code: removed depreciated USE_BOOST_REGEX define in dateAndTime helpers * Fixed libxml call to xmlCleanupParser (see http://xmlsoft.org/html/libxml-parser.html#xmlCleanupParser) * IO : * Evolution of patient folder version, now is v3 and replace fwXML archive default extension .fxz by .yaf to avoid user problem * IWriter/IReader refactoring, these classes propose now new API to regroup common source code * Added some unit tests and fixed few io problems * Added ioBasic to read/write .bio file * Reintroduced bad management of rescale data with gdcm * Testing : * Added some unit test on bundles (io) * Added some unit test on lib (io) * Added fwDataTools::Image to generate and test image and added unit test * Added new project fwTest that propose few helpers used in different UT ( for example management of data path ) * Added helper in fwTest to check patient struct after a dicom file parsing to regroup test concerning dicom format e sptr ) * Updated object comparator/generator in fwDataTools for test * Apps : * Updated Tutorials build.options : disable wx on osx64 * Updated TutoDevForum : use new image API and use generic gui * Added a basic python code usage sample with TutoPython * Added new tuto dedicated to fw4spl beginner training === fw4spl_0.8.1.2 === === fw4spl_0.8.0.0 === sight-23.1.0/CMakeLists.txt000066400000000000000000000402501450532053500154560ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.19) # Use new policy for 'install_name' and RPATH on macOS (use `cmake --help-policy CMP0068` for details) cmake_policy(SET CMP0068 NEW) # Use new policy for `FindOpenGL` to prefer GLVND by default when available on linux. # (use `cmake --help-policy CMP0072` for details). cmake_policy(SET CMP0072 NEW) # Use new policy for 'Honor visibility properties for all target types'. # (use `cmake --help-policy CMP0063` for details) cmake_policy(SET CMP0063 NEW) # Adds support for the new IN_LIST operator. cmake_policy(SET CMP0057 NEW) # Use new policy to use CMAKE_CXX_STANDARD in try_compile() macro cmake_policy(SET CMP0067 NEW) # Use old policy for Documentation to add cache variables and find VTK documentation dependent packages. # (Needed for doxygen..) cmake_policy(SET CMP0106 OLD) # Use new policy for CMAKE_MSVC_DEBUG_INFORMATION_FORMAT cmake_policy(SET CMP0141 NEW) if(${CMAKE_VERSION} VERSION_GREATER "3.25.0") # Transform the ``DEPFILE`` after running the custom command for Ninja generator. cmake_policy(SET CMP0116 OLD) endif() # On Windows, if the user doesn't specify a value, # 'CMAKE_BUILD_TYPE' is automatically initialized to 'Debug' after 'project()'. # So we need to check this variable at this point. set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Choose the type of build, options are: Debug, Release, RelWithDebInfo" ) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug;Release;RelWithDebInfo") if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug" AND NOT CMAKE_BUILD_TYPE STREQUAL "Release" AND NOT CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo" ) message( FATAL_ERROR "Invalid value for CMAKE_BUILD_TYPE: '${CMAKE_BUILD_TYPE}' (required Debug, Release, RelWithDebInfo)" ) endif() project( sight VERSION 23.1.0 DESCRIPTION "Surgical Image Guidance and Healthcare Toolkit" HOMEPAGE_URL "https://git.ircad.fr/sight/sight" ) if(APPLE) message(FATAL_ERROR "macOS is not supported.") endif() enable_testing() include(CheckVariableExists) include(CMakeParseArguments) include(GNUInstallDirs) include(CMakePackageConfigHelpers) option(SIGHT_ENABLE_PCH "Use pre-compiled headers to speedup the compilation" ON) option(SIGHT_VERBOSE_PCH "Display debug messages to help debugging PCH" OFF) mark_as_advanced(SIGHT_ENABLE_PCH) mark_as_advanced(SIGHT_VERBOSE_PCH) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/build/flags.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/build/macros.cmake) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/build/pch.cmake) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/build/linux/modules) # We find VTK to know its version so we can enable PCL or not find_package(VTK CONFIG QUIET REQUIRED) ######################################################################################################################## # User options ######################################################################################################################## # Tests build / run options option(SIGHT_BUILD_TESTS "Configures projects associated tests (Test projects)" ON) option(SIGHT_TESTS_XML_OUTPUT "Tests will generate an xml output, suitable for CI integration" ON) mark_as_advanced(SIGHT_TESTS_XML_OUTPUT) set(SIGHT_TESTS_FILTER "" CACHE STRING "Allows to only build/run tests whose path contains the filter string.") mark_as_advanced(SIGHT_TESTS_FILTER) if(UNIX) option(SIGHT_ENABLE_GDB "Test scripts will attach GDB, allowing to generate core file and print backtrace in case of crash." OFF ) mark_as_advanced(SIGHT_ENABLE_GDB) if(SIGHT_ENABLE_GDB) find_program(GDB NAMES "gdb" REQUIRED) endif() endif() # Use clang-tidy linter option(SIGHT_ENABLE_CLANG_TIDY "Enable Clang Tidy checks" OFF) mark_as_advanced(SIGHT_ENABLE_CLANG_TIDY) if(SIGHT_ENABLE_CLANG_TIDY) # cmake-lint: disable=C0301 find_program(CLANG_TIDY NAMES "clang-tidy" "clang-tidy-14" REQUIRED) set(CMAKE_CXX_CLANG_TIDY ${CLANG_TIDY};--use-color;--export-fixes=.clang-tidy-fixes.yaml) # Also generate compile_commands.json which is useful when launching clang-tidy by "hand" set(CMAKE_EXPORT_COMPILE_COMMANDS ON) endif() # QML_IMPORT_PATH allows qtCreator to find the qml modules created in our modules set(QML_IMPORT_PATH "" CACHE STRING "Path of the Qml modules." FORCE) mark_as_advanced(QML_IMPORT_PATH) if(CMAKE_CONFIGURATION_TYPES) set(CMAKE_CONFIGURATION_TYPES ${CMAKE_BUILD_TYPE} CACHE STRING "List of supported configurations." FORCE) endif() # Allow to use an encrypted log option(SIGHT_ENABLE_ENCRYPTED_LOG "Allow log encryption" OFF) # Defines the default hardcoded password. The password itself will be obfuscated during build process, it will not # appear in "clear" text in the final binary. set(SIGHT_DEFAULT_PASSWORD "" CACHE STRING "Default password to use for encryption (log, preferences, session, ...).") mark_as_advanced(SIGHT_DEFAULT_PASSWORD) # Add global compile definitions because of precompiled headers if(SIGHT_ENABLE_ENCRYPTED_LOG) add_compile_definitions(SIGHT_ENABLE_ENCRYPTED_LOG) endif() if(SIGHT_DEFAULT_PASSWORD) add_compile_definitions(SIGHT_DEFAULT_PASSWORD="${SIGHT_DEFAULT_PASSWORD}") endif() # Use solution folders. set_property(GLOBAL PROPERTY USE_FOLDERS ON) set_property(GLOBAL PROPERTY AUTOGEN_TARGETS_FOLDER automoc) # Make openvslam optional on Linux if(NOT MSVC) option(SIGHT_ENABLE_OPENVSLAM "Enable OpenVSLAM" OFF) endif() # Make Realsense optional option(SIGHT_ENABLE_REALSENSE "Enable RealSense" OFF) # Make samples/tutorials build optional option(SIGHT_BUILD_EXAMPLES "Build examples and tutorials" ON) option(SIGHT_BUILD_MANPAGES "Generate man pages for applications" OFF) ######################################################################################################################## # Warn user of install dir isn't empty ######################################################################################################################## file(GLOB_RECURSE INSTALL_DIR_CONTENT ${CMAKE_INSTALL_PREFIX}/*) list(LENGTH INSTALL_DIR_CONTENT CONTENT) if(NOT CONTENT EQUAL 0) # DIR isn't empty, warn user. message(WARNING "CMAKE_INSTALL_PREFIX (${CMAKE_INSTALL_PREFIX}) isn't empty." "Please select another folder or clean it before running install command." ) endif() ######################################################################################################################## # External libraries management ######################################################################################################################## set(FWCMAKE_RESOURCE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/) # Append our 'FindPackages.cmake' to CMAKE_MODULE_PATH list(APPEND CMAKE_MODULE_PATH ${FWCMAKE_RESOURCE_PATH}/modules) if(UNIX) list(APPEND CMAKE_PREFIX_PATH ${FWCMAKE_RESOURCE_PATH}/modules) list(APPEND CMAKE_FIND_ROOT_PATH ${FWCMAKE_RESOURCE_PATH}/modules) if(UNIX) list(APPEND CMAKE_PREFIX_PATH /usr/share/OGRE/cmake/modules) endif() set(SIGHT_EXTERNAL_LIBRARIES CACHE PATH "External libraries location") mark_as_advanced(SIGHT_EXTERNAL_LIBRARIES) # Use directly SIGHT_EXTERNAL_LIBRARIES if set, otherwise, download and install sight-deps package # OpenVSLAM is the only package provided by sight-deps if(NOT SIGHT_EXTERNAL_LIBRARIES AND SIGHT_ENABLE_OPENVSLAM) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/build/download_deps.cmake) endif() if(SIGHT_EXTERNAL_LIBRARIES) get_filename_component(ABSOLUTE_SIGHT_EXTERNAL_LIBRARIES ${SIGHT_EXTERNAL_LIBRARIES} REALPATH) set(SIGHT_EXTERNAL_LIBRARIES ${ABSOLUTE_SIGHT_EXTERNAL_LIBRARIES}) unset(ABSOLUTE_SIGHT_EXTERNAL_LIBRARIES) list(APPEND CMAKE_PREFIX_PATH ${SIGHT_EXTERNAL_LIBRARIES}) list(APPEND CMAKE_MODULE_PATH ${SIGHT_EXTERNAL_LIBRARIES}/lib/cmake/) list(APPEND CMAKE_FIND_ROOT_PATH ${SIGHT_EXTERNAL_LIBRARIES}) # To be added into LD_LIBRARY_PATH in our "launch" scripts. set(SIGHT_EXTERNAL_LIBRARIES_LIB_PATH ${SIGHT_EXTERNAL_LIBRARIES}/lib/) endif() endif() # We always need CppUnit, no need to put that in subdirectories find_package(CppUnit QUIET REQUIRED) ######################################################################################################################## # Default paths settings for libraries, modules and resources ######################################################################################################################## set(FW_INSTALL_PATH_SUFFIX "${PROJECT_NAME}") set(SIGHT_MODULE_RC_PREFIX "${CMAKE_INSTALL_DATADIR}/${FW_INSTALL_PATH_SUFFIX}") if(WIN32) set(SIGHT_MODULE_LIB_PREFIX "${CMAKE_INSTALL_BINDIR}") else() set(SIGHT_MODULE_LIB_PREFIX "${CMAKE_INSTALL_LIBDIR}") endif() set(FWCONFIG_PACKAGE_LOCATION lib/cmake/sight) set_property(GLOBAL PROPERTY ${PROJECT_NAME}_COMPONENTS "") # Define the path 'FW_SIGHT_EXTERNAL_LIBRARIES_DIR' used to find external libraries required by our applications set_external_libraries_dir() if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") set(SIGHT_VCPKG_ROOT_DIR "${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/debug") else() set(SIGHT_VCPKG_ROOT_DIR "${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}") set(EXCLUDE_PATTERN ".*/debug/.*") endif() add_subdirectory(libs) add_subdirectory(modules) add_subdirectory(configs) add_subdirectory(activities) add_subdirectory(utils) add_subdirectory(apps) if(SIGHT_BUILD_EXAMPLES) add_subdirectory(tutorials) add_subdirectory(examples) endif() add_subdirectory(3rd-party) ######################################################################################################################## # Export and install targets ######################################################################################################################## # Will export COMPONENTS: list of all available components ordered by dependency (no dependency first). sight_generate_component_list(COMPONENTS) # Create the sightConfigVersion file configure_file(${CMAKE_SOURCE_DIR}/cmake/build/sightConfig.cmake.in ${CMAKE_BINARY_DIR}/cmake/sightConfig.cmake @ONLY) write_basic_package_version_file( "${CMAKE_BINARY_DIR}/cmake/sightConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) # Install a special xvfb-run wrapper script to workaround bugs withe the system xvfb-run launcher script configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/install/linux/safe-xvfb-run ${CMAKE_CURRENT_BINARY_DIR}/bin/safe-xvfb-run COPYONLY ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/install/linux/exec_gui_tests.sh ${CMAKE_CURRENT_BINARY_DIR}/bin/exec_gui_tests.sh COPYONLY ) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/install/windows/exec_gui_tests.bat ${CMAKE_CURRENT_BINARY_DIR}/bin/exec_gui_tests.bat COPYONLY ) # Install the sightConfig.cmake and sightConfigVersion.cmake install( FILES "${CMAKE_BINARY_DIR}/cmake/sightConfig.cmake" "${CMAKE_BINARY_DIR}/cmake/sightConfigVersion.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/macros.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/linux/modules/FindFilesystem.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION} COMPONENT dev ) # install CppUnitConfig.cmake in a modules folder. install(FILES "${CMAKE_SOURCE_DIR}/cmake/modules/CppUnitConfig.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/modules COMPONENT dev ) # Install some files needed for the build install( FILES "${CMAKE_SOURCE_DIR}/cmake/build/configure_file.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/flags.cmake" "${FWCMAKE_RESOURCE_PATH}/build/cppunit_main.cpp" "${CMAKE_SOURCE_DIR}/cmake/build/config.hpp.in" "${CMAKE_SOURCE_DIR}/cmake/build/plugin_config.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/plugin_config_command.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/profile_config.cmake" "${CMAKE_SOURCE_DIR}/cmake/build/profile.xml.in" "${CMAKE_SOURCE_DIR}/cmake/build/registerServices.cpp.in" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/build COMPONENT dev ) # Install some files needed for the install install( FILES "${CMAKE_SOURCE_DIR}/cmake/install/generic_install.cmake" "${CMAKE_SOURCE_DIR}/cmake/install/get_git_rev.cmake" "${CMAKE_SOURCE_DIR}/cmake/install/helper.cmake" "${CMAKE_SOURCE_DIR}/cmake/install/install_imported.cmake.in" "${CMAKE_SOURCE_DIR}/cmake/install/pre_package.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install COMPONENT dev ) if(WIN32) install( FILES "${CMAKE_SOURCE_DIR}/cmake/build/windows/template.bat.in" "${CMAKE_SOURCE_DIR}/cmake/build/windows/template_exe.bat.in" "${CMAKE_SOURCE_DIR}/cmake/build/windows/template_test.bat.in" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/build/windows COMPONENT dev ) install( FILES "${CMAKE_SOURCE_DIR}/cmake/install/windows/package.cmake" "${CMAKE_SOURCE_DIR}/cmake/install/windows/install_plugins.cmake" "${CMAKE_SOURCE_DIR}/cmake/install/windows/template.bat.in" "${CMAKE_SOURCE_DIR}/cmake/install/windows/template_exe.bat.in" "${CMAKE_SOURCE_DIR}/cmake/install/windows/setpath.bat.in" "${CMAKE_SOURCE_DIR}/cmake/install/windows/windows_fixup.cmake.in" "${CMAKE_SOURCE_DIR}/cmake/install/windows/generate_headers.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/windows COMPONENT dev ) install(FILES "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/NSIS.InstallOptions.ini.in" "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/NSIS.template.in" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/windows/NSIS/ ) install( FILES "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/rc/banner_nsis.bmp" "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/rc/dialog_nsis.bmp" "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/rc/app.ico" "${CMAKE_SOURCE_DIR}/cmake/install/windows/NSIS/rc/license.rtf" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/windows/NSIS/rc/ ) install(PROGRAMS "${CMAKE_SOURCE_DIR}/cmake/install/windows/exec_gui_tests.bat" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/windows COMPONENT dev ) elseif(UNIX) install( FILES "${CMAKE_SOURCE_DIR}/cmake/build/linux/template.sh.in" "${CMAKE_SOURCE_DIR}/cmake/build/linux/template_exe.sh.in" "${CMAKE_SOURCE_DIR}/cmake/build/linux/template_test.sh.in" "${CMAKE_SOURCE_DIR}/cmake/build/linux/manpage.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/build/linux COMPONENT dev ) install(FILES "${CMAKE_SOURCE_DIR}/cmake/install/linux/package.cmake" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/linux COMPONENT dev ) install(PROGRAMS "${CMAKE_SOURCE_DIR}/cmake/install/linux/safe-xvfb-run" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/linux COMPONENT dev ) install(PROGRAMS "${CMAKE_SOURCE_DIR}/cmake/install/linux/exec_gui_tests.sh" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/linux COMPONENT dev ) install( FILES "${CMAKE_SOURCE_DIR}/cmake/install/linux/template.sh.in" "${CMAKE_SOURCE_DIR}/cmake/install/linux/template_exe.sh.in" "${CMAKE_SOURCE_DIR}/cmake/install/linux/linux_fixup.cmake.in" DESTINATION ${FWCONFIG_PACKAGE_LOCATION}/install/linux COMPONENT dev ) endif() ######################################################################################################################## # Misc generators ######################################################################################################################## # Doxygen documentation option(SIGHT_BUILD_DOC "Build the doxygen documentation" OFF) if(SIGHT_BUILD_DOC) option(SIGHT_BUILD_DOCSET "Build a Dash/Zeal/XCode docset" OFF) include(${FWCMAKE_RESOURCE_PATH}doxygen/doxygen_generator.cmake) doxygengenerator(${PROJECT_LIST}) if(SIGHT_BUILD_DOCSET) docsetgenerator(${PROJECT_LIST}) endif() else() unset(SIGHT_BUILD_DOCSET CACHE) endif() sight_create_package_targets("${COMPONENTS}" "") sight-23.1.0/COPYING000066400000000000000000001055101450532053500137520ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Sight is: Copyright (C) 2009-2020 IRCAD France Copyright (C) 2012-2020 IHU Strasbourg Contact: sds.ircad@ircad.fr You may use, distribute and copy Sight under the terms of GNU Lesser General Public License version 3. That license references the General Public License version 3, that is displayed below. Other portions of Sight may be licensed directly under this license. ------------------------------------------------------------------------- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . sight-23.1.0/COPYING.LESSER000066400000000000000000000177331450532053500147570ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Sight is: Copyright (C) 2009-2020 IRCAD France Copyright (C) 2012-2020 IHU Strasbourg Contact: sds.ircad@ircad.fr You may use, distribute and copy Sight under the terms of GNU Lesser General Public License version 3, which is displayed below. This license makes reference to the version 3 of the GNU General Public License, which you can find in the COPYING file. ------------------------------------------------------------------------- GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. sight-23.1.0/README.md000066400000000000000000000162551450532053500142050ustar00rootroot00000000000000# Sight | Branch | Status | |--------|-----------| | Dev | [![pipeline status](https://git.ircad.fr/Sight/sight/badges/dev/pipeline.svg)](https://git.ircad.fr/Sight/sight/commits/dev) | | Master | [![pipeline status](https://git.ircad.fr/Sight/sight/badges/master/pipeline.svg)](https://git.ircad.fr/Sight/sight/commits/master) | ## Description [//]: # (cspell: disable) **Sight**, the **S**urgical **I**mage **G**uidance and **H**ealthcare **T**oolkit aims to ease the creation of applications based on medical imaging. [//]: # (cspell: enable) It includes various functionalities such as 2D and 3D digital image processing, visualization, augmented reality and medical interaction simulation. It runs on Microsoft Windows and Linux, is written in C++, and features rapid interface design using XML files. It is freely available under the LGPL. **Sight** is mainly developed by the Surgical Data Sciences Team of [IRCAD France](https://www.ircad.fr), where it is used everyday to develop innovative applications for the operating room and medical research centers. Many **tutorials** and **examples**, which can help you to learn smoothly how to use **Sight**, are located in the `tutorials` and `examples` directories. Detailed steps are described [here](https://sight.pages.ircad.fr/sight-doc/Tutorials/index.html). ### Features - 2D/3D visualization of medical images, meshes, and many widgets. - Import / export medical data from various formats (DICOM, [VTK](https://www.vtk.org/), ...) and sources (files, devices, PACS, ...). - Playing, recording, processing videos (webcams, network streams, Intel RealSense devices, ...). - Easy GUI configuration and customization (XML description and stylesheets support). - Timeline, allowing to store various data (video, matrices, markers, etc...) and synchronize these data across time. - Mono and stereo camera calibration, - [ArUco](https://sourceforge.net/projects/aruco/) optical markers tracking, - [openIGTLink](http://openigtlink.org/) support through client and server services, - Advanced memory management to support large data. Unused data can be offloaded to disk, saving memory for foreground tasks. - Work session or any part of it, can be saved and restored on disk. The data itself can be encrypted using AES256 to ensure a high level of security and privacy ### Hardware / Operating System / Compiler support **Sight** is written in standard C++17 and use [CMake](https://cmake.org/) as its build system, which means that Sight should at least compile on any operating system that provide support for a decent C++17 compiler, CMake, **AND** Sight's dependencies (see [Install](#install) for a list of dependencies for Linux platform). However, we currently have access to a limited set of hardware/OS/compiler combinations where the code is actually tested on a regular basis. Such combination includes: - [Debian 11 stable on AMD64 with GCC 10.2.1](https://www.debian.org/ports/amd64) - [Ubuntu 21.04 on AMD64 with GCC 10.3.0 or CLang 12](https://releases.ubuntu.com/21.04/) - [Microsoft Windows 10 on AMD64 with VisualStudio 2019](https://www.microsoft.com/windows/) > If your platform is not listed, that *doesn't* mean **Sight** will not work, just we cannot guarantee that it is well > tested. If you are on this kind of platform and are able to build and use **Sight**, feel free to share with us your > success ! > We use some fine tuned compiler flags (like `/arch:AVX2`) to optimize and generate code specifically for CPUs that > were released around 2013 and later. It means, if your CPU is too old, **Sight** will crash at runtime because some > CPU instructions are not implemented. In such situation, you can modify hidden cmake variable `SIGHT_ARCH` at > configuring time or modify the default compiler flag directly in **Sight** CMake code. ## Applications ### SightViewer **SightViewer** is a full featured medical image and mesh viewer with advanced rendering features such as volume rendering. It supports most medical image formats, and can also retrieve DICOM files from a PACS. It demonstrates many useful features of Sight.
MPR view of a medical 3D image with additional volume rendering
Volume rendering and transfer function tuning
Volume rendering mixed with 3D surfacic meshes
### DicomXplorer **DicomXplorer** is a simple medical image viewer that can connect to a PACS to retrieve DICOM data. It supports CT-scan and MRI images.
DICOM and medical image files navigation
MPR view of a medical 3D image
### SightCalibrator **SightCalibrator** is a user-friendly application to calibrate mono and stereo cameras. This software is a must-have since camera calibration is a mandatory step in any AR application.
Intrinsic & extrinsic calibration of mono/stereo cameras with live reprojection error display
## Install See [detailed install instructions](https://sight.pages.ircad.fr/sight-doc/Installation/index.html) for Windows and Linux. ## Documentation * [Documentation](https://sight.pages.ircad.fr/sight-doc) * [Tutorials](https://sight.pages.ircad.fr/sight-doc/Tutorials/index.html) * [Doxygen](https://sight.pages.ircad.fr/sight) ## Support Please note that our GitLab is currently only available in read-only access for external developers and users. This is a restriction because of the licensing model of GitLab. Since we use an EE version, we would be forced to pay for every community user, and unfortunately we cannot afford it. This licensing model might change in the future https://gitlab.com/gitlab-org/gitlab-ee/issues/4382 though. Until then, we gently ask our community users to use our GitHub mirror to [report any issues](https://github.com/IRCAD/sight/issues) or propose [contributions](https://github.com/IRCAD/sight/pulls). You can also get live community support on the [gitter chat room](https://gitter.im/IRCAD-IHU/sight-support). sight-23.1.0/activities/000077500000000000000000000000001450532053500150615ustar00rootroot00000000000000sight-23.1.0/activities/CMakeLists.txt000066400000000000000000000001101450532053500176110ustar00rootroot00000000000000add_subdirectory(navigation) add_subdirectory(io) add_subdirectory(viz) sight-23.1.0/activities/io/000077500000000000000000000000001450532053500154705ustar00rootroot00000000000000sight-23.1.0/activities/io/CMakeLists.txt000066400000000000000000000001201450532053500202210ustar00rootroot00000000000000add_subdirectory(dicom) add_subdirectory(dicomweb) add_subdirectory(ioActivity) sight-23.1.0/activities/io/dicom/000077500000000000000000000000001450532053500165635ustar00rootroot00000000000000sight-23.1.0/activities/io/dicom/CMakeLists.txt000066400000000000000000000005361450532053500213270ustar00rootroot00000000000000sight_add_target(activity_io_dicom TYPE MODULE) add_dependencies( activity_io_dicom data io_dimse module_activity module_memory module_data module_ui_base module_ui_qt module_ui_dicom module_io_dicom module_io_dimse module_ui_icons module_service module_viz_scene3d module_viz_scene3dQt ) sight-23.1.0/activities/io/dicom/rc/000077500000000000000000000000001450532053500171675ustar00rootroot00000000000000sight-23.1.0/activities/io/dicom/rc/configurations/000077500000000000000000000000001450532053500222215ustar00rootroot00000000000000sight-23.1.0/activities/io/dicom/rc/configurations/2DLocalPreviewConfig.xml000066400000000000000000000062611450532053500266600ustar00rootroot00000000000000 2DLocalPreviewConfig false false never sight-23.1.0/activities/io/dicom/rc/configurations/2DPacsPreviewConfig.xml000066400000000000000000000057151450532053500265170ustar00rootroot00000000000000 2DPacsPreviewConfig sight-23.1.0/activities/io/dicom/rc/configurations/DicomFiltering.xml000066400000000000000000000176271450532053500256570ustar00rootroot00000000000000 DicomFiltering dicomFilteringActivity/quickstart.pdf action_readDicomSeries/jobCreated action_convertSeries/jobCreated sight-23.1.0/activities/io/dicom/rc/configurations/DicomPacsReader.xml000066400000000000000000000221301450532053500257260ustar00rootroot00000000000000 DicomPacsReader pullSeriesController/progressed progressBarController/updateProgress pullSeriesController/progressStarted progressBarController/startProgress pullSeriesController/progressStopped progressBarController/stopProgress action_pullSeries/clicked pullSeriesController/update sight-23.1.0/activities/io/dicom/rc/configurations/DicomPacsWriter.xml000066400000000000000000000145161450532053500260110ustar00rootroot00000000000000 DicomPacsWriter pushSeriesController/progressed progressBarController/updateProgress pushSeriesController/startedProgress progressBarController/startProgress pushSeriesController/stoppedProgress progressBarController/stopProgress anonymizeController/jobCreated action_anonymize/clicked anonymizeController/update action_pushSeriesToPacs/clicked pushSeriesController/update sight-23.1.0/activities/io/dicom/rc/configurations/DicomPreview.xml000066400000000000000000000047561450532053500253540ustar00rootroot00000000000000 DicomPreview DICOM Preview ${ICON_PATH} dicomPreviewFrame/closed sight-23.1.0/activities/io/dicom/rc/configurations/PacsConfigurationManager.xml000066400000000000000000000035051450532053500276570ustar00rootroot00000000000000 PacsConfigurationManager Pacs Configuration Manager ${ICON_PATH}