diff --git a/.gitignore b/.gitignore index 023f589edc..bfb826b60f 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,4 @@ DesktopEditor/fontengine/js/common/freetype-2.10.4 *_resource.rc .qtc_clangd +Common/3dParty/openssl/openssl/ diff --git a/Common/3dParty/boost/boost.pri b/Common/3dParty/boost/boost.pri index c2c73453c9..e590f9c27d 100644 --- a/Common/3dParty/boost/boost.pri +++ b/Common/3dParty/boost/boost.pri @@ -6,6 +6,14 @@ core_android { CORE_BOOST_LIBS = $$PWD/build/android/lib/$$CORE_BUILDS_PLATFORM_PREFIX } +bundle_xcframeworks { + xcframework_platform_ios_simulator { + CORE_BOOST_LIBS = $$PWD/build/ios_xcframework/ios_simulator/lib/$$CORE_BUILDS_PLATFORM_PREFIX + } else { + CORE_BOOST_LIBS = $$PWD/build/ios_xcframework/ios/lib/$$CORE_BUILDS_PLATFORM_PREFIX + } +} + core_windows { VS_VERSION=140 VS_DEBUG= diff --git a/Common/3dParty/boost/boost_ios.sh b/Common/3dParty/boost/boost_ios.sh index bac8c2b758..6114f9f579 100755 --- a/Common/3dParty/boost/boost_ios.sh +++ b/Common/3dParty/boost/boost_ios.sh @@ -291,8 +291,8 @@ generateOut() $BOOST_SRC/iphonesim-build/stage/lib/libboost_${NAME}.a \ -o $SRCDIR/build/ios/lib/libboost_${NAME}.a - lipo $SRCDIR/build/ios/lib/libboost_${NAME}.a -remove i386 -o $SRCDIR/build/ios/lib/libboost_${NAME}.a - lipo $SRCDIR/build/ios/lib/libboost_${NAME}.a -remove armv4t -o $SRCDIR/build/ios/lib/libboost_${NAME}.a + #lipo $SRCDIR/build/ios/lib/libboost_${NAME}.a -remove i386 -o $SRCDIR/build/ios/lib/libboost_${NAME}.a + #lipo $SRCDIR/build/ios/lib/libboost_${NAME}.a -remove armv4t -o $SRCDIR/build/ios/lib/libboost_${NAME}.a done doneSection diff --git a/Common/3dParty/icu/icu.pri b/Common/3dParty/icu/icu.pri index e84f65dff4..d63020fa5c 100644 --- a/Common/3dParty/icu/icu.pri +++ b/Common/3dParty/icu/icu.pri @@ -27,9 +27,18 @@ core_mac { core_ios { INCLUDEPATH += $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build/include - LIBS += $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build/libicudata.a - LIBS += $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build/libicui18n.a - LIBS += $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build/libicuuc.a + ICU_LIBS_PATH_IOS = $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build + bundle_xcframeworks { + xcframework_platform_ios_simulator { + ICU_LIBS_PATH_IOS = $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build_xc/simulator + } else { + ICU_LIBS_PATH_IOS = $$PWD/$$CORE_BUILDS_PLATFORM_PREFIX/build_xc + } + } + + LIBS += $$ICU_LIBS_PATH_IOS/libicudata.a + LIBS += $$ICU_LIBS_PATH_IOS/libicui18n.a + LIBS += $$ICU_LIBS_PATH_IOS/libicuuc.a } core_android { diff --git a/Common/3dParty/icu/icu_ios.sh b/Common/3dParty/icu/icu_ios.sh index 62458c1b91..7de74b8e1a 100755 --- a/Common/3dParty/icu/icu_ios.sh +++ b/Common/3dParty/icu/icu_ios.sh @@ -199,20 +199,25 @@ function build() { echo "preparing $1 toolchain" - export BUILD_DIR="${PWD}/build-${2}" + export BUILD_DIR="${PWD}/build-${5}" SDKROOT="$(xcodebuild -version -sdk $4 | grep -E '^Path' | sed 's/Path: //')" ARCH=$2 ICU_FLAGS="-I$ICU_SOURCE/common/ -I$ICU_SOURCE/tools/tzcode/ " + IOS_MIN_VER = "-miphoneos-version-min=11.0" + if [ "$4" = "iphonesimulator" ]; then + IOS_MIN_VER = "-mios-simulator-version-min=11.0" + fi; + export ADDITION_FLAG="-DIOS_SYSTEM_FIX" export CXX="$(xcrun -find clang++)" export CC="$(xcrun -find clang)" - export CFLAGS="-fembed-bitcode -isysroot $SDKROOT -I$SDKROOT/usr/include/ -I./include/ -arch $ARCH -miphoneos-version-min=9.0 $ICU_FLAGS $CFLAGS ${ADDITION_FLAG}" - export CXXFLAGS="${CXXFLAGS} -fembed-bitcode -stdlib=libc++ -isysroot $SDKROOT -I$SDKROOT/usr/include/ -I./include/ -arch $ARCH -miphoneos-version-min=9.0 $ICU_FLAGS ${ADDITION_FLAG}" - export LDFLAGS="-fembed-bitcode -stdlib=libc++ -L$SDKROOT/usr/lib/ -isysroot $SDKROOT -Wl,-dead_strip -miphoneos-version-min=9.0 -lstdc++ ${ADDITION_FLAG}" + export CFLAGS="-fembed-bitcode -isysroot $SDKROOT -I$SDKROOT/usr/include/ -I./include/ -arch $ARCH $IOS_MIN_VER $ICU_FLAGS $CFLAGS ${ADDITION_FLAG}" + export CXXFLAGS="${CXXFLAGS} -fembed-bitcode -stdlib=libc++ -isysroot $SDKROOT -I$SDKROOT/usr/include/ -I./include/ -arch $ARCH $IOS_MIN_VER $ICU_FLAGS ${ADDITION_FLAG}" + export LDFLAGS="-fembed-bitcode -stdlib=libc++ -L$SDKROOT/usr/lib/ -isysroot $SDKROOT -Wl,-dead_strip $IOS_MIN_VER -lstdc++ ${ADDITION_FLAG}" mkdir -p ${BUILD_DIR} cd ${BUILD_DIR} @@ -221,7 +226,6 @@ function build() { make clean make -j4 - make install cd .. } @@ -232,19 +236,25 @@ echo "------------------------------------------------------" echo " ICU build armv7 libraries" echo "------------------------------------------------------" -build "armv7" "armv7" "armv7-apple-darwin" "iphoneos" +build "armv7" "armv7" "armv7-apple-darwin" "iphoneos" "armv7" echo "------------------------------------------------------" echo " ICU build arm64 libraries" echo "------------------------------------------------------" -build "arm64" "arm64" "aarch64-apple-darwin" "iphoneos" +build "arm64" "arm64" "aarch64-apple-darwin" "iphoneos" "arm64" echo "------------------------------------------------------" echo " ICU combining x86_64 libraries" echo "------------------------------------------------------" -build "x86_64" "x86_64" "x86_64-apple-darwin" "iphonesimulator" +build "x86_64" "x86_64" "x86_64-apple-darwin" "iphonesimulator" "x86_64" + +echo "------------------------------------------------------" +echo " ICU combining arm64 (simulator) libraries" +echo "------------------------------------------------------" + +build "arm64" "arm64" "aarch64-apple-darwin" "iphonesimulator" "sim-arm64" cd .. @@ -259,13 +269,31 @@ function buildUniversal() { "${PWD}/ios/build-armv7/lib/$1armv7.a" } +function buildUniversalXC() { + lipo -create -output "${PWD}/ios/build_xc/$1.a" \ + "${PWD}/ios/build-arm64/lib/$1arm64.a" + + lipo -create -output "${PWD}/ios/build_xc/simulator/${1}.a" \ + "${PWD}/ios/build-sim-arm64/lib/$1arm64.a" \ + "${PWD}/ios/build-x86_64/lib/$1x86_64.a" +} + mkdir -p build mkdir -p ios/build +mkdir -p ios/build_xc +mkdir -p ios/build_xc/simulator mkdir -p ios/build/include +mkdir -p ios/build_xc/include mkdir -p ios/build/include/unicode +mkdir -p ios/build_xc/include/unicode cp ${ICU_SOURCE}/common/unicode/*.h ios/build/include/unicode +cp ${ICU_SOURCE}/common/unicode/*.h ios/build_xc/include/unicode buildUniversal "libicuuc" buildUniversal "libicui18n" buildUniversal "libicudata" + +buildUniversalXC "libicuuc" +buildUniversalXC "libicui18n" +buildUniversalXC "libicudata" diff --git a/Common/3dParty/ixwebsocket/openssl.pri b/Common/3dParty/ixwebsocket/openssl.pri index 09b5bf789b..f82baa4618 100644 --- a/Common/3dParty/ixwebsocket/openssl.pri +++ b/Common/3dParty/ixwebsocket/openssl.pri @@ -17,6 +17,14 @@ core_ios { OPENSSL_LIBS_DIRECTORY = $$PWD/../openssl/build/ios/openssl-universal/lib + bundle_xcframeworks { + xcframework_platform_ios_simulator { + OPENSSL_LIBS_DIRECTORY = $$PWD/../openssl/build/ios/openssl-xc/simulator/lib + } else { + OPENSSL_LIBS_DIRECTORY = $$PWD/../openssl/build/ios/openssl-xc/lib + } + } + } core_windows { diff --git a/Common/3dParty/openssl/build-ios-common.sh b/Common/3dParty/openssl/build-ios-common.sh index c073b70cd1..bbfe97ee33 100755 --- a/Common/3dParty/openssl/build-ios-common.sh +++ b/Common/3dParty/openssl/build-ios-common.sh @@ -18,9 +18,9 @@ source ./build-common.sh export PLATFORM_TYPE="iOS" export IOS_MIN_TARGET="10.0" -export ARCHS=("armv7" "arm64" "i386" "x86_64") -export SDKS=("iphoneos" "iphoneos" "iphonesimulator" "iphonesimulator") -export PLATFORMS=("iPhoneOS" "iPhoneOS" "iPhoneSimulator" "iPhoneSimulator") +export ARCHS=("armv7" "arm64" "i386" "x86_64" "sim_arm64") +export SDKS=("iphoneos" "iphoneos" "iphonesimulator" "iphonesimulator" "iphonesimulator") +export PLATFORMS=("iPhoneOS" "iPhoneOS" "iPhoneSimulator" "iPhoneSimulator" "iphonesimulator") # for test !!! # export ARCHS=("armv7") @@ -45,6 +45,9 @@ function get_ios_arch() { x86_64) echo "x86-64" ;; + sim_arm64) + echo "sim-arm64" + ;; esac } @@ -66,6 +69,9 @@ function ios_get_build_host() { x86-64) echo "x86_64-ios-darwin" ;; + sim-arm64) + echo "aarch64-ios-darwin" + ;; esac } @@ -111,6 +117,13 @@ function set_ios_cpu_feature() { export LDFLAGS="-arch x86_64 -target x86_64-ios-darwin -march=x86-64 -isysroot ${sysroot} -L${sysroot}/usr/lib " export CXXFLAGS="-std=c++11 -arch x86_64 -target x86_64-ios-darwin -march=x86-64 -msse4.2 -mpopcnt -m64 -mtune=intel -fstrict-aliasing -DIOS -mios-simulator-version-min=${ios_min_target} -I${sysroot}/usr/include" ;; + sim-arm64) + export CC="xcrun -sdk iphonesimulator clang -arch arm64" + export CXX="xcrun -sdk iphonesimulator clang++ -arch arm64" + export CFLAGS="-arch arm64 -target aarch64-apple-darwin -march=armv8 -mcpu=generic -Wno-unused-function -fstrict-aliasing -Oz -Wno-ignored-optimization-argument -DIOS -isysroot ${sysroot} -fembed-bitcode -mios-simulator-version-min=${ios_min_target} -I${sysroot}/usr/include" + export LDFLAGS="-arch arm64 -target aaarch64-apple-darwin -march=armv8 -isysroot ${sysroot} -fembed-bitcode -L${sysroot}/usr/lib " + export CXXFLAGS="-std=c++11 -arch arm64 -target aarch64-apple-darwin -march=armv8 -mcpu=generic -fstrict-aliasing -fembed-bitcode -DIOS -mios-simulator-version-min=${ios_min_target} -I${sysroot}/usr/include" + ;; *) log_error "not support" && exit 1 ;; diff --git a/Common/3dParty/openssl/build-ios-openssl.sh b/Common/3dParty/openssl/build-ios-openssl.sh index 70f4f8de19..c19f1da9ff 100755 --- a/Common/3dParty/openssl/build-ios-openssl.sh +++ b/Common/3dParty/openssl/build-ios-openssl.sh @@ -38,6 +38,7 @@ echo TOOLS_ROOT=${TOOLS_ROOT} LIB_VERSION="OpenSSL_1_1_1d" LIB_NAME="openssl-1.1.1d" LIB_DEST_DIR="${pwd_path}/build/ios/openssl-universal/lib" +LIB_DEST_DIR_XC="${pwd_path}/build/ios/openssl-xc/lib" init_log_color @@ -53,11 +54,17 @@ rm -rf "${LIB_DEST_DIR}" "${LIB_NAME}" function configure_make() { - ARCH=$1 + ARCH_NAME=$1 + ARCH=$ARCH_NAME + + if [ "$ARCH" = "sim_arm64" ]; then + ARCH = "arm64" + fi; + SDK=$2 PLATFORM=$3 - log_info "configure $ARCH start..." + log_info "configure $ARCH_NAME start..." if [ -d "${LIB_NAME}" ]; then rm -fr "${LIB_NAME}" @@ -75,56 +82,62 @@ function configure_make() { exit -1 fi - PREFIX_DIR="${pwd_path}/build/ios/${ARCH}" + PREFIX_DIR="${pwd_path}/build/ios/${ARCH_NAME}" if [ -d "${PREFIX_DIR}" ]; then rm -fr "${PREFIX_DIR}" fi mkdir -p "${PREFIX_DIR}" - OUTPUT_ROOT=${TOOLS_ROOT}/build/ios/${ARCH} + OUTPUT_ROOT=${TOOLS_ROOT}/build/ios/${ARCH_NAME} mkdir -p ${OUTPUT_ROOT}/log - set_ios_cpu_feature "openssl" "${ARCH}" "${IOS_MIN_TARGET}" "${CROSS_TOP}/SDKs/${CROSS_SDK}" + set_ios_cpu_feature "openssl" "${ARCH_NAME}" "${IOS_MIN_TARGET}" "${CROSS_TOP}/SDKs/${CROSS_SDK}" - ios_printf_global_params "$ARCH" "$SDK" "$PLATFORM" "$PREFIX_DIR" "$OUTPUT_ROOT" + ios_printf_global_params "$ARCH_NAME" "$SDK" "$PLATFORM" "$PREFIX_DIR" "$OUTPUT_ROOT" unset IPHONEOS_DEPLOYMENT_TARGET - if [[ "${ARCH}" == "x86_64" ]]; then + if [[ "${ARCH_NAME}" == "x86_64" ]]; then # openssl1.1.1d can be set normally, 1.1.0f does not take effect ./Configure darwin64-x86_64-cc no-shared --prefix="${PREFIX_DIR}" sed -i -e 's/-mtune=intel//g' "Makefile" - elif [[ "${ARCH}" == "armv7" ]]; then + elif [[ "${ARCH_NAME}" == "armv7" ]]; then # openssl1.1.1d can be set normally, 1.1.0f does not take effect ./Configure iphoneos-cross no-shared --prefix="${PREFIX_DIR}" enable-ssl3 enable-ssl3-method sed -ie "s!-fno-common!-fno-common -fembed-bitcode !" "Makefile" - elif [[ "${ARCH}" == "arm64" ]]; then + elif [[ "${ARCH_NAME}" == "arm64" ]]; then # openssl1.1.1d can be set normally, 1.1.0f does not take effect ./Configure iphoneos-cross no-shared --prefix="${PREFIX_DIR}" enable-ssl3 enable-ssl3-method sed -ie "s!-fno-common!-fno-common -fembed-bitcode !" "Makefile" - elif [[ "${ARCH}" == "i386" ]]; then + elif [[ "${ARCH_NAME}" == "i386" ]]; then # openssl1.1.1d can be set normally, 1.1.0f does not take effect ./Configure darwin-i386-cc no-shared --prefix="${PREFIX_DIR}" enable-ssl3 enable-ssl3-method sed -ie "s!-fno-common!-fno-common -fembed-bitcode !" "Makefile" sed -i -e 's/-mtune=intel//g' "Makefile" + elif [[ "${ARCH_NAME}" == "sim_arm64" ]]; then + + # openssl1.1.1d can be set normally, 1.1.0f does not take effect + ./Configure iphoneos-cross no-shared --prefix="${PREFIX_DIR}" enable-ssl3 enable-ssl3-method + sed -ie "s!-fno-common!-fno-common -fembed-bitcode !" "Makefile" + else log_error "not support" && exit 1 fi log_info "make $ARCH start..." - make clean >"${OUTPUT_ROOT}/log/${ARCH}.log" - if make -j8 >>"${OUTPUT_ROOT}/log/${ARCH}.log" 2>&1; then - make install_sw >>"${OUTPUT_ROOT}/log/${ARCH}.log" 2>&1 - make install_ssldirs >>"${OUTPUT_ROOT}/log/${ARCH}.log" 2>&1 + make clean >"${OUTPUT_ROOT}/log/${ARCH_NAME}.log" + if make -j8 >>"${OUTPUT_ROOT}/log/${ARCH_NAME}.log" 2>&1; then + make install_sw >>"${OUTPUT_ROOT}/log/${ARCH_NAME}.log" 2>&1 + make install_ssldirs >>"${OUTPUT_ROOT}/log/${ARCH_NAME}.log" 2>&1 fi popd @@ -143,28 +156,36 @@ log_info "lipo start..." function lipo_library() { LIB_SRC=$1 - LIB_DST=$2 - LIB_PATHS=("${ARCHS[@]/#/${pwd_path}/build/ios/}") - LIB_PATHS=("${LIB_PATHS[@]/%//lib/${LIB_SRC}}") - lipo ${LIB_PATHS[@]} -create -output "${LIB_DST}" + lipo -create -output "${LIB_DEST_DIR}/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/arm64/lib/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/armv7/lib/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/x86_64/lib/${LIB_SRC}.a" +} + +function lipo_library_xc() { + LIB_SRC=$1 + lipo -create -output "${LIB_DEST_DIR_XC}/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/arm64/lib/${LIB_SRC}.a" + + lipo -create -output "${LIB_DEST_DIR_XC}/../simulator/lib/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/sim_arm64/lib/${LIB_SRC}.a" \ + "${pwd_path}/build/ios/x86_64/lib/${LIB_SRC}.a" } function copy_include() { - DST=$1 - if [ -d "${pwd_path}/build/ios/x86_64/include" ]; then - cp -r "${pwd_path}/build/ios/x86_64/include" "${DST}" - elif [ -d "${pwd_path}/build/ios/armv7/include" ]; then - cp -r "${pwd_path}/build/ios/armv7/include" "${DST}" - elif [ -d "${pwd_path}/build/ios/arm64/include" ]; then - cp -r "${pwd_path}/build/ios/arm64/include" "${DST}" - elif [ -d "${pwd_path}/build/ios/i386/include" ]; then - cp -r "${pwd_path}/build/ios/i386/include" "${DST}" - fi + cp -r "${pwd_path}/build/ios/arm64/include" "${1}" } mkdir -p "${LIB_DEST_DIR}" -lipo_library "libcrypto.a" "${LIB_DEST_DIR}/libcrypto.a" -lipo_library "libssl.a" "${LIB_DEST_DIR}/libssl.a" +lipo_library "libcrypto" +lipo_library "libssl" copy_include "${LIB_DEST_DIR}/../" +mkdir -p "${LIB_DEST_DIR_XC}" +mkdir -p "${LIB_DEST_DIR_XC}/../simulator/lib" +lipo_library_xc "libcrypto" +lipo_library_xc "libssl" +copy_include "${LIB_DEST_DIR_XC}/../" +copy_include "${LIB_DEST_DIR_XC}/../simulator" + log_info "${PLATFORM_TYPE} ${LIB_NAME} end..." diff --git a/Common/Network/WebSocket/src/socketio/make.py b/Common/Network/WebSocket/src/socketio/make.py new file mode 100755 index 0000000000..75839ce689 --- /dev/null +++ b/Common/Network/WebSocket/src/socketio/make.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python + +import sys +sys.path.append('../../../../../../build_tools/scripts') +import base + +file_path = "./socketio_internal_private_no_tls.h" +if not base.is_file(file_path): + file.delete_file(file_path) + +base.copy_file("./socketio_internal_private.h", file_path) + +header = "///////////////////////////////////////////////////////////\n" +header += "/// auto generated file. please use generator (make.py) ///\n" +header += "///////////////////////////////////////////////////////////\n" +header += "\n#pragma once" + +base.replaceInFile(file_path, "#pragma once", header) +base.replaceInFile(file_path, "/socket.io-client-cpp/src/", "/socket.io-client-cpp/src_no_tls/") +base.replaceInFile(file_path, "sio::", "sio_no_tls::") +base.replaceInFile(file_path, "CIOWebSocket_private_tls", "CIOWebSocket_private_no_tls") diff --git a/Common/Network/WebSocket/src/socketio/socketio_internal.cpp b/Common/Network/WebSocket/src/socketio/socketio_internal.cpp index abbb092776..c49cf3f6ed 100644 --- a/Common/Network/WebSocket/src/socketio/socketio_internal.cpp +++ b/Common/Network/WebSocket/src/socketio/socketio_internal.cpp @@ -30,149 +30,19 @@ * */ -#include "socketio_internal.h" -#include -#include "../../../../3dParty/socketio/socket.io-client-cpp/src/internal/sio_packet.h" -#include "../../../../3dParty/socketio/socket.io-client-cpp/src/sio_client.h" -#include "../../../../../DesktopEditor/graphics/TemporaryCS.h" +#include "socketio_internal_private.h" +#include "socketio_internal_private_no_tls.h" namespace NSNetwork { namespace NSWebSocket { - class CIOWebSocket_private - { - public: - sio::client m_socket; - NSCriticalSection::CRITICAL_SECTION m_oCS; - CIOWebSocket* m_base; - - public: - CIOWebSocket_private(CIOWebSocket* base) - { - m_base = base; - m_oCS.InitializeCriticalSection(); - } - ~CIOWebSocket_private() - { - m_socket.close(); - m_oCS.DeleteCriticalSection(); - } - - public: - void event_onConnected() - { - m_base->listener->onOpen(); - } - void event_onClose(sio::client::close_reason const& reason) - { - m_base->listener->onClose(0, ""); - } - void event_onFail() - { - m_base->listener->onError(""); - } - - public: - void open(const std::map& query) - { - m_socket.set_open_listener (std::bind(&CIOWebSocket_private::event_onConnected, this)); - m_socket.set_close_listener(std::bind(&CIOWebSocket_private::event_onClose, this, std::placeholders::_1)); - m_socket.set_fail_listener (std::bind(&CIOWebSocket_private::event_onFail, this)); - - sio::message::ptr objAuth = sio::object_message::create(); - //std::string sAuth; - - std::map queryDst = query; - std::map::iterator iterAuth = queryDst.find("token"); - if (iterAuth != queryDst.end()) - { - objAuth->get_map()["token"] = sio::string_message::create(iterAuth->second); - //sAuth = "{\"token\":\"" + iterAuth->second + "\"}"; - queryDst.erase(iterAuth); - } - - //webSocket.connect(url, queryDst, sio::string_message::create(sAuth)); - m_socket.connect(m_base->url, queryDst, objAuth); - - m_socket.socket()->on("message", [&](sio::event& event){ - CTemporaryCS oCS(&m_oCS); - const sio::message::ptr& message = event.get_message(); - if (!message) - return; - - // TODO: пока только текстовые и json команды - switch (message->get_flag()) - { - case sio::message::flag_null: - { - m_base->listener->onMessage("null"); - break; - } - case sio::message::flag_integer: - case sio::message::flag_double: - case sio::message::flag_boolean: - { - m_base->listener->onMessage(""); - break; - } - case sio::message::flag_binary: - { - m_base->listener->onMessage(""); - break; - } - case sio::message::flag_array: - { - m_base->listener->onMessage(""); - break; - } - case sio::message::flag_object: - { - sio::packet_manager manager; - - std::stringstream ss; - sio::packet packet("/", message); - manager.encode( packet, [&](bool isBinary, std::shared_ptr const& json) - { - ss << *json; - }); - manager.reset(); - - std::string result = ss.str(); - - std::size_t indexList = result.find('['); - std::size_t indexObject = result.find('{'); - std::size_t indexString = result.find('"'); - - std::size_t index = indexList; - if (indexObject != std::string::npos && indexObject < index) - index = indexObject; - if (indexString != std::string::npos && indexString < index) - index = indexString; - - if (index != std::string::npos) - result = result.substr(index); - else - result = ""; - - m_base->listener->onMessage(result); - break; - } - case sio::message::flag_string: - { - m_base->listener->onMessage(message->get_string()); - break; - } - default: - break; - } - }); - } - }; - CIOWebSocket::CIOWebSocket(const std::string& url, std::shared_ptr listener): CWebWorkerBase(url, listener) { - m_internal = new CIOWebSocket_private(this); + if (0 == url.find("http://")) + m_internal = new CIOWebSocket_private_no_tls(this); + else + m_internal = new CIOWebSocket_private_tls(this); } void CIOWebSocket::open(const std::map& query) @@ -182,36 +52,12 @@ namespace NSNetwork void CIOWebSocket::send(const std::string& message_str) { - //CTemporaryCS (&m_internal->m_oCS); - - // если json -то надо объект - if (0 == message_str.find("{") || - 0 == message_str.find("[")) - { - sio::packet_manager manager; - sio::message::ptr message; - manager.set_decode_callback([&](sio::packet const& p) - { - message = p.get_message(); - }); - - // Magic message type / ID - manager.put_payload("42" + message_str); - manager.reset(); - - m_internal->m_socket.socket()->emit("message", message); - } - else - { - m_internal->m_socket.socket()->emit("message", sio::string_message::create(message_str)); - } + m_internal->send(message_str); } void CIOWebSocket::close() { - //CTemporaryCS (&m_internal->m_oCS); - m_internal->m_socket.socket()->off_all(); - m_internal->m_socket.close(); + m_internal->close(); } CIOWebSocket::~CIOWebSocket() diff --git a/Common/Network/WebSocket/src/socketio/socketio_internal.h b/Common/Network/WebSocket/src/socketio/socketio_internal.h index 3c4e7bc9f9..fb202320fa 100644 --- a/Common/Network/WebSocket/src/socketio/socketio_internal.h +++ b/Common/Network/WebSocket/src/socketio/socketio_internal.h @@ -34,12 +34,34 @@ #define _IO_WEB_SOCKET_H_ #include "../websocketbase.h" +#include "../../../../../DesktopEditor/graphics/TemporaryCS.h" namespace NSNetwork { namespace NSWebSocket { - class CIOWebSocket_private; + class CIOWebSocket; + class CIOWebSocket_private + { + protected: + CIOWebSocket* m_base; + NSCriticalSection::CRITICAL_SECTION m_oCS; + public: + CIOWebSocket_private(CIOWebSocket* base) + { + m_base = base; + m_oCS.InitializeCriticalSection(); + } + virtual ~CIOWebSocket_private() + { + m_oCS.DeleteCriticalSection(); + } + + virtual void open(const std::map& query) = 0; + virtual void send(const std::string& message) = 0; + virtual void close() = 0; + }; + class CIOWebSocket: public CWebWorkerBase { private: @@ -55,6 +77,8 @@ namespace NSNetwork virtual void close() override; friend class CIOWebSocket_private; + friend class CIOWebSocket_private_tls; + friend class CIOWebSocket_private_no_tls; }; } } diff --git a/Common/Network/WebSocket/src/socketio/socketio_internal_private.h b/Common/Network/WebSocket/src/socketio/socketio_internal_private.h new file mode 100644 index 0000000000..cbe46e1efa --- /dev/null +++ b/Common/Network/WebSocket/src/socketio/socketio_internal_private.h @@ -0,0 +1,203 @@ +/* + * (c) Copyright Ascensio System SIA 2010-2021 + * + * This program is a free software product. You can redistribute it and/or + * modify it under the terms of the GNU Affero General Public License (AGPL) + * version 3 as published by the Free Software Foundation. In accordance with + * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect + * that Ascensio System SIA expressly excludes the warranty of non-infringement + * of any third-party rights. + * + * This program is distributed WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For + * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html + * + * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha + * street, Riga, Latvia, EU, LV-1050. + * + * The interactive user interfaces in modified source and object code versions + * of the Program must display Appropriate Legal Notices, as required under + * Section 5 of the GNU AGPL version 3. + * + * Pursuant to Section 7(b) of the License you must retain the original Product + * logo when distributing the program. Pursuant to Section 7(e) we decline to + * grant you any rights under trademark law for use of our trademarks. + * + * All the Product's GUI elements, including illustrations and icon sets, as + * well as technical writing content are licensed under the terms of the + * Creative Commons Attribution-ShareAlike 4.0 International. See the License + * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + * + */ + +#pragma once +#include "socketio_internal.h" +#include +#include "../../../../3dParty/socketio/socket.io-client-cpp/src/internal/sio_packet.h" +#include "../../../../3dParty/socketio/socket.io-client-cpp/src/sio_client.h" + +namespace NSNetwork +{ + namespace NSWebSocket + { + class CIOWebSocket_private_tls : public CIOWebSocket_private + { + public: + sio::client m_socket; + + public: + CIOWebSocket_private_tls(CIOWebSocket* base) : CIOWebSocket_private(base) + { + m_base = base; + } + ~CIOWebSocket_private_tls() + { + m_socket.close(); + } + + public: + void event_onConnected() + { + m_base->listener->onOpen(); + } + void event_onClose(sio::client::close_reason const& reason) + { + m_base->listener->onClose(0, ""); + } + void event_onFail() + { + m_base->listener->onError(""); + } + + public: + virtual void open(const std::map& query) override + { + m_socket.set_open_listener (std::bind(&CIOWebSocket_private_tls::event_onConnected, this)); + m_socket.set_close_listener(std::bind(&CIOWebSocket_private_tls::event_onClose, this, std::placeholders::_1)); + m_socket.set_fail_listener (std::bind(&CIOWebSocket_private_tls::event_onFail, this)); + + sio::message::ptr objAuth = sio::object_message::create(); + //std::string sAuth; + + std::map queryDst = query; + std::map::iterator iterAuth = queryDst.find("token"); + if (iterAuth != queryDst.end()) + { + objAuth->get_map()["token"] = sio::string_message::create(iterAuth->second); + //sAuth = "{\"token\":\"" + iterAuth->second + "\"}"; + queryDst.erase(iterAuth); + } + + //webSocket.connect(url, queryDst, sio::string_message::create(sAuth)); + m_socket.connect(m_base->url, queryDst, objAuth); + + m_socket.socket()->on("message", [&](sio::event& event){ + CTemporaryCS oCS(&m_oCS); + const sio::message::ptr& message = event.get_message(); + if (!message) + return; + + // TODO: пока только текстовые и json команды + switch (message->get_flag()) + { + case sio::message::flag_null: + { + m_base->listener->onMessage("null"); + break; + } + case sio::message::flag_integer: + case sio::message::flag_double: + case sio::message::flag_boolean: + { + m_base->listener->onMessage(""); + break; + } + case sio::message::flag_binary: + { + m_base->listener->onMessage(""); + break; + } + case sio::message::flag_array: + { + m_base->listener->onMessage(""); + break; + } + case sio::message::flag_object: + { + sio::packet_manager manager; + + std::stringstream ss; + sio::packet packet("/", message); + manager.encode( packet, [&](bool isBinary, std::shared_ptr const& json) + { + ss << *json; + }); + manager.reset(); + + std::string result = ss.str(); + + std::size_t indexList = result.find('['); + std::size_t indexObject = result.find('{'); + std::size_t indexString = result.find('"'); + + std::size_t index = indexList; + if (indexObject != std::string::npos && indexObject < index) + index = indexObject; + if (indexString != std::string::npos && indexString < index) + index = indexString; + + if (index != std::string::npos) + result = result.substr(index); + else + result = ""; + + m_base->listener->onMessage(result); + break; + } + case sio::message::flag_string: + { + m_base->listener->onMessage(message->get_string()); + break; + } + default: + break; + } + }); + } + + virtual void send(const std::string& message_str) override + { + //CTemporaryCS (&m_internal->m_oCS); + + // если json -то надо объект + if (0 == message_str.find("{") || + 0 == message_str.find("[")) + { + sio::packet_manager manager; + sio::message::ptr message; + manager.set_decode_callback([&](sio::packet const& p) + { + message = p.get_message(); + }); + + // Magic message type / ID + manager.put_payload("42" + message_str); + manager.reset(); + + m_socket.socket()->emit("message", message); + } + else + { + m_socket.socket()->emit("message", sio::string_message::create(message_str)); + } + } + + virtual void close() override + { + //CTemporaryCS (&m_internal->m_oCS); + m_socket.socket()->off_all(); + m_socket.close(); + } + }; + } +} diff --git a/Common/Network/WebSocket/src/socketio/socketio_internal_private_no_tls.h b/Common/Network/WebSocket/src/socketio/socketio_internal_private_no_tls.h new file mode 100644 index 0000000000..7d2dcf488c --- /dev/null +++ b/Common/Network/WebSocket/src/socketio/socketio_internal_private_no_tls.h @@ -0,0 +1,207 @@ +/* + * (c) Copyright Ascensio System SIA 2010-2021 + * + * This program is a free software product. You can redistribute it and/or + * modify it under the terms of the GNU Affero General Public License (AGPL) + * version 3 as published by the Free Software Foundation. In accordance with + * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect + * that Ascensio System SIA expressly excludes the warranty of non-infringement + * of any third-party rights. + * + * This program is distributed WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For + * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html + * + * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha + * street, Riga, Latvia, EU, LV-1050. + * + * The interactive user interfaces in modified source and object code versions + * of the Program must display Appropriate Legal Notices, as required under + * Section 5 of the GNU AGPL version 3. + * + * Pursuant to Section 7(b) of the License you must retain the original Product + * logo when distributing the program. Pursuant to Section 7(e) we decline to + * grant you any rights under trademark law for use of our trademarks. + * + * All the Product's GUI elements, including illustrations and icon sets, as + * well as technical writing content are licensed under the terms of the + * Creative Commons Attribution-ShareAlike 4.0 International. See the License + * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode + * + */ + +/////////////////////////////////////////////////////////// +/// auto generated file. please use generator (make.py) /// +/////////////////////////////////////////////////////////// + +#pragma once +#include "socketio_internal.h" +#include +#include "../../../../3dParty/socketio/socket.io-client-cpp/src_no_tls/internal/sio_packet.h" +#include "../../../../3dParty/socketio/socket.io-client-cpp/src_no_tls/sio_client.h" + +namespace NSNetwork +{ + namespace NSWebSocket + { + class CIOWebSocket_private_no_tls : public CIOWebSocket_private + { + public: + sio_no_tls::client m_socket; + + public: + CIOWebSocket_private_no_tls(CIOWebSocket* base) : CIOWebSocket_private(base) + { + m_base = base; + } + ~CIOWebSocket_private_no_tls() + { + m_socket.close(); + } + + public: + void event_onConnected() + { + m_base->listener->onOpen(); + } + void event_onClose(sio_no_tls::client::close_reason const& reason) + { + m_base->listener->onClose(0, ""); + } + void event_onFail() + { + m_base->listener->onError(""); + } + + public: + virtual void open(const std::map& query) override + { + m_socket.set_open_listener (std::bind(&CIOWebSocket_private_no_tls::event_onConnected, this)); + m_socket.set_close_listener(std::bind(&CIOWebSocket_private_no_tls::event_onClose, this, std::placeholders::_1)); + m_socket.set_fail_listener (std::bind(&CIOWebSocket_private_no_tls::event_onFail, this)); + + sio_no_tls::message::ptr objAuth = sio_no_tls::object_message::create(); + //std::string sAuth; + + std::map queryDst = query; + std::map::iterator iterAuth = queryDst.find("token"); + if (iterAuth != queryDst.end()) + { + objAuth->get_map()["token"] = sio_no_tls::string_message::create(iterAuth->second); + //sAuth = "{\"token\":\"" + iterAuth->second + "\"}"; + queryDst.erase(iterAuth); + } + + //webSocket.connect(url, queryDst, sio_no_tls::string_message::create(sAuth)); + m_socket.connect(m_base->url, queryDst, objAuth); + + m_socket.socket()->on("message", [&](sio_no_tls::event& event){ + CTemporaryCS oCS(&m_oCS); + const sio_no_tls::message::ptr& message = event.get_message(); + if (!message) + return; + + // TODO: пока только текстовые и json команды + switch (message->get_flag()) + { + case sio_no_tls::message::flag_null: + { + m_base->listener->onMessage("null"); + break; + } + case sio_no_tls::message::flag_integer: + case sio_no_tls::message::flag_double: + case sio_no_tls::message::flag_boolean: + { + m_base->listener->onMessage(""); + break; + } + case sio_no_tls::message::flag_binary: + { + m_base->listener->onMessage(""); + break; + } + case sio_no_tls::message::flag_array: + { + m_base->listener->onMessage(""); + break; + } + case sio_no_tls::message::flag_object: + { + sio_no_tls::packet_manager manager; + + std::stringstream ss; + sio_no_tls::packet packet("/", message); + manager.encode( packet, [&](bool isBinary, std::shared_ptr const& json) + { + ss << *json; + }); + manager.reset(); + + std::string result = ss.str(); + + std::size_t indexList = result.find('['); + std::size_t indexObject = result.find('{'); + std::size_t indexString = result.find('"'); + + std::size_t index = indexList; + if (indexObject != std::string::npos && indexObject < index) + index = indexObject; + if (indexString != std::string::npos && indexString < index) + index = indexString; + + if (index != std::string::npos) + result = result.substr(index); + else + result = ""; + + m_base->listener->onMessage(result); + break; + } + case sio_no_tls::message::flag_string: + { + m_base->listener->onMessage(message->get_string()); + break; + } + default: + break; + } + }); + } + + virtual void send(const std::string& message_str) override + { + //CTemporaryCS (&m_internal->m_oCS); + + // если json -то надо объект + if (0 == message_str.find("{") || + 0 == message_str.find("[")) + { + sio_no_tls::packet_manager manager; + sio_no_tls::message::ptr message; + manager.set_decode_callback([&](sio_no_tls::packet const& p) + { + message = p.get_message(); + }); + + // Magic message type / ID + manager.put_payload("42" + message_str); + manager.reset(); + + m_socket.socket()->emit("message", message); + } + else + { + m_socket.socket()->emit("message", sio_no_tls::string_message::create(message_str)); + } + } + + virtual void close() override + { + //CTemporaryCS (&m_internal->m_oCS); + m_socket.socket()->off_all(); + m_socket.close(); + } + }; + } +} diff --git a/Common/Network/WebSocket/websocket.pri b/Common/Network/WebSocket/websocket.pri index d6a0a9ca46..26629f5330 100644 --- a/Common/Network/WebSocket/websocket.pri +++ b/Common/Network/WebSocket/websocket.pri @@ -35,6 +35,19 @@ libsocketio { $$SOCKET_IO_LIB/src/sio_socket.cpp \ $$SOCKET_IO_LIB/src/sio_client.cpp + HEADERS += \ + $$SOCKET_IO_LIB/src_no_tls/internal/sio_client_impl.h \ + $$SOCKET_IO_LIB/src_no_tls/internal/sio_packet.h \ + $$SOCKET_IO_LIB/src_no_tls/sio_message.h \ + $$SOCKET_IO_LIB/src_no_tls/sio_socket.h \ + $$SOCKET_IO_LIB/src_no_tls/sio_client.h + + SOURCES += \ + $$SOCKET_IO_LIB/src_no_tls/internal/sio_client_impl.cpp \ + $$SOCKET_IO_LIB/src_no_tls/internal/sio_packet.cpp \ + $$SOCKET_IO_LIB/src_no_tls/sio_socket.cpp \ + $$SOCKET_IO_LIB/src_no_tls/sio_client.cpp + DEFINES += \ BOOST_DATE_TIME_NO_LIB \ BOOST_REGEX_NO_LIB \ @@ -45,13 +58,18 @@ libsocketio { _WEBSOCKETPP_CPP11_TYPE_TRAITS_ \ _WEBSOCKETPP_CPP11_CHRONO_ \ \ - "SIO_TLS=1" + "SIO_TLS=1" \ + "SIO_TLS_NO=0" include($$PWD/../../3dParty/boost/boost.pri) DEFINES += USE_IOWEBSOCKET - HEADERS += $$PWD/src/socketio/socketio_internal.h + HEADERS += \ + $$PWD/src/socketio/socketio_internal.h \ + $$PWD/src/socketio/socketio_internal_private.h \ + $$PWD/src/socketio/socketio_internal_private_no_tls.h + SOURCES += $$PWD/src/socketio/socketio_internal.cpp } diff --git a/Common/base.pri b/Common/base.pri index f5136ad6b5..d480af4ef8 100644 --- a/Common/base.pri +++ b/Common/base.pri @@ -263,12 +263,23 @@ core_ios { } else { QMAKE_IOS_DEPLOYMENT_TARGET = 11.0 - CONFIG += core_ios_main_arch QMAKE_CFLAGS += -fembed-bitcode QMAKE_CXXFLAGS += -fembed-bitcode QMAKE_LFLAGS += -fembed-bitcode + bundle_xcframeworks { + xcframework_platform_ios_simulator { + QMAKE_APPLE_DEVICE_ARCHS= + QMAKE_APPLE_SIMULATOR_ARCHS=x86_64 arm64 + } else { + QMAKE_APPLE_DEVICE_ARCHS = arm64 + QMAKE_APPLE_SIMULATOR_ARCHS= + } + } else { + CONFIG += core_ios_main_arch + } + core_ios_main_arch { QMAKE_APPLE_DEVICE_ARCHS = arm64 core_ios_no_simulator_arch : QMAKE_APPLE_SIMULATOR_ARCHS= @@ -276,10 +287,6 @@ core_ios { core_ios_32 { QMAKE_APPLE_DEVICE_ARCHS = $$QMAKE_APPLE_DEVICE_ARCHS armv7 } - } else { - plugin : TARGET = $$join(TARGET, TARGET, "", "_addition") - QMAKE_APPLE_DEVICE_ARCHS= - QMAKE_APPLE_SIMULATOR_ARCHS= } core_ios_nomain_arch { @@ -398,6 +405,16 @@ OBJECTS_DIR = $$PWD_ROOT_DIR/core_build/$$CORE_BUILDS_PLATFORM_PREFIX/$$CORE_BUI MOC_DIR = $$PWD_ROOT_DIR/core_build/$$CORE_BUILDS_PLATFORM_PREFIX/$$CORE_BUILDS_CONFIGURATION_PREFIX/moc RCC_DIR = $$PWD_ROOT_DIR/core_build/$$CORE_BUILDS_PLATFORM_PREFIX/$$CORE_BUILDS_CONFIGURATION_PREFIX/rcc UI_DIR = $$PWD_ROOT_DIR/core_build/$$CORE_BUILDS_PLATFORM_PREFIX/$$CORE_BUILDS_CONFIGURATION_PREFIX/ui + +bundle_xcframeworks { + xcframework_platform_ios_simulator { + OBJECTS_DIR = $$OBJECTS_DIR/simulator + MOC_DIR = $$MOC_DIR/simulator + RCC_DIR = $$RCC_DIR/simulator + UI_DIR = $$UI_DIR/simulator + } +} + build_xp { OBJECTS_DIR = $$OBJECTS_DIR/xp MOC_DIR = $$MOC_DIR/xp @@ -426,6 +443,13 @@ core_debug { CORE_BUILDS_BINARY_PATH = $$OO_DESTDIR_BUILD_OVERRIDE } +core_ios { + xcframework_platform_ios_simulator { + CORE_BUILDS_LIBRARIES_PATH = $$CORE_BUILDS_LIBRARIES_PATH/simulator + CORE_BUILDS_BINARY_PATH = $$CORE_BUILDS_BINARY_PATH/simulator + } +} + plugin { DESTDIR = $$CORE_BUILDS_LIBRARIES_PATH } diff --git a/Common/cfcpp/cfstorage.cpp b/Common/cfcpp/cfstorage.cpp index 25da9368e2..c51c52b31d 100644 --- a/Common/cfcpp/cfstorage.cpp +++ b/Common/cfcpp/cfstorage.cpp @@ -103,7 +103,7 @@ std::shared_ptr CFStorage::GetStream(const std::wstring& streamName) } else { - throw CFItemNotFound(L"Cannot find item [" + streamName + L"] within the current storage"); + return std::shared_ptr(); } } diff --git a/DesktopEditor/agg-2.4/include/agg_span_gradient.h b/DesktopEditor/agg-2.4/include/agg_span_gradient.h index d3a573c9e2..bc9cceda19 100644 --- a/DesktopEditor/agg-2.4/include/agg_span_gradient.h +++ b/DesktopEditor/agg-2.4/include/agg_span_gradient.h @@ -234,7 +234,6 @@ namespace agg double _y = y; m_trans.transform(&_x, &_y); double t = calculate_param(_x, _y); - int a = 0; int index = int( t * MaxColorIndex + 0.5 ); if( !m_valid_table[index] ) CalcColor( index ); diff --git a/DesktopEditor/common/File.cpp b/DesktopEditor/common/File.cpp index 5f6a69217b..bf1608c4c9 100644 --- a/DesktopEditor/common/File.cpp +++ b/DesktopEditor/common/File.cpp @@ -1448,10 +1448,12 @@ namespace NSFile #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN64) src.open(strSrc.c_str(), std::ios::binary); - dst.open(strDst.c_str(), std::ios::binary); + if (src.is_open()) + dst.open(strDst.c_str(), std::ios::binary); #else src.open(strSrcA.c_str(), std::ios::binary); - dst.open(strDstA.c_str(), std::ios::binary); + if (src.is_open()) + dst.open(strDstA.c_str(), std::ios::binary); #endif bool bRet = false; @@ -1469,6 +1471,7 @@ namespace NSFile return bRet; #endif } + bool CFileBinary::Remove(const std::wstring& strFileName) { #if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN64) diff --git a/DesktopEditor/cximage/CxImage/ximacfg.h b/DesktopEditor/cximage/CxImage/ximacfg.h index 5de66c8949..b5dcefb559 100644 --- a/DesktopEditor/cximage/CxImage/ximacfg.h +++ b/DesktopEditor/cximage/CxImage/ximacfg.h @@ -71,7 +71,7 @@ #endif ///////////////////////////////////////////////////////////////////////////// -#define CXIMAGE_MAX_MEMORY 268435456 +#define CXIMAGE_MAX_MEMORY 1073741824 // 1Gb #define CXIMAGE_DEFAULT_DPI 96 diff --git a/DesktopEditor/cximage/CxImage/ximaexif.cpp b/DesktopEditor/cximage/CxImage/ximaexif.cpp index d5cd21cc3d..3a6c4c925e 100644 --- a/DesktopEditor/cximage/CxImage/ximaexif.cpp +++ b/DesktopEditor/cximage/CxImage/ximaexif.cpp @@ -487,6 +487,8 @@ bool CxImageJPG::CxExifInfo::ProcessExifDir(uint8_t * DirStart, uint8_t * Offset break; case TAG_USERCOMMENT: + if (ByteCount > 0) + { // Olympus has this padded with trailing spaces. Remove these first. for (a=ByteCount;;){ a--; @@ -497,6 +499,7 @@ bool CxImageJPG::CxExifInfo::ProcessExifDir(uint8_t * DirStart, uint8_t * Offset } if (a == 0) break; } + } /* Copy the comment */ if (memcmp(ValuePtr, "ASCII",5) == 0){ @@ -803,7 +806,7 @@ bool CxImageJPG::CxExifInfo::ProcessExifDir2(CSafeReader DirStart, CSafeReader O case TAG_USERCOMMENT: // Olympus has this padded with trailing spaces. Remove these first. - if (ValuePtr.Check(ByteCount)) + if (ValuePtr.Check(ByteCount) && ByteCount > 0) { for (a=ByteCount;;){ a--; diff --git a/DesktopEditor/doctrenderer/docbuilder.com/src/docbuilder.com_2019.vcxproj b/DesktopEditor/doctrenderer/docbuilder.com/src/docbuilder.com_2019.vcxproj index dc4fda4308..9382446c1f 100644 --- a/DesktopEditor/doctrenderer/docbuilder.com/src/docbuilder.com_2019.vcxproj +++ b/DesktopEditor/doctrenderer/docbuilder.com/src/docbuilder.com_2019.vcxproj @@ -116,7 +116,7 @@ true EnableFastChecks MultiThreadedDebugDLL - Use + NotUsing Level3 EditAndContinue @@ -192,7 +192,7 @@ %(AdditionalIncludeDirectories) WIN32;_WINDOWS;NDEBUG;_USRDLL;_ATL_ATTRIBUTES;%(PreprocessorDefinitions) MultiThreadedDLL - Use + NotUsing Level3 ProgramDatabase diff --git a/DesktopEditor/doctrenderer/docbuilder_p.cpp b/DesktopEditor/doctrenderer/docbuilder_p.cpp index 7631a34af0..4804c61a00 100644 --- a/DesktopEditor/doctrenderer/docbuilder_p.cpp +++ b/DesktopEditor/doctrenderer/docbuilder_p.cpp @@ -76,8 +76,8 @@ bool CV8RealTimeWorker::ExecuteCommand(const std::wstring& command, NSDoctRender { LOGGER_SPEED_START - if (retValue) - retValue->Clear(); + if (retValue) + retValue->Clear(); std::string commandA = U_TO_UTF8(command); //commandA = "Api." + commandA; @@ -87,7 +87,7 @@ bool CV8RealTimeWorker::ExecuteCommand(const std::wstring& command, NSDoctRender LOGGER_SPEED_LAP("compile_command") - JSSmart retNativeVal = m_context->runScript(commandA, try_catch); + JSSmart retNativeVal = m_context->runScript(commandA, try_catch); if(try_catch->Check()) return false; @@ -100,7 +100,7 @@ bool CV8RealTimeWorker::ExecuteCommand(const std::wstring& command, NSDoctRender LOGGER_SPEED_LAP("run_command") - return true; + return true; } std::string CV8RealTimeWorker::GetGlobalVariable() @@ -139,7 +139,7 @@ bool CV8RealTimeWorker::OpenFile(const std::wstring& sBasePath, const std::wstri { LOGGER_SPEED_START - JSSmart context_scope = m_context->CreateContextScope(); + JSSmart context_scope = m_context->CreateContextScope(); JSSmart try_catch = m_context->GetExceptions(); LOGGER_SPEED_LAP("compile"); @@ -150,7 +150,7 @@ bool CV8RealTimeWorker::OpenFile(const std::wstring& sBasePath, const std::wstri LOGGER_SPEED_LAP("run") - if (true) + if (true) { std::string sArg = m_sUtf8ArgumentJSON; if (sArg.empty()) @@ -249,7 +249,7 @@ bool CV8RealTimeWorker::OpenFile(const std::wstring& sBasePath, const std::wstri LOGGER_SPEED_LAP("open") - return !bIsBreak; + return !bIsBreak; } bool CV8RealTimeWorker::SaveFileWithChanges(int type, const std::wstring& _path, const std::wstring& sJsonParams) diff --git a/DesktopEditor/doctrenderer/docbuilder_p.h b/DesktopEditor/doctrenderer/docbuilder_p.h index 3b3866c2d8..48c833976e 100644 --- a/DesktopEditor/doctrenderer/docbuilder_p.h +++ b/DesktopEditor/doctrenderer/docbuilder_p.h @@ -890,7 +890,7 @@ namespace NSDoctRenderer LOGGER_SPEED_START - CheckFileDir(); + CheckFileDir(); NSDirectory::CreateDirectory(m_sFileDir + L"/changes"); std::wstring sExtCopy = GetFileCopyExt(path); @@ -912,8 +912,8 @@ namespace NSDoctRenderer LOGGER_SPEED_LAP("open_convert") - if (0 == nReturnCode) - return 0; + if (0 == nReturnCode) + return 0; NSDirectory::DeleteDirectory(m_sFileDir); m_sFileDir = L""; diff --git a/DesktopEditor/doctrenderer/doctrenderer.cpp b/DesktopEditor/doctrenderer/doctrenderer.cpp index 96d1e71e08..2a082d52cb 100644 --- a/DesktopEditor/doctrenderer/doctrenderer.cpp +++ b/DesktopEditor/doctrenderer/doctrenderer.cpp @@ -380,25 +380,6 @@ namespace NSDoctRenderer { std::string sHTML_Utf8 = js_result2->toStringA(); - JSSmart js_objectCoreVal = js_objectApi->call_func("asc_getCoreProps", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"core_props\""; - bIsBreak = true; - } - else if (js_objectCoreVal->isObject()) - { - JSSmart js_objectCore = js_objectCoreVal->toObject(); - JSSmart js_results = js_objectCore->call_func("asc_getTitle", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_title\""; - bIsBreak = true; - } - else if (!js_results->isNull() && sHTML_Utf8.find("") == std::string::npos) - sHTML_Utf8.insert(sHTML_Utf8.find("</head>"), "<title>" + js_results->toStringA() + ""); - } - NSFile::CFileBinary oFile; if (true == oFile.CreateFileW(pParams->m_strDstFilePath)) { @@ -844,129 +825,6 @@ namespace NSDoctRenderer bIsBreak = Doct_renderer_SaveFile(&m_oParams, pNative, context, args, strError, js_objectApi); } - // CORE PARAMS - if (!bIsBreak && !bIsMailMerge && - (m_oParams.m_eDstFormat == DoctRendererFormat::HTML || - m_oParams.m_eDstFormat == DoctRendererFormat::PDF)) - { - JSSmart js_objectCoreVal = js_objectApi->call_func("asc_getCoreProps", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"core_props\""; - bIsBreak = true; - } - else if (js_objectCoreVal->isObject()) - { - JSSmart js_objectCore = js_objectCoreVal->toObject(); - JSSmart js_results = js_objectCore->call_func("asc_getTitle", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_title\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getCreator", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_creator\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - if (!js_results->toStringW().empty()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - } - - js_results = js_objectCore->call_func("asc_getDescription", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_description\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getSubject", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_subject\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getIdentifier", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_identifier\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getLanguage", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_language\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getKeywords", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_keywords\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - - js_results = js_objectCore->call_func("asc_getVersion", 1, args); - if(try_catch->Check()) - { - strError = L"code=\"get_version\""; - bIsBreak = true; - } - else if (!js_results->isNull()) - { - strReturnParams += L""; - strReturnParams += js_results->toStringW(); - strReturnParams += L""; - } - } - } - LOGGER_SPEED_LAP("save") } diff --git a/DesktopEditor/doctrenderer/embed/GraphicsEmbed.cpp b/DesktopEditor/doctrenderer/embed/GraphicsEmbed.cpp index 224c052202..02f86b9b0f 100644 --- a/DesktopEditor/doctrenderer/embed/GraphicsEmbed.cpp +++ b/DesktopEditor/doctrenderer/embed/GraphicsEmbed.cpp @@ -5,6 +5,11 @@ JSSmart CGraphicsEmbed::init(JSSmart Native, JSSmartinit((NSNativeControl::CNativeControl*)Native->toObjectSmart()->getNative()->getObject(), width_px->toDouble(), height_px->toDouble(), width_mm->toDouble(), height_mm->toDouble()); return NULL; } +JSSmart CGraphicsEmbed::Destroy() +{ + m_pInternal->Destroy(); + return NULL; +} JSSmart CGraphicsEmbed::EndDraw() { m_pInternal->EndDraw(); diff --git a/DesktopEditor/doctrenderer/embed/GraphicsEmbed.h b/DesktopEditor/doctrenderer/embed/GraphicsEmbed.h index ebbc322e5b..16f74725f1 100644 --- a/DesktopEditor/doctrenderer/embed/GraphicsEmbed.h +++ b/DesktopEditor/doctrenderer/embed/GraphicsEmbed.h @@ -18,6 +18,7 @@ public: public: JSSmart init(JSSmart Native, JSSmart width_px, JSSmart height_px, JSSmart width_mm, JSSmart height_mm); + JSSmart Destroy(); JSSmart EndDraw(); JSSmart put_GlobalAlpha(JSSmart enable, JSSmart globalAlpha); JSSmart Start_GlobalAlpha(); diff --git a/DesktopEditor/doctrenderer/embed/ZipEmbed.cpp b/DesktopEditor/doctrenderer/embed/ZipEmbed.cpp index 2e199e42b2..80364323d2 100644 --- a/DesktopEditor/doctrenderer/embed/ZipEmbed.cpp +++ b/DesktopEditor/doctrenderer/embed/ZipEmbed.cpp @@ -104,6 +104,24 @@ JSSmart CZipEmbed::close() return CJSContext::createUndefined(); } +JSSmart CZipEmbed::getPaths() +{ + if (!m_pFolder) + return CJSContext::createArray(0); + + std::vector arFiles = m_pFolder->getFiles(L"", true); + JSSmart retFiles = CJSContext::createArray((int)arFiles.size()); + + int nCurCount = 0; + for (std::vector::const_iterator i = arFiles.begin(); i != arFiles.end(); i++) + { + const std::wstring& val = *i; + retFiles->set(nCurCount++, CJSContext::createString(val.empty() ? val : val.substr(1))); + } + + return retFiles->toValue(); +} + JSSmart CZipEmbed::decodeImage(JSSmart typedArray, JSSmart isRgba) { JSSmart oArray = typedArray->toTypedArray(); diff --git a/DesktopEditor/doctrenderer/embed/ZipEmbed.h b/DesktopEditor/doctrenderer/embed/ZipEmbed.h index e182b6ca21..60464be032 100644 --- a/DesktopEditor/doctrenderer/embed/ZipEmbed.h +++ b/DesktopEditor/doctrenderer/embed/ZipEmbed.h @@ -30,6 +30,7 @@ public: JSSmart addFile(JSSmart filePath, JSSmart typedArray); JSSmart removeFile(JSSmart filePath); JSSmart close(); + JSSmart getPaths(); JSSmart decodeImage(JSSmart typedArray, JSSmart isRgba); JSSmart encodeImageData(JSSmart typedArray, JSSmart w, JSSmart h, JSSmart stride, JSSmart format, JSSmart isRgba); diff --git a/DesktopEditor/doctrenderer/embed/jsc/jsc_Graphics.mm b/DesktopEditor/doctrenderer/embed/jsc/jsc_Graphics.mm index 4a9d4b44e2..c2e3493ebe 100644 --- a/DesktopEditor/doctrenderer/embed/jsc/jsc_Graphics.mm +++ b/DesktopEditor/doctrenderer/embed/jsc/jsc_Graphics.mm @@ -3,6 +3,7 @@ @protocol IJSCGraphics -(JSValue*) create : (JSValue*)Native : (JSValue*)width_px : (JSValue*)height_px : (JSValue*)width_mm : (JSValue*)height_mm; +-(JSValue*) Destroy; -(JSValue*) EndDraw; -(JSValue*) put_GlobalAlpha : (JSValue*)enable : (JSValue*)globalAlpha; -(JSValue*) Start_GlobalAlpha; @@ -130,6 +131,7 @@ EMBED_OBJECT_WRAPPER_METHODS(CGraphicsEmbed) FUNCTION_WRAPPER_JS_5(create, init) +FUNCTION_WRAPPER_JS(Destroy, Destroy) FUNCTION_WRAPPER_JS(EndDraw, EndDraw) FUNCTION_WRAPPER_JS_2(put_GlobalAlpha, put_GlobalAlpha) FUNCTION_WRAPPER_JS(Start_GlobalAlpha, Start_GlobalAlpha) diff --git a/DesktopEditor/doctrenderer/embed/jsc/jsc_NativeControl.mm b/DesktopEditor/doctrenderer/embed/jsc/jsc_NativeControl.mm index 2b8cbdf265..9ee9ce0c32 100644 --- a/DesktopEditor/doctrenderer/embed/jsc/jsc_NativeControl.mm +++ b/DesktopEditor/doctrenderer/embed/jsc/jsc_NativeControl.mm @@ -14,8 +14,8 @@ -(JSValue*) CheckNextChange; -(JSValue*) GetCountChanges; -(JSValue*) GetChangesFile : (JSValue*)index; --(JSValue*) Save_AllocNative : (JSValue*)len; --(JSValue*) Save_ReAllocNative : (JSValue*)pos : (JSValue*)len; +//-(JSValue*) Save_AllocNative : (JSValue*)len; +//-(JSValue*) Save_ReAllocNative : (JSValue*)pos : (JSValue*)len; -(JSValue*) Save_End : (JSValue*)pos : (JSValue*)len; -(JSValue*) AddImageInChanges : (JSValue*)img; -(JSValue*) ConsoleLog : (JSValue*)message; @@ -54,8 +54,8 @@ FUNCTION_WRAPPER_JS(GetEditorType, GetEditorType) FUNCTION_WRAPPER_JS(CheckNextChange, CheckNextChange) FUNCTION_WRAPPER_JS(GetCountChanges, GetCountChanges) FUNCTION_WRAPPER_JS_1(GetChangesFile, GetChangesFile) -FUNCTION_WRAPPER_JS_1(Save_AllocNative, Save_AllocNative) -FUNCTION_WRAPPER_JS_2(Save_ReAllocNative, Save_ReAllocNative) +//FUNCTION_WRAPPER_JS_1(Save_AllocNative, Save_AllocNative) +//FUNCTION_WRAPPER_JS_2(Save_ReAllocNative, Save_ReAllocNative) FUNCTION_WRAPPER_JS_2(Save_End, Save_End) FUNCTION_WRAPPER_JS_1(AddImageInChanges, AddImageInChanges) FUNCTION_WRAPPER_JS_1(ConsoleLog, ConsoleLog) diff --git a/DesktopEditor/doctrenderer/embed/jsc/jsc_Zip.mm b/DesktopEditor/doctrenderer/embed/jsc/jsc_Zip.mm index 48ad8092cd..5c44c56420 100644 --- a/DesktopEditor/doctrenderer/embed/jsc/jsc_Zip.mm +++ b/DesktopEditor/doctrenderer/embed/jsc/jsc_Zip.mm @@ -9,6 +9,7 @@ -(JSValue*) addFile : (JSValue*)path : (JSValue*)data; -(JSValue*) removeFile : (JSValue*)path; -(JSValue*) close; +-(JSValue*) getPaths; -(JSValue*) decodeImage : (JSValue*)typedArray : (JSValue*)isRgba; -(JSValue*) encodeImageData : (JSValue*)typedArray : (JSValue*)w : (JSValue*)h : (JSValue*)stride : (JSValue*)format : (JSValue*)isRgba; @@ -35,6 +36,7 @@ FUNCTION_WRAPPER_JS_1(getFile, getFile) FUNCTION_WRAPPER_JS_2(addFile, addFile) FUNCTION_WRAPPER_JS_1(removeFile, removeFile) FUNCTION_WRAPPER_JS(close, close) +FUNCTION_WRAPPER_JS(getPaths, getPaths) FUNCTION_WRAPPER_JS_2(decodeImage, decodeImage) FUNCTION_WRAPPER_JS_6(encodeImageData, encodeImageData) diff --git a/DesktopEditor/doctrenderer/embed/v8/v8_Graphics.cpp b/DesktopEditor/doctrenderer/embed/v8/v8_Graphics.cpp index ab321777ce..9060e289c1 100644 --- a/DesktopEditor/doctrenderer/embed/v8/v8_Graphics.cpp +++ b/DesktopEditor/doctrenderer/embed/v8/v8_Graphics.cpp @@ -7,6 +7,7 @@ namespace NSGraphics // FUNCTION FUNCTION_WRAPPER_V8_5(_init, init) + FUNCTION_WRAPPER_V8 (_destroy, Destroy) FUNCTION_WRAPPER_V8 (_EndDraw, EndDraw) FUNCTION_WRAPPER_V8_2(_put_GlobalAlpha, put_GlobalAlpha) FUNCTION_WRAPPER_V8 (_Start_GlobalAlpha, Start_GlobalAlpha) @@ -131,6 +132,7 @@ namespace NSGraphics // методы NSV8Objects::Template_Set(result, "create", _init); + NSV8Objects::Template_Set(result, "Destroy", _destroy); NSV8Objects::Template_Set(result, "EndDraw", _EndDraw); NSV8Objects::Template_Set(result, "put_GlobalAlpha", _put_GlobalAlpha); NSV8Objects::Template_Set(result, "Start_GlobalAlpha", _Start_GlobalAlpha); @@ -247,6 +249,8 @@ namespace NSGraphics v8::Local obj = GraphicsTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pGraphics)); + NSJSBase::CJSEmbedObjectPrivate::CreateWeaker(obj); + args.GetReturnValue().Set(obj); } } diff --git a/DesktopEditor/doctrenderer/embed/v8/v8_MemoryStream.cpp b/DesktopEditor/doctrenderer/embed/v8/v8_MemoryStream.cpp index 3932cff241..a4f96fa277 100644 --- a/DesktopEditor/doctrenderer/embed/v8/v8_MemoryStream.cpp +++ b/DesktopEditor/doctrenderer/embed/v8/v8_MemoryStream.cpp @@ -57,6 +57,8 @@ namespace NSMemoryStream v8::Local obj = MemoryObjectTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pMemoryObject)); + NSJSBase::CJSEmbedObjectPrivate::CreateWeaker(obj); + args.GetReturnValue().Set(obj); } } diff --git a/DesktopEditor/doctrenderer/embed/v8/v8_NativeControl.cpp b/DesktopEditor/doctrenderer/embed/v8/v8_NativeControl.cpp index 3d18f5c511..bc25fddeb4 100644 --- a/DesktopEditor/doctrenderer/embed/v8/v8_NativeControl.cpp +++ b/DesktopEditor/doctrenderer/embed/v8/v8_NativeControl.cpp @@ -3,147 +3,159 @@ namespace NSNativeControl { - #define CURRENTWRAPPER CNativeControlEmbed +#define CURRENTWRAPPER CNativeControlEmbed - FUNCTION_WRAPPER_V8(_GetFilePath, GetFilePath) - FUNCTION_WRAPPER_V8_1(_SetFilePath, SetFilePath) - FUNCTION_WRAPPER_V8(_GetFileId, GetFileId) - FUNCTION_WRAPPER_V8_1(_SetFileId, SetFileId) - FUNCTION_WRAPPER_V8_1(_GetFileArrayBuffer, GetFileBinary) - FUNCTION_WRAPPER_V8_1(_GetFontArrayBuffer, GetFontBinary) - FUNCTION_WRAPPER_V8(_GetFontsDirectory, GetFontsDirectory) - FUNCTION_WRAPPER_V8_1(_GetFileString, GetFileString) - FUNCTION_WRAPPER_V8(_GetEditorType, GetEditorType) - FUNCTION_WRAPPER_V8(_CheckNextChange, CheckNextChange) - FUNCTION_WRAPPER_V8(_GetChangesCount, GetCountChanges) - FUNCTION_WRAPPER_V8_1(_GetChangesFile, GetChangesFile) - FUNCTION_WRAPPER_V8_1(_Save_AllocNative, Save_AllocNative) - FUNCTION_WRAPPER_V8_2(_Save_ReAllocNative, Save_ReAllocNative) - FUNCTION_WRAPPER_V8_2(_Save_End, Save_End) - FUNCTION_WRAPPER_V8_1(_AddImageInChanges, AddImageInChanges) - FUNCTION_WRAPPER_V8_1(_ConsoleLog, ConsoleLog) - FUNCTION_WRAPPER_V8_3(_SaveChanges, SaveChanges) - FUNCTION_WRAPPER_V8_1(_zipOpenFile, zipOpenFile) - FUNCTION_WRAPPER_V8_1(_zipOpenFileBase64, zipOpenFileBase64) - FUNCTION_WRAPPER_V8_1(_zipGetFileAsString, zipGetFileAsString) - FUNCTION_WRAPPER_V8_1(_zipGetFileAsBinary, zipGetFileAsBinary) - FUNCTION_WRAPPER_V8(_zipCloseFile, zipCloseFile) - FUNCTION_WRAPPER_V8_1(_GetImageUrl, GetImageUrl) - FUNCTION_WRAPPER_V8_1(_GetImageOriginalSize, GetImageOriginalSize) - FUNCTION_WRAPPER_V8(_GetImagesPath, GetImagesPath) + FUNCTION_WRAPPER_V8(_GetFilePath, GetFilePath) + FUNCTION_WRAPPER_V8_1(_SetFilePath, SetFilePath) + FUNCTION_WRAPPER_V8(_GetFileId, GetFileId) + FUNCTION_WRAPPER_V8_1(_SetFileId, SetFileId) + FUNCTION_WRAPPER_V8_1(_GetFileArrayBuffer, GetFileBinary) + FUNCTION_WRAPPER_V8_1(_GetFontArrayBuffer, GetFontBinary) + FUNCTION_WRAPPER_V8(_GetFontsDirectory, GetFontsDirectory) + FUNCTION_WRAPPER_V8_1(_GetFileString, GetFileString) + FUNCTION_WRAPPER_V8(_GetEditorType, GetEditorType) + FUNCTION_WRAPPER_V8(_CheckNextChange, CheckNextChange) + FUNCTION_WRAPPER_V8(_GetChangesCount, GetCountChanges) + FUNCTION_WRAPPER_V8_1(_GetChangesFile, GetChangesFile) + FUNCTION_WRAPPER_V8_1(_Save_AllocNative, Save_AllocNative) + FUNCTION_WRAPPER_V8_2(_Save_ReAllocNative, Save_ReAllocNative) + FUNCTION_WRAPPER_V8_2(_Save_End, Save_End) + FUNCTION_WRAPPER_V8_1(_AddImageInChanges, AddImageInChanges) + FUNCTION_WRAPPER_V8_1(_ConsoleLog, ConsoleLog) + FUNCTION_WRAPPER_V8_3(_SaveChanges, SaveChanges) + FUNCTION_WRAPPER_V8_1(_zipOpenFile, zipOpenFile) + FUNCTION_WRAPPER_V8_1(_zipOpenFileBase64, zipOpenFileBase64) + FUNCTION_WRAPPER_V8_1(_zipGetFileAsString, zipGetFileAsString) + FUNCTION_WRAPPER_V8_1(_zipGetFileAsBinary, zipGetFileAsBinary) + FUNCTION_WRAPPER_V8(_zipCloseFile, zipCloseFile) + FUNCTION_WRAPPER_V8_1(_GetImageUrl, GetImageUrl) + FUNCTION_WRAPPER_V8_1(_GetImageOriginalSize, GetImageOriginalSize) + FUNCTION_WRAPPER_V8(_GetImagesPath, GetImagesPath) - v8::Handle CreateNativeControlTemplate(v8::Isolate* isolate) - { - v8::EscapableHandleScope handle_scope(isolate); + v8::Handle CreateNativeControlTemplate(v8::Isolate* isolate) + { + v8::EscapableHandleScope handle_scope(isolate); - v8::Local result = v8::ObjectTemplate::New(V8IsolateOneArg); - result->SetInternalFieldCount(1); + v8::Local result = v8::ObjectTemplate::New(V8IsolateOneArg); + result->SetInternalFieldCount(1); - NSV8Objects::Template_Set(result, "SetFilePath", _SetFilePath); - NSV8Objects::Template_Set(result, "GetFilePath", _GetFilePath); - NSV8Objects::Template_Set(result, "SetFileId", _SetFileId); - NSV8Objects::Template_Set(result, "GetFileId", _GetFileId); - NSV8Objects::Template_Set(result, "GetFileBinary", _GetFileArrayBuffer); - NSV8Objects::Template_Set(result, "GetFontBinary", _GetFontArrayBuffer); - NSV8Objects::Template_Set(result, "GetFontsDirectory", _GetFontsDirectory); - NSV8Objects::Template_Set(result, "GetFileString", _GetFileString); - NSV8Objects::Template_Set(result, "GetEditorType", _GetEditorType); - NSV8Objects::Template_Set(result, "CheckNextChange", _CheckNextChange); - NSV8Objects::Template_Set(result, "GetCountChanges", _GetChangesCount); - NSV8Objects::Template_Set(result, "GetChangesFile", _GetChangesFile); - NSV8Objects::Template_Set(result, "Save_AllocNative", _Save_AllocNative); - NSV8Objects::Template_Set(result, "Save_ReAllocNative", _Save_ReAllocNative); - NSV8Objects::Template_Set(result, "Save_End", _Save_End); - NSV8Objects::Template_Set(result, "AddImageInChanges", _AddImageInChanges); - NSV8Objects::Template_Set(result, "ConsoleLog", _ConsoleLog); - NSV8Objects::Template_Set(result, "SaveChanges", _SaveChanges); - NSV8Objects::Template_Set(result, "ZipOpen", _zipOpenFile); - NSV8Objects::Template_Set(result, "ZipOpenBase64", _zipOpenFileBase64); - NSV8Objects::Template_Set(result, "ZipFileAsString", _zipGetFileAsString); - NSV8Objects::Template_Set(result, "ZipFileAsBinary", _zipGetFileAsBinary); - NSV8Objects::Template_Set(result, "ZipClose", _zipCloseFile); - NSV8Objects::Template_Set(result, "getImageUrl", _GetImageUrl); - NSV8Objects::Template_Set(result, "getImagesDirectory", _GetImagesPath); - NSV8Objects::Template_Set(result, "GetImageOriginalSize", _GetImageOriginalSize); + NSV8Objects::Template_Set(result, "SetFilePath", _SetFilePath); + NSV8Objects::Template_Set(result, "GetFilePath", _GetFilePath); + NSV8Objects::Template_Set(result, "SetFileId", _SetFileId); + NSV8Objects::Template_Set(result, "GetFileId", _GetFileId); + NSV8Objects::Template_Set(result, "GetFileBinary", _GetFileArrayBuffer); + NSV8Objects::Template_Set(result, "GetFontBinary", _GetFontArrayBuffer); + NSV8Objects::Template_Set(result, "GetFontsDirectory", _GetFontsDirectory); + NSV8Objects::Template_Set(result, "GetFileString", _GetFileString); + NSV8Objects::Template_Set(result, "GetEditorType", _GetEditorType); + NSV8Objects::Template_Set(result, "CheckNextChange", _CheckNextChange); + NSV8Objects::Template_Set(result, "GetCountChanges", _GetChangesCount); + NSV8Objects::Template_Set(result, "GetChangesFile", _GetChangesFile); + //NSV8Objects::Template_Set(result, "Save_AllocNative", _Save_AllocNative); + //NSV8Objects::Template_Set(result, "Save_ReAllocNative", _Save_ReAllocNative); + NSV8Objects::Template_Set(result, "Save_End", _Save_End); + NSV8Objects::Template_Set(result, "AddImageInChanges", _AddImageInChanges); + NSV8Objects::Template_Set(result, "ConsoleLog", _ConsoleLog); + NSV8Objects::Template_Set(result, "SaveChanges", _SaveChanges); + NSV8Objects::Template_Set(result, "ZipOpen", _zipOpenFile); + NSV8Objects::Template_Set(result, "ZipOpenBase64", _zipOpenFileBase64); + NSV8Objects::Template_Set(result, "ZipFileAsString", _zipGetFileAsString); + NSV8Objects::Template_Set(result, "ZipFileAsBinary", _zipGetFileAsBinary); + NSV8Objects::Template_Set(result, "ZipClose", _zipCloseFile); + NSV8Objects::Template_Set(result, "getImageUrl", _GetImageUrl); + NSV8Objects::Template_Set(result, "getImagesDirectory", _GetImagesPath); + NSV8Objects::Template_Set(result, "GetImageOriginalSize", _GetImageOriginalSize); - return handle_scope.Escape(result); - } + return handle_scope.Escape(result); + } - // Без SaveChanges - v8::Handle CreateNativeControlTemplateBuilder(v8::Isolate* isolate) - { - v8::EscapableHandleScope handle_scope(isolate); + // Без SaveChanges + v8::Handle CreateNativeControlTemplateBuilder(v8::Isolate* isolate) + { + v8::EscapableHandleScope handle_scope(isolate); - v8::Local result = v8::ObjectTemplate::New(V8IsolateOneArg); - result->SetInternalFieldCount(1); + v8::Local result = v8::ObjectTemplate::New(V8IsolateOneArg); + result->SetInternalFieldCount(1); - NSV8Objects::Template_Set(result, "SetFilePath", _SetFilePath); - NSV8Objects::Template_Set(result, "GetFilePath", _GetFilePath); - NSV8Objects::Template_Set(result, "SetFileId", _SetFileId); - NSV8Objects::Template_Set(result, "GetFileId", _GetFileId); - NSV8Objects::Template_Set(result, "GetFileBinary", _GetFileArrayBuffer); - NSV8Objects::Template_Set(result, "GetFontBinary", _GetFontArrayBuffer); - NSV8Objects::Template_Set(result, "GetFontsDirectory", _GetFontsDirectory); - NSV8Objects::Template_Set(result, "GetFileString", _GetFileString); - NSV8Objects::Template_Set(result, "GetEditorType", _GetEditorType); - NSV8Objects::Template_Set(result, "CheckNextChange", _CheckNextChange); - NSV8Objects::Template_Set(result, "GetCountChanges", _GetChangesCount); - NSV8Objects::Template_Set(result, "GetChangesFile", _GetChangesFile); - NSV8Objects::Template_Set(result, "Save_AllocNative", _Save_AllocNative); - NSV8Objects::Template_Set(result, "Save_ReAllocNative", _Save_ReAllocNative); - NSV8Objects::Template_Set(result, "Save_End", _Save_End); - NSV8Objects::Template_Set(result, "AddImageInChanges", _AddImageInChanges); - NSV8Objects::Template_Set(result, "ConsoleLog", _ConsoleLog); - NSV8Objects::Template_Set(result, "ZipOpen", _zipOpenFile); - NSV8Objects::Template_Set(result, "ZipOpenBase64", _zipOpenFileBase64); - NSV8Objects::Template_Set(result, "ZipFileAsString", _zipGetFileAsString); - NSV8Objects::Template_Set(result, "ZipFileAsBinary", _zipGetFileAsBinary); - NSV8Objects::Template_Set(result, "ZipClose", _zipCloseFile); - NSV8Objects::Template_Set(result, "getImageUrl", _GetImageUrl); - NSV8Objects::Template_Set(result, "getImagesDirectory", _GetImagesPath); - NSV8Objects::Template_Set(result, "GetImageOriginalSize", _GetImageOriginalSize); + NSV8Objects::Template_Set(result, "SetFilePath", _SetFilePath); + NSV8Objects::Template_Set(result, "GetFilePath", _GetFilePath); + NSV8Objects::Template_Set(result, "SetFileId", _SetFileId); + NSV8Objects::Template_Set(result, "GetFileId", _GetFileId); + NSV8Objects::Template_Set(result, "GetFileBinary", _GetFileArrayBuffer); + NSV8Objects::Template_Set(result, "GetFontBinary", _GetFontArrayBuffer); + NSV8Objects::Template_Set(result, "GetFontsDirectory", _GetFontsDirectory); + NSV8Objects::Template_Set(result, "GetFileString", _GetFileString); + NSV8Objects::Template_Set(result, "GetEditorType", _GetEditorType); + NSV8Objects::Template_Set(result, "CheckNextChange", _CheckNextChange); + NSV8Objects::Template_Set(result, "GetCountChanges", _GetChangesCount); + NSV8Objects::Template_Set(result, "GetChangesFile", _GetChangesFile); + //NSV8Objects::Template_Set(result, "Save_AllocNative", _Save_AllocNative); + //NSV8Objects::Template_Set(result, "Save_ReAllocNative", _Save_ReAllocNative); + NSV8Objects::Template_Set(result, "Save_End", _Save_End); + NSV8Objects::Template_Set(result, "AddImageInChanges", _AddImageInChanges); + NSV8Objects::Template_Set(result, "ConsoleLog", _ConsoleLog); + NSV8Objects::Template_Set(result, "ZipOpen", _zipOpenFile); + NSV8Objects::Template_Set(result, "ZipOpenBase64", _zipOpenFileBase64); + NSV8Objects::Template_Set(result, "ZipFileAsString", _zipGetFileAsString); + NSV8Objects::Template_Set(result, "ZipFileAsBinary", _zipGetFileAsBinary); + NSV8Objects::Template_Set(result, "ZipClose", _zipCloseFile); + NSV8Objects::Template_Set(result, "getImageUrl", _GetImageUrl); + NSV8Objects::Template_Set(result, "getImagesDirectory", _GetImagesPath); + NSV8Objects::Template_Set(result, "GetImageOriginalSize", _GetImageOriginalSize); - return handle_scope.Escape(result); - } + return handle_scope.Escape(result); + } - void CreateNativeObject(const v8::FunctionCallbackInfo& args) - { - v8::Isolate* isolate = args.GetIsolate(); - v8::HandleScope scope(isolate); + void CreateNativeObject(const v8::FunctionCallbackInfo& args) + { + v8::Isolate* isolate = args.GetIsolate(); + v8::HandleScope scope(isolate); - v8::Handle NativeObjectTemplate = CreateNativeControlTemplate(isolate); - CNativeControlEmbed* pNativeObject = new CNativeControlEmbed(); + if (CIsolateAdditionalData::CheckSingletonType(isolate, CIsolateAdditionalData::iadtSingletonNative)) + { + args.GetReturnValue().Set(v8::Undefined(isolate)); + return; + } - v8::Local obj = NativeObjectTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); - obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pNativeObject)); + v8::Handle NativeObjectTemplate = CreateNativeControlTemplate(isolate); + CNativeControlEmbed* pNativeObject = new CNativeControlEmbed(); - args.GetReturnValue().Set(obj); - } + v8::Local obj = NativeObjectTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); + obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pNativeObject)); - // Без SaveChanges - void CreateNativeObjectBuilder(const v8::FunctionCallbackInfo& args) - { - v8::Isolate* isolate = args.GetIsolate(); - v8::HandleScope scope(isolate); + args.GetReturnValue().Set(obj); + } - v8::Handle NativeObjectTemplate = CreateNativeControlTemplateBuilder(isolate); - CNativeControlEmbed* pNativeObject = new CNativeControlEmbed(); + // Без SaveChanges + void CreateNativeObjectBuilder(const v8::FunctionCallbackInfo& args) + { + v8::Isolate* isolate = args.GetIsolate(); + v8::HandleScope scope(isolate); - v8::Local obj = NativeObjectTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); - obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pNativeObject)); + if (CIsolateAdditionalData::CheckSingletonType(isolate, CIsolateAdditionalData::iadtSingletonNative)) + { + args.GetReturnValue().Set(v8::Undefined(isolate)); + return; + } - args.GetReturnValue().Set(obj); - } + v8::Handle NativeObjectTemplate = CreateNativeControlTemplateBuilder(isolate); + CNativeControlEmbed* pNativeObject = new CNativeControlEmbed(); + + v8::Local obj = NativeObjectTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); + obj->SetInternalField(0, v8::External::New(CV8Worker::GetCurrent(), pNativeObject)); + + args.GetReturnValue().Set(obj); + } } void CNativeControlEmbed::CreateObjectInContext(const std::string& name, JSSmart context) { - v8::Isolate* current = CV8Worker::GetCurrent(); - context->m_internal->m_global->Set(current, name.c_str(), v8::FunctionTemplate::New(current, NSNativeControl::CreateNativeObject)); + v8::Isolate* current = CV8Worker::GetCurrent(); + context->m_internal->m_global->Set(current, name.c_str(), v8::FunctionTemplate::New(current, NSNativeControl::CreateNativeObject)); } void CNativeControlEmbed::CreateObjectBuilderInContext(const std::string& name, JSSmart context) { - v8::Isolate* current = CV8Worker::GetCurrent(); - context->m_internal->m_global->Set(current, name.c_str(), v8::FunctionTemplate::New(current, NSNativeControl::CreateNativeObjectBuilder)); + v8::Isolate* current = CV8Worker::GetCurrent(); + context->m_internal->m_global->Set(current, name.c_str(), v8::FunctionTemplate::New(current, NSNativeControl::CreateNativeObjectBuilder)); } diff --git a/DesktopEditor/doctrenderer/embed/v8/v8_Zip.cpp b/DesktopEditor/doctrenderer/embed/v8/v8_Zip.cpp index ed38de2fbd..fc48aeb6be 100644 --- a/DesktopEditor/doctrenderer/embed/v8/v8_Zip.cpp +++ b/DesktopEditor/doctrenderer/embed/v8/v8_Zip.cpp @@ -12,6 +12,7 @@ namespace NSZip FUNCTION_WRAPPER_V8_2(_addFile, addFile) FUNCTION_WRAPPER_V8_1(_removeFile, removeFile) FUNCTION_WRAPPER_V8 (_close, close) + FUNCTION_WRAPPER_V8 (_getPaths, getPaths) FUNCTION_WRAPPER_V8_2(_decodeImage, decodeImage) FUNCTION_WRAPPER_V8_6(_encodeImageData, encodeImageData) @@ -33,6 +34,7 @@ namespace NSZip NSV8Objects::Template_Set(result, "addFile", _addFile); NSV8Objects::Template_Set(result, "removeFile", _removeFile); NSV8Objects::Template_Set(result, "close", _close); + NSV8Objects::Template_Set(result, "getPaths", _getPaths); NSV8Objects::Template_Set(result, "decodeImage", _decodeImage); NSV8Objects::Template_Set(result, "encodeImageData", _encodeImageData); diff --git a/DesktopEditor/doctrenderer/graphics.cpp b/DesktopEditor/doctrenderer/graphics.cpp index af414c4e11..84bc587a59 100644 --- a/DesktopEditor/doctrenderer/graphics.cpp +++ b/DesktopEditor/doctrenderer/graphics.cpp @@ -27,8 +27,21 @@ namespace NSGraphics int nRasterW = (int)width_px; int nRasterH = (int)height_px; - BYTE* pData = new BYTE[4 * nRasterW * nRasterH]; + // TODO: + int nLimit = 2000; + int nMax = (nRasterW > nRasterH) ? nRasterW : nRasterH; + if (nMax > nLimit) + { + double dKoef = (double)nLimit / nMax; + nRasterW = (int)(0.5 + dKoef * nRasterW); + nRasterH = (int)(0.5 + dKoef * nRasterH); + + if (nRasterW < 1) nRasterW = 0; + if (nRasterH < 1) nRasterH = 0; + } + + BYTE* pData = new BYTE[4 * nRasterW * nRasterH]; unsigned int back = 0xffffff; unsigned int* pData32 = (unsigned int*)pData; unsigned int* pData32End = pData32 + nRasterW * nRasterH; diff --git a/DesktopEditor/doctrenderer/graphics.h b/DesktopEditor/doctrenderer/graphics.h index bbedaac943..2b8a45b1c7 100644 --- a/DesktopEditor/doctrenderer/graphics.h +++ b/DesktopEditor/doctrenderer/graphics.h @@ -128,11 +128,15 @@ namespace NSGraphics CGraphics() {} ~CGraphics() { - RELEASEINTERFACE(m_pRenderer); - RELEASEINTERFACE(m_pApplicationFonts); + Destroy(); } void init(NSNativeControl::CNativeControl* oNative, double width_px, double height_px, double width_mm, double height_mm); + void Destroy() + { + RELEASEINTERFACE(m_pRenderer); + RELEASEINTERFACE(m_pApplicationFonts); + } void EndDraw() {} void put_GlobalAlpha(bool enable, double globalAlpha); void Start_GlobalAlpha() {} diff --git a/DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp b/DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp index 1e25b12362..ef15d4c5dc 100644 --- a/DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp +++ b/DesktopEditor/doctrenderer/js_internal/v8/v8_base.cpp @@ -219,6 +219,17 @@ namespace NSJSBase #ifdef V8_INSPECTOR v8_debug::disposeInspector(m_internal->m_context); #endif + unsigned int nEmbedDataCount = m_internal->m_isolate->GetNumberOfDataSlots(); + if (nEmbedDataCount > 0) + { + void* pSingletonData = m_internal->m_isolate->GetData(0); + if (NULL != pSingletonData) + { + CIsolateAdditionalData* pData = (CIsolateAdditionalData*)pSingletonData; + delete pData; + } + } + m_internal->m_isolate->Dispose(); m_internal->m_isolate = NULL; } diff --git a/DesktopEditor/doctrenderer/js_internal/v8/v8_base.h b/DesktopEditor/doctrenderer/js_internal/v8/v8_base.h index 293886553c..2700377c3d 100644 --- a/DesktopEditor/doctrenderer/js_internal/v8/v8_base.h +++ b/DesktopEditor/doctrenderer/js_internal/v8/v8_base.h @@ -72,6 +72,44 @@ public: }; #endif +class CIsolateAdditionalData +{ +public: + enum IsolateAdditionlDataType { + iadtSingletonNative = 0, + iadtUndefined = 255 + }; + + IsolateAdditionlDataType m_eType; +public: + CIsolateAdditionalData(const IsolateAdditionlDataType& type = iadtUndefined) { m_eType = type; } + virtual ~CIsolateAdditionalData() {} + + static bool CheckSingletonType(v8::Isolate* isolate, const IsolateAdditionlDataType& type, const bool& isAdd = true) + { + unsigned int nCount = isolate->GetNumberOfDataSlots(); + if (nCount == 0) + return false; + + void* pSingletonData = isolate->GetData(0); + if (NULL != pSingletonData) + { + CIsolateAdditionalData* pData = (CIsolateAdditionalData*)pSingletonData; + if (pData->m_eType == type) + return true; + + return false; + } + + if (isAdd) + { + isolate->SetData(0, (void*)(new CIsolateAdditionalData(type))); + } + + return false; + } +}; + class CV8Initializer { private: diff --git a/DesktopEditor/fontengine/FontManager.cpp b/DesktopEditor/fontengine/FontManager.cpp index fe487a4862..27702bd05c 100644 --- a/DesktopEditor/fontengine/FontManager.cpp +++ b/DesktopEditor/fontengine/FontManager.cpp @@ -135,11 +135,13 @@ NSFonts::IFontStream* CApplicationFontStreams::GetStream(const std::wstring &str } } +#ifndef FONT_ENGINE_DISABLE_FILESYSTEM if (!pStream) { pStream = new CFontStream(); pStream->CreateFromFile(strFile); } +#endif m_mapStreams[strFile] = pStream; return pStream; diff --git a/DesktopEditor/fontengine/TextShaper.cpp b/DesktopEditor/fontengine/TextShaper.cpp index ba2d9ada1b..37712f4597 100644 --- a/DesktopEditor/fontengine/TextShaper.cpp +++ b/DesktopEditor/fontengine/TextShaper.cpp @@ -31,620 +31,614 @@ */ #include "./TextShaper.h" - -#include -#include "ftsnames.h" -#include FT_OUTLINE_H -#include FT_SIZES_H -#include FT_GLYPH_H -#include FT_TRUETYPE_IDS_H -#include FT_TRUETYPE_TABLES_H -#include FT_XFREE86_H -#include FT_ADVANCES_H -#include FT_LCD_FILTER_H -#include FT_DRIVER_H -#include -#include "ftmodapi.h" +#include "./TextShaper_p.h" namespace NSShaper { - #define ALLOC_WRITER(size) result->Alloc((size)); unsigned char* pCurData = result->Data - #define WRITE_INT(value) result->WriteInt(pCurData, value); pCurData += 4 - #define WRITE_UINT(value) result->WriteUInt(pCurData, value); pCurData += 4 - #define WRITE_UCHAR(value) *pCurData++ = value - - CExternalPointer::CExternalPointer() - { - Data = NULL; - Len = 0; - } - CExternalPointer::~CExternalPointer() - { - } - - void CExternalPointer::WriteInt(unsigned char* data, const int& value) - { - WriteUInt(data, (unsigned int)value); - } - void CExternalPointer::WriteUInt(unsigned char* data, const unsigned int& value) - { - data[0] = (value & 0xFF); - data[1] = ((value >> 8) & 0xFF); - data[2] = ((value >> 16) & 0xFF); - data[3] = ((value >> 24) & 0xFF); - } - - void CExternalPointer::Alloc(const unsigned int& len) - { - Len = len; - Data = new unsigned char[Len]; - } - void CExternalPointer::Free() - { - if (Data) - delete [] Data; - } - - // outline - #define FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE 200 - typedef struct FT_Decompose_Outline_Buffer_ - { - FT_Pos* buffer; - FT_Int size; - FT_Int pos; - } FT_Decompose_Outline_Buffer; - - void FT_Decompose_Outline_Buffer_Init(FT_Decompose_Outline_Buffer* buffer) - { - buffer->buffer = NULL; - buffer->size = 0; - buffer->pos = 0; - } - - void FT_Decompose_Outline_Buffer_Destroy(FT_Decompose_Outline_Buffer* buffer) - { - ft_sfree(buffer->buffer); - } - - void FT_Decompose_Outline_Buffer_Check(FT_Decompose_Outline_Buffer* buffer, FT_Int add) - { - if ((buffer->pos + add) < buffer->size) - return; - - if (NULL == buffer->buffer) - { - buffer->buffer = (FT_Pos*)ft_smalloc(FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE * sizeof(FT_Pos)); - buffer->size = FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE; - buffer->pos = 0; - return; - } - - FT_Int sizeNew = 2 * buffer->size; - FT_Pos* bufferNew = (FT_Pos*)ft_smalloc((size_t)sizeNew * sizeof(FT_Pos)); - memcpy(bufferNew, buffer->buffer, (size_t)buffer->pos * sizeof(FT_Pos)); - ft_sfree(buffer->buffer); - buffer->buffer = bufferNew; - buffer->size = sizeNew; - // pos - } - - int GlyphPathMoveTo(const FT_Vector *point, void *user) - { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 3); - buffer->buffer[buffer->pos++] = 0; - buffer->buffer[buffer->pos++] = point->x; - buffer->buffer[buffer->pos++] = point->y; - return 0; - } - - int GlyphPathLineTo(const FT_Vector *point, void *user) - { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 3); - buffer->buffer[buffer->pos++] = 1; - buffer->buffer[buffer->pos++] = point->x; - buffer->buffer[buffer->pos++] = point->y; - return 0; - } - - int GlyphPathConicTo(const FT_Vector *pControlPoint, const FT_Vector *pEndPoint, void *user) - { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 5); - buffer->buffer[buffer->pos++] = 2; - buffer->buffer[buffer->pos++] = pControlPoint->x; - buffer->buffer[buffer->pos++] = pControlPoint->y; - buffer->buffer[buffer->pos++] = pEndPoint->x; - buffer->buffer[buffer->pos++] = pEndPoint->y; - return 0; - } - - int GlyphPathCubicTo(const FT_Vector *pFirstControlPoint, const FT_Vector *pSecondControlPoint, const FT_Vector *pEndPoint, void *user) - { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 7); - buffer->buffer[buffer->pos++] = 3; - buffer->buffer[buffer->pos++] = pFirstControlPoint->x; - buffer->buffer[buffer->pos++] = pFirstControlPoint->y; - buffer->buffer[buffer->pos++] = pSecondControlPoint->x; - buffer->buffer[buffer->pos++] = pSecondControlPoint->y; - buffer->buffer[buffer->pos++] = pEndPoint->x; - buffer->buffer[buffer->pos++] = pEndPoint->y; - return 0; - } - ///////////////////////////////////////////////////////////////////// - - void FT_Free(void* data) - { - ft_sfree(data); - } - - void* FT_Library_Init() - { - FT_Library library = NULL; - FT_Init_FreeType(&library); - FT_Library_SetLcdFilter(library, FT_LCD_FILTER_DEFAULT); - return library; - } - void FT_Library_Destroy(void* library) - { - ::FT_Done_FreeType((FT_Library)library); - } - void FT_Library_Reference(void* library) - { - FT_Reference_Library((FT_Library)library); - } - void FT_Library_UnReference(void* library_) - { - FT_Library library = (FT_Library)library_; - if (library->refcount == 1) - ::FT_Done_FreeType(library); - else - ::FT_Done_Library(library); - } - - int FT_Set_TrueType_HintProp(void* library, unsigned int interpreter_version) - { - FT_UInt ft_interpreter_version = interpreter_version; - return FT_Property_Set((FT_Library)library, "truetype", "interpreter-version", &ft_interpreter_version); - } - - void* FT_Open_Face(void* library, unsigned char* memory, unsigned int size, int face_index) - { - FT_Open_Args oOpenArgs; - oOpenArgs.flags = FT_OPEN_MEMORY | FT_OPEN_PARAMS; - oOpenArgs.memory_base = memory; - oOpenArgs.memory_size = (FT_Long)size; - - FT_Parameter *pParams = (FT_Parameter *)ft_smalloc( sizeof(FT_Parameter) * 4 ); - pParams[0].tag = FT_MAKE_TAG( 'i', 'g', 'p', 'f' ); - pParams[0].data = NULL; - pParams[1].tag = FT_MAKE_TAG( 'i', 'g', 'p', 's' ); - pParams[1].data = NULL; - pParams[2].tag = FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY; - pParams[2].data = NULL; - pParams[3].tag = FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY; - pParams[3].data = NULL; - - oOpenArgs.params = pParams; - oOpenArgs.num_params = 4; - - FT_Face face; - int error = ::FT_Open_Face( (FT_Library)library, &oOpenArgs, face_index, &face ); - - ft_sfree(pParams); - - if (error) - return NULL; - - return face; - } - - void FT_Done_Face(void* face) - { - ::FT_Done_Face((FT_Face)face); - } - - void FT_Done_Face_With_Library(void* face) - { - FT_Face ftface = (FT_Face)face; - FT_Library library = ftface->driver->root.library; - - bool bIsNeedUnreferenceLibrary = (1 == ftface->internal->refcount) ? true : false; - ::FT_Done_Face(ftface); - - if (bIsNeedUnreferenceLibrary) - FT_Library_UnReference(library); - } - - unsigned int FT_SetCMapForCharCode(void* face_pointer, unsigned int unicode) - { - if (!face_pointer) - return 0; - - FT_Face face = (FT_Face)face_pointer; - - if ( 0 == face->num_charmaps ) - return unicode; - - unsigned int nCharIndex = 0; - - for ( int nIndex = 0; nIndex < face->num_charmaps; ++nIndex ) - { - FT_CharMap pCharMap = face->charmaps[nIndex]; - - if ( FT_Set_Charmap( face, pCharMap ) ) - continue; - - FT_Encoding pEncoding = pCharMap->encoding; - - if ( FT_ENCODING_UNICODE == pEncoding ) - { - nCharIndex = FT_Get_Char_Index( face, unicode ); - if ( nCharIndex ) - { - return nCharIndex; - } - } - else if ( FT_ENCODING_NONE == pEncoding || FT_ENCODING_MS_SYMBOL == pEncoding || FT_ENCODING_APPLE_ROMAN == pEncoding ) - { - #if 0 - FT_ULong charcode; - FT_UInt gindex; - - charcode = FT_Get_First_Char( face, &gindex ); - while ( gindex != 0 ) - { - charcode = FT_Get_Next_Char( face, charcode, &gindex ); - if ( charcode == unicode ) - { - nCharIndex = gindex; - break; - } - } - #endif - - nCharIndex = FT_Get_Char_Index( face, unicode ); - } - } - - return nCharIndex; - } - - int FT_GetFaceMaxAdvanceX(void* face_pointer) - { - if (!face_pointer) - return 0; - - FT_Face face = (FT_Face)face_pointer; - if (!face->size) - return 0; - - return (int)face->size->metrics.max_advance; - } - - int FT_GetKerningX(void* face, unsigned int prev_gid, unsigned int gid) - { - FT_Vector vec; - vec.x = 0; - vec.y = 0; - FT_Get_Kerning((FT_Face)face, prev_gid, gid, 0, &vec); - return vec.x; - } - - void FT_Set_Transform(void* face, int xx, int yx, int xy, int yy) - { - FT_Matrix m; - m.xx = xx; - m.yx = yx; - m.xy = xy; - m.yy = yy; - ::FT_Set_Transform((FT_Face)face, &m, NULL); - } - - int FT_Load_Glyph(void* face, unsigned int glyph_index, int load_flags) - { - return ::FT_Load_Glyph((FT_Face)face, glyph_index, load_flags); - } - - int FT_Set_Char_Size(void* face, int char_width, int char_height, unsigned int hres, unsigned int vres) - { - return ::FT_Set_Char_Size((FT_Face)face, char_width, char_height, hres, vres); - } - - void FT_Glyph_Get_CBox(void* glyph, unsigned int bbox_mode, CExternalPointer* result) - { - FT_BBox bbox; - FT_Glyph_Get_CBox((FT_Glyph)glyph, bbox_mode, &bbox); - ALLOC_WRITER(4 * 4); - WRITE_INT(bbox.xMin); - WRITE_INT(bbox.yMin); - WRITE_INT(bbox.xMax); - WRITE_INT(bbox.yMax); - } - - unsigned char* FT_Get_Glyph_Render_Buffer(void* face) - { - return ((FT_Face)face)->glyph->bitmap.buffer; - } - - bool FT_Get_Glyph_Render_Params(void* face, int render_mode, CExternalPointer* result) - { - FT_GlyphSlot slot = ((FT_Face)face)->glyph; - if (FT_Render_Glyph(slot, (FT_Render_Mode)render_mode)) - return false; - - ALLOC_WRITER(6 * 4); - WRITE_INT(slot->bitmap_left); - WRITE_INT(slot->bitmap_top); - WRITE_UINT(slot->bitmap.width); - WRITE_UINT(slot->bitmap.rows); - WRITE_INT(slot->bitmap.pitch); - WRITE_INT(slot->bitmap.pixel_mode); - return true; - } - - bool FT_GetFaceInfo(void* face_pointer, CExternalPointer* result) - { - if (!face_pointer) - return false; - - FT_Face face = (FT_Face)face_pointer; - - //face->units_per_EM - //face->ascender - //face->descender - //face->height - //face->face_flags - //face->num_faces - //face->num_glyphs - //face->num_charmaps - //face->style_flags - //face->face_index - //face->family_name - //face->style_name - - TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 ); - //os2->version - //os2->usWeightClass - //os2->fsSelection - //os2->usWinAscent - //os2->usWinDescent - //os2->usDefaultChar - //os2->sTypoAscender; - //os2->sTypoDescender; - //os2->sTypoLineGap; - - //os2->ulUnicodeRange1 - //os2->ulUnicodeRange2 - //os2->ulUnicodeRange3 - //os2->ulUnicodeRange4 - //os2->ulCodePageRange1 - //os2->ulCodePageRange2 - - int isSymbolic = -1; - if (os2 && 0xFFFF != os2->version) - { - FT_ULong ulCodePageRange1 = os2->ulCodePageRange1; - FT_ULong ulCodePageRange2 = os2->ulCodePageRange2; - - if ((ulCodePageRange1 & 0x80000000) || (ulCodePageRange1 == 0 && ulCodePageRange2 == 0)) - { - for( int nIndex = 0; nIndex < face->num_charmaps; nIndex++ ) - { - if (0 == face->charmaps[nIndex]->encoding_id && 3 == face->charmaps[nIndex]->platform_id) - { - isSymbolic = nIndex; - break; - } - } - } - } - - int nHeader_yMin = face->descender; - int nHeader_yMax = face->ascender; - if (face && FT_IS_SFNT(face)) - { - TT_Face ttface = (TT_Face)face; - nHeader_yMin = ttface->header.yMin; - nHeader_yMax = ttface->header.yMax; - } - - //isSymbolic - - unsigned int nLen1 = (unsigned int)strlen(face->family_name); - unsigned int nLen2 = (unsigned int)strlen(face->style_name); - - unsigned int nLen = 28 + nLen1 + 1 + nLen2 + 1 + 1 + (int)face->num_fixed_sizes; - - ALLOC_WRITER(nLen * 4); - WRITE_INT((int)face->units_per_EM); - WRITE_INT((int)face->ascender); - WRITE_INT((int)face->descender); - WRITE_INT((int)face->height); - WRITE_INT((int)face->face_flags); - WRITE_INT((int)face->num_faces); - WRITE_INT((int)face->num_glyphs); - WRITE_INT((int)face->num_charmaps); - WRITE_INT((int)face->style_flags); - WRITE_INT((int)face->face_index); - - for (unsigned int i = 0; i < nLen1; ++i) - { - WRITE_INT(face->family_name[i]); - } - WRITE_INT(0); - - for (unsigned int i = 0; i < nLen2; ++i) - { - WRITE_INT(face->style_name[i]); - } - WRITE_INT(0); - - if (os2) - { - WRITE_INT((int)os2->version); - WRITE_INT((int)os2->usWeightClass); - WRITE_INT((int)os2->fsSelection); - WRITE_INT((int)os2->usWinAscent); - WRITE_INT((int)os2->usWinDescent); - WRITE_INT((int)os2->usDefaultChar); - WRITE_INT((int)os2->sTypoAscender); - WRITE_INT((int)os2->sTypoDescender); - WRITE_INT((int)os2->sTypoLineGap); - - WRITE_INT((int)os2->ulUnicodeRange1); - WRITE_INT((int)os2->ulUnicodeRange2); - WRITE_INT((int)os2->ulUnicodeRange3); - WRITE_INT((int)os2->ulUnicodeRange4); - WRITE_INT((int)os2->ulCodePageRange1); - WRITE_INT((int)os2->ulCodePageRange2); - } - else - { - WRITE_INT((int)0xFFFF); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - WRITE_INT((int)0); - } - - WRITE_INT((int)isSymbolic); - WRITE_INT((int)nHeader_yMin); - WRITE_INT((int)nHeader_yMax); - - WRITE_INT((int)face->num_fixed_sizes); - - for (int i = 0; i < face->num_fixed_sizes; ++i) - { - WRITE_INT((int)face->available_sizes[i].size); - } - - return true; - } - - bool FT_Get_Glyph_Measure_Params(void* face, bool isVector, CExternalPointer* result) - { - FT_GlyphSlot slot = ((FT_Face)face)->glyph; - - if (!isVector && slot->bitmap.buffer != NULL && slot->format == FT_GLYPH_FORMAT_BITMAP) - { - ALLOC_WRITER(15 * 4); - WRITE_INT(15); - WRITE_INT(0); - WRITE_INT(0); - WRITE_INT(slot->metrics.width); - WRITE_INT(slot->metrics.height); - - WRITE_INT(slot->metrics.width); - WRITE_INT(slot->metrics.height); - - WRITE_INT(slot->metrics.horiAdvance); - WRITE_INT(slot->metrics.horiBearingX); - WRITE_INT(slot->metrics.horiBearingY); - - WRITE_INT(slot->metrics.vertAdvance); - WRITE_INT(slot->metrics.vertBearingX); - WRITE_INT(slot->metrics.vertBearingY); - - WRITE_INT(slot->linearHoriAdvance); - WRITE_INT(slot->linearVertAdvance); - return true; - } - - FT_Glyph glyph; - FT_Get_Glyph(slot, &glyph); - if (!glyph) - return false; - - FT_BBox bbox; - FT_Glyph_Get_CBox(glyph, 1, &bbox); - - if (isVector) - { - FT_Decompose_Outline_Buffer buffer; - FT_Decompose_Outline_Buffer_Init(&buffer); - - static FT_Outline_Funcs pOutlineFuncs = - { - &GlyphPathMoveTo, - &GlyphPathLineTo, - &GlyphPathConicTo, - &GlyphPathCubicTo, - 0, 0 - }; - - FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline, &pOutlineFuncs, &buffer); - - int nCount = buffer.pos; - - ALLOC_WRITER((nCount + 15) * 4); - WRITE_INT((nCount + 15)); - WRITE_INT(bbox.xMin); - WRITE_INT(bbox.yMin); - WRITE_INT(bbox.xMax); - WRITE_INT(bbox.yMax); - - WRITE_INT(slot->metrics.width); - WRITE_INT(slot->metrics.height); - - WRITE_INT(slot->metrics.horiAdvance); - WRITE_INT(slot->metrics.horiBearingX); - WRITE_INT(slot->metrics.horiBearingY); - - WRITE_INT(slot->metrics.vertAdvance); - WRITE_INT(slot->metrics.vertBearingX); - WRITE_INT(slot->metrics.vertBearingY); - - WRITE_INT(slot->linearHoriAdvance); - WRITE_INT(slot->linearVertAdvance); - - for (int i = 0; i < nCount; i++) - { - WRITE_INT(buffer.buffer[i]); - } - - FT_Decompose_Outline_Buffer_Destroy(&buffer); - } - else - { - ALLOC_WRITER(15 * 4); - WRITE_INT(15); - WRITE_INT(bbox.xMin); - WRITE_INT(bbox.yMin); - WRITE_INT(bbox.xMax); - WRITE_INT(bbox.yMax); - - WRITE_INT(slot->metrics.width); - WRITE_INT(slot->metrics.height); - - WRITE_INT(slot->metrics.horiAdvance); - WRITE_INT(slot->metrics.horiBearingX); - WRITE_INT(slot->metrics.horiBearingY); - - WRITE_INT(slot->metrics.vertAdvance); - WRITE_INT(slot->metrics.vertBearingX); - WRITE_INT(slot->metrics.vertBearingY); - - WRITE_INT(slot->linearHoriAdvance); - WRITE_INT(slot->linearVertAdvance); - } - - FT_Done_Glyph(glyph); - return true; - } +#define ALLOC_WRITER(size) result->Alloc((size)); unsigned char* pCurData = result->Data +#define WRITE_INT(value) result->WriteInt(pCurData, value); pCurData += 4 +#define WRITE_UINT(value) result->WriteUInt(pCurData, value); pCurData += 4 +#define WRITE_UCHAR(value) *pCurData++ = value + + CExternalPointer::CExternalPointer() + { + Data = NULL; + Len = 0; + } + CExternalPointer::~CExternalPointer() + { + } + + void CExternalPointer::WriteInt(unsigned char* data, const int& value) + { + WriteUInt(data, (unsigned int)value); + } + void CExternalPointer::WriteUInt(unsigned char* data, const unsigned int& value) + { + data[0] = (value & 0xFF); + data[1] = ((value >> 8) & 0xFF); + data[2] = ((value >> 16) & 0xFF); + data[3] = ((value >> 24) & 0xFF); + } + + void CExternalPointer::Alloc(const unsigned int& len) + { + Len = len; + Data = new unsigned char[Len]; + } + void CExternalPointer::Free() + { + if (Data) + delete [] Data; + } + + // outline +#define FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE 200 + typedef struct FT_Decompose_Outline_Buffer_ + { + FT_Pos* buffer; + FT_Int size; + FT_Int pos; + } FT_Decompose_Outline_Buffer; + + void FT_Decompose_Outline_Buffer_Init(FT_Decompose_Outline_Buffer* buffer) + { + buffer->buffer = NULL; + buffer->size = 0; + buffer->pos = 0; + } + + void FT_Decompose_Outline_Buffer_Destroy(FT_Decompose_Outline_Buffer* buffer) + { + ft_sfree(buffer->buffer); + } + + void FT_Decompose_Outline_Buffer_Check(FT_Decompose_Outline_Buffer* buffer, FT_Int add) + { + if ((buffer->pos + add) < buffer->size) + return; + + if (NULL == buffer->buffer) + { + buffer->buffer = (FT_Pos*)ft_smalloc(FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE * sizeof(FT_Pos)); + buffer->size = FT_DECOMPOSE_OUTLINE_BUFFER_INIT_SIZE; + buffer->pos = 0; + return; + } + + FT_Int sizeNew = 2 * buffer->size; + FT_Pos* bufferNew = (FT_Pos*)ft_smalloc((size_t)sizeNew * sizeof(FT_Pos)); + memcpy(bufferNew, buffer->buffer, (size_t)buffer->pos * sizeof(FT_Pos)); + ft_sfree(buffer->buffer); + buffer->buffer = bufferNew; + buffer->size = sizeNew; + // pos + } + + int GlyphPathMoveTo(const FT_Vector *point, void *user) + { + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 3); + buffer->buffer[buffer->pos++] = 0; + buffer->buffer[buffer->pos++] = point->x; + buffer->buffer[buffer->pos++] = point->y; + return 0; + } + + int GlyphPathLineTo(const FT_Vector *point, void *user) + { + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 3); + buffer->buffer[buffer->pos++] = 1; + buffer->buffer[buffer->pos++] = point->x; + buffer->buffer[buffer->pos++] = point->y; + return 0; + } + + int GlyphPathConicTo(const FT_Vector *pControlPoint, const FT_Vector *pEndPoint, void *user) + { + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 5); + buffer->buffer[buffer->pos++] = 2; + buffer->buffer[buffer->pos++] = pControlPoint->x; + buffer->buffer[buffer->pos++] = pControlPoint->y; + buffer->buffer[buffer->pos++] = pEndPoint->x; + buffer->buffer[buffer->pos++] = pEndPoint->y; + return 0; + } + + int GlyphPathCubicTo(const FT_Vector *pFirstControlPoint, const FT_Vector *pSecondControlPoint, const FT_Vector *pEndPoint, void *user) + { + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 7); + buffer->buffer[buffer->pos++] = 3; + buffer->buffer[buffer->pos++] = pFirstControlPoint->x; + buffer->buffer[buffer->pos++] = pFirstControlPoint->y; + buffer->buffer[buffer->pos++] = pSecondControlPoint->x; + buffer->buffer[buffer->pos++] = pSecondControlPoint->y; + buffer->buffer[buffer->pos++] = pEndPoint->x; + buffer->buffer[buffer->pos++] = pEndPoint->y; + return 0; + } + ///////////////////////////////////////////////////////////////////// + + void FT_Free(void* data) + { + ft_sfree(data); + } + + void* FT_Library_Init() + { + FT_Library library = NULL; + FT_Init_FreeType(&library); + FT_Library_SetLcdFilter(library, FT_LCD_FILTER_DEFAULT); + return library; + } + void FT_Library_Destroy(void* library) + { + ::FT_Done_FreeType((FT_Library)library); + } + void FT_Library_Reference(void* library) + { + FT_Reference_Library((FT_Library)library); + } + void FT_Library_UnReference(void* library_) + { + FT_Library library = (FT_Library)library_; + if (library->refcount == 1) + ::FT_Done_FreeType(library); + else + ::FT_Done_Library(library); + } + + int FT_Set_TrueType_HintProp(void* library, unsigned int interpreter_version) + { + FT_UInt ft_interpreter_version = interpreter_version; + return FT_Property_Set((FT_Library)library, "truetype", "interpreter-version", &ft_interpreter_version); + } + + void* FT_Open_Face(void* library, unsigned char* memory, unsigned int size, int face_index) + { + FT_Open_Args oOpenArgs; + oOpenArgs.flags = FT_OPEN_MEMORY | FT_OPEN_PARAMS; + oOpenArgs.memory_base = memory; + oOpenArgs.memory_size = (FT_Long)size; + + FT_Parameter *pParams = (FT_Parameter *)ft_smalloc( sizeof(FT_Parameter) * 4 ); + pParams[0].tag = FT_MAKE_TAG( 'i', 'g', 'p', 'f' ); + pParams[0].data = NULL; + pParams[1].tag = FT_MAKE_TAG( 'i', 'g', 'p', 's' ); + pParams[1].data = NULL; + pParams[2].tag = FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY; + pParams[2].data = NULL; + pParams[3].tag = FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY; + pParams[3].data = NULL; + + oOpenArgs.params = pParams; + oOpenArgs.num_params = 4; + + FT_Face face; + int error = ::FT_Open_Face( (FT_Library)library, &oOpenArgs, face_index, &face ); + + ft_sfree(pParams); + + if (error) + return NULL; + + return face; + } + + void FT_Done_Face(void* face) + { + ::FT_Done_Face((FT_Face)face); + } + + void FT_Done_Face_With_Library(void* face) + { + FT_Face ftface = (FT_Face)face; + FT_Library library = ftface->driver->root.library; + + bool bIsNeedUnreferenceLibrary = (1 == ftface->internal->refcount) ? true : false; + ::FT_Done_Face(ftface); + + if (bIsNeedUnreferenceLibrary) + FT_Library_UnReference(library); + } + + unsigned int FT_SetCMapForCharCode(void* face_pointer, unsigned int unicode) + { + if (!face_pointer) + return 0; + + FT_Face face = (FT_Face)face_pointer; + + if ( 0 == face->num_charmaps ) + return unicode; + + unsigned int nCharIndex = 0; + + for ( int nIndex = 0; nIndex < face->num_charmaps; ++nIndex ) + { + FT_CharMap pCharMap = face->charmaps[nIndex]; + + if ( FT_Set_Charmap( face, pCharMap ) ) + continue; + + FT_Encoding pEncoding = pCharMap->encoding; + + if ( FT_ENCODING_UNICODE == pEncoding ) + { + nCharIndex = FT_Get_Char_Index( face, unicode ); + if ( nCharIndex ) + { + return nCharIndex; + } + } + else if ( FT_ENCODING_NONE == pEncoding || FT_ENCODING_MS_SYMBOL == pEncoding || FT_ENCODING_APPLE_ROMAN == pEncoding ) + { +#if 0 + FT_ULong charcode; + FT_UInt gindex; + + charcode = FT_Get_First_Char( face, &gindex ); + while ( gindex != 0 ) + { + charcode = FT_Get_Next_Char( face, charcode, &gindex ); + if ( charcode == unicode ) + { + nCharIndex = gindex; + break; + } + } +#endif + + nCharIndex = FT_Get_Char_Index( face, unicode ); + } + } + + return nCharIndex; + } + + int FT_GetFaceMaxAdvanceX(void* face_pointer) + { + if (!face_pointer) + return 0; + + FT_Face face = (FT_Face)face_pointer; + if (!face->size) + return 0; + + return (int)face->size->metrics.max_advance; + } + + int FT_GetKerningX(void* face, unsigned int prev_gid, unsigned int gid) + { + FT_Vector vec; + vec.x = 0; + vec.y = 0; + FT_Get_Kerning((FT_Face)face, prev_gid, gid, 0, &vec); + return vec.x; + } + + void FT_Set_Transform(void* face, int xx, int yx, int xy, int yy) + { + FT_Matrix m; + m.xx = xx; + m.yx = yx; + m.xy = xy; + m.yy = yy; + ::FT_Set_Transform((FT_Face)face, &m, NULL); + } + + int FT_Load_Glyph(void* face, unsigned int glyph_index, int load_flags) + { + return ::FT_Load_Glyph((FT_Face)face, glyph_index, load_flags); + } + + int FT_Set_Char_Size(void* face, int char_width, int char_height, unsigned int hres, unsigned int vres) + { + return ::FT_Set_Char_Size((FT_Face)face, char_width, char_height, hres, vres); + } + + void FT_Glyph_Get_CBox(void* glyph, unsigned int bbox_mode, CExternalPointer* result) + { + FT_BBox bbox; + FT_Glyph_Get_CBox((FT_Glyph)glyph, bbox_mode, &bbox); + ALLOC_WRITER(4 * 4); + WRITE_INT(bbox.xMin); + WRITE_INT(bbox.yMin); + WRITE_INT(bbox.xMax); + WRITE_INT(bbox.yMax); + } + + unsigned char* FT_Get_Glyph_Render_Buffer(void* face) + { + return ((FT_Face)face)->glyph->bitmap.buffer; + } + + bool FT_Get_Glyph_Render_Params(void* face, int render_mode, CExternalPointer* result) + { + FT_GlyphSlot slot = ((FT_Face)face)->glyph; + if (FT_Render_Glyph(slot, (FT_Render_Mode)render_mode)) + return false; + + ALLOC_WRITER(6 * 4); + WRITE_INT(slot->bitmap_left); + WRITE_INT(slot->bitmap_top); + WRITE_UINT(slot->bitmap.width); + WRITE_UINT(slot->bitmap.rows); + WRITE_INT(slot->bitmap.pitch); + WRITE_INT(slot->bitmap.pixel_mode); + return true; + } + + bool FT_GetFaceInfo(void* face_pointer, CExternalPointer* result) + { + if (!face_pointer) + return false; + + FT_Face face = (FT_Face)face_pointer; + + //face->units_per_EM + //face->ascender + //face->descender + //face->height + //face->face_flags + //face->num_faces + //face->num_glyphs + //face->num_charmaps + //face->style_flags + //face->face_index + //face->family_name + //face->style_name + + TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 ); + //os2->version + //os2->usWeightClass + //os2->fsSelection + //os2->usWinAscent + //os2->usWinDescent + //os2->usDefaultChar + //os2->sTypoAscender; + //os2->sTypoDescender; + //os2->sTypoLineGap; + + //os2->ulUnicodeRange1 + //os2->ulUnicodeRange2 + //os2->ulUnicodeRange3 + //os2->ulUnicodeRange4 + //os2->ulCodePageRange1 + //os2->ulCodePageRange2 + + int isSymbolic = -1; + if (os2 && 0xFFFF != os2->version) + { + FT_ULong ulCodePageRange1 = os2->ulCodePageRange1; + FT_ULong ulCodePageRange2 = os2->ulCodePageRange2; + + if ((ulCodePageRange1 & 0x80000000) || (ulCodePageRange1 == 0 && ulCodePageRange2 == 0)) + { + for( int nIndex = 0; nIndex < face->num_charmaps; nIndex++ ) + { + if (0 == face->charmaps[nIndex]->encoding_id && 3 == face->charmaps[nIndex]->platform_id) + { + isSymbolic = nIndex; + break; + } + } + } + } + + int nHeader_yMin = face->descender; + int nHeader_yMax = face->ascender; + if (face && FT_IS_SFNT(face)) + { + TT_Face ttface = (TT_Face)face; + nHeader_yMin = ttface->header.yMin; + nHeader_yMax = ttface->header.yMax; + } + + //isSymbolic + + int* family_name = NULL; + unsigned int family_name_len = 0; + CheckUnicodeFaceName(face, family_name, family_name_len); + + unsigned int nLen1 = (unsigned int)family_name_len; + unsigned int nLen2 = (unsigned int)strlen(face->style_name); + + unsigned int nLen = 28 + nLen1 + 1 + nLen2 + 1 + 1 + (int)face->num_fixed_sizes; + + ALLOC_WRITER(nLen * 4); + WRITE_INT((int)face->units_per_EM); + WRITE_INT((int)face->ascender); + WRITE_INT((int)face->descender); + WRITE_INT((int)face->height); + WRITE_INT((int)face->face_flags); + WRITE_INT((int)face->num_faces); + WRITE_INT((int)face->num_glyphs); + WRITE_INT((int)face->num_charmaps); + WRITE_INT((int)face->style_flags); + WRITE_INT((int)face->face_index); + + for (unsigned int i = 0; i < nLen1; ++i) + { + WRITE_INT(family_name[i]); + } + WRITE_INT(0); + + for (unsigned int i = 0; i < nLen2; ++i) + { + WRITE_INT(face->style_name[i]); + } + WRITE_INT(0); + + if (os2) + { + WRITE_INT((int)os2->version); + WRITE_INT((int)os2->usWeightClass); + WRITE_INT((int)os2->fsSelection); + WRITE_INT((int)os2->usWinAscent); + WRITE_INT((int)os2->usWinDescent); + WRITE_INT((int)os2->usDefaultChar); + WRITE_INT((int)os2->sTypoAscender); + WRITE_INT((int)os2->sTypoDescender); + WRITE_INT((int)os2->sTypoLineGap); + + WRITE_INT((int)os2->ulUnicodeRange1); + WRITE_INT((int)os2->ulUnicodeRange2); + WRITE_INT((int)os2->ulUnicodeRange3); + WRITE_INT((int)os2->ulUnicodeRange4); + WRITE_INT((int)os2->ulCodePageRange1); + WRITE_INT((int)os2->ulCodePageRange2); + } + else + { + WRITE_INT((int)0xFFFF); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + WRITE_INT((int)0); + } + + WRITE_INT((int)isSymbolic); + WRITE_INT((int)nHeader_yMin); + WRITE_INT((int)nHeader_yMax); + + WRITE_INT((int)face->num_fixed_sizes); + + for (int i = 0; i < face->num_fixed_sizes; ++i) + { + WRITE_INT((int)face->available_sizes[i].size); + } + + if (family_name) + delete [] family_name; + + return true; + } + + bool FT_Get_Glyph_Measure_Params(void* face, bool isVector, CExternalPointer* result) + { + FT_GlyphSlot slot = ((FT_Face)face)->glyph; + + if (!isVector && slot->bitmap.buffer != NULL && slot->format == FT_GLYPH_FORMAT_BITMAP) + { + ALLOC_WRITER(15 * 4); + WRITE_INT(15); + WRITE_INT(0); + WRITE_INT(0); + WRITE_INT(slot->metrics.width); + WRITE_INT(slot->metrics.height); + + WRITE_INT(slot->metrics.width); + WRITE_INT(slot->metrics.height); + + WRITE_INT(slot->metrics.horiAdvance); + WRITE_INT(slot->metrics.horiBearingX); + WRITE_INT(slot->metrics.horiBearingY); + + WRITE_INT(slot->metrics.vertAdvance); + WRITE_INT(slot->metrics.vertBearingX); + WRITE_INT(slot->metrics.vertBearingY); + + WRITE_INT(slot->linearHoriAdvance); + WRITE_INT(slot->linearVertAdvance); + return true; + } + + FT_Glyph glyph; + FT_Get_Glyph(slot, &glyph); + if (!glyph) + return false; + + FT_BBox bbox; + FT_Glyph_Get_CBox(glyph, 1, &bbox); + + if (isVector) + { + FT_Decompose_Outline_Buffer buffer; + FT_Decompose_Outline_Buffer_Init(&buffer); + + static FT_Outline_Funcs pOutlineFuncs = + { + &GlyphPathMoveTo, + &GlyphPathLineTo, + &GlyphPathConicTo, + &GlyphPathCubicTo, + 0, 0 + }; + + FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline, &pOutlineFuncs, &buffer); + + int nCount = buffer.pos; + + ALLOC_WRITER((nCount + 15) * 4); + WRITE_INT((nCount + 15)); + WRITE_INT(bbox.xMin); + WRITE_INT(bbox.yMin); + WRITE_INT(bbox.xMax); + WRITE_INT(bbox.yMax); + + WRITE_INT(slot->metrics.width); + WRITE_INT(slot->metrics.height); + + WRITE_INT(slot->metrics.horiAdvance); + WRITE_INT(slot->metrics.horiBearingX); + WRITE_INT(slot->metrics.horiBearingY); + + WRITE_INT(slot->metrics.vertAdvance); + WRITE_INT(slot->metrics.vertBearingX); + WRITE_INT(slot->metrics.vertBearingY); + + WRITE_INT(slot->linearHoriAdvance); + WRITE_INT(slot->linearVertAdvance); + + for (int i = 0; i < nCount; i++) + { + WRITE_INT(buffer.buffer[i]); + } + + FT_Decompose_Outline_Buffer_Destroy(&buffer); + } + else + { + ALLOC_WRITER(15 * 4); + WRITE_INT(15); + WRITE_INT(bbox.xMin); + WRITE_INT(bbox.yMin); + WRITE_INT(bbox.xMax); + WRITE_INT(bbox.yMax); + + WRITE_INT(slot->metrics.width); + WRITE_INT(slot->metrics.height); + + WRITE_INT(slot->metrics.horiAdvance); + WRITE_INT(slot->metrics.horiBearingX); + WRITE_INT(slot->metrics.horiBearingY); + + WRITE_INT(slot->metrics.vertAdvance); + WRITE_INT(slot->metrics.vertBearingX); + WRITE_INT(slot->metrics.vertBearingY); + + WRITE_INT(slot->linearHoriAdvance); + WRITE_INT(slot->linearVertAdvance); + } + + FT_Done_Glyph(glyph); + return true; + } } #ifdef SUPPORT_HARFBUZZ_SHAPER @@ -655,133 +649,133 @@ namespace NSShaper namespace NSShaper { - #define g_userfeatures_count 5 - hb_feature_t g_userfeatures[g_userfeatures_count]; - bool g_userfeatures_init = false; +#define g_userfeatures_count 5 + hb_feature_t g_userfeatures[g_userfeatures_count]; + bool g_userfeatures_init = false; - void* HB_LanguageFromString(const std::string language_bcp_47) - { - return (void*)hb_language_from_string(language_bcp_47.c_str(), language_bcp_47.length()); - } + void* HB_LanguageFromString(const std::string language_bcp_47) + { + return (void*)hb_language_from_string(language_bcp_47.c_str(), language_bcp_47.length()); + } - static void _hb_ft_face_destroy_js(void *data) - { - FT_Done_Face_With_Library(data); - } + static void _hb_ft_face_destroy_js(void *data) + { + FT_Done_Face_With_Library(data); + } - inline void HB_ShapeTextRaw(void* face, void*& font, char* text_str, const size_t& text_length, - unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, - CExternalPointer* result, bool bIsJSVersion) - { - // init features - if (!g_userfeatures_init) - { - hb_tag_t tags[] = { - HB_TAG('l','i','g','a'), - HB_TAG('c','l','i','g'), - HB_TAG('h','l','i','g'), - HB_TAG('d','l','i','g'), - HB_TAG('k','e','r','n') - }; - for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) - { - g_userfeatures[nTag].tag = tags[nTag]; - g_userfeatures[nTag].value = 0; - g_userfeatures[nTag].start = HB_FEATURE_GLOBAL_START; - g_userfeatures[nTag].end = HB_FEATURE_GLOBAL_END; - } - g_userfeatures_init = true; - } + inline void HB_ShapeTextRaw(void* face, void*& font, char* text_str, const size_t& text_length, + unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, + CExternalPointer* result, bool bIsJSVersion) + { + // init features + if (!g_userfeatures_init) + { + hb_tag_t tags[] = { + HB_TAG('l','i','g','a'), + HB_TAG('c','l','i','g'), + HB_TAG('h','l','i','g'), + HB_TAG('d','l','i','g'), + HB_TAG('k','e','r','n') + }; + for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) + { + g_userfeatures[nTag].tag = tags[nTag]; + g_userfeatures[nTag].value = 0; + g_userfeatures[nTag].start = HB_FEATURE_GLOBAL_START; + g_userfeatures[nTag].end = HB_FEATURE_GLOBAL_END; + } + g_userfeatures_init = true; + } - // font - hb_font_t* pFont; - if (NULL == font) - { - if (!bIsJSVersion) - { - pFont = hb_ft_font_create_referenced((FT_Face)face); - } - else - { - FT_Reference_Face((FT_Face)face); - pFont = hb_ft_font_create((FT_Face)face, _hb_ft_face_destroy_js); - } - hb_ft_font_set_funcs(pFont); - font = (void*)pFont; - } - else - pFont = (hb_font_t*)font; + // font + hb_font_t* pFont; + if (NULL == font) + { + if (!bIsJSVersion) + { + pFont = hb_ft_font_create_referenced((FT_Face)face); + } + else + { + FT_Reference_Face((FT_Face)face); + pFont = hb_ft_font_create((FT_Face)face, _hb_ft_face_destroy_js); + } + hb_ft_font_set_funcs(pFont); + font = (void*)pFont; + } + else + pFont = (hb_font_t*)font; - // features - for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) - g_userfeatures[nTag].value = (nFeatures & (1 << nTag)) ? 1 : 0; + // features + for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) + g_userfeatures[nTag].value = (nFeatures & (1 << nTag)) ? 1 : 0; - // buffer - hb_buffer_t* hbBuffer = hb_buffer_create(); - hb_buffer_set_direction(hbBuffer, (hb_direction_t)nDirection); - hb_buffer_set_script(hbBuffer, (hb_script_t)nScript); - hb_buffer_set_language(hbBuffer, (hb_language_t)nLanguage); - hb_buffer_set_cluster_level(hbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES); - int text_len = (int)text_length; - hb_buffer_add_utf8(hbBuffer, text_str, text_len, 0, text_len); - hb_buffer_guess_segment_properties(hbBuffer); + // buffer + hb_buffer_t* hbBuffer = hb_buffer_create(); + hb_buffer_set_direction(hbBuffer, (hb_direction_t)nDirection); + hb_buffer_set_script(hbBuffer, (hb_script_t)nScript); + hb_buffer_set_language(hbBuffer, (hb_language_t)nLanguage); + hb_buffer_set_cluster_level(hbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES); + int text_len = (int)text_length; + hb_buffer_add_utf8(hbBuffer, text_str, text_len, 0, text_len); + hb_buffer_guess_segment_properties(hbBuffer); - // shape - hb_shape(pFont, hbBuffer, g_userfeatures, g_userfeatures_count); + // shape + hb_shape(pFont, hbBuffer, g_userfeatures, g_userfeatures_count); - unsigned int glyph_count; - hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hbBuffer, &glyph_count); - hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hbBuffer, &glyph_count); + unsigned int glyph_count; + hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hbBuffer, &glyph_count); + hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hbBuffer, &glyph_count); - int nSize = 4 + 8 + glyph_count * (1 + 1 + 4 * 6); + int nSize = 4 + 8 + glyph_count * (1 + 1 + 4 * 6); - ALLOC_WRITER(nSize); + ALLOC_WRITER(nSize); - WRITE_UINT(nSize); + WRITE_UINT(nSize); - uint64_t pFontPointer = (uint64_t)pFont; - WRITE_UINT(pFontPointer & 0xFFFFFFFF); - WRITE_UINT((pFontPointer >> 32) & 0xFFFFFFFF); + uint64_t pFontPointer = (uint64_t)pFont; + WRITE_UINT(pFontPointer & 0xFFFFFFFF); + WRITE_UINT((pFontPointer >> 32) & 0xFFFFFFFF); - for (unsigned i = 0; i < glyph_count; ++i) - { - unsigned char nGlyphType = (unsigned char)hb_ot_layout_get_glyph_class(hb_font_get_face(pFont), glyph_info[i].codepoint); - unsigned char nGlyphFlags = (unsigned char)hb_glyph_info_get_glyph_flags(&glyph_info[i]); + for (unsigned i = 0; i < glyph_count; ++i) + { + unsigned char nGlyphType = (unsigned char)hb_ot_layout_get_glyph_class(hb_font_get_face(pFont), glyph_info[i].codepoint); + unsigned char nGlyphFlags = (unsigned char)hb_glyph_info_get_glyph_flags(&glyph_info[i]); - WRITE_UCHAR(nGlyphType); - WRITE_UCHAR(nGlyphFlags); + WRITE_UCHAR(nGlyphType); + WRITE_UCHAR(nGlyphFlags); - WRITE_UINT(glyph_info[i].codepoint); - WRITE_UINT(glyph_info[i].cluster); + WRITE_UINT(glyph_info[i].codepoint); + WRITE_UINT(glyph_info[i].cluster); - WRITE_INT(glyph_pos[i].x_advance); - WRITE_INT(glyph_pos[i].y_advance); - WRITE_INT(glyph_pos[i].x_offset); - WRITE_INT(glyph_pos[i].y_offset); - } + WRITE_INT(glyph_pos[i].x_advance); + WRITE_INT(glyph_pos[i].y_advance); + WRITE_INT(glyph_pos[i].x_offset); + WRITE_INT(glyph_pos[i].y_offset); + } - hb_buffer_destroy(hbBuffer); - } + hb_buffer_destroy(hbBuffer); + } - void HB_ShapeText(void* face, void*& font, char* text, - unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, - CExternalPointer* result, bool bIsJSVersion) - { - HB_ShapeTextRaw(face, font, text, strlen(text), nFeatures, nScript, nDirection, nLanguage, result, bIsJSVersion); - } + void HB_ShapeText(void* face, void*& font, char* text, + unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, + CExternalPointer* result, bool bIsJSVersion) + { + HB_ShapeTextRaw(face, font, text, strlen(text), nFeatures, nScript, nDirection, nLanguage, result, bIsJSVersion); + } - void HB_ShapeText(void* face, void*& font, const std::string& text, - unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, - CExternalPointer* result, bool bIsJSVersion) - { - HB_ShapeTextRaw(face, font, (char*)text.c_str(), text.length(), nFeatures, nScript, nDirection, nLanguage, result, bIsJSVersion); - } + void HB_ShapeText(void* face, void*& font, const std::string& text, + unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, void* nLanguage, + CExternalPointer* result, bool bIsJSVersion) + { + HB_ShapeTextRaw(face, font, (char*)text.c_str(), text.length(), nFeatures, nScript, nDirection, nLanguage, result, bIsJSVersion); + } - void HB_FontFree(void* font) - { - if (NULL == font) - return; - hb_font_destroy((hb_font_t*)font); - } + void HB_FontFree(void* font) + { + if (NULL == font) + return; + hb_font_destroy((hb_font_t*)font); + } } #endif diff --git a/DesktopEditor/fontengine/TextShaper_p.h b/DesktopEditor/fontengine/TextShaper_p.h new file mode 100644 index 0000000000..ed9078e732 --- /dev/null +++ b/DesktopEditor/fontengine/TextShaper_p.h @@ -0,0 +1,286 @@ +#pragma once + +#include +#include "ftsnames.h" +#include FT_OUTLINE_H +#include FT_SIZES_H +#include FT_GLYPH_H +#include FT_TRUETYPE_IDS_H +#include FT_TRUETYPE_TABLES_H +#include FT_XFREE86_H +#include FT_ADVANCES_H +#include FT_LCD_FILTER_H +#include FT_DRIVER_H +#include +#include "ftmodapi.h" + +#include FT_SFNT_NAMES_H +#include "internal/tttypes.h" +#include "internal/ftstream.h" + +void GetUnicodeFromUTF16BE(char* Data, unsigned int Length, int*& DataU, unsigned int& DataULen) +{ + DataU = 0; + DataULen = 0; + + if (0 == Length) + return; + + DataULen = Length + 1; + DataU = new int[DataULen]; + DataULen = 0; + + unsigned int nCount = Length / 2; + unsigned char* pData = (unsigned char*)Data; + + unsigned int nCurrent = 0; + while (nCurrent < nCount) + { + unsigned short codeBE = (pData[0] << 8) | pData[1]; + if (codeBE < 0xD800 || codeBE > 0xDBFF) + { + DataU[DataULen++] = codeBE; + pData += 2; + ++nCurrent; + } + else + { + unsigned short codeBE1 = (pData[0] << 8) | pData[1]; + unsigned short codeBE2 = (pData[2] << 8) | pData[3]; + + DataU[DataULen++] = (int)(((((codeBE1 - 0xD800) & 0x03FF) << 10) | ((codeBE2 - 0xDC00) & 0x03FF)) + 0x10000); + pData += 4; + nCurrent += 2; + } + } + + DataU[DataULen] = '\0'; +} + +void CheckUnicodeFaceName(FT_Face pFace, int*& UName, unsigned int& ULen) +{ + char* face_name = pFace->family_name; + bool isBadASCII = false; + + unsigned int face_name_len = 0; + while ('\0' != face_name[face_name_len]) + { + if ('?' == face_name[face_name_len]) + isBadASCII = true; + ++face_name_len; + } + + if (face_name_len > 6 && + '<' == face_name[0] && 'u' == face_name[1] && 't' == face_name[2] && + 'f' == face_name[3] && '8' == face_name[4] && '>' == face_name[5]) + { + ULen = 0; + unsigned int index = 6; + UName = new int[face_name_len - index + 1]; + + while (index < face_name_len) + { + unsigned char byteMain = face_name[index]; + if (0x00 == (byteMain & 0x80)) + { + // 1 byte + UName[ULen++] = (int)byteMain; + ++index; + } + else if (0x00 == (byteMain & 0x20)) + { + // 2 byte + int val = 0; + if ((index + 1) < face_name_len) + { + val = (int)(((byteMain & 0x1F) << 6) | + (face_name[index + 1] & 0x3F)); + } + + UName[ULen++] = val; + index += 2; + } + else if (0x00 == (byteMain & 0x10)) + { + // 3 byte + int val = 0; + if ((index + 2) < face_name_len) + { + val = (int)(((byteMain & 0x0F) << 12) | + ((face_name[index + 1] & 0x3F) << 6) | + (face_name[index + 2] & 0x3F)); + } + + UName[ULen++] = val; + index += 3; + } + else if (0x00 == (byteMain & 0x0F)) + { + // 4 byte + int val = 0; + if ((index + 3) < face_name_len) + { + val = (int)(((byteMain & 0x07) << 18) | + ((face_name[index + 1] & 0x3F) << 12) | + ((face_name[index + 2] & 0x3F) << 6) | + (face_name[index + 3] & 0x3F)); + } + + UName[ULen++] = val; + index += 4; + } + else if (0x00 == (byteMain & 0x08)) + { + // 4 byte + int val = 0; + if ((index + 3) < face_name_len) + { + val = (int)(((byteMain & 0x07) << 18) | + ((face_name[index + 1] & 0x3F) << 12) | + ((face_name[index + 2] & 0x3F) << 6) | + (face_name[index + 3] & 0x3F)); + } + + UName[ULen++] = val; + index += 4; + } + else if (0x00 == (byteMain & 0x04)) + { + // 5 byte + int val = 0; + if ((index + 4) < face_name_len) + { + val = (int)(((byteMain & 0x03) << 24) | + ((face_name[index + 1] & 0x3F) << 18) | + ((face_name[index + 2] & 0x3F) << 12) | + ((face_name[index + 3] & 0x3F) << 6) | + (face_name[index + 4] & 0x3F)); + } + + UName[ULen++] = val; + index += 5; + } + else + { + // 6 byte + int val = 0; + if ((index + 5) < face_name_len) + { + val = (int)(((byteMain & 0x01) << 30) | + ((face_name[index + 1] & 0x3F) << 24) | + ((face_name[index + 2] & 0x3F) << 18) | + ((face_name[index + 3] & 0x3F) << 12) | + ((face_name[index + 4] & 0x3F) << 6) | + (face_name[index + 5] & 0x3F)); + } + + UName[ULen++] = val; + index += 5; + } + } + + UName[ULen] = 0; + return; + } + + if (!isBadASCII) + { + ULen = face_name_len; + UName = new int[ULen + 1]; + + for (unsigned int i = 0; i < ULen; ++i) + UName[i] = (int)face_name[i]; + + UName[ULen] = 0; + return; + } + + if (pFace && FT_IS_SFNT(pFace)) + { + TT_Face pTTFace = (TT_Face)pFace; + + int nNamesCount = (int)pTTFace->num_names; + TT_NameRec* pNameRecs = pTTFace->name_table.names; + + for (int nNameIndex = 0; nNameIndex < nNamesCount; ++nNameIndex) + { + TT_NameRec* rec = pNameRecs + nNameIndex; + + if (rec->nameID != TT_NAME_ID_FONT_FAMILY || rec->stringLength <= 0) + continue; + + const char* sEncoding = 0; + switch (rec->platformID) + { + case TT_PLATFORM_APPLE_UNICODE: + { + sEncoding = "UTF-16BE"; + break; + } + case TT_PLATFORM_MACINTOSH: + { + break; + } + case TT_PLATFORM_MICROSOFT: + { + switch (rec->encodingID) + { + case TT_MS_ID_SYMBOL_CS: + case TT_MS_ID_UNICODE_CS: + sEncoding = "UTF-16BE"; + break; + case TT_MS_ID_UCS_4: + //sEncoding = "UCS4"; // см tt_ + sEncoding = "UTF-16BE"; + break; + //case TT_MS_ID_SJIS: + // sEncoding = "Shift-JIS"; + // break; + //case TT_MS_ID_GB2312: + // sEncoding = "GB2312"; + // break; + //case TT_MS_ID_BIG_5: + // sEncoding = "Big5"; + // break; + default: + break; + } + } + default: + break; + } + + if (0 != sEncoding) + { + FT_Stream stream = pTTFace->name_table.stream; + FT_Memory memory = pFace->memory; + FT_Error error = 0; + + if ( FT_QNEW_ARRAY ( rec->string, rec->stringLength ) || + FT_STREAM_SEEK( rec->stringOffset ) || + FT_STREAM_READ( rec->string, rec->stringLength ) ) + { + FT_FREE( rec->string ); + rec->stringLength = 0; + } + else + { + if (0 == strcmp(sEncoding, "UTF-16BE")) + { + GetUnicodeFromUTF16BE((char*)rec->string, (unsigned int)rec->stringLength, UName, ULen); + return; + } + } + } + } + } + + // default + ULen = face_name_len; + UName = new int[ULen + 1]; + + for (unsigned int i = 0; i < ULen; ++i) + UName[i] = (int)face_name[i]; + + UName[ULen] = 0; +} diff --git a/DesktopEditor/fontengine/js/cpp/text.cpp b/DesktopEditor/fontengine/js/cpp/text.cpp index c38df087d9..35d9d19ceb 100644 --- a/DesktopEditor/fontengine/js/cpp/text.cpp +++ b/DesktopEditor/fontengine/js/cpp/text.cpp @@ -1,16 +1,4 @@ -#include -#include "ftsnames.h" -#include FT_OUTLINE_H -#include FT_SIZES_H -#include FT_GLYPH_H -#include FT_TRUETYPE_IDS_H -#include FT_TRUETYPE_TABLES_H -#include FT_XFREE86_H -#include FT_ADVANCES_H -#include FT_LCD_FILTER_H -#include FT_DRIVER_H -#include -#include "ftmodapi.h" +#include "../../TextShaper_p.h" #ifdef _WIN32 #define WASM_EXPORT __declspec(dllexport) @@ -43,13 +31,13 @@ WASM_EXPORT FT_Library ASC_FT_Init() WASM_EXPORT void ASC_FT_Done_FreeType(FT_Library library) { - FT_Done_FreeType(library); + FT_Done_FreeType(library); } WASM_EXPORT int ASC_FT_Set_TrueType_HintProp(FT_Library library, unsigned int interpreter_version) { - FT_UInt _interpreter_version = interpreter_version; - return FT_Property_Set(library, "truetype", "interpreter-version", &_interpreter_version); + FT_UInt _interpreter_version = interpreter_version; + return FT_Property_Set(library, "truetype", "interpreter-version", &_interpreter_version); } // ------------------------------------------------------------ @@ -61,23 +49,23 @@ WASM_EXPORT FT_Face ASC_FT_Open_Face(FT_Library library, unsigned char* memory, FT_Open_Args oOpenArgs; oOpenArgs.flags = FT_OPEN_MEMORY | FT_OPEN_PARAMS; oOpenArgs.memory_base = memory; - oOpenArgs.memory_size = (FT_Long)size; + oOpenArgs.memory_size = (FT_Long)size; FT_Parameter *pParams = (FT_Parameter *)ft_smalloc( sizeof(FT_Parameter) * 4 ); pParams[0].tag = FT_MAKE_TAG( 'i', 'g', 'p', 'f' ); pParams[0].data = NULL; pParams[1].tag = FT_MAKE_TAG( 'i', 'g', 'p', 's' ); - pParams[1].data = NULL; + pParams[1].data = NULL; pParams[2].tag = FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY; - pParams[2].data = NULL; + pParams[2].data = NULL; pParams[3].tag = FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY; - pParams[3].data = NULL; + pParams[3].data = NULL; oOpenArgs.params = pParams; oOpenArgs.num_params = 4; FT_Face face; - int error = FT_Open_Face( library, &oOpenArgs, face_index, &face ); + int error = FT_Open_Face( library, &oOpenArgs, face_index, &face ); ft_sfree(pParams); @@ -89,7 +77,7 @@ WASM_EXPORT FT_Face ASC_FT_Open_Face(FT_Library library, unsigned char* memory, WASM_EXPORT void ASC_FT_Done_Face(FT_Face face) { - FT_Done_Face(face); + FT_Done_Face(face); } WASM_EXPORT unsigned int ASC_FT_SetCMapForCharCode(FT_Face face, unsigned int unicode) @@ -100,7 +88,7 @@ WASM_EXPORT unsigned int ASC_FT_SetCMapForCharCode(FT_Face face, unsigned int un if ( 0 == face->num_charmaps ) return unicode; - unsigned int nCharIndex = 0; + unsigned int nCharIndex = 0; for ( int nIndex = 0; nIndex < face->num_charmaps; ++nIndex ) { @@ -115,7 +103,7 @@ WASM_EXPORT unsigned int ASC_FT_SetCMapForCharCode(FT_Face face, unsigned int un { nCharIndex = FT_Get_Char_Index( face, unicode ); if ( nCharIndex ) - { + { return nCharIndex; } } @@ -125,199 +113,206 @@ WASM_EXPORT unsigned int ASC_FT_SetCMapForCharCode(FT_Face face, unsigned int un FT_ULong charcode; FT_UInt gindex; - charcode = FT_Get_First_Char( face, &gindex ); - while ( gindex != 0 ) - { - charcode = FT_Get_Next_Char( face, charcode, &gindex ); + charcode = FT_Get_First_Char( face, &gindex ); + while ( gindex != 0 ) + { + charcode = FT_Get_Next_Char( face, charcode, &gindex ); if ( charcode == unicode ) { nCharIndex = gindex; break; } - } + } #endif nCharIndex = FT_Get_Char_Index( face, unicode ); } } - return nCharIndex; + return nCharIndex; } WASM_EXPORT int* ASC_FT_GetFaceInfo(FT_Face face) { - if (!face) - return NULL; + if (!face) + return NULL; - //face->units_per_EM - //face->ascender - //face->descender - //face->height - //face->face_flags - //face->num_faces - //face->num_glyphs - //face->num_charmaps - //face->style_flags - //face->face_index - //face->family_name - //face->style_name + //face->units_per_EM + //face->ascender + //face->descender + //face->height + //face->face_flags + //face->num_faces + //face->num_glyphs + //face->num_charmaps + //face->style_flags + //face->face_index + //face->family_name + //face->style_name - TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 ); - //os2->version - //os2->usWeightClass - //os2->fsSelection - //os2->usWinAscent - //os2->usWinDescent - //os2->usDefaultChar - //os2->sTypoAscender; - //os2->sTypoDescender; - //os2->sTypoLineGap; + TT_OS2* os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 ); + //os2->version + //os2->usWeightClass + //os2->fsSelection + //os2->usWinAscent + //os2->usWinDescent + //os2->usDefaultChar + //os2->sTypoAscender; + //os2->sTypoDescender; + //os2->sTypoLineGap; - //os2->ulUnicodeRange1 - //os2->ulUnicodeRange2 - //os2->ulUnicodeRange3 - //os2->ulUnicodeRange4 - //os2->ulCodePageRange1 - //os2->ulCodePageRange2 + //os2->ulUnicodeRange1 + //os2->ulUnicodeRange2 + //os2->ulUnicodeRange3 + //os2->ulUnicodeRange4 + //os2->ulCodePageRange1 + //os2->ulCodePageRange2 - int isSymbolic = -1; - if (os2 && 0xFFFF != os2->version) - { - FT_ULong ulCodePageRange1 = os2->ulCodePageRange1; - FT_ULong ulCodePageRange2 = os2->ulCodePageRange2; + int isSymbolic = -1; + if (os2 && 0xFFFF != os2->version) + { + FT_ULong ulCodePageRange1 = os2->ulCodePageRange1; + FT_ULong ulCodePageRange2 = os2->ulCodePageRange2; - if ((ulCodePageRange1 & 0x80000000) || (ulCodePageRange1 == 0 && ulCodePageRange2 == 0)) - { - for( int nIndex = 0; nIndex < face->num_charmaps; nIndex++ ) - { - if (0 == face->charmaps[nIndex]->encoding_id && 3 == face->charmaps[nIndex]->platform_id) - { - isSymbolic = nIndex; - break; - } - } - } - } + if ((ulCodePageRange1 & 0x80000000) || (ulCodePageRange1 == 0 && ulCodePageRange2 == 0)) + { + for( int nIndex = 0; nIndex < face->num_charmaps; nIndex++ ) + { + if (0 == face->charmaps[nIndex]->encoding_id && 3 == face->charmaps[nIndex]->platform_id) + { + isSymbolic = nIndex; + break; + } + } + } + } - int nHeader_yMin = face->descender; - int nHeader_yMax = face->ascender; - if (face && FT_IS_SFNT(face)) - { - TT_Face ttface = (TT_Face)face; - nHeader_yMin = ttface->header.yMin; - nHeader_yMax = ttface->header.yMax; - } + int nHeader_yMin = face->descender; + int nHeader_yMax = face->ascender; + if (face && FT_IS_SFNT(face)) + { + TT_Face ttface = (TT_Face)face; + nHeader_yMin = ttface->header.yMin; + nHeader_yMax = ttface->header.yMax; + } - //isSymbolic + //isSymbolic - unsigned int nLen1 = (unsigned int)strlen(face->family_name); - unsigned int nLen2 = (unsigned int)strlen(face->style_name); + int* family_name = NULL; + unsigned int family_name_len = 0; + CheckUnicodeFaceName(face, family_name, family_name_len); - unsigned int nLen = 28 + nLen1 + 1 + nLen2 + 1 + 1 + (int)face->num_fixed_sizes; + unsigned int nLen1 = (unsigned int)family_name_len; + unsigned int nLen2 = (unsigned int)strlen(face->style_name); - int* res = (int*)ASC_FT_Malloc(nLen * sizeof(int)); - int* resTmp = res; + unsigned int nLen = 28 + nLen1 + 1 + nLen2 + 1 + 1 + (int)face->num_fixed_sizes; - *resTmp++ = (int)face->units_per_EM; - *resTmp++ = (int)face->ascender; - *resTmp++ = (int)face->descender; - *resTmp++ = (int)face->height; - *resTmp++ = (int)face->face_flags; - *resTmp++ = (int)face->num_faces; - *resTmp++ = (int)face->num_glyphs; - *resTmp++ = (int)face->num_charmaps; - *resTmp++ = (int)face->style_flags; - *resTmp++ = (int)face->face_index; + int* res = (int*)ASC_FT_Malloc(nLen * sizeof(int)); + int* resTmp = res; - for (unsigned int i = 0; i < nLen1; ++i) - *resTmp++ = face->family_name[i]; - *resTmp++ = 0; + *resTmp++ = (int)face->units_per_EM; + *resTmp++ = (int)face->ascender; + *resTmp++ = (int)face->descender; + *resTmp++ = (int)face->height; + *resTmp++ = (int)face->face_flags; + *resTmp++ = (int)face->num_faces; + *resTmp++ = (int)face->num_glyphs; + *resTmp++ = (int)face->num_charmaps; + *resTmp++ = (int)face->style_flags; + *resTmp++ = (int)face->face_index; - for (unsigned int i = 0; i < nLen2; ++i) - *resTmp++ = face->style_name[i]; - *resTmp++ = 0; + for (unsigned int i = 0; i < nLen1; ++i) + *resTmp++ = family_name[i]; + *resTmp++ = 0; - if (os2) - { - *resTmp++ = (int)os2->version; - *resTmp++ = (int)os2->usWeightClass; - *resTmp++ = (int)os2->fsSelection; - *resTmp++ = (int)os2->usWinAscent; - *resTmp++ = (int)os2->usWinDescent; - *resTmp++ = (int)os2->usDefaultChar; - *resTmp++ = (int)os2->sTypoAscender; - *resTmp++ = (int)os2->sTypoDescender; - *resTmp++ = (int)os2->sTypoLineGap; + for (unsigned int i = 0; i < nLen2; ++i) + *resTmp++ = face->style_name[i]; + *resTmp++ = 0; - *resTmp++ = (int)os2->ulUnicodeRange1; - *resTmp++ = (int)os2->ulUnicodeRange2; - *resTmp++ = (int)os2->ulUnicodeRange3; - *resTmp++ = (int)os2->ulUnicodeRange4; - *resTmp++ = (int)os2->ulCodePageRange1; - *resTmp++ = (int)os2->ulCodePageRange2; - } - else - { - *resTmp++ = (int)0xFFFF; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; + if (os2) + { + *resTmp++ = (int)os2->version; + *resTmp++ = (int)os2->usWeightClass; + *resTmp++ = (int)os2->fsSelection; + *resTmp++ = (int)os2->usWinAscent; + *resTmp++ = (int)os2->usWinDescent; + *resTmp++ = (int)os2->usDefaultChar; + *resTmp++ = (int)os2->sTypoAscender; + *resTmp++ = (int)os2->sTypoDescender; + *resTmp++ = (int)os2->sTypoLineGap; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - *resTmp++ = (int)0; - } + *resTmp++ = (int)os2->ulUnicodeRange1; + *resTmp++ = (int)os2->ulUnicodeRange2; + *resTmp++ = (int)os2->ulUnicodeRange3; + *resTmp++ = (int)os2->ulUnicodeRange4; + *resTmp++ = (int)os2->ulCodePageRange1; + *resTmp++ = (int)os2->ulCodePageRange2; + } + else + { + *resTmp++ = (int)0xFFFF; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; - *resTmp++ = (int)isSymbolic; - *resTmp++ = (int)nHeader_yMin; - *resTmp++ = (int)nHeader_yMax; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + *resTmp++ = (int)0; + } - *resTmp++ = (int)face->num_fixed_sizes; + *resTmp++ = (int)isSymbolic; + *resTmp++ = (int)nHeader_yMin; + *resTmp++ = (int)nHeader_yMax; - for (int i = 0; i < face->num_fixed_sizes; ++i) - *resTmp++ = (int)face->available_sizes[i].size; + *resTmp++ = (int)face->num_fixed_sizes; - return res; + for (int i = 0; i < face->num_fixed_sizes; ++i) + *resTmp++ = (int)face->available_sizes[i].size; + + if (family_name) + delete [] family_name; + + return res; } WASM_EXPORT int ASC_FT_GetFaceMaxAdvanceX(FT_Face face) { - if (!face || !face->size) - return 0; + if (!face || !face->size) + return 0; - return (int)face->size->metrics.max_advance; + return (int)face->size->metrics.max_advance; } WASM_EXPORT int ASC_FT_GetKerningX(FT_Face face, unsigned int prev_gid, unsigned int gid) { - FT_Vector vec; - vec.x = 0; - vec.y = 0; - FT_Get_Kerning(face, prev_gid, gid, 0, &vec); - return vec.x; + FT_Vector vec; + vec.x = 0; + vec.y = 0; + FT_Get_Kerning(face, prev_gid, gid, 0, &vec); + return vec.x; } WASM_EXPORT void ASC_FT_Set_Transform(FT_Face face, int xx, int yx, int xy, int yy) { - FT_Matrix m; - m.xx = xx; - m.yx = yx; - m.xy = xy; - m.yy = yy; - FT_Set_Transform(face, &m, NULL); + FT_Matrix m; + m.xx = xx; + m.yx = yx; + m.xy = xy; + m.yy = yy; + FT_Set_Transform(face, &m, NULL); } WASM_EXPORT int ASC_FT_Set_Char_Size(FT_Face face, FT_F26Dot6 char_width, FT_F26Dot6 char_height, FT_UInt horz_resolution, FT_UInt vert_resolution) { - return FT_Set_Char_Size(face, char_width, char_height, horz_resolution, vert_resolution); + return FT_Set_Char_Size(face, char_width, char_height, horz_resolution, vert_resolution); } // ------------------------------------------------------------ @@ -326,207 +321,207 @@ WASM_EXPORT int ASC_FT_Set_Char_Size(FT_Face face, FT_F26Dot6 char_width, FT_F26 WASM_EXPORT int ASC_FT_Load_Glyph(FT_Face face, FT_UInt glyph_index, FT_Int32 load_flags) { - return FT_Load_Glyph(face, glyph_index, load_flags); + return FT_Load_Glyph(face, glyph_index, load_flags); } WASM_EXPORT int* ASC_FT_Glyph_Get_CBox(FT_Glyph glyph, FT_UInt bbox_mode) { - FT_BBox bbox; - FT_Glyph_Get_CBox(glyph, bbox_mode, &bbox); - int* res = (int*)ASC_FT_Malloc(4 * sizeof(int)); - res[0] = bbox.xMin; - res[1] = bbox.yMin; - res[2] = bbox.xMax; - res[3] = bbox.yMax; - return res; + FT_BBox bbox; + FT_Glyph_Get_CBox(glyph, bbox_mode, &bbox); + int* res = (int*)ASC_FT_Malloc(4 * sizeof(int)); + res[0] = bbox.xMin; + res[1] = bbox.yMin; + res[2] = bbox.xMax; + res[3] = bbox.yMax; + return res; } // outline typedef struct FT_Decompose_Outline_Buffer_ { - FT_Pos* buffer; - FT_Int size; - FT_Int pos; + FT_Pos* buffer; + FT_Int size; + FT_Int pos; } FT_Decompose_Outline_Buffer; void FT_Decompose_Outline_Buffer_Init(FT_Decompose_Outline_Buffer* buffer) { - buffer->buffer = NULL; - buffer->size = 0; - buffer->pos = 0; + buffer->buffer = NULL; + buffer->size = 0; + buffer->pos = 0; } void FT_Decompose_Outline_Buffer_Check(FT_Decompose_Outline_Buffer* buffer, FT_Int add) { - if ((buffer->pos + add) < buffer->size) - return; + if ((buffer->pos + add) < buffer->size) + return; - if (NULL == buffer->buffer) - { - buffer->buffer = (FT_Pos*)ft_smalloc(200 * sizeof(FT_Pos)); - buffer->size = 200; - buffer->pos = 0; - return; - } + if (NULL == buffer->buffer) + { + buffer->buffer = (FT_Pos*)ft_smalloc(200 * sizeof(FT_Pos)); + buffer->size = 200; + buffer->pos = 0; + return; + } - FT_Int sizeNew = 2 * buffer->size; - FT_Pos* bufferNew = (FT_Pos*)ft_smalloc((size_t)sizeNew * sizeof(FT_Pos)); - memcpy(bufferNew, buffer->buffer, (size_t)buffer->pos * sizeof(FT_Pos)); - ft_sfree(buffer->buffer); - buffer->buffer = bufferNew; - buffer->size = sizeNew; - // pos + FT_Int sizeNew = 2 * buffer->size; + FT_Pos* bufferNew = (FT_Pos*)ft_smalloc((size_t)sizeNew * sizeof(FT_Pos)); + memcpy(bufferNew, buffer->buffer, (size_t)buffer->pos * sizeof(FT_Pos)); + ft_sfree(buffer->buffer); + buffer->buffer = bufferNew; + buffer->size = sizeNew; + // pos } int GlyphPathMoveTo(const FT_Vector *point, void *user) { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 3); - buffer->buffer[buffer->pos++] = 0; - buffer->buffer[buffer->pos++] = point->x; - buffer->buffer[buffer->pos++] = point->y; - return 0; + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 3); + buffer->buffer[buffer->pos++] = 0; + buffer->buffer[buffer->pos++] = point->x; + buffer->buffer[buffer->pos++] = point->y; + return 0; } int GlyphPathLineTo(const FT_Vector *point, void *user) { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 3); - buffer->buffer[buffer->pos++] = 1; - buffer->buffer[buffer->pos++] = point->x; - buffer->buffer[buffer->pos++] = point->y; - return 0; + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 3); + buffer->buffer[buffer->pos++] = 1; + buffer->buffer[buffer->pos++] = point->x; + buffer->buffer[buffer->pos++] = point->y; + return 0; } int GlyphPathConicTo(const FT_Vector *pControlPoint, const FT_Vector *pEndPoint, void *user) { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 5); - buffer->buffer[buffer->pos++] = 2; - buffer->buffer[buffer->pos++] = pControlPoint->x; - buffer->buffer[buffer->pos++] = pControlPoint->y; - buffer->buffer[buffer->pos++] = pEndPoint->x; - buffer->buffer[buffer->pos++] = pEndPoint->y; - return 0; + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 5); + buffer->buffer[buffer->pos++] = 2; + buffer->buffer[buffer->pos++] = pControlPoint->x; + buffer->buffer[buffer->pos++] = pControlPoint->y; + buffer->buffer[buffer->pos++] = pEndPoint->x; + buffer->buffer[buffer->pos++] = pEndPoint->y; + return 0; } int GlyphPathCubicTo(const FT_Vector *pFirstControlPoint, const FT_Vector *pSecondControlPoint, const FT_Vector *pEndPoint, void *user) { - FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; - FT_Decompose_Outline_Buffer_Check(buffer, 7); - buffer->buffer[buffer->pos++] = 3; - buffer->buffer[buffer->pos++] = pFirstControlPoint->x; - buffer->buffer[buffer->pos++] = pFirstControlPoint->y; - buffer->buffer[buffer->pos++] = pSecondControlPoint->x; - buffer->buffer[buffer->pos++] = pSecondControlPoint->y; - buffer->buffer[buffer->pos++] = pEndPoint->x; - buffer->buffer[buffer->pos++] = pEndPoint->y; - return 0; + FT_Decompose_Outline_Buffer* buffer = (FT_Decompose_Outline_Buffer*)user; + FT_Decompose_Outline_Buffer_Check(buffer, 7); + buffer->buffer[buffer->pos++] = 3; + buffer->buffer[buffer->pos++] = pFirstControlPoint->x; + buffer->buffer[buffer->pos++] = pFirstControlPoint->y; + buffer->buffer[buffer->pos++] = pSecondControlPoint->x; + buffer->buffer[buffer->pos++] = pSecondControlPoint->y; + buffer->buffer[buffer->pos++] = pEndPoint->x; + buffer->buffer[buffer->pos++] = pEndPoint->y; + return 0; } WASM_EXPORT int* ASC_FT_Get_Glyph_Measure_Params(FT_Face face, int isVector) { - FT_GlyphSlot slot = face->glyph; + FT_GlyphSlot slot = face->glyph; - if (!isVector && slot->bitmap.buffer != NULL && slot->format == FT_GLYPH_FORMAT_BITMAP) - { - int* res = (int*)ASC_FT_Malloc(15 * sizeof(int)); - res[0] = 15; - res[1] = 0; - res[2] = 0; - res[3] = slot->metrics.width; - res[4] = slot->metrics.height; + if (!isVector && slot->bitmap.buffer != NULL && slot->format == FT_GLYPH_FORMAT_BITMAP) + { + int* res = (int*)ASC_FT_Malloc(15 * sizeof(int)); + res[0] = 15; + res[1] = 0; + res[2] = 0; + res[3] = slot->metrics.width; + res[4] = slot->metrics.height; - res[5] = slot->metrics.width; - res[6] = slot->metrics.height; + res[5] = slot->metrics.width; + res[6] = slot->metrics.height; - res[7] = slot->metrics.horiAdvance; - res[8] = slot->metrics.horiBearingX; - res[9] = slot->metrics.horiBearingY; + res[7] = slot->metrics.horiAdvance; + res[8] = slot->metrics.horiBearingX; + res[9] = slot->metrics.horiBearingY; - res[10] = slot->metrics.vertAdvance; - res[11] = slot->metrics.vertBearingX; - res[12] = slot->metrics.vertBearingY; + res[10] = slot->metrics.vertAdvance; + res[11] = slot->metrics.vertBearingX; + res[12] = slot->metrics.vertBearingY; - res[13] = slot->linearHoriAdvance; - res[14] = slot->linearVertAdvance; - return res; - } + res[13] = slot->linearHoriAdvance; + res[14] = slot->linearVertAdvance; + return res; + } - FT_Glyph glyph; - FT_Get_Glyph(slot, &glyph); - if (!glyph) - return NULL; + FT_Glyph glyph; + FT_Get_Glyph(slot, &glyph); + if (!glyph) + return NULL; - FT_Decompose_Outline_Buffer buffer; - FT_Decompose_Outline_Buffer_Init(&buffer); - FT_Decompose_Outline_Buffer_Check(&buffer, 15); + FT_Decompose_Outline_Buffer buffer; + FT_Decompose_Outline_Buffer_Init(&buffer); + FT_Decompose_Outline_Buffer_Check(&buffer, 15); - FT_Pos* _buffer = buffer.buffer; - _buffer[0] = 0; + FT_Pos* _buffer = buffer.buffer; + _buffer[0] = 0; - FT_BBox bbox; - FT_Glyph_Get_CBox(glyph, 1, &bbox); - _buffer[1] = bbox.xMin; - _buffer[2] = bbox.yMin; - _buffer[3] = bbox.xMax; - _buffer[4] = bbox.yMax; + FT_BBox bbox; + FT_Glyph_Get_CBox(glyph, 1, &bbox); + _buffer[1] = bbox.xMin; + _buffer[2] = bbox.yMin; + _buffer[3] = bbox.xMax; + _buffer[4] = bbox.yMax; - _buffer[5] = slot->metrics.width; - _buffer[6] = slot->metrics.height; + _buffer[5] = slot->metrics.width; + _buffer[6] = slot->metrics.height; - _buffer[7] = slot->metrics.horiAdvance; - _buffer[8] = slot->metrics.horiBearingX; - _buffer[9] = slot->metrics.horiBearingY; + _buffer[7] = slot->metrics.horiAdvance; + _buffer[8] = slot->metrics.horiBearingX; + _buffer[9] = slot->metrics.horiBearingY; - _buffer[10] = slot->metrics.vertAdvance; - _buffer[11] = slot->metrics.vertBearingX; - _buffer[12] = slot->metrics.vertBearingY; + _buffer[10] = slot->metrics.vertAdvance; + _buffer[11] = slot->metrics.vertBearingX; + _buffer[12] = slot->metrics.vertBearingY; - _buffer[13] = slot->linearHoriAdvance; - _buffer[14] = slot->linearVertAdvance; + _buffer[13] = slot->linearHoriAdvance; + _buffer[14] = slot->linearVertAdvance; - buffer.pos = 15; + buffer.pos = 15; - if (isVector) - { - static FT_Outline_Funcs pOutlineFuncs = - { - &GlyphPathMoveTo, - &GlyphPathLineTo, - &GlyphPathConicTo, - &GlyphPathCubicTo, - 0, 0 - }; + if (isVector) + { + static FT_Outline_Funcs pOutlineFuncs = + { + &GlyphPathMoveTo, + &GlyphPathLineTo, + &GlyphPathConicTo, + &GlyphPathCubicTo, + 0, 0 + }; - FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline, &pOutlineFuncs, &buffer); - } + FT_Outline_Decompose(&((FT_OutlineGlyph)glyph)->outline, &pOutlineFuncs, &buffer); + } - buffer.buffer[0] = buffer.pos; + buffer.buffer[0] = buffer.pos; - FT_Done_Glyph(glyph); - return (int*)buffer.buffer; + FT_Done_Glyph(glyph); + return (int*)buffer.buffer; } WASM_EXPORT int* ASC_FT_Get_Glyph_Render_Params(FT_Face face, int render_mode) { - FT_GlyphSlot slot = face->glyph; - if (FT_Render_Glyph(slot, (FT_Render_Mode)render_mode)) - return NULL; + FT_GlyphSlot slot = face->glyph; + if (FT_Render_Glyph(slot, (FT_Render_Mode)render_mode)) + return NULL; - int* res = (int*)ASC_FT_Malloc(6 * sizeof(int)); - res[0] = slot->bitmap_left; - res[1] = slot->bitmap_top; - res[2] = (int)slot->bitmap.width; - res[3] = (int)slot->bitmap.rows; - res[4] = slot->bitmap.pitch; - res[5] = slot->bitmap.pixel_mode; - return res; + int* res = (int*)ASC_FT_Malloc(6 * sizeof(int)); + res[0] = slot->bitmap_left; + res[1] = slot->bitmap_top; + res[2] = (int)slot->bitmap.width; + res[3] = (int)slot->bitmap.rows; + res[4] = slot->bitmap.pitch; + res[5] = slot->bitmap.pixel_mode; + return res; } WASM_EXPORT unsigned char* ASC_FT_Get_Glyph_Render_Buffer(FT_Face face) { - return face->glyph->bitmap.buffer; + return face->glyph->bitmap.buffer; } // ------------------------------------------------------------ @@ -542,98 +537,98 @@ bool g_userfeatures_init = false; WASM_EXPORT void* ASC_HB_LanguageFromString(char* language_bcp_47) { - return (void*)hb_language_from_string(language_bcp_47, strlen(language_bcp_47)); + return (void*)hb_language_from_string(language_bcp_47, strlen(language_bcp_47)); } WASM_EXPORT unsigned char* ASC_HB_ShapeText(FT_Face pFace, hb_font_t* pFont, char* pText, - unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, unsigned char* nLanguage) + unsigned int nFeatures, unsigned int nScript, unsigned int nDirection, unsigned char* nLanguage) { - // init features - if (!g_userfeatures_init) - { - hb_tag_t tags[] = { - HB_TAG('l','i','g','a'), - HB_TAG('c','l','i','g'), - HB_TAG('h','l','i','g'), - HB_TAG('d','l','i','g'), - HB_TAG('k','e','r','n') - }; - for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) - { - g_userfeatures[nTag].tag = tags[nTag]; - g_userfeatures[nTag].value = 0; - g_userfeatures[nTag].start = HB_FEATURE_GLOBAL_START; - g_userfeatures[nTag].end = HB_FEATURE_GLOBAL_END; - } - g_userfeatures_init = true; - } + // init features + if (!g_userfeatures_init) + { + hb_tag_t tags[] = { + HB_TAG('l','i','g','a'), + HB_TAG('c','l','i','g'), + HB_TAG('h','l','i','g'), + HB_TAG('d','l','i','g'), + HB_TAG('k','e','r','n') + }; + for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) + { + g_userfeatures[nTag].tag = tags[nTag]; + g_userfeatures[nTag].value = 0; + g_userfeatures[nTag].start = HB_FEATURE_GLOBAL_START; + g_userfeatures[nTag].end = HB_FEATURE_GLOBAL_END; + } + g_userfeatures_init = true; + } - // font - if (NULL == pFont) - { - pFont = hb_ft_font_create(pFace, NULL); - hb_ft_font_set_funcs(pFont); - } + // font + if (NULL == pFont) + { + pFont = hb_ft_font_create(pFace, NULL); + hb_ft_font_set_funcs(pFont); + } - // features - for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) - g_userfeatures[nTag].value = (nFeatures & (1 << nTag)) ? 1 : 0; + // features + for (int nTag = 0; nTag < g_userfeatures_count; ++nTag) + g_userfeatures[nTag].value = (nFeatures & (1 << nTag)) ? 1 : 0; - // buffer - hb_buffer_t* hbBuffer = hb_buffer_create(); - hb_buffer_set_direction(hbBuffer, (hb_direction_t)nDirection); - hb_buffer_set_script(hbBuffer, (hb_script_t)nScript); - hb_buffer_set_language(hbBuffer, (hb_language_t)nLanguage); - hb_buffer_set_cluster_level(hbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES); - int text_len = (int)strlen(pText); - hb_buffer_add_utf8(hbBuffer, pText, text_len, 0, text_len); - hb_buffer_guess_segment_properties(hbBuffer); + // buffer + hb_buffer_t* hbBuffer = hb_buffer_create(); + hb_buffer_set_direction(hbBuffer, (hb_direction_t)nDirection); + hb_buffer_set_script(hbBuffer, (hb_script_t)nScript); + hb_buffer_set_language(hbBuffer, (hb_language_t)nLanguage); + hb_buffer_set_cluster_level(hbBuffer, HB_BUFFER_CLUSTER_LEVEL_MONOTONE_GRAPHEMES); + int text_len = (int)strlen(pText); + hb_buffer_add_utf8(hbBuffer, pText, text_len, 0, text_len); + hb_buffer_guess_segment_properties(hbBuffer); - // shape - hb_shape(pFont, hbBuffer, g_userfeatures, g_userfeatures_count); + // shape + hb_shape(pFont, hbBuffer, g_userfeatures, g_userfeatures_count); - unsigned int glyph_count; - hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hbBuffer, &glyph_count); - hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hbBuffer, &glyph_count); + unsigned int glyph_count; + hb_glyph_info_t* glyph_info = hb_buffer_get_glyph_infos(hbBuffer, &glyph_count); + hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions(hbBuffer, &glyph_count); - int nSize = 4 + 8 + glyph_count * (1 + 1 + 4 * 6); - unsigned char* pBuffer = (unsigned char*)ASC_FT_Malloc(nSize); - memset(pBuffer, 0, nSize); + int nSize = 4 + 8 + glyph_count * (1 + 1 + 4 * 6); + unsigned char* pBuffer = (unsigned char*)ASC_FT_Malloc(nSize); + memset(pBuffer, 0, nSize); - int nSizeofInt = sizeof(int); - unsigned char* pBufferCurrent = pBuffer; + int nSizeofInt = sizeof(int); + unsigned char* pBufferCurrent = pBuffer; - memcpy(pBufferCurrent, &nSize, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &nSize, nSizeofInt); pBufferCurrent += nSizeofInt; - uint64_t pFontPointer = (uint64_t)pFont; - memcpy(pBufferCurrent, &pFontPointer, sizeof(uint64_t)); - pBufferCurrent += 8; + uint64_t pFontPointer = (uint64_t)pFont; + memcpy(pBufferCurrent, &pFontPointer, sizeof(uint64_t)); + pBufferCurrent += 8; - for (unsigned i = 0; i < glyph_count; ++i) - { - unsigned char nGlyphType = (unsigned char)hb_ot_layout_get_glyph_class(hb_font_get_face(pFont), glyph_info[i].codepoint); - unsigned char nGlyphFlags = (unsigned char)hb_glyph_info_get_glyph_flags(&glyph_info[i]); + for (unsigned i = 0; i < glyph_count; ++i) + { + unsigned char nGlyphType = (unsigned char)hb_ot_layout_get_glyph_class(hb_font_get_face(pFont), glyph_info[i].codepoint); + unsigned char nGlyphFlags = (unsigned char)hb_glyph_info_get_glyph_flags(&glyph_info[i]); - memcpy(pBufferCurrent, &nGlyphType, nSizeofInt); pBufferCurrent++; - memcpy(pBufferCurrent, &nGlyphFlags, nSizeofInt); pBufferCurrent++; + memcpy(pBufferCurrent, &nGlyphType, nSizeofInt); pBufferCurrent++; + memcpy(pBufferCurrent, &nGlyphFlags, nSizeofInt); pBufferCurrent++; - memcpy(pBufferCurrent, &glyph_info[i].codepoint, nSizeofInt); pBufferCurrent += nSizeofInt; - memcpy(pBufferCurrent, &glyph_info[i].cluster, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &glyph_info[i].codepoint, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &glyph_info[i].cluster, nSizeofInt); pBufferCurrent += nSizeofInt; - memcpy(pBufferCurrent, &glyph_pos[i].x_advance, nSizeofInt); pBufferCurrent += nSizeofInt; - memcpy(pBufferCurrent, &glyph_pos[i].y_advance, nSizeofInt); pBufferCurrent += nSizeofInt; - memcpy(pBufferCurrent, &glyph_pos[i].x_offset, nSizeofInt); pBufferCurrent += nSizeofInt; - memcpy(pBufferCurrent, &glyph_pos[i].y_offset, nSizeofInt); pBufferCurrent += nSizeofInt; - } + memcpy(pBufferCurrent, &glyph_pos[i].x_advance, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &glyph_pos[i].y_advance, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &glyph_pos[i].x_offset, nSizeofInt); pBufferCurrent += nSizeofInt; + memcpy(pBufferCurrent, &glyph_pos[i].y_offset, nSizeofInt); pBufferCurrent += nSizeofInt; + } - hb_buffer_destroy(hbBuffer); + hb_buffer_destroy(hbBuffer); - return pBuffer; + return pBuffer; } WASM_EXPORT void ASC_HB_FontFree(hb_font_t* font) { - hb_font_destroy(font); + hb_font_destroy(font); } #ifdef __cplusplus diff --git a/DesktopEditor/fontengine/js/libfont.json b/DesktopEditor/fontengine/js/libfont.json index 926cd896a6..fb5442410a 100644 --- a/DesktopEditor/fontengine/js/libfont.json +++ b/DesktopEditor/fontengine/js/libfont.json @@ -55,7 +55,7 @@ "./../../../OfficeUtils/src", "./../../../OfficeUtils/src/zlib-1.2.11" ], - "define": ["WIN32", "NDEBUG", "_LIB", "_CRT_SECURE_NO_WARNINGS", "FT2_BUILD_LIBRARY", "HAVE_FREETYPE", "FT_CONFIG_OPTION_SYSTEM_ZLIB"], + "define": ["__linux__", "_LINUX", "UNIX", "NDEBUG", "_LIB", "_CRT_SECURE_NO_WARNINGS", "FT2_BUILD_LIBRARY", "HAVE_FREETYPE", "FT_CONFIG_OPTION_SYSTEM_ZLIB"], "compile_files_array": [ { "name": "f", diff --git a/DesktopEditor/graphics/Clip.cpp b/DesktopEditor/graphics/Clip.cpp index 36d54ee829..b2a2c5f902 100644 --- a/DesktopEditor/graphics/Clip.cpp +++ b/DesktopEditor/graphics/Clip.cpp @@ -193,6 +193,8 @@ namespace Aggplus void CClipMulti::Create(LONG width, LONG height) { + m_lWidth = width; + m_lHeight = height; m_rasterizer.clip_box(0, 0, width, height); m_bIsClip = false; m_bIsClip2 = false; @@ -227,6 +229,7 @@ namespace Aggplus { // смешивать надо с растерайзером agg::rasterizer_scanline_aa<> rasterizer; + rasterizer.clip_box(0, 0, m_lWidth, m_lHeight); typedef agg::conv_transform trans_type; trans_type trans(pPath->m_internal->m_agg_ps, pMatrix->m_internal->m_agg_mtx); @@ -249,6 +252,7 @@ namespace Aggplus { // надо смешивать со стораджем agg::rasterizer_scanline_aa<> rasterizer; + rasterizer.clip_box(0, 0, m_lWidth, m_lHeight); typedef agg::conv_transform trans_type; trans_type trans(pPath->m_internal->m_agg_ps, pMatrix->m_internal->m_agg_mtx); diff --git a/DesktopEditor/graphics/Clip.h b/DesktopEditor/graphics/Clip.h index f9f63ed869..592893996d 100644 --- a/DesktopEditor/graphics/Clip.h +++ b/DesktopEditor/graphics/Clip.h @@ -151,6 +151,9 @@ public: bool m_bIsClip; bool m_bIsClip2; + LONG m_lWidth; + LONG m_lHeight; + public: CClipMulti(); ~CClipMulti(); diff --git a/DesktopEditor/graphics/Graphics.cpp b/DesktopEditor/graphics/Graphics.cpp index 3f7c88d8f7..3691a58a0d 100644 --- a/DesktopEditor/graphics/Graphics.cpp +++ b/DesktopEditor/graphics/Graphics.cpp @@ -58,17 +58,19 @@ namespace Aggplus #endif m_dGlobalAlpha = 1.0; - m_bSwapRGB = false; - m_bIsDarkMode = false; + m_bSwapRGB = false; + m_bIsDarkMode = false; #if defined (_LINUX) || defined (_QT) - m_bSwapRGB = true; + m_bSwapRGB = true; #endif - m_dDpiTile = -1; + m_dDpiTile = -1; - m_nTextRenderMode = FT_RENDER_MODE_NORMAL; - m_nBlendMode = agg::comp_op_src_over; + m_nTextRenderMode = FT_RENDER_MODE_NORMAL; + m_nBlendMode = agg::comp_op_src_over; + + m_bIs0PenWidthAs1px = false; } CGraphics::CGraphics(int dwWidth, int dwHeight, int stride, BYTE* pBuffer) : m_dwConfigFlags(0) @@ -93,23 +95,25 @@ namespace Aggplus m_pGraphics = NULL; #endif - m_bSwapRGB = false; + m_bSwapRGB = false; #if defined (_LINUX) || defined (_QT) - m_bSwapRGB = true; + m_bSwapRGB = true; #endif - m_dDpiTile = -1; + m_dDpiTile = -1; m_nTextRenderMode = FT_RENDER_MODE_NORMAL; m_nBlendMode = agg::comp_op_src_over; + + m_bIs0PenWidthAs1px = false; } CGraphics::CGraphics(CImage* pImage) : m_dwConfigFlags(0) { m_dGlobalAlpha = 1.0; - if (!pImage) - { + if (!pImage) + { return; } @@ -132,16 +136,18 @@ namespace Aggplus m_pGraphics = NULL; #endif - m_bSwapRGB = false; + m_bSwapRGB = false; #if defined (_LINUX) || defined (_QT) - m_bSwapRGB = true; + m_bSwapRGB = true; #endif - m_dDpiTile = -1; + m_dDpiTile = -1; m_nTextRenderMode = FT_RENDER_MODE_NORMAL; m_nBlendMode = agg::comp_op_src_over; + + m_bIs0PenWidthAs1px = false; } CGraphics::~CGraphics() @@ -235,7 +241,7 @@ namespace Aggplus m_pPixels = pPixels; m_pDib = pDib; - + return Ok; } @@ -277,24 +283,24 @@ namespace Aggplus switch (lUnit) { case UnitPoint: - { - lWidth /= c_ag_Inch_to_Point; - SetDpiX(m_dWidthPix / lWidth); + { + lWidth /= c_ag_Inch_to_Point; + SetDpiX(m_dWidthPix / lWidth); - break; - } + break; + } case UnitMillimeter: - { - lWidth /= c_ag_Inch_to_MM; - SetDpiX(m_dWidthPix / lWidth); + { + lWidth /= c_ag_Inch_to_MM; + SetDpiX(m_dWidthPix / lWidth); - break; - } + break; + } case UnitInch: - { - SetDpiX(m_dWidthPix / lWidth); - break; - } + { + SetDpiX(m_dWidthPix / lWidth); + break; + } default: break; }; @@ -307,24 +313,24 @@ namespace Aggplus switch (lUnit) { case UnitPoint: - { - lHeight /= c_ag_Inch_to_Point; - SetDpiY(m_dHeightPix / lHeight); + { + lHeight /= c_ag_Inch_to_Point; + SetDpiY(m_dHeightPix / lHeight); - break; - } + break; + } case UnitMillimeter: - { - lHeight /= c_ag_Inch_to_MM; - SetDpiY(m_dHeightPix / lHeight); + { + lHeight /= c_ag_Inch_to_MM; + SetDpiY(m_dHeightPix / lHeight); - break; - } + break; + } case UnitInch: - { - SetDpiY(m_dHeightPix / lHeight); - break; - } + { + SetDpiY(m_dHeightPix / lHeight); + break; + } default: break; }; @@ -401,10 +407,10 @@ namespace Aggplus m_oFullTransform.TransformPoint(dx1, dy1); m_oFullTransform.TransformPoint(dx2, dy2); - m_dClipLeft = std::max(0.0, dx1); - m_dClipTop = std::max(0.0, dy1); - m_dClipWidth = std::min(dx2, m_dWidthPix - 1) - m_dClipLeft; - m_dClipHeight = std::min(dy2, m_dHeightPix - 1) - m_dClipTop; + m_dClipLeft = std::max(0.0, dx1); + m_dClipTop = std::max(0.0, dy1); + m_dClipWidth = std::min(dx2, m_dWidthPix - 1) - m_dClipLeft; + m_dClipHeight = std::min(dy2, m_dHeightPix - 1) - m_dClipTop; m_oClip.Reset(); @@ -412,10 +418,10 @@ namespace Aggplus } Status CGraphics::SetClipRect2(double dLeft, double dTop, double dWidth, double dHeight) { - m_dClipLeft = std::max(0.0, dLeft); - m_dClipTop = std::max(0.0, dTop); - m_dClipWidth = std::min(dWidth, m_dWidthPix - 1 - m_dClipLeft); - m_dClipHeight = std::min(dHeight, m_dHeightPix - 1 - m_dClipTop); + m_dClipLeft = std::max(0.0, dLeft); + m_dClipTop = std::max(0.0, dTop); + m_dClipWidth = std::min(dWidth, m_dWidthPix - 1 - m_dClipLeft); + m_dClipHeight = std::min(dHeight, m_dHeightPix - 1 - m_dClipTop); m_rasterizer.get_rasterizer().clip_box(m_dClipLeft, m_dClipTop, m_dClipWidth + m_dClipLeft, m_dClipHeight + m_dClipTop); m_oClip.Reset(); @@ -432,7 +438,7 @@ namespace Aggplus m_oFullTransform.TransformPoint(dRight, dBottom); dWidth = dRight - dLeft; - dHeight = dBottom - dTop; + dHeight = dBottom - dTop; m_dClipLeft = dLeft; m_dClipTop = dTop; @@ -461,7 +467,7 @@ namespace Aggplus Status CGraphics::ResetClip() { m_oClip.Reset(); - m_oClipState.Clear(); + m_oClipState.Clear(); return Ok; } @@ -480,26 +486,26 @@ namespace Aggplus Status CGraphics::CombineClip(CGraphicsPath* pPath, agg::sbool_op_e op) { - Aggplus::CMatrix m; - return InternalClip(pPath, (m_bIntegerGrid || pPath->m_internal->m_pTransform != NULL) ? &m : &m_oFullTransform, op); + Aggplus::CMatrix m; + return InternalClip(pPath, (m_bIntegerGrid || pPath->m_internal->m_pTransform != NULL) ? &m : &m_oFullTransform, op); } - Status CGraphics::InternalClip(CGraphicsPath* pPath, CMatrix* pTransform, agg::sbool_op_e op) - { - if (NULL == pPath) - return InvalidParameter; + Status CGraphics::InternalClip(CGraphicsPath* pPath, CMatrix* pTransform, agg::sbool_op_e op) + { + if (NULL == pPath) + return InvalidParameter; - m_oClip.Combine(pPath, pTransform, op); + m_oClip.Combine(pPath, pTransform, op); - // write to clips history - CGraphics_ClipStateRecord* pRecord = new CGraphics_ClipStateRecord(); - pRecord->Path = (NULL != pPath) ? pPath->Clone() : NULL; - pRecord->Transform = (NULL != pTransform) ? new CMatrix(*pTransform) : new CMatrix(); - pRecord->Operation = op; - m_oClipState.AddRecord(pRecord); + // write to clips history + CGraphics_ClipStateRecord* pRecord = new CGraphics_ClipStateRecord(); + pRecord->Path = (NULL != pPath) ? pPath->Clone() : NULL; + pRecord->Transform = (NULL != pTransform) ? new CMatrix(*pTransform) : new CMatrix(); + pRecord->Operation = op; + m_oClipState.AddRecord(pRecord); - return Ok; - } + return Ok; + } INT CGraphics::MeasureString(const std::wstring& strText, CFontManager* pManager, double* lWidth, double* lHeight) { @@ -508,7 +514,7 @@ namespace Aggplus pManager->LoadString1(strText, 0, 0); - TBBox oBox = pManager->MeasureString(); + TBBox oBox = pManager->MeasureString(); *lWidth = (double)oBox.fMaxX - oBox.fMinX; *lHeight = (double)oBox.fMaxY - oBox.fMinY; @@ -558,7 +564,7 @@ namespace Aggplus return DrawPath(pPen, &oPath); } - Status CGraphics::DrawLines(NSStructures::CPen* pPen, double* pPoints, LONG lCount) + Status CGraphics::DrawLines(NSStructures::CPen* pPen, double* pPoints, LONG lCount) { CGraphicsPath oPath; oPath.AddLines(pPoints, lCount); @@ -579,7 +585,7 @@ namespace Aggplus return DrawPath(pPen, &oPath); } - Status CGraphics::DrawPath(NSStructures::CPen* pPen, CGraphicsPath* pPath, const double& gamma) + Status CGraphics::DrawPath(NSStructures::CPen* pPen, CGraphicsPath* pPath, const double& gamma) { if (NULL == pPen || NULL == pPath) return InvalidParameter; @@ -593,7 +599,7 @@ namespace Aggplus case LineJoinBevel : LineJoin = agg::bevel_join; break; case LineJoinRound : LineJoin = agg::round_join; break; case LineJoinMiterClipped : LineJoin = agg::miter_join_revert; break; - default: break; + default: break; } agg::line_cap_e LineCap = agg::round_cap; switch(pPen->LineStartCap) @@ -601,7 +607,7 @@ namespace Aggplus case LineCapFlat : LineCap = agg::butt_cap; break; case LineCapRound : LineCap = agg::round_cap; break; case LineCapSquare : LineCap = agg::square_cap; break; - default: break; + default: break; } double dWidth = pPen->Size; @@ -609,7 +615,8 @@ namespace Aggplus if ((0 == dWidth && !m_bIntegerGrid) || dWidth < dWidthMinSize) { - //dWidth = dWidthMinSize; + if (m_bIs0PenWidthAs1px) + dWidth = dWidthMinSize; } double dblMiterLimit = pPen->MiterLimit; @@ -631,38 +638,38 @@ namespace Aggplus } typedef agg::conv_curve conv_crv_type; - + conv_crv_type c_c_path(path_copy); c_c_path.approximation_scale(25.0); c_c_path.approximation_method(agg::curve_inc); DashStyle eStyle = (DashStyle)pPen->DashStyle; - if (DashStyleCustom == eStyle) - { - if (0 == pPen->Count || NULL == pPen->DashPattern) - { - eStyle = DashStyleSolid; - } - else - { - bool bFoundNormal = false; - for (int i = 0; i < pPen->Count; i++) - { - if (fabs(pPen->DashPattern[i]) > 0.0001) - { - bFoundNormal = true; - break; - } - } - if (!bFoundNormal) - eStyle = DashStyleSolid; - } - } + if (DashStyleCustom == eStyle) + { + if (0 == pPen->Count || NULL == pPen->DashPattern) + { + eStyle = DashStyleSolid; + } + else + { + bool bFoundNormal = false; + for (int i = 0; i < pPen->Count; i++) + { + if (fabs(pPen->DashPattern[i]) > 0.0001) + { + bFoundNormal = true; + break; + } + } + if (!bFoundNormal) + eStyle = DashStyleSolid; + } + } agg::trans_affine* pAffine = &m_oFullTransform.m_internal->m_agg_mtx; if (bIsUseIdentity) pAffine = new agg::trans_affine(); - + if (DashStyleSolid == eStyle) { typedef agg::conv_stroke Path_Conv_StrokeN; @@ -712,37 +719,37 @@ namespace Aggplus break; default: case DashStyleCustom: + { + double offset = pPen->DashOffset; + double* params = pPen->DashPattern; + LONG lCount = pPen->Count; + LONG lCount2 = lCount / 2; + + double dKoef = 1.0; + + for (LONG i = 0; i < lCount2; ++i) { - double offset = pPen->DashOffset; - double* params = pPen->DashPattern; - LONG lCount = pPen->Count; - LONG lCount2 = lCount / 2; - - double dKoef = 1.0; - - for (LONG i = 0; i < lCount2; ++i) + if (0 == i) { - if (0 == i) - { - poly2_dash.add_dash((params[i * 2]) * dKoef, params[i * 2 + 1] * dKoef); - } - else - { - poly2_dash.add_dash(params[i * 2] * dKoef, params[i * 2 + 1] * dKoef); - } + poly2_dash.add_dash((params[i * 2]) * dKoef, params[i * 2 + 1] * dKoef); } - if (1 == (lCount % 2)) + else { - poly2_dash.add_dash(params[lCount - 1] * dKoef, 0); + poly2_dash.add_dash(params[i * 2] * dKoef, params[i * 2 + 1] * dKoef); } - poly2_dash.dash_start(offset * dKoef); - - break; } + if (1 == (lCount % 2)) + { + poly2_dash.add_dash(params[lCount - 1] * dKoef, 0); + } + poly2_dash.dash_start(offset * dKoef); + + break; + } } - if ((0 == dWidth && !m_bIntegerGrid) || dWidth < dWidthMinSize) - dWidth = dWidthMinSize; + if ((0 == dWidth && !m_bIntegerGrid) || dWidth < dWidthMinSize) + dWidth = dWidthMinSize; pgD.line_cap(LineCap); pgD.line_join(LineJoin); @@ -753,18 +760,18 @@ namespace Aggplus m_rasterizer.get_rasterizer().add_path(trans); } - CColor oColor((BYTE)(pPen->Alpha * m_dGlobalAlpha), pPen->Color, m_bSwapRGB); + CColor oColor((BYTE)(pPen->Alpha * m_dGlobalAlpha), pPen->Color, m_bSwapRGB); CBrushSolid oBrush(oColor); m_rasterizer.get_rasterizer().filling_rule(agg::fill_non_zero); - if (gamma >= 0) - m_rasterizer.get_rasterizer().gamma(agg::gamma_threshold(gamma)); + if (gamma >= 0) + m_rasterizer.get_rasterizer().gamma(agg::gamma_threshold(gamma)); DoFillPath(&oBrush); - if (gamma >= 0) - m_rasterizer.gamma(1.0); + if (gamma >= 0) + m_rasterizer.gamma(1.0); if (bIsUseIdentity) RELEASEOBJECT(pAffine); @@ -784,11 +791,11 @@ namespace Aggplus agg::line_join_e LineJoin; switch(pPen->LineJoin) { - case LineJoinMiter : LineJoin = agg::miter_join; break; - case LineJoinBevel : LineJoin = agg::bevel_join; break; - default: - case LineJoinRound : LineJoin = agg::round_join; break; - case LineJoinMiterClipped: LineJoin = agg::miter_join_revert; break; + case LineJoinMiter : LineJoin = agg::miter_join; break; + case LineJoinBevel : LineJoin = agg::bevel_join; break; + default: + case LineJoinRound : LineJoin = agg::round_join; break; + case LineJoinMiterClipped: LineJoin = agg::miter_join_revert; break; } double dWidth = pPen->Size; @@ -797,12 +804,12 @@ namespace Aggplus agg::path_storage path_copy(pPath->m_internal->m_agg_ps); typedef agg::conv_curve conv_crv_type; - + conv_crv_type c_c_path(path_copy); c_c_path.approximation_scale(25.0); c_c_path.approximation_method(agg::curve_inc); DashStyle eStyle = (DashStyle)pPen->DashStyle; - + if (DashStyleSolid == eStyle || DashStyleCustom == eStyle) { typedef agg::conv_stroke Path_Conv_StrokeN; @@ -857,7 +864,7 @@ namespace Aggplus m_rasterizer.get_rasterizer().add_path(trans); } - CColor oColor((BYTE)pPen->Alpha, pPen->Color, m_bSwapRGB); + CColor oColor((BYTE)pPen->Alpha, pPen->Color, m_bSwapRGB); CBrushSolid oBrush(oColor); m_rasterizer.get_rasterizer().filling_rule(agg::fill_non_zero); @@ -901,9 +908,9 @@ namespace Aggplus trans_type* ptrans = NULL; agg::trans_affine* paffine = NULL; - if (!m_bIntegerGrid) + if (!m_bIntegerGrid) ptrans = new trans_type(p2, m_oFullTransform.m_internal->m_agg_mtx); - else + else { paffine = new agg::trans_affine(); ptrans = new trans_type(p2, *paffine); @@ -911,7 +918,7 @@ namespace Aggplus typedef agg::conv_curve conv_crv_type; conv_crv_type c_c_path(*ptrans); - + m_rasterizer.get_rasterizer().add_path(c_c_path); m_rasterizer.get_rasterizer().filling_rule(pPath->m_internal->m_bEvenOdd ? agg::fill_even_odd : agg::fill_non_zero); @@ -931,20 +938,20 @@ namespace Aggplus double r = 0; double b = 0; - if (!ptxBrush->m_bUseBounds) - { - pPath->GetBounds(x, y, r, b); + if (!ptxBrush->m_bUseBounds) + { + pPath->GetBounds(x, y, r, b); - r += x; - b += y; - } - else - { - x = ptxBrush->m_oBounds.left; - y = ptxBrush->m_oBounds.top; - r = ptxBrush->m_oBounds.right; - b = ptxBrush->m_oBounds.bottom; - } + r += x; + b += y; + } + else + { + x = ptxBrush->m_oBounds.left; + y = ptxBrush->m_oBounds.top; + r = ptxBrush->m_oBounds.right; + b = ptxBrush->m_oBounds.bottom; + } CMatrix brushMatrix; if (ptxBrush->GetWrapMode() == Aggplus::WrapModeClamp) @@ -955,13 +962,13 @@ namespace Aggplus brushMatrix.Scale(dScaleX, dScaleY, Aggplus::MatrixOrderAppend); } - if (ptxBrush->GetWrapMode() != Aggplus::WrapModeClamp && m_dDpiTile > 1) - { - double dScaleX = m_dDpiX / m_dDpiTile; - double dScaleY = m_dDpiY / m_dDpiTile; + if (ptxBrush->GetWrapMode() != Aggplus::WrapModeClamp && m_dDpiTile > 1) + { + double dScaleX = m_dDpiX / m_dDpiTile; + double dScaleY = m_dDpiY / m_dDpiTile; - brushMatrix.Scale(dScaleX, dScaleY, Aggplus::MatrixOrderAppend); - } + brushMatrix.Scale(dScaleX, dScaleY, Aggplus::MatrixOrderAppend); + } brushMatrix.Translate(x, y, Aggplus::MatrixOrderAppend); brushMatrix.Multiply(&m_oFullTransform, MatrixOrderAppend); @@ -979,10 +986,10 @@ namespace Aggplus // отрисовка картинки Status CGraphics::DrawImage(CImage* pImage, double x, double y, double width, double height) { - if (!pImage || pImage->GetLastStatus() != Ok) + if (!pImage || pImage->GetLastStatus() != Ok) return UnknownImageFormat; - if(width == 0.00 || height == 0.00) + if(width == 0.00 || height == 0.00) return InvalidParameter; CGraphicsPath oPath; @@ -1004,15 +1011,15 @@ namespace Aggplus #ifdef _WINDOW_GDIPLUS_USE_ Status CGraphics::DrawGdiplusImage(Gdiplus::Bitmap* pImage, double x, double y, double width, double height) { - if (!pImage || pImage->GetLastStatus() != Gdiplus::Ok) + if (!pImage || pImage->GetLastStatus() != Gdiplus::Ok) return UnknownImageFormat; - if(width == 0.00 || height == 0.00) + if(width == 0.00 || height == 0.00) return InvalidParameter; m_pGraphics->SetPageUnit(Gdiplus::UnitPixel); - double x1 = x; + double x1 = x; double y1 = y; m_oFullTransform.TransformPoint(x1, y1); @@ -1043,7 +1050,7 @@ namespace Aggplus } INT CGraphics::DrawString(const std::wstring& strText, CFontManager* pFont, CBrush* pBrush, double x, double y) - { + { if (pBrush->GetType() != BrushTypeSolidColor) return TRUE; @@ -1062,7 +1069,7 @@ namespace Aggplus oM1.TransformPoint(_x, _y); pFont->SetTextMatrix((float)mass[0], (float)mass[1], (float)mass[2], (float)mass[3], (float)mass[4], (float)mass[5]); - m_nTextRenderMode = pFont->m_nRENDER_MODE; + m_nTextRenderMode = pFont->m_nRENDER_MODE; pFont->LoadString2(strText, (float)_x, (float)_y); float fX = 0; @@ -1071,7 +1078,7 @@ namespace Aggplus while (TRUE) { - TGlyph* pGlyph = NULL; + TGlyph* pGlyph = NULL; bRes = pFont->GetNextChar2(pGlyph, fX, fY); @@ -1086,53 +1093,53 @@ namespace Aggplus return TRUE; } - INT CGraphics::DrawString(const unsigned int* pGids, const unsigned int nGidsCount, CFontManager* pFont, CBrush* pBrush, double x, double y) - { - if (pBrush->GetType() != BrushTypeSolidColor) - return TRUE; + INT CGraphics::DrawString(const unsigned int* pGids, const unsigned int nGidsCount, CFontManager* pFont, CBrush* pBrush, double x, double y) + { + if (pBrush->GetType() != BrushTypeSolidColor) + return TRUE; - CMatrix oMatrix = m_oBaseTransform; - oMatrix.Multiply(&m_oTransform, MatrixOrderPrepend); + CMatrix oMatrix = m_oBaseTransform; + oMatrix.Multiply(&m_oTransform, MatrixOrderPrepend); - double mass[6]; - oMatrix.GetElements(mass); + double mass[6]; + oMatrix.GetElements(mass); - double _x = x; - double _y = y; + double _x = x; + double _y = y; - CMatrix oM1 = oMatrix; - oM1.Invert(); - oM1.Multiply(&m_oFullTransform, MatrixOrderPrepend); - oM1.TransformPoint(_x, _y); + CMatrix oM1 = oMatrix; + oM1.Invert(); + oM1.Multiply(&m_oFullTransform, MatrixOrderPrepend); + oM1.TransformPoint(_x, _y); - pFont->SetTextMatrix((float)mass[0], (float)mass[1], (float)mass[2], (float)mass[3], (float)mass[4], (float)mass[5]); - m_nTextRenderMode = pFont->m_nRENDER_MODE; + pFont->SetTextMatrix((float)mass[0], (float)mass[1], (float)mass[2], (float)mass[3], (float)mass[4], (float)mass[5]); + m_nTextRenderMode = pFont->m_nRENDER_MODE; - pFont->LoadString2(pGids, nGidsCount, (float)_x, (float)_y); - float fX = 0; - float fY = 0; - INT bRes = FALSE; + pFont->LoadString2(pGids, nGidsCount, (float)_x, (float)_y); + float fX = 0; + float fY = 0; + INT bRes = FALSE; - while (TRUE) - { - TGlyph* pGlyph = NULL; + while (TRUE) + { + TGlyph* pGlyph = NULL; - bRes = pFont->GetNextChar2(pGlyph, fX, fY); + bRes = pFont->GetNextChar2(pGlyph, fX, fY); - if (FALSE == bRes) - break; + if (FALSE == bRes) + break; - if (NULL != pGlyph) - { - FillGlyph2((int)fX, (int)fY, pGlyph, pBrush); - } - } + if (NULL != pGlyph) + { + FillGlyph2((int)fX, (int)fY, pGlyph, pBrush); + } + } - return TRUE; - } + return TRUE; + } INT CGraphics::DrawStringC(const LONG& lText, CFontManager* pFont, CBrush* pBrush, double x, double y) - { + { if (pBrush->GetType() != BrushTypeSolidColor) return TRUE; @@ -1160,7 +1167,7 @@ namespace Aggplus while (TRUE) { - TGlyph* pGlyph = NULL; + TGlyph* pGlyph = NULL; bRes = pFont->GetNextChar2(pGlyph, fX, fY); @@ -1176,7 +1183,7 @@ namespace Aggplus return TRUE; } INT CGraphics::DrawStringPath(const std::wstring& strText, CFontManager* pFont, CBrush* pBrush, double x, double y) - { + { if (pBrush->GetType() != BrushTypeSolidColor) return TRUE; @@ -1188,7 +1195,7 @@ namespace Aggplus return TRUE; } INT CGraphics::DrawStringPathC(const LONG& lText, CFontManager* pFont, CBrush* pBrush, double x, double y) - { + { if (pBrush->GetType() != BrushTypeSolidColor) return TRUE; @@ -1213,7 +1220,7 @@ namespace Aggplus template void CGraphics::render_scanlines(Renderer& ren) - { + { if (!m_oClip.IsClip()) { return agg::render_scanlines(m_rasterizer.get_rasterizer(), m_rasterizer.get_scanline(), ren); @@ -1228,8 +1235,8 @@ namespace Aggplus sbool_scanline_type sl1; sbool_scanline_type sl2; - agg::sbool_combine_shapes_aa(agg::sbool_and, m_rasterizer.get_rasterizer(), m_oClip.m_rasterizer, - sl1, sl2, sl_result, ren); + agg::sbool_combine_shapes_aa(agg::sbool_and, m_rasterizer.get_rasterizer(), m_oClip.m_rasterizer, + sl1, sl2, sl_result, ren); } else { @@ -1242,30 +1249,30 @@ namespace Aggplus sbool_scanline_type sl; agg::sbool_combine_shapes_aa(agg::sbool_and, m_rasterizer.get_rasterizer(), - (1 == m_oClip.m_lCurStorage) ? m_oClip.m_storage1 : m_oClip.m_storage2, sl1, sl2, sl_result, ren); + (1 == m_oClip.m_lCurStorage) ? m_oClip.m_storage1 : m_oClip.m_storage2, sl1, sl2, sl_result, ren); } - } - } + } + } - template - void CGraphics::render_scanlines_alpha(Renderer& ren, BYTE Alpha) - { - double dAlpha = m_dGlobalAlpha * Alpha / 255.0; - if (fabs(dAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ren); - } - else - { - m_rasterizer.gamma_multi(dAlpha); - render_scanlines(ren); - m_rasterizer.gamma(1.0); - } - } + template + void CGraphics::render_scanlines_alpha(Renderer& ren, BYTE Alpha) + { + double dAlpha = m_dGlobalAlpha * Alpha / 255.0; + if (fabs(dAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ren); + } + else + { + m_rasterizer.gamma_multi(dAlpha); + render_scanlines(ren); + m_rasterizer.gamma(1.0); + } + } template void CGraphics::render_scanlines(Rasterizer& ras, Renderer& ren) - { + { if (!m_oClip.IsClip()) { return agg::render_scanlines(ras, m_rasterizer.get_scanline(), ren); @@ -1280,8 +1287,8 @@ namespace Aggplus sbool_scanline_type sl1; sbool_scanline_type sl2; - agg::sbool_combine_shapes_aa(agg::sbool_and, ras, m_oClip.m_rasterizer, - sl1, sl2, sl_result, ren); + agg::sbool_combine_shapes_aa(agg::sbool_and, ras, m_oClip.m_rasterizer, + sl1, sl2, sl_result, ren); } else { @@ -1294,10 +1301,10 @@ namespace Aggplus sbool_scanline_type sl; agg::sbool_combine_shapes_aa(agg::sbool_and, ras, - (1 == m_oClip.m_lCurStorage) ? m_oClip.m_storage1 : m_oClip.m_storage2, sl1, sl2, sl_result, ren); + (1 == m_oClip.m_lCurStorage) ? m_oClip.m_storage1 : m_oClip.m_storage2, sl1, sl2, sl_result, ren); } - } - } + } + } void CGraphics::DoFillPathSolid(CColor dwColor) { @@ -1347,13 +1354,16 @@ namespace Aggplus { int x = m_rasterizer.get_rasterizer().min_x(); int y = m_rasterizer.get_rasterizer().min_y(); - int width = m_rasterizer.get_rasterizer().max_x() - m_rasterizer.get_rasterizer().min_x(); - int height = m_rasterizer.get_rasterizer().max_y() - m_rasterizer.get_rasterizer().min_y(); + int r = m_rasterizer.get_rasterizer().max_x(); + int b = m_rasterizer.get_rasterizer().max_y(); + + if (r < x || b < y) + return; rect.x1 = x; - rect.x2 = x + width; + rect.x2 = r; rect.y1 = y; - rect.y2 = y + height; + rect.y2 = b; } typedef agg::my_span_gradient gradient_span_gen; @@ -1389,16 +1399,16 @@ namespace Aggplus typedef agg::renderer_scanline_aa renderer_gradient_type; renderer_gradient_type ren_gradient( m_frame_buffer.ren_base(), span_alloc, span_gen ); - if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ren_gradient); - } - else - { - m_rasterizer.gamma_multi(m_dGlobalAlpha); - render_scanlines(ren_gradient); - m_rasterizer.gamma(1.0); - } + if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ren_gradient); + } + else + { + m_rasterizer.gamma_multi(m_dGlobalAlpha); + render_scanlines(ren_gradient); + m_rasterizer.gamma(1.0); + } if( pSubColors ) delete [] pSubColors; if( pSubBlends ) delete [] pSubBlends; @@ -1425,13 +1435,16 @@ namespace Aggplus { int x = m_rasterizer.get_rasterizer().min_x(); int y = m_rasterizer.get_rasterizer().min_y(); - int width = m_rasterizer.get_rasterizer().max_x() - m_rasterizer.get_rasterizer().min_x(); - int height = m_rasterizer.get_rasterizer().max_y() - m_rasterizer.get_rasterizer().min_y(); + int r = m_rasterizer.get_rasterizer().max_x(); + int b = m_rasterizer.get_rasterizer().max_y(); + + if (r < x || b < y) + return; rect.x1 = x; - rect.x2 = x + width; + rect.x2 = r; rect.y1 = y; - rect.y2 = y + height; + rect.y2 = b; } typedef agg::my_span_path_gradient gradient_span_gen; @@ -1467,16 +1480,16 @@ namespace Aggplus typedef agg::renderer_scanline_aa renderer_gradient_type; renderer_gradient_type ren_gradient( m_frame_buffer.ren_base(), span_alloc, span_gen ); - if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ren_gradient); - } - else - { - m_rasterizer.gamma_multi(m_dGlobalAlpha); - render_scanlines(ren_gradient); - m_rasterizer.gamma(1.0); - } + if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ren_gradient); + } + else + { + m_rasterizer.gamma_multi(m_dGlobalAlpha); + render_scanlines(ren_gradient); + m_rasterizer.gamma(1.0); + } if( pSubColors ) delete [] pSubColors; if( pSubBlends ) delete [] pSubBlends; @@ -1497,7 +1510,7 @@ namespace Aggplus rect.x2 = oBounds.right; rect.y2 = oBounds.bottom; - oMatrix = m_oFullTransform; + oMatrix = m_oFullTransform; } else { @@ -1518,7 +1531,7 @@ namespace Aggplus agg::rgba8 c1 = agg::rgba8(pBrush->m_dwColor1.GetB(), pBrush->m_dwColor1.GetG(), pBrush->m_dwColor1.GetR(), pBrush->m_dwColor1.GetA()); agg::rgba8 c2 = agg::rgba8(pBrush->m_dwColor2.GetB(), pBrush->m_dwColor2.GetG(), pBrush->m_dwColor2.GetR(), pBrush->m_dwColor2.GetA()); - span_gen.SetDirection(pBrush->m_name, rect, oMatrix.m_agg_mtx, c1, c2); + span_gen.SetDirection(pBrush->m_name, rect, oMatrix.m_agg_mtx, c1, c2); typedef agg::span_allocator hatch_span_alloc; hatch_span_alloc span_alloc; @@ -1526,19 +1539,19 @@ namespace Aggplus typedef agg::renderer_scanline_aa renderer_hatch_type; renderer_hatch_type ren_hatch( m_frame_buffer.ren_base(), span_alloc, span_gen ); - if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ren_hatch); - } - else - { - m_rasterizer.gamma_multi(m_dGlobalAlpha); - render_scanlines(ren_hatch); - m_rasterizer.gamma(1.0); - } + if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ren_hatch); + } + else + { + m_rasterizer.gamma_multi(m_dGlobalAlpha); + render_scanlines(ren_hatch); + m_rasterizer.gamma(1.0); + } #else - agg::rgba8 c1 = agg::rgba8(pBrush->m_dwColor1.GetR(), pBrush->m_dwColor1.GetG(), pBrush->m_dwColor1.GetB(), pBrush->m_dwColor1.GetA()); - agg::rgba8 c2 = agg::rgba8(pBrush->m_dwColor2.GetR(), pBrush->m_dwColor2.GetG(), pBrush->m_dwColor2.GetB(), pBrush->m_dwColor2.GetA()); + agg::rgba8 c1 = agg::rgba8(pBrush->m_dwColor1.GetR(), pBrush->m_dwColor1.GetG(), pBrush->m_dwColor1.GetB(), pBrush->m_dwColor1.GetA()); + agg::rgba8 c2 = agg::rgba8(pBrush->m_dwColor2.GetR(), pBrush->m_dwColor2.GetG(), pBrush->m_dwColor2.GetB(), pBrush->m_dwColor2.GetA()); BYTE* pPattern = new BYTE[HATCH_TX_SIZE * HATCH_TX_SIZE * 4]; agg::GetHatchPattern(pBrush->m_name, (agg::rgba8*)pPattern, c1, c2); @@ -1549,9 +1562,9 @@ namespace Aggplus mtx_Work.invert(); - span_alloc_type span_allocator; + span_alloc_type span_allocator; interpolator_type_linear interpolator(mtx_Work); - + agg::rendering_buffer PatRendBuff; PatRendBuff.attach(pPattern, HATCH_TX_SIZE, HATCH_TX_SIZE, HATCH_TX_SIZE << 2); @@ -1568,16 +1581,16 @@ namespace Aggplus span_gen_type sg(img_src, interpolator); renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ri); - } - else - { - m_rasterizer.gamma_multi(m_dGlobalAlpha); - render_scanlines(ri); - m_rasterizer.gamma(1.0); - } + if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ri); + } + else + { + m_rasterizer.gamma_multi(m_dGlobalAlpha); + render_scanlines(ri); + m_rasterizer.gamma(1.0); + } RELEASEARRAYOBJECTS(pPattern); #endif @@ -1599,7 +1612,7 @@ namespace Aggplus //agg::rendering_buffer PatRendBuff((BYTE *)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); agg::rendering_buffer PatRendBuff; - PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); + PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); pixfmt img_pixf(PatRendBuff); img_source_type img_src(img_pixf, agg::rgba(0, 0, 0, 0)); @@ -1612,368 +1625,378 @@ namespace Aggplus void CGraphics::DoFillPathTextureClampSz2(const CMatrix &mImgMtx, const void *pImgBuff, DWORD dwImgWidth, DWORD dwImgHeight, int nImgStride, BYTE Alpha) { - span_alloc_type span_allocator; - agg::trans_affine mtx_Work(mImgMtx.m_internal->m_agg_mtx); - mtx_Work.invert(); - interpolator_type_linear interpolator(mtx_Work); + span_alloc_type span_allocator; + agg::trans_affine mtx_Work(mImgMtx.m_internal->m_agg_mtx); + mtx_Work.invert(); + interpolator_type_linear interpolator(mtx_Work); - agg::rendering_buffer PatRendBuff; - PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); + agg::rendering_buffer PatRendBuff; + PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); - int nCurrentMode = 255; - if (!m_bSwapRGB) - { - typedef agg::pixfmt_bgra32 pixfmt; - typedef agg::image_accessor_clone img_source_type; + int nCurrentMode = 255; + if (!m_bSwapRGB) + { + typedef agg::pixfmt_bgra32 pixfmt; + typedef agg::image_accessor_clone img_source_type; - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); - switch (nCurrentMode) - { - case 0: - { - typedef agg::span_image_filter_rgba_nn span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 1: - { - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 2: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_bicubic(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 3: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_spline16(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 4: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_blackman256(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 255: - { - typedef agg::span_image_resample_rgba_affine_for_draw span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_bilinear(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - default: - break; - } - } - else - { - typedef agg::pixfmt_rgba32 pixfmt; - typedef agg::image_accessor_clone img_source_type; + switch (nCurrentMode) + { + case 0: + { + typedef agg::span_image_filter_rgba_nn span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 1: + { + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 2: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_bicubic(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 3: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_spline16(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 4: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_blackman256(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 255: + { + typedef agg::span_image_resample_rgba_affine_for_draw span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_bilinear(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + default: + break; + } + } + else + { + typedef agg::pixfmt_rgba32 pixfmt; + typedef agg::image_accessor_clone img_source_type; - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); - switch (nCurrentMode) - { - case 0: - { - typedef agg::span_image_filter_rgba_nn span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 1: - { - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 2: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_bicubic(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 3: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_spline16(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 4: - { - typedef agg::span_image_filter_rgba_2x2 span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_blackman256(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - case 255: - { - typedef agg::span_image_resample_rgba_affine_for_draw span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - agg::image_filter_lut filter; - filter.calculate(agg::image_filter_bilinear(), false); - span_gen_type sg(img_src, interpolator, filter); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - render_scanlines_alpha(ri, Alpha); - break; - } - default: - break; - } - } + switch (nCurrentMode) + { + case 0: + { + typedef agg::span_image_filter_rgba_nn span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 1: + { + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 2: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_bicubic(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 3: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_spline16(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 4: + { + typedef agg::span_image_filter_rgba_2x2 span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_blackman256(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + case 255: + { + typedef agg::span_image_resample_rgba_affine_for_draw span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + agg::image_filter_lut filter; + filter.calculate(agg::image_filter_bilinear(), false); + span_gen_type sg(img_src, interpolator, filter); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + render_scanlines_alpha(ri, Alpha); + break; + } + default: + break; + } + } + } + + template + void CGraphics::DoFillPathTextureClampSz3(const CMatrix &matrix, const void *pImgBuff, DWORD dwImgWidth, DWORD dwImgHeight, int nImgStride, Aggplus::WrapMode wrapmode, BYTE Alpha) + { + agg::trans_affine mtx_Work( matrix.m_internal->m_agg_mtx ); + + agg::trans_affine coords = m_oCoordTransform.m_internal->m_agg_mtx; + coords.invert(); + mtx_Work.premultiply(coords); + + //mtx_Work.multiply(m_oFullTransform.m_agg_mtx); + mtx_Work.invert(); + + span_alloc_type span_allocator; // Span Allocator + interpolator_type_linear interpolator(mtx_Work); + + //agg::rendering_buffer PatRendBuff((BYTE *)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); + agg::rendering_buffer PatRendBuff; + PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); + + typedef ColorSpacePix pixfmt; + if(wrapmode == WrapModeTileFlipX) + { + //image_accessor_wrap + typedef agg::wrap_mode_reflect wrap_x_type; + typedef agg::wrap_mode_repeat wrap_y_type; + typedef agg::image_accessor_wrap img_source_type; + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + + double dAlpha = m_dGlobalAlpha * Alpha / 255.0; + if (fabs(dAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ri); + } + else + { + m_rasterizer.gamma_multi(dAlpha); + render_scanlines(ri); + m_rasterizer.gamma(1.0); + } + } + else if(wrapmode == WrapModeTileFlipY) + { + //image_accessor_wrap + typedef agg::wrap_mode_repeat wrap_x_type; + typedef agg::wrap_mode_reflect wrap_y_type; + typedef agg::image_accessor_wrap img_source_type; + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + + double dAlpha = m_dGlobalAlpha * Alpha / 255.0; + if (fabs(dAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ri); + } + else + { + m_rasterizer.gamma_multi(dAlpha); + render_scanlines(ri); + m_rasterizer.gamma(1.0); + } + } + else if(wrapmode == WrapModeTileFlipXY) + { + //image_accessor_wrap + typedef agg::wrap_mode_reflect wrap_x_type; + typedef agg::wrap_mode_reflect wrap_y_type; + typedef agg::image_accessor_wrap img_source_type; + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + + double dAlpha = m_dGlobalAlpha * Alpha / 255.0; + if (fabs(dAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ri); + } + else + { + m_rasterizer.gamma_multi(dAlpha); + render_scanlines(ri); + m_rasterizer.gamma(1.0); + } + } + else //Repeat + { + //image_accessor_wrap + typedef agg::wrap_mode_repeat wrap_x_type; + typedef agg::wrap_mode_repeat wrap_y_type; + typedef agg::image_accessor_wrap img_source_type; + typedef agg::span_image_filter_rgba_bilinear span_gen_type; + typedef agg::renderer_scanline_aa renderer_type; + + pixfmt img_pixf(PatRendBuff); + img_source_type img_src(img_pixf); + span_gen_type sg(img_src, interpolator); + renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); + + double dAlpha = m_dGlobalAlpha * Alpha / 255.0; + if (fabs(dAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ri); + } + else + { + m_rasterizer.gamma_multi(dAlpha); + render_scanlines(ri); + m_rasterizer.gamma(1.0); + } + } } - - template - void CGraphics::DoFillPathTextureClampSz3(const CMatrix &matrix, const void *pImgBuff, DWORD dwImgWidth, DWORD dwImgHeight, int nImgStride, Aggplus::WrapMode wrapmode, BYTE Alpha) - { - agg::trans_affine mtx_Work( matrix.m_internal->m_agg_mtx ); - - agg::trans_affine coords = m_oCoordTransform.m_internal->m_agg_mtx; - coords.invert(); - mtx_Work.premultiply(coords); - - //mtx_Work.multiply(m_oFullTransform.m_agg_mtx); - mtx_Work.invert(); - - span_alloc_type span_allocator; // Span Allocator - interpolator_type_linear interpolator(mtx_Work); - - //agg::rendering_buffer PatRendBuff((BYTE *)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); - agg::rendering_buffer PatRendBuff; - PatRendBuff.attach((BYTE*)pImgBuff, dwImgWidth, dwImgHeight, nImgStride); - - typedef ColorSpacePix pixfmt; - if(wrapmode == WrapModeTileFlipX) - { - //image_accessor_wrap - typedef agg::wrap_mode_reflect wrap_x_type; - typedef agg::wrap_mode_repeat wrap_y_type; - typedef agg::image_accessor_wrap img_source_type; - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - - double dAlpha = m_dGlobalAlpha * Alpha / 255.0; - if (fabs(dAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ri); - } - else - { - m_rasterizer.gamma_multi(dAlpha); - render_scanlines(ri); - m_rasterizer.gamma(1.0); - } - } - else if(wrapmode == WrapModeTileFlipY) - { - //image_accessor_wrap - typedef agg::wrap_mode_repeat wrap_x_type; - typedef agg::wrap_mode_reflect wrap_y_type; - typedef agg::image_accessor_wrap img_source_type; - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - - double dAlpha = m_dGlobalAlpha * Alpha / 255.0; - if (fabs(dAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ri); - } - else - { - m_rasterizer.gamma_multi(dAlpha); - render_scanlines(ri); - m_rasterizer.gamma(1.0); - } - } - else if(wrapmode == WrapModeTileFlipXY) - { - //image_accessor_wrap - typedef agg::wrap_mode_reflect wrap_x_type; - typedef agg::wrap_mode_reflect wrap_y_type; - typedef agg::image_accessor_wrap img_source_type; - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - - double dAlpha = m_dGlobalAlpha * Alpha / 255.0; - if (fabs(dAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ri); - } - else - { - m_rasterizer.gamma_multi(dAlpha); - render_scanlines(ri); - m_rasterizer.gamma(1.0); - } - } - else //Repeat - { - //image_accessor_wrap - typedef agg::wrap_mode_repeat wrap_x_type; - typedef agg::wrap_mode_repeat wrap_y_type; - typedef agg::image_accessor_wrap img_source_type; - typedef agg::span_image_filter_rgba_bilinear span_gen_type; - typedef agg::renderer_scanline_aa renderer_type; - - pixfmt img_pixf(PatRendBuff); - img_source_type img_src(img_pixf); - span_gen_type sg(img_src, interpolator); - renderer_type ri(m_frame_buffer.ren_base(), span_allocator, sg); - - double dAlpha = m_dGlobalAlpha * Alpha / 255.0; - if (fabs(dAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ri); - } - else - { - m_rasterizer.gamma_multi(dAlpha); - render_scanlines(ri); - m_rasterizer.gamma(1.0); - } - } - } void CGraphics::DoFillPath(const CBrush* Brush) { - if (NULL == Brush) + if (NULL == Brush) return; - if (Brush->GetType() == BrushTypeSolidColor) + Aggplus::BrushType eBrushType = Brush->GetType(); + switch (eBrushType) { - CColor clr; + case BrushTypeSolidColor: + { + CColor clr; ((CBrushSolid*)Brush)->GetColor(&clr); DoFillPathSolid(clr); + break; } - else if (Brush->GetType() == BrushTypeHatchFill) + case BrushTypeHatchFill: { DoFillPathHatch((Aggplus::CBrushHatch*)Brush); + break; } - else if (Brush->GetType() == BrushTypeTextureFill) + case BrushTypeTextureFill: { CBrushTexture *ptxBrush = (CBrushTexture *)Brush; - + LPVOID pImgBuff = ptxBrush->GetData(); if (pImgBuff) { DWORD dwImgWidth = ptxBrush->PatternGetWidth(); DWORD dwImgHeight = ptxBrush->PatternGetHeight(); int nImgStride = ptxBrush->PatternGetStride(); - + if(pImgBuff && dwImgWidth && dwImgHeight) { Aggplus::WrapMode wrapmode = ptxBrush->m_wrapMode; Aggplus::CMatrix matrix = ptxBrush->m_mtx; - + if(wrapmode == WrapModeClamp) { DoFillPathTextureClampSz2( matrix, pImgBuff, dwImgWidth, dwImgHeight, nImgStride, ptxBrush->Alpha); } else { - if (!m_bSwapRGB) - { - DoFillPathTextureClampSz3(matrix, pImgBuff, dwImgWidth, dwImgHeight, nImgStride, wrapmode, ptxBrush->Alpha); - } - else - { - DoFillPathTextureClampSz3(matrix, pImgBuff, dwImgWidth, dwImgHeight, nImgStride, wrapmode, ptxBrush->Alpha); - } + if (!m_bSwapRGB) + { + DoFillPathTextureClampSz3(matrix, pImgBuff, dwImgWidth, dwImgHeight, nImgStride, wrapmode, ptxBrush->Alpha); + } + else + { + DoFillPathTextureClampSz3(matrix, pImgBuff, dwImgWidth, dwImgHeight, nImgStride, wrapmode, ptxBrush->Alpha); + } } } } + break; } - else if (Brush->GetType() == BrushTypeLinearGradient) + case BrushTypeLinearGradient: { DoFillPathGradient((CBrushLinearGradient*)Brush); + break; } - else if (Brush->GetType() == BrushTypePathGradient) + case BrushTypePathGradient: { DoFillPathGradient2((CBrushLinearGradient*)Brush); + break; } - auto Type = Brush->GetType(); - if (( BrushTypeMyTestGradient == Type) || - (BrushTypeNewLinearGradient == Type) || - (BrushTypeConicalGradient == Type) || - (BrushTypeRadialGradient == Type) || - (BrushTypeDiamondGradient == Type) || - (BrushTypeTriagnleMeshGradient == Type) || - (BrushTypeCurveGradient == Type) || - (BrushTypeTensorCurveGradient == Type) ) + case BrushTypeMyTestGradient: + case BrushTypeNewLinearGradient: + case BrushTypeConicalGradient: + case BrushTypeRadialGradient: + case BrushTypeDiamondGradient: + case BrushTypeTriagnleMeshGradient: + case BrushTypeCurveGradient: + case BrushTypeTensorCurveGradient: { DoFillPathGradientType((CBrushLinearGradient*)Brush); + break; + } + default: + break; } - } // text methods - int CGraphics::FillGlyph2(int nX, int nY, TGlyph* pGlyph, Aggplus::CBrush* pBrush) + int CGraphics::FillGlyph2(int nX, int nY, TGlyph* pGlyph, Aggplus::CBrush* pBrush) { int lWidth = pGlyph->oBitmap.nWidth; int lHeight = pGlyph->oBitmap.nHeight; @@ -1990,7 +2013,7 @@ namespace Aggplus return 0; if (!m_oClip.IsClip() && (0 <= nX) && (0 <= nY) && ((nX + lWidth) < nFrameW) && ((nY + lHeight) < nFrameH)) - { + { return FillGlyphSimple(nX, nY, lWidth, lHeight, pData, pBrush); } @@ -2012,7 +2035,7 @@ namespace Aggplus if (pBrush->GetType() == Aggplus::BrushTypeSolidColor) { - CColor clr; + CColor clr; ((CBrushSolid*)pBrush)->GetColor(&clr); typedef agg::renderer_scanline_aa_solid solid_renderer_type; @@ -2025,23 +2048,23 @@ namespace Aggplus return 0; } - int CGraphics::FillGlyphSimple(int nX, int nY, LONG lWidth, LONG lHeight, BYTE* pData, Aggplus::CBrush* pBrush) + int CGraphics::FillGlyphSimple(int nX, int nY, LONG lWidth, LONG lHeight, BYTE* pData, Aggplus::CBrush* pBrush) { - CColor clr; + CColor clr; ((CBrushSolid*)pBrush)->GetColor(&clr); typedef agg::renderer_scanline_aa_solid solid_renderer_type; solid_renderer_type ren_fine(m_frame_buffer.ren_base()); ren_fine.color(clr.GetAggColor()); - if (m_nTextRenderMode == FT_RENDER_MODE_LCD) - { - ren_fine.render_subpix(lWidth / 3, lHeight, pData, nX, nY); - } - else - { - ren_fine.render(lWidth, lHeight, pData, nX, nY); - } + if (m_nTextRenderMode == FT_RENDER_MODE_LCD) + { + ren_fine.render_subpix(lWidth / 3, lHeight, pData, nX, nY); + } + else + { + ren_fine.render(lWidth, lHeight, pData, nX, nY); + } return 0; } @@ -2071,23 +2094,23 @@ namespace Aggplus switch (m_ePageUnits) { case UnitPoint: - { - dScaleX = m_dDpiX / c_ag_Inch_to_Point; - dScaleY = m_dDpiY / c_ag_Inch_to_Point; - break; - } + { + dScaleX = m_dDpiX / c_ag_Inch_to_Point; + dScaleY = m_dDpiY / c_ag_Inch_to_Point; + break; + } case UnitMillimeter: - { - dScaleX = m_dDpiX / c_ag_Inch_to_MM; - dScaleY = m_dDpiY / c_ag_Inch_to_MM; - break; - } + { + dScaleX = m_dDpiX / c_ag_Inch_to_MM; + dScaleY = m_dDpiY / c_ag_Inch_to_MM; + break; + } case UnitInch: - { - dScaleX = m_dDpiX; - dScaleY = m_dDpiY; - break; - } + { + dScaleX = m_dDpiX; + dScaleY = m_dDpiY; + break; + } default: break; }; @@ -2097,8 +2120,8 @@ namespace Aggplus } - // Testing - void CGraphics::DoFillPathGradientType(CBrushLinearGradient *pBrush) + // Testing + void CGraphics::DoFillPathGradientType(CBrushLinearGradient *pBrush) { CDoubleRect& oBounds = pBrush->GetBounds(); @@ -2119,13 +2142,16 @@ namespace Aggplus { int x = m_rasterizer.get_rasterizer().min_x(); int y = m_rasterizer.get_rasterizer().min_y(); - int width = m_rasterizer.get_rasterizer().max_x() - m_rasterizer.get_rasterizer().min_x(); - int height = m_rasterizer.get_rasterizer().max_y() - m_rasterizer.get_rasterizer().min_y(); + int r = m_rasterizer.get_rasterizer().max_x(); + int b = m_rasterizer.get_rasterizer().max_y(); + + if (r < x || b < y) + return; rect.x1 = x; - rect.x2 = x + width; + rect.x2 = r; rect.y1 = y; - rect.y2 = y + height; + rect.y2 = b; } ScaleGranientInfo(pBrush->GetType(), pBrush->m_oGradientInfo); @@ -2133,8 +2159,8 @@ namespace Aggplus typedef agg::gradient_base gradient_span_gen; gradient_span_gen span_gen; - span_gen.SetDirection(rect, oMatrix.m_internal->m_agg_mtx, m_bSwapRGB); - span_gen.SetGradientInfo(pBrush->m_oGradientInfo, pBrush->GetType()); + span_gen.SetDirection(rect, oMatrix.m_internal->m_agg_mtx, m_bSwapRGB); + span_gen.SetGradientInfo(pBrush->m_oGradientInfo, pBrush->GetType()); agg::rgba8* pSubColors = NULL; float* pSubBlends = NULL; @@ -2163,81 +2189,81 @@ namespace Aggplus typedef agg::renderer_scanline_aa renderer_gradient_type; renderer_gradient_type ren_gradient( m_frame_buffer.ren_base(), span_alloc, span_gen ); - if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) - { - render_scanlines(ren_gradient); - } - else - { - m_rasterizer.gamma_multi(m_dGlobalAlpha); - render_scanlines(ren_gradient); - m_rasterizer.gamma(1.0); - } + if (fabs(m_dGlobalAlpha - 1.0) < FLT_EPSILON) + { + render_scanlines(ren_gradient); + } + else + { + m_rasterizer.gamma_multi(m_dGlobalAlpha); + render_scanlines(ren_gradient); + m_rasterizer.gamma(1.0); + } if( pSubColors ) delete [] pSubColors; if( pSubBlends ) delete [] pSubBlends; } - void CGraphics::ScaleGranientInfo(long type, NSStructures::GradientInfo &ginfo) + void CGraphics::ScaleGranientInfo(long type, NSStructures::GradientInfo &ginfo) { if (type == BrushTypeMyTestGradient) { - std::vector new_map(6); - float M[6]; - std::vector G = ginfo.shading.mapping; - m_oFullTransform.GetElements(M); + std::vector new_map(6); + float M[6]; + std::vector G = ginfo.shading.mapping; + m_oFullTransform.GetElements(M); - new_map[0] = M[0] * G[0] + M[2] * G[1]; - new_map[1] = M[1] * G[0] + M[3] * G[1]; - new_map[2] = M[0] * G[2] + M[2] * G[3]; - new_map[3] = M[1] * G[2] + M[3] * G[3]; + new_map[0] = M[0] * G[0] + M[2] * G[1]; + new_map[1] = M[1] * G[0] + M[3] * G[1]; + new_map[2] = M[0] * G[2] + M[2] * G[3]; + new_map[3] = M[1] * G[2] + M[3] * G[3]; - new_map[4] = M[0] * G[4] + M[2] * G[5] + M[4]; - new_map[5] = M[1] * G[4] + M[3] * G[5] + M[5]; - ginfo.shading.mapping = new_map; + new_map[4] = M[0] * G[4] + M[2] * G[5] + M[4]; + new_map[5] = M[1] * G[4] + M[3] * G[5] + M[5]; + ginfo.shading.mapping = new_map; - float D = new_map[0] * new_map[3] - new_map[1] * new_map[2]; + float D = new_map[0] * new_map[3] - new_map[1] * new_map[2]; - ginfo.shading.inv_map[0] = new_map[3] / D; - ginfo.shading.inv_map[1] = -new_map[1] / D; - ginfo.shading.inv_map[2] = -new_map[2] / D; - ginfo.shading.inv_map[3] = new_map[0] / D; + ginfo.shading.inv_map[0] = new_map[3] / D; + ginfo.shading.inv_map[1] = -new_map[1] / D; + ginfo.shading.inv_map[2] = -new_map[2] / D; + ginfo.shading.inv_map[3] = new_map[0] / D; - ginfo.shading.inv_map[4] = -new_map[4]; - ginfo.shading.inv_map[5] = -new_map[5]; + ginfo.shading.inv_map[4] = -new_map[4]; + ginfo.shading.inv_map[5] = -new_map[5]; return; } if (type == BrushTypeNewLinearGradient) { - ScaleCoords(ginfo.shading.point1.x, ginfo.shading.point1.y); - ScaleCoords(ginfo.shading.point2.x, ginfo.shading.point2.y); + ScaleCoords(ginfo.shading.point1.x, ginfo.shading.point1.y); + ScaleCoords(ginfo.shading.point2.x, ginfo.shading.point2.y); return; } if (type == BrushTypeRadialGradient) { ginfo.r0 = ginfo.r0 * sqrt(fabs(m_oFullTransform.Determinant())); - ginfo.r1 = ginfo.r1 * sqrt(fabs(m_oFullTransform.Determinant())); - ScaleCoords(ginfo.p0.x, ginfo.p0.y); - ScaleCoords(ginfo.p1.x, ginfo.p1.y); + ginfo.r1 = ginfo.r1 * sqrt(fabs(m_oFullTransform.Determinant())); + ScaleCoords(ginfo.p0.x, ginfo.p0.y); + ScaleCoords(ginfo.p1.x, ginfo.p1.y); return; } if (type == BrushTypeTriagnleMeshGradient) { - for (int i = 0; i < 3; i++) - { - ScaleCoords(ginfo.shading.triangle[i].x, ginfo.shading.triangle[i].y); - } + for (int i = 0; i < 3; i++) + { + ScaleCoords(ginfo.shading.triangle[i].x, ginfo.shading.triangle[i].y); + } return; } if (type == BrushTypeCurveGradient || type == BrushTypeTensorCurveGradient) { - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 4; j++) - { - ScaleCoords(ginfo.shading.patch[i][j].x, ginfo.shading.patch[i][j].y); - } - } + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + { + ScaleCoords(ginfo.shading.patch[i][j].x, ginfo.shading.patch[i][j].y); + } + } return; } } diff --git a/DesktopEditor/graphics/Graphics.h b/DesktopEditor/graphics/Graphics.h index bccb67aef8..3f4ef88868 100644 --- a/DesktopEditor/graphics/Graphics.h +++ b/DesktopEditor/graphics/Graphics.h @@ -309,6 +309,8 @@ public: int m_nTextRenderMode; unsigned int m_nBlendMode; + bool m_bIs0PenWidthAs1px; + public: CGraphics(); diff --git a/DesktopEditor/graphics/GraphicsRenderer.cpp b/DesktopEditor/graphics/GraphicsRenderer.cpp index 7e10359002..f7889202c2 100644 --- a/DesktopEditor/graphics/GraphicsRenderer.cpp +++ b/DesktopEditor/graphics/GraphicsRenderer.cpp @@ -1158,6 +1158,9 @@ HRESULT CGraphicsRenderer::CommandLong(const LONG& lType, const LONG& lCommand) m_pRenderer->m_bIsDarkMode = (1 == lCommand); if (c_nUseDictionaryFonts == lType && m_pFontManager) m_pFontManager->SetUseCorrentFontByName((1 == lCommand) ? true : false); + if (c_nPenWidth0As1px == lType && m_pRenderer) + m_pRenderer->m_bIs0PenWidthAs1px = (1 == lCommand) ? true : false; + return S_OK; } HRESULT CGraphicsRenderer::CommandDouble(const LONG& lType, const double& dCommand) diff --git a/DesktopEditor/graphics/IRenderer.h b/DesktopEditor/graphics/IRenderer.h index c441bb54e9..068498f459 100644 --- a/DesktopEditor/graphics/IRenderer.h +++ b/DesktopEditor/graphics/IRenderer.h @@ -107,6 +107,7 @@ const long c_nParamFlipY = 0x0002; const long c_nFlipNextRotate = 0x0004; const long c_nDarkMode = 0x0008; const long c_nUseDictionaryFonts = 0x0010; +const long c_nPenWidth0As1px = 0x0020; // типы рендерера const long c_nUnknownRenderer = 0x0000; diff --git a/DesktopEditor/graphics/MetafileToRenderer.cpp b/DesktopEditor/graphics/MetafileToRenderer.cpp index 64532225bb..0d52907b37 100644 --- a/DesktopEditor/graphics/MetafileToRenderer.cpp +++ b/DesktopEditor/graphics/MetafileToRenderer.cpp @@ -1223,10 +1223,17 @@ namespace NSOnlineOfficeBinToPdf } case ctDocInfo: { - std::wstring wsTitle = ReadString(current, curindex); - std::wstring wsCreator = ReadString(current, curindex); - std::wstring wsSubject = ReadString(current, curindex); - std::wstring wsKeywords = ReadString(current, curindex); + int nFlags = ReadInt(current, curindex); + + std::wstring wsTitle, wsCreator, wsSubject, wsKeywords; + if (nFlags & 1) + wsTitle = ReadString(current, curindex); + if (nFlags & 2) + wsCreator = ReadString(current, curindex); + if (nFlags & 4) + wsSubject = ReadString(current, curindex); + if (nFlags & 8) + wsKeywords = ReadString(current, curindex); pRenderer->DocInfo(wsTitle, wsCreator, wsSubject, wsKeywords); break; @@ -1548,6 +1555,21 @@ namespace NSOnlineOfficeBinToPdf curindex = nStartIndex + nLen; break; } + case ctDocInfo: + { + int nFlags = ReadInt(current, curindex); + + std::wstring wsTitle, wsCreator, wsSubject, wsKeywords; + if (nFlags & 1) + SkipString(current, curindex); + if (nFlags & 2) + SkipString(current, curindex); + if (nFlags & 4) + SkipString(current, curindex); + if (nFlags & 8) + SkipString(current, curindex); + break; + } default: { break; diff --git a/DesktopEditor/graphics/pro/js/drawingfile.json b/DesktopEditor/graphics/pro/js/drawingfile.json index 05786c2286..41037b105e 100644 --- a/DesktopEditor/graphics/pro/js/drawingfile.json +++ b/DesktopEditor/graphics/pro/js/drawingfile.json @@ -43,7 +43,7 @@ "wasm/src/lib", "../../../agg-2.4/include", "../../../cximage/jasper/include", "../../../cximage/jpeg", "../../../cximage/png", "freetype-2.10.4/include", "freetype-2.10.4/include/freetype", "../../../../OfficeUtils/src/zlib-1.2.11", "../../../../OfficeUtils/src", "../../../../Common/3dParty/icu/icu/source/common", "../../../xml/libxml2/include", "../../../xml/build/qt", "../../../../OfficeUtils/src/zlib-1.2.11/contrib/minizip", "../../../../PdfFile/lib/goo", "../../../../PdfFile/lib/fofi", "../../../../PdfFile/lib/splash", "../../../../PdfFile/lib", "../../../raster/Jp2/openjpeg", "../../../raster/Jp2/openjpeg/openjpeg-2.4.0/src/lib/openjp2" ], "define": [ - "__linux__", "_LINUX", "UNIX", "FT2_BUILD_LIBRARY", "HAVE_FCNTL_H", "FT_CONFIG_OPTION_SYSTEM_ZLIB", "BUILDING_WASM_MODULE", "U_COMMON_IMPLEMENTATION", "errno=0", "THREADMODEL=0", "DEBUGLVL=0", "HAVE_MBSTATE_T", "HAVE_STDINCLUDES", "HAS_WCHAR", "HAVE_VA_COPY", "LIBXML_READER_ENABLED", "LIBXML_PUSH_ENABLED", "LIBXML_HTML_ENABLED", "LIBXML_XPATH_ENABLED", "LIBXML_OUTPUT_ENABLED", "LIBXML_C14N_ENABLED", "LIBXML_SAX1_ENABLED", "LIBXML_TREE_ENABLED", "LIBXML_XPTR_ENABLED", "IN_LIBXML", "LIBXML_STATIC", "BUILD_ZLIB_AS_SOURCES", "_ARM_ALIGN_", "_tcsnicmp=strncmp", "_lseek=lseek", "_getcwd=getcwd", "NO_CONSOLE_IO", "USE_EXTERNAL_JPEG2000", "USE_JPIP", "OPJ_STATIC" + "__linux__", "_LINUX", "UNIX", "FT2_BUILD_LIBRARY", "HAVE_FCNTL_H", "FT_CONFIG_OPTION_SYSTEM_ZLIB", "BUILDING_WASM_MODULE", "U_COMMON_IMPLEMENTATION", "errno=0", "THREADMODEL=0", "DEBUGLVL=0", "HAVE_MBSTATE_T", "HAVE_STDINCLUDES", "HAS_WCHAR", "HAVE_VA_COPY", "LIBXML_READER_ENABLED", "LIBXML_PUSH_ENABLED", "LIBXML_HTML_ENABLED", "LIBXML_XPATH_ENABLED", "LIBXML_OUTPUT_ENABLED", "LIBXML_C14N_ENABLED", "LIBXML_SAX1_ENABLED", "LIBXML_TREE_ENABLED", "LIBXML_XPTR_ENABLED", "IN_LIBXML", "LIBXML_STATIC", "BUILD_ZLIB_AS_SOURCES", "_ARM_ALIGN_", "_tcsnicmp=strncmp", "_lseek=lseek", "_getcwd=getcwd", "NO_CONSOLE_IO", "USE_EXTERNAL_JPEG2000", "USE_JPIP", "OPJ_STATIC", "FONT_ENGINE_DISABLE_FILESYSTEM" ], "compile_files_array": [ { diff --git a/DesktopEditor/graphics/pro/js/wasm/src/drawingfile.cpp b/DesktopEditor/graphics/pro/js/wasm/src/drawingfile.cpp index 1327d5f9b4..da001bb86b 100644 --- a/DesktopEditor/graphics/pro/js/wasm/src/drawingfile.cpp +++ b/DesktopEditor/graphics/pro/js/wasm/src/drawingfile.cpp @@ -181,7 +181,7 @@ int READ_INT(BYTE* x) #include "../../../../../fontengine/ApplicationFontsWorker.h" #include "../../../../../common/Directory.h" -int main() +int main(int argc, char* argv[]) { // CHECK SYSTEM FONTS CApplicationFontsWorker oWorker; @@ -246,7 +246,7 @@ int main() nLength -= 4; int nPagesCount = 0; - int nTestPage = 0; + int nTestPage = argc > 1 ? atoi(argv[1]) : 0; int nWidth = 100; int nHeight = 100; @@ -299,7 +299,7 @@ int main() } // LINKS - if (nPagesCount > 0) + if (false && nPagesCount > 0) { BYTE* pLinks = GetLinks(pGrFile, nTestPage); nLength = READ_INT(pLinks); @@ -335,7 +335,7 @@ int main() } // STRUCTURE - if (true) + if (false) { BYTE* pStructure = GetStructure(pGrFile); nLength = READ_INT(pStructure); diff --git a/DesktopEditor/raster/BgraFrame.cpp b/DesktopEditor/raster/BgraFrame.cpp index 1a4556dbc9..6768099c7d 100644 --- a/DesktopEditor/raster/BgraFrame.cpp +++ b/DesktopEditor/raster/BgraFrame.cpp @@ -40,13 +40,16 @@ #include "JBig2/source/JBig2File.h" #endif -void CxImageToMediaFrame( CxImage& img, CBgraFrame* bgra ) +#include +#define BGRA_FRAME_CXIMAGE_MAX_MEMORY 67108864 // 256Mb (*4 channel) + +void CxImageToMediaFrame( CxImage* img, CBgraFrame* bgra ) { - if( !img.IsValid() ) + if( !img || !img->IsValid() ) return; - int nWidth = img.GetWidth(); - int nHeight = img.GetHeight(); + int nWidth = img->GetWidth(); + int nHeight = img->GetHeight(); BYTE* pData = new BYTE[4 * nWidth * nHeight]; @@ -60,11 +63,11 @@ void CxImageToMediaFrame( CxImage& img, CBgraFrame* bgra ) BYTE* pPixels = bgra->get_Data(); - int nBitsPerPixel = img.GetBpp(); - int nStride = img.GetEffWidth(); - BYTE* pBuffer = img.GetBits(); - RGBQUAD* pPalette = img.GetPalette(); - bool bIsAlphaPalettePresent = img.AlphaPaletteIsEnabled(); + int nBitsPerPixel = img->GetBpp(); + int nStride = img->GetEffWidth(); + BYTE* pBuffer = img->GetBits(); + RGBQUAD* pPalette = img->GetPalette(); + bool bIsAlphaPalettePresent = img->AlphaPaletteIsEnabled(); bool bIsAlphaApplied = false; bool bIsRGBA = !bgra->get_IsRGBA(); @@ -149,7 +152,7 @@ void CxImageToMediaFrame( CxImage& img, CBgraFrame* bgra ) BYTE* src = pBuffer; BYTE* dst = pPixels; - int nTransIndex = img.GetTransIndex(); + int nTransIndex = img->GetTransIndex(); if (bIsAlphaApplied) nTransIndex = -1; @@ -185,7 +188,7 @@ void CxImageToMediaFrame( CxImage& img, CBgraFrame* bgra ) nStride -= nWidth; - int nTransIndex = img.GetTransIndex(); + int nTransIndex = img->GetTransIndex(); if (bIsAlphaApplied) nTransIndex = -1; @@ -269,10 +272,10 @@ void CxImageToMediaFrame( CxImage& img, CBgraFrame* bgra ) return; } - if( img.AlphaIsValid() ) + if( img->AlphaIsValid() ) { - BYTE* pAlpha = img.AlphaGetPointer(); - DWORD nMaxAlpha = img.AlphaGetMax(); + BYTE* pAlpha = img->AlphaGetPointer(); + DWORD nMaxAlpha = img->AlphaGetMax(); if( 255 == nMaxAlpha ) { @@ -440,13 +443,50 @@ bool CBgraFrame::OpenFile(const std::wstring& strFileName, unsigned int nFileTyp if (!oFile.OpenFile(strFileName)) return false; - CxImage img; + CxImage* img = new CxImage(); - if (!img.Decode(oFile.GetFileNative(), m_nFileType)) + if (!img->Decode(oFile.GetFileNative(), m_nFileType)) return false; - CxImageToMediaFrame(img, this); - m_bIsGrayScale = img.IsGrayScale(); + CxImage* imgResample = NULL; + + if (false) + { + // slow!!! + int nWidth = img->GetWidth(); + int nHeight = img->GetHeight(); + + double dSizeWH = (double)nWidth * nHeight; + double dSizeLimit = (double)BGRA_FRAME_CXIMAGE_MAX_MEMORY; + if (dSizeWH > dSizeLimit) + { + double dKoef = sqrt(dSizeLimit / dSizeWH); + int nW = (int)(dKoef * nWidth); + int nH = (int)(dKoef * nHeight); + + if (nW > 10 && nH > 10) + { + imgResample = new CxImage(); + if (!img->Resample(nW, nH, 2/*bicubic spline interpolation*/, imgResample)) + { + delete imgResample; + imgResample = NULL; + } + } + } + } + + CxImage* imageFinal = img; + if (imgResample) + { + delete img; + imageFinal = imgResample; + } + + CxImageToMediaFrame(imageFinal, this); + m_bIsGrayScale = imageFinal->IsGrayScale(); + delete imageFinal; + return true; } bool CBgraFrame::Decode(BYTE* pBuffer, int nSize, unsigned int nFileType) @@ -472,7 +512,7 @@ bool CBgraFrame::Decode(BYTE* pBuffer, int nSize, unsigned int nFileType) if (!img.Decode(pBuffer, nSize, m_nFileType)) return false; - CxImageToMediaFrame(img, this); + CxImageToMediaFrame(&img, this); m_bIsGrayScale = img.IsGrayScale(); return true; } @@ -548,7 +588,7 @@ bool CBgraFrame::Resize(const long& nNewWidth, const long& nNewHeight, bool bDes if (bDestroyData) Destroy(); - CxImageToMediaFrame( imgDst, this ); + CxImageToMediaFrame( &imgDst, this ); return true; } bool CBgraFrame::ReColorPatternImage(const std::wstring& strFileName, unsigned int rgbColorBack, unsigned int rgbColorFore) diff --git a/DesktopEditor/raster/Jp2/openjpeg/opj_bgraframe.cpp b/DesktopEditor/raster/Jp2/openjpeg/opj_bgraframe.cpp index f9836f6beb..887a2a931b 100644 --- a/DesktopEditor/raster/Jp2/openjpeg/opj_bgraframe.cpp +++ b/DesktopEditor/raster/Jp2/openjpeg/opj_bgraframe.cpp @@ -363,8 +363,9 @@ namespace openjpeg if (!opj_set_decode_area(l_codec, image, image->x0, nOffsetY, image->x1, nOffsetY + nTileHeight)) { - opj_stream_destroy(l_stream); - opj_destroy_codec(l_codec); + opj_stream_destroy(l_stream); l_stream = NULL; + opj_destroy_codec(l_codec); l_codec = NULL; + opj_image_destroy(image); image = NULL; l_stream = get_file_stream(pFileData, nFileSize, codec); diff --git a/DesktopEditor/raster/Metafile/Common/MetaFileRenderer.h b/DesktopEditor/raster/Metafile/Common/MetaFileRenderer.h index 5650f86235..3ace78b40d 100644 --- a/DesktopEditor/raster/Metafile/Common/MetaFileRenderer.h +++ b/DesktopEditor/raster/Metafile/Common/MetaFileRenderer.h @@ -57,6 +57,8 @@ #define LOGGING(_value) #endif +#define M_MINFONTSIZE 5 + namespace MetaFile { struct TRenderConditional @@ -272,8 +274,21 @@ namespace MetaFile UpdateTransform(); UpdateClip(); + double dFontScale = 1.; + double dLogicalFontHeight = std::fabs(pFont->GetHeight()); + + double dM11, dM12, dM21, dM22, dRx, dRy; + + if (dLogicalFontHeight < M_MINFONTSIZE) + { + m_pRenderer->GetTransform(&dM11, &dM12, &dM21, &dM22, &dRx, &dRy); + dFontScale = dM22; + dLogicalFontHeight *= dFontScale; + m_pRenderer->SetTransform(dM11 / std::fabs(dM11), dM12, dM21, dM22 / std::fabs(dM22), dRx, dRy); + } + m_pRenderer->put_FontName(pFont->GetFaceName()); - m_pRenderer->put_FontSize(fabs(pFont->GetHeight() * m_dScaleX / 25.4 * 72)); + m_pRenderer->put_FontSize(fabs(dLogicalFontHeight * m_dScaleX / 25.4 * 72)); int lStyle = 0; if (pFont->GetWeight() > 550) @@ -291,19 +306,15 @@ namespace MetaFile m_pRenderer->put_BrushColor1(m_pFile->GetTextColor()); m_pRenderer->put_BrushAlpha1(255); - double dM11, dM12, dM21, dM22, dX, dY; - - m_pRenderer->GetTransform(&dM11, &dM12, &dM21, &dM22, &dX, &dY); + m_pRenderer->GetTransform(&dM11, &dM12, &dM21, &dM22, &dRx, &dRy); m_pRenderer->ResetTransform(); - m_pRenderer->put_FontSize(fabs(pFont->GetHeight() * dM22 * m_dScaleY / 25.4 * 72)); - std::vector arGlyphPoint(arPoints.size()); for (unsigned int unIndex = 0; unIndex < arPoints.size(); ++unIndex) { - arGlyphPoint[unIndex].x = (arPoints[unIndex].x * dM11) * m_dScaleX + dX; - arGlyphPoint[unIndex].y = (arPoints[unIndex].y * dM22) * m_dScaleY + dY; + arGlyphPoint[unIndex].x = (arPoints[unIndex].x * dM11) * m_dScaleX * dFontScale + dRx; + arGlyphPoint[unIndex].y = (arPoints[unIndex].y * dM22) * m_dScaleY * dFontScale + dRy; } for (unsigned int unIndex = 0; unIndex < std::min(arPoints.size(), wsString.length()); ++unIndex) @@ -323,6 +334,17 @@ namespace MetaFile double dLogicalFontHeight = std::fabs(pFont->GetHeight()); + double dM11, dM12, dM21, dM22, dRx, dRy; + double dFontScale = 1.; + + if (dLogicalFontHeight < M_MINFONTSIZE) + { + m_pRenderer->GetTransform(&dM11, &dM12, &dM21, &dM22, &dRx, &dRy); + dFontScale = dM22; + dLogicalFontHeight *= dFontScale; + m_pRenderer->SetTransform(dM11 / std::fabs(dM11), dM12, dM21, dM22 / std::fabs(dM22), dRx, dRy); + } + double dFontHeight = fabs(dLogicalFontHeight * m_dScaleY / 25.4 * 72); std::wstring wsFaceName = pFont->GetFaceName(); @@ -346,13 +368,10 @@ namespace MetaFile double dCosTheta = cosf(dTheta); double dSinTheta = sinf(dTheta); - double dM11, dM12, dM21, dM22, dRx, dRy; - m_pRenderer->GetTransform(&dM11, &dM12, &dM21, &dM22, &dRx, &dRy); - if (dYScale > 0) dSinTheta = -dSinTheta; - double dFontCharSpace = m_pFile->GetCharSpace() * m_dScaleX * m_pFile->GetPixelWidth(); + double dFontCharSpace = m_pFile->GetCharSpace() * m_dScaleX * m_pFile->GetPixelWidth() * dFontScale; m_pRenderer->put_FontCharSpace(dFontCharSpace); float fL = 0, fT = 0, fW = 0, fH = 0; @@ -463,7 +482,7 @@ namespace MetaFile fH = (float)dFHeight; } - TPointD oTextPoint = TranslatePoint(_dX, _dY); + TPointD oTextPoint = TranslatePoint(_dX * dFontScale, _dY * dFontScale); double dX = oTextPoint.x; double dY = oTextPoint.y + dSkipY; @@ -474,7 +493,6 @@ namespace MetaFile unsigned int ulVTextAlign = m_pFile->GetTextAlign() >> 8; - if (ulTextAlign & TA_UPDATECP) { ulTextAlign -= TA_UPDATECP; @@ -629,7 +647,6 @@ namespace MetaFile m_pRenderer->put_BrushAlpha1(255); // Рисуем сам текст - if (NULL == pDx) { m_pRenderer->CommandDrawText(wsString, dX, dY, 0, 0); @@ -641,7 +658,7 @@ namespace MetaFile if (pUnicode && unUnicodeLen) { double dOffset = 0; - double dKoefX = m_dScaleX; + double dKoefX = m_dScaleX * dFontScale; for (unsigned int unCharIndex = 0; unCharIndex < unUnicodeLen; unCharIndex++) { m_pRenderer->CommandDrawTextCHAR(pUnicode[unCharIndex], dX + dOffset, dY, 0, 0); @@ -1119,8 +1136,6 @@ namespace MetaFile if (!pPen) return false; - int nColor = pPen->GetColor(); - unsigned int unMetaPenStyle = pPen->GetStyle(); unsigned int ulPenStyle = unMetaPenStyle & PS_STYLE_MASK; @@ -1133,8 +1148,6 @@ namespace MetaFile unsigned int ulPenEndCap = unMetaPenStyle & PS_ENDCAP_MASK; unsigned int ulPenJoin = unMetaPenStyle & PS_JOIN_MASK; - // TODO: dWidth зависит еще от флага PS_GEOMETRIC в стиле карандаша - BYTE nStartCapStyle = 0; if (PS_STARTCAP_ROUND == ulPenStartCap) nStartCapStyle = Aggplus::LineCapRound; @@ -1171,7 +1184,7 @@ namespace MetaFile dWidth = 25.4 / dRendererDpiX; - if (1 == pPen->GetWidth() && PS_COSMETIC == ulPenType) + if (PS_COSMETIC == ulPenType) dWidth /= m_pFile->GetTransform()->M11 / (m_pFile->GetDpi() / 96.); nStartCapStyle = nEndCapStyle = Aggplus::LineCapFlat; @@ -1182,7 +1195,6 @@ namespace MetaFile double dMiterLimit = (0 != pPen->GetMiterLimit()) ? pPen->GetMiterLimit() : m_pFile->GetMiterLimit() * m_dScaleX; - // TODO: Реализовать PS_USERSTYLE BYTE nDashStyle = Aggplus::DashStyleSolid; double *pDataDash; @@ -1196,111 +1208,84 @@ namespace MetaFile //поэтому замещает по возможно его на стандартный m_pRenderer->put_PenDashOffset(pPen->GetDashOffset()); - if (1 == unSizeDash) - ulPenStyle = Aggplus::DashStyleSolid; - else if (2 == unSizeDash) - ulPenStyle = (pDataDash[0] != pDataDash[1]) ? Aggplus::DashStyleDash : Aggplus::DashStyleDot; - else if (4 == unSizeDash) - ulPenStyle = Aggplus::DashStyleDashDot; - else if (6 == unSizeDash) - ulPenStyle = Aggplus::DashStyleDashDotDot; + std::vector arDashData; + + for (unsigned int unIndex = 0; unIndex < unSizeDash; ++unIndex) + arDashData.push_back(pDataDash[unIndex] * dWidth); + + m_pRenderer->PenDashPattern(arDashData.data(), unSizeDash); + nDashStyle = Aggplus::DashStyleCustom; } - - // В WinGDI все карандаши толщиной больше 1px рисуются в стиле PS_SOLID - if (1 >= pPen->GetWidth() && PS_SOLID != ulPenStyle && false) + else if (PS_SOLID != ulPenStyle) { - // TODO: Ранее здесь специально ставилась толщина 0, что любой рендерер должен - // воспринимать как толщину в 1px. Но сейчас это не работает в графическом ренедерере, - // поэтому временно это убрано. - // Толщиной в 1px - именно так рисуется в винде любая пунктирная линия в метафайле. + std::vector arDashPattern; - //dWidth = 0; // Специальное значение для 1pх карандаша + double dPixWidth = 0; - double dDpiX; - m_pRenderer->get_DpiX(&dDpiX); - double dPixelW = dDpiX > 1 ? 25.4 / dDpiX : 25.4 / 72; + if (0 == pPen->GetWidth() || (1 == pPen->GetWidth() && PS_COSMETIC == ulPenType)) + { + dPixWidth = dWidth; + } + else + { + dPixWidth = dWidth * 25.4 / 72.; - double dDashOff = 0; - double* pDashPattern = NULL; - int nDashLen = 0; + if (1 == pPen->GetWidth() && PS_COSMETIC == ulPenType) + dPixWidth /= m_pFile->GetTransform()->M11 / (m_pFile->GetDpi() / 96.); + } switch (ulPenStyle) { - case PS_DASH: - { - dDashOff = 0 * dPixelW; - nDashLen = 2; - pDashPattern = new double[2]; - if (pDashPattern) + case PS_DASH: { - pDashPattern[0] = 18 * dPixelW; - pDashPattern[1] = 3 * dPixelW; + arDashPattern.push_back(9 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + + break; } - break; - } - case PS_DOT: - { - dDashOff = 4 * dPixelW; - nDashLen = 2; - pDashPattern = new double[2]; - if (pDashPattern) + case PS_DOT: { - pDashPattern[0] = 3 * dPixelW; - pDashPattern[1] = 3 * dPixelW; + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + + break; } - break; - } - case PS_DASHDOT: - { - dDashOff = 22 * dPixelW; - nDashLen = 4; - pDashPattern = new double[4]; - if (pDashPattern) + case PS_DASHDOT: { - pDashPattern[0] = 9 * dPixelW; - pDashPattern[1] = 6 * dPixelW; - pDashPattern[2] = 3 * dPixelW; - pDashPattern[3] = 6 * dPixelW; + arDashPattern.push_back(9 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + + break; } - break; - } - case PS_DASHDOTDOT: - { - dDashOff = 22 * dPixelW; - nDashLen = 6; - pDashPattern = new double[6]; - if (pDashPattern) + case PS_DASHDOTDOT: { - pDashPattern[0] = 9 * dPixelW; - pDashPattern[1] = 3 * dPixelW; - pDashPattern[2] = 3 * dPixelW; - pDashPattern[3] = 3 * dPixelW; - pDashPattern[4] = 3 * dPixelW; - pDashPattern[5] = 3 * dPixelW; + arDashPattern.push_back(9 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + arDashPattern.push_back(3 * dPixWidth); + + break; } - break; - } } - if (NULL != pDashPattern) + if (!arDashPattern.empty()) { - m_pRenderer->put_PenDashOffset(dDashOff); - m_pRenderer->PenDashPattern(pDashPattern, nDashLen); + m_pRenderer->PenDashPattern(arDashPattern.data(), arDashPattern.size()); nDashStyle = Aggplus::DashStyleCustom; - delete[] pDashPattern; + nStartCapStyle = nEndCapStyle = Aggplus::LineCapFlat; + nJoinStyle = Aggplus::LineJoinMiter; } } - if (1 <= pPen->GetWidth() && PS_SOLID != ulPenStyle) - { - nStartCapStyle = Aggplus::LineCapFlat; - } - - m_pRenderer->put_PenDashStyle(ulPenStyle); + m_pRenderer->put_PenDashStyle(nDashStyle); m_pRenderer->put_PenLineJoin(nJoinStyle); m_pRenderer->put_PenLineStartCap(nStartCapStyle); m_pRenderer->put_PenLineEndCap(nEndCapStyle); - m_pRenderer->put_PenColor(nColor); + m_pRenderer->put_PenColor(pPen->GetColor()); m_pRenderer->put_PenSize(dWidth); m_pRenderer->put_PenAlpha(pPen->GetAlpha()); m_pRenderer->put_PenMiterLimit(dMiterLimit); @@ -1317,9 +1302,6 @@ namespace MetaFile case R2_WHITE: m_pRenderer->put_PenColor(METAFILE_RGBA(255, 255, 255)); break; } - if (PS_NULL == ulPenStyle) - return false; - return true; } bool UpdateClip() diff --git a/DesktopEditor/raster/Metafile/Common/MetaFileTypes.cpp b/DesktopEditor/raster/Metafile/Common/MetaFileTypes.cpp index 8815541f6d..779bf48d48 100644 --- a/DesktopEditor/raster/Metafile/Common/MetaFileTypes.cpp +++ b/DesktopEditor/raster/Metafile/Common/MetaFileTypes.cpp @@ -43,6 +43,10 @@ namespace MetaFile nBottom = 1024; } + TRect::TRect(int nNewLeft, int nNewTop, int nNewRight, int nNewBottom) + : nLeft(nNewLeft), nTop(nNewTop), nRight(nNewRight), nBottom(nNewBottom) + {} + TRect::TRect(const TWmfRect &oRect) { nLeft = oRect.Left; @@ -66,6 +70,21 @@ namespace MetaFile nBottom = oRect.Bottom; return *this; } + bool operator!=(const TRect& oLeftRect, const TRect& oRightRect) + { + return (oLeftRect.nLeft != oRightRect.nLeft && + oLeftRect.nTop != oRightRect.nTop && + oLeftRect.nRight != oRightRect.nRight && + oLeftRect.nBottom != oRightRect.nBottom); + } + bool operator==(const TRect& oLeftRect, const TRect& oRightRect) + { + return (oLeftRect.nLeft == oRightRect.nLeft && + oLeftRect.nTop == oRightRect.nTop && + oLeftRect.nRight == oRightRect.nRight && + oLeftRect.nBottom == oRightRect.nBottom); + } + TPointL::TPointL() { diff --git a/DesktopEditor/raster/Metafile/Common/MetaFileTypes.h b/DesktopEditor/raster/Metafile/Common/MetaFileTypes.h index f95897621b..33a8353b2a 100644 --- a/DesktopEditor/raster/Metafile/Common/MetaFileTypes.h +++ b/DesktopEditor/raster/Metafile/Common/MetaFileTypes.h @@ -382,9 +382,12 @@ namespace MetaFile int nBottom; TRect(); + TRect(int nNewLeft, int nNewTop, int nNewRight, int nNewBottom); TRect(const TWmfRect& oRect); TRect(const TEmfRectL& oRect); TRect& operator=(TWmfRect& oRect); + friend bool operator!=(const TRect& oLeftRect, const TRect& oRightRect); + friend bool operator==(const TRect& oLeftRect, const TRect& oRightRect); }; struct TRectD diff --git a/DesktopEditor/raster/Metafile/Emf/EmfInterpretator/CEmfInterpretatorSvg.cpp b/DesktopEditor/raster/Metafile/Emf/EmfInterpretator/CEmfInterpretatorSvg.cpp index 1e7f4b63e4..d748e56ba0 100644 --- a/DesktopEditor/raster/Metafile/Emf/EmfInterpretator/CEmfInterpretatorSvg.cpp +++ b/DesktopEditor/raster/Metafile/Emf/EmfInterpretator/CEmfInterpretatorSvg.cpp @@ -1022,8 +1022,8 @@ namespace MetaFile {L"y", ConvertToWString(oNewRect.dTop)}, {L"width", ConvertToWString(oNewRect.dRight - oNewRect.dLeft)}, {L"height", ConvertToWString(oNewRect.dBottom - oNewRect.dTop)}, - {L"rx", ConvertToWString(oCorner.cx)}, - {L"ry", ConvertToWString(oCorner.cy)}}; + {L"rx", ConvertToWString((double)oCorner.cx / 2.)}, + {L"ry", ConvertToWString((double)oCorner.cy / 2.)}}; AddStroke(arAttributes); AddFill(arAttributes); diff --git a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.cpp b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.cpp index 7ae15da560..84b623d328 100644 --- a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.cpp +++ b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.cpp @@ -21,8 +21,6 @@ namespace MetaFile CEmfParser::~CEmfParser() { ClearFile(); - - RELEASEOBJECT(m_pEmfPlusParser); RELEASEOBJECT(m_pInterpretator); } @@ -230,6 +228,13 @@ namespace MetaFile m_pInterpretator = pInterpretator; } + void CEmfParser::ClearFile() + { + RELEASEOBJECT(m_pEmfPlusParser); + + CEmfParserBase::ClearFile(); + } + EmfParserType CEmfParser::GetType() { return EmfParserType::EmfParser; diff --git a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.h b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.h index 0013a3a761..3f081af6c1 100644 --- a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.h +++ b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfParser.h @@ -18,6 +18,8 @@ namespace MetaFile void PlayFile() override; void Scan() override; + void ClearFile() override; + EmfParserType GetType() override; void SetStream(BYTE* pBuf, unsigned int unSize); diff --git a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfPlusParser.cpp b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfPlusParser.cpp index 6e2ca1449a..b3bc400967 100644 --- a/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfPlusParser.cpp +++ b/DesktopEditor/raster/Metafile/Emf/EmfParser/CEmfPlusParser.cpp @@ -634,8 +634,11 @@ namespace MetaFile for (unsigned int unIndex = 0; unIndex < unPositionCount; ++unIndex) m_oStream >> arBlendColors[unIndex]; - if (0 != unPositionCount) + if (1 < unPositionCount) + { pEmfPlusBrush->ColorBack = arBlendColors[0]; + pEmfPlusBrush->Color = arBlendColors.back(); + } } break; diff --git a/DesktopEditor/raster/Metafile/Emf/EmfPlayer.cpp b/DesktopEditor/raster/Metafile/Emf/EmfPlayer.cpp index c2b6a36fae..065c989c97 100644 --- a/DesktopEditor/raster/Metafile/Emf/EmfPlayer.cpp +++ b/DesktopEditor/raster/Metafile/Emf/EmfPlayer.cpp @@ -677,7 +677,7 @@ namespace MetaFile { unsigned int ulMapMode = m_ulMapMode; - if (0 == m_oWindow.ulW || 0 == m_oViewport.ulW) + if (1 >= m_oWindow.ulW || 1 >= m_oViewport.ulW) return false; if (MM_ISOTROPIC == ulMapMode) diff --git a/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CInterpretatorSvgBase.cpp b/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CInterpretatorSvgBase.cpp index 5d0ad2e62a..10880984a3 100644 --- a/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CInterpretatorSvgBase.cpp +++ b/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CInterpretatorSvgBase.cpp @@ -272,6 +272,10 @@ namespace MetaFile unsigned int ulTextAlign = m_pParser->GetTextAlign() & TA_MASK; unsigned int ulVTextAlign = m_pParser->GetTextAlign() >> 8; + if (ulTextAlign & TA_UPDATECP) + { + ulTextAlign -= TA_UPDATECP; + } if (ulTextAlign & TA_BASELINE) { ulTextAlign -= TA_BASELINE; @@ -290,7 +294,7 @@ namespace MetaFile } else // if (ulTextAlign & TA_TOP) { - arNodeAttributes.push_back({L"dominant-baseline", L"hanging"}); + dYCoord += dFontHeight; } if (ulTextAlign == TA_RIGHT) @@ -382,21 +386,31 @@ namespace MetaFile if (NULL == pPen || PS_NULL == pPen->GetStyle()) return; + switch (m_pParser->GetRop2Mode()) + { + case R2_BLACK: arAttributes.push_back({L"stroke", L"rgb(0, 0, 0)"}); break; + case R2_NOP: return; + case R2_WHITE: arAttributes.push_back({L"stroke", L"rgb(255, 255, 255)"}); break; + default: arAttributes.push_back({L"stroke", L"rgb(" + INTCOLOR_TO_RGB(pPen->GetColor()) + L')'}); break; + } + double dStrokeWidth = std::fabs(pPen->GetWidth()); - if (0 == dStrokeWidth && 0 == pPen->GetColor() && (NULL != m_pParser->GetBrush() && BS_NULL == m_pParser->GetBrush()->GetStyle())) - return; - if (0 == dStrokeWidth || (1.0 == dStrokeWidth && PS_COSMETIC == (pPen->GetStyle() & PS_TYPE_MASK))) - dStrokeWidth = (m_oViewport.GetWidth() / m_oSizeWindow.x) / std::fabs(m_pParser->GetTransform()->M11); + { + double dScale = m_pParser->GetDpi() / 96.; + + if (0 != m_oViewport.GetWidth() && 0 != m_oSizeWindow.x) + dScale *= m_oViewport.GetWidth() / m_oSizeWindow.x; + + dStrokeWidth = dScale / std::fabs(m_pParser->GetTransform()->M11); + } arAttributes.push_back({L"stroke-width", ConvertToWString(dStrokeWidth)}); if (pPen->GetAlpha() != 255) arAttributes.push_back({L"stroke-opacity" , ConvertToWString(pPen->GetAlpha() / 255., 3)}); - arAttributes.push_back({L"stroke", L"rgb(" + INTCOLOR_TO_RGB(pPen->GetColor()) + L')'}); - unsigned int unMetaPenStyle = pPen->GetStyle(); // unsigned int ulPenType = unMetaPenStyle & PS_TYPE_MASK; unsigned int ulPenStyle = unMetaPenStyle & PS_STYLE_MASK; @@ -644,6 +658,9 @@ namespace MetaFile dStrokeWidth = 1. / m_pParser->GetTransform()->M11; } + if (0 != m_oViewport.GetWidth() && 0 != m_oSizeWindow.x) + dStrokeWidth *= m_oViewport.GetWidth() / m_oSizeWindow.x; + std::wstring wsStrokeColor = L"rgba(" + INTCOLOR_TO_RGB(m_pParser->GetBrush()->GetColor()) + L"," + ConvertToWString(m_pParser->GetBrush()->GetAlpha(), 0) + L")"; std::wstring wsBgColor; @@ -733,6 +750,9 @@ namespace MetaFile dStrokeWidth = 1. / m_pParser->GetTransform()->M11; } + if (0 != m_oViewport.GetWidth() && 0 != m_oSizeWindow.x) + dStrokeWidth *= m_oViewport.GetWidth() / m_oSizeWindow.x; + std::wstring wsWidth = ConvertToWString(dStrokeWidth * unWidth); std::wstring wsHeight = ConvertToWString(dStrokeWidth * unHeight); @@ -833,10 +853,13 @@ namespace MetaFile pBrush->GetBounds(dLeft, dTop, dWidth, dHeight); - dX = ((dX - dLeft) / dWidth); - dY = ((dY - dTop) / dHeight); + if (0 != dWidth && 0 != dHeight) + { + dX = ((dX - dLeft) / dWidth); + dY = ((dY - dTop) / dHeight); - wsIndlude = L" cx=\"" + ConvertToWString(dX) + L"\" cy=\"" + ConvertToWString(dY) + L"\" r=\"1\""; + wsIndlude = L" cx=\"" + ConvertToWString(dX) + L"\" cy=\"" + ConvertToWString(dY) + L"\" r=\"1\""; + } } m_wsDefs += L"" + diff --git a/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CWmfInterpretatorSvg.cpp b/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CWmfInterpretatorSvg.cpp index 1d395c38e3..d0dccbe72f 100644 --- a/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CWmfInterpretatorSvg.cpp +++ b/DesktopEditor/raster/Metafile/Wmf/WmfInterpretator/CWmfInterpretatorSvg.cpp @@ -402,13 +402,12 @@ namespace MetaFile oNewRect.dRight = shR; oNewRect.dBottom = shB; - NodeAttributes arAttributes = {{L"x", ConvertToWString(oNewRect.dLeft)}, {L"y", ConvertToWString(oNewRect.dTop)}, {L"width", ConvertToWString(oNewRect.dRight - oNewRect.dLeft)}, {L"height", ConvertToWString(oNewRect.dBottom - oNewRect.dTop)}, - {L"rx", ConvertToWString(shW)}, - {L"ry", ConvertToWString(shH)}}; + {L"rx", ConvertToWString((double)shW / 2.)}, + {L"ry", ConvertToWString((double)shH / 2.)}}; AddStroke(arAttributes); AddFill(arAttributes); @@ -549,6 +548,7 @@ namespace MetaFile {L"y", ConvertToWString(dY)}, {L"width", ConvertToWString(dW)}, {L"height", ConvertToWString(dH)}, + {L"preserveAspectRatio", L"xMinYMin slice"}, {L"xlink:href", L"data:image/png;base64," + wsValue}}; AddTransform(arAttributes); diff --git a/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.cpp b/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.cpp index 3fb94af8b7..4b2849e0ff 100644 --- a/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.cpp +++ b/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.cpp @@ -724,21 +724,36 @@ namespace MetaFile return true; } - void CWmfParserBase::DrawImage(int nX, int nY, int nW, int nH, unsigned int unColorUsage, unsigned int unRasterOperation) + void CWmfParserBase::DrawImage(const TRect& oDestRect, const TRect& oSrcRect, unsigned int unColorUsage, unsigned int unRasterOperation) { if (NULL != m_pInterpretator) { BYTE* pBgra = NULL; unsigned int unWidth, unHeight; + if (ReadImage(unColorUsage, &pBgra, &unWidth, &unHeight)) { ProcessRasterOperation(unRasterOperation, &pBgra, unWidth, unHeight); double dX, dY, dX1, dY1; - TranslatePoint(nX, nY, dX, dY); - TranslatePoint(nX + nW, nY + nH, dX1, dY1); + TranslatePoint(oDestRect.nLeft, oDestRect.nTop, dX, dY); + TranslatePoint(oDestRect.nRight, oDestRect.nBottom, dX1, dY1); - m_pInterpretator->DrawBitmap(dX, dY, fabs(dX1 - dX), fabs(dY1 - dY), pBgra, unWidth, unHeight); + if (oDestRect != oSrcRect) + { + TRect oClip = oSrcRect; + BYTE* pNewBuffer = ClipBuffer(pBgra, unWidth, unHeight, oClip); + + if (NULL != pNewBuffer) + { + m_pInterpretator->DrawBitmap(dX, dY, fabs(dX1 - dX), fabs(dY1 - dY), pNewBuffer, std::abs(oClip.nRight - oClip.nLeft), std::abs(oClip.nBottom - oClip.nTop)); + delete[] pNewBuffer; + } + else + m_pInterpretator->DrawBitmap(dX, dY, fabs(dX1 - dX), fabs(dY1 - dY), pBgra, unWidth, unHeight); + } + else + m_pInterpretator->DrawBitmap(dX, dY, fabs(dX1 - dX), fabs(dY1 - dY), pBgra, unWidth, unHeight); } if (pBgra) @@ -750,11 +765,58 @@ namespace MetaFile } else { - RegisterPoint(nX, nY); - RegisterPoint(nX + nW, nY + nH); + RegisterPoint(oDestRect.nLeft, oDestRect.nTop); + RegisterPoint(oDestRect.nRight, oDestRect.nBottom); } } + BYTE *CWmfParserBase::ClipBuffer(BYTE *pBuffer, unsigned int unWidth, unsigned int unHeight, TRect &oNewRect) + { + if (NULL == pBuffer || + oNewRect.nLeft < 0 || oNewRect.nRight < 0 || + oNewRect.nTop < 0 || oNewRect.nBottom < 0) + return NULL; + + if (unHeight < (oNewRect.nBottom - oNewRect.nTop)) + oNewRect.nBottom = oNewRect.nTop + unWidth; + + if (unWidth < (oNewRect.nRight - oNewRect.nLeft)) + oNewRect.nRight = oNewRect.nLeft + unWidth; + + if (unHeight == (oNewRect.nBottom - oNewRect.nTop) && + unWidth == (oNewRect.nRight - oNewRect.nLeft)) + return NULL; + + int nBeginX, nBeginY, nEndX, nEndY; + + nBeginX = (std::min)(oNewRect.nLeft, oNewRect.nRight); + nBeginY = (std::min)(oNewRect.nTop, oNewRect.nBottom); + + nEndX = (std::max)(oNewRect.nLeft, oNewRect.nRight); + nEndY = (std::max)(oNewRect.nTop, oNewRect.nBottom); + + int nWidth = nEndX - nBeginX; + int nHeight = nEndY - nBeginY; + + BYTE* pNewBuffer = new BYTE[nWidth * nHeight * 4]; + + ULONG ulPos = 0; + + for (ULONG ulPosY = nBeginY * 4; ulPosY < nEndY * 4; ulPosY += 4) + { + for (ULONG ulPosX = nBeginX * 4; ulPosX < nEndX * 4; ulPosX += 4) + { + pNewBuffer[ulPos + 0] = (BYTE)pBuffer[ulPosY * unWidth + ulPosX + 0]; + pNewBuffer[ulPos + 1] = (BYTE)pBuffer[ulPosY * unWidth + ulPosX + 1]; + pNewBuffer[ulPos + 2] = (BYTE)pBuffer[ulPosY * unWidth + ulPosX + 2]; + pNewBuffer[ulPos + 3] = (BYTE)pBuffer[ulPosY * unWidth + ulPosX + 3]; + ulPos += 4; + } + } + + return pNewBuffer; + } + void CWmfParserBase::UpdateOutputDC() { if (NULL != m_pInterpretator) @@ -828,7 +890,9 @@ namespace MetaFile } else { - DrawImage(oWmfBitBlt.XDest, oWmfBitBlt.YDest, oWmfBitBlt.Width, oWmfBitBlt.Height, 0, oWmfBitBlt.RasterOperation); + TRect oDestRect(oWmfBitBlt.XDest, oWmfBitBlt.YDest, oWmfBitBlt.XDest + oWmfBitBlt.Width, oWmfBitBlt.YDest + oWmfBitBlt.Height); + + DrawImage(oDestRect, oDestRect, 0, oWmfBitBlt.RasterOperation); } } @@ -846,7 +910,9 @@ namespace MetaFile } else { - DrawImage(oWmfStretchBlt.XDest, oWmfStretchBlt.YDest, oWmfStretchBlt.DestWidth, oWmfStretchBlt.DestHeight, 0, oWmfStretchBlt.RasterOperation); + TRect oDestRect(oWmfStretchBlt.XDest, oWmfStretchBlt.YDest, oWmfStretchBlt.XDest + oWmfStretchBlt.DestWidth, oWmfStretchBlt.YDest + oWmfStretchBlt.DestHeight); + + DrawImage(oDestRect, oDestRect, 0, oWmfStretchBlt.RasterOperation); } } @@ -855,8 +921,10 @@ namespace MetaFile if (NULL != m_pInterpretator) m_pInterpretator->HANDLE_META_SETDIBTODEV(oWmfSetDibToDev, oDataStream); + TRect oDestRect(oWmfSetDibToDev.xDest, oWmfSetDibToDev.yDest, oWmfSetDibToDev.xDest + oWmfSetDibToDev.Width, oWmfSetDibToDev.yDest + oWmfSetDibToDev.Height); + // TODO: Тут надо делать обрезку в зависимости от ScanCount и StartScan. Как встретится файл сделать. - DrawImage(oWmfSetDibToDev.xDest, oWmfSetDibToDev.yDest, oWmfSetDibToDev.Width, oWmfSetDibToDev.Height, oWmfSetDibToDev.ColorUsage, 0); + DrawImage(oDestRect, oDestRect, oWmfSetDibToDev.ColorUsage, 0); } void CWmfParserBase::HANDLE_META_STRETCHBLT(const TWmfStretchBlt &oWmfStretchBlt, CDataStream &oDataStream) @@ -870,7 +938,10 @@ namespace MetaFile if (NULL != m_pInterpretator) m_pInterpretator->HANDLE_META_STRETCHDIB(oWmfStretchDib, oDataStream); - DrawImage(oWmfStretchDib.xDst, oWmfStretchDib.yDst, oWmfStretchDib.DestWidth, oWmfStretchDib.DestHeight, oWmfStretchDib.ColorUsage, oWmfStretchDib.RasterOperation); + TRect oDestRect(oWmfStretchDib.xDst, oWmfStretchDib.yDst, oWmfStretchDib.xDst + oWmfStretchDib.DestWidth, oWmfStretchDib.yDst + oWmfStretchDib.DestHeight); + TRect oScrcRect(oWmfStretchDib.XSrc, oWmfStretchDib.YSrc, oWmfStretchDib.XSrc + oWmfStretchDib.SrcWidth, oWmfStretchDib.YSrc + oWmfStretchDib.SrcHeight); + + DrawImage(oDestRect, oScrcRect, oWmfStretchDib.ColorUsage, oWmfStretchDib.RasterOperation); } void CWmfParserBase::HANDLE_META_EOF() diff --git a/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.h b/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.h index 2f22443136..f968c92b2e 100644 --- a/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.h +++ b/DesktopEditor/raster/Metafile/Wmf/WmfParser/CWmfParserBase.h @@ -89,7 +89,9 @@ namespace MetaFile void RegisterPoint(short shX, short shY); bool ReadImage(unsigned short ushColorUsage, BYTE** ppBgraBuffer, unsigned int* pulWidth, unsigned int* pulHeight); - void DrawImage(int nX, int nY, int nW, int nH, unsigned int unColorUsage, unsigned int unRasterOperation); + void DrawImage(const TRect& oDestRect, const TRect& oSrcRect, unsigned int unColorUsage, unsigned int unRasterOperation); + + static BYTE* ClipBuffer(BYTE* pBuffer, unsigned int unWidth, unsigned int unHeight, TRect& oNewRect); void UpdateOutputDC(); private: diff --git a/DesktopEditor/raster/Metafile/Wmf/WmfPlayer.cpp b/DesktopEditor/raster/Metafile/Wmf/WmfPlayer.cpp index de9486e3c6..f2a86a66f0 100644 --- a/DesktopEditor/raster/Metafile/Wmf/WmfPlayer.cpp +++ b/DesktopEditor/raster/Metafile/Wmf/WmfPlayer.cpp @@ -537,6 +537,9 @@ namespace MetaFile } bool CWmfDC::UpdatePixelMetrics() { + if (1 >= m_oWindow.w || 1 >= m_oViewport.w) + return false; + unsigned short ushMapMode = m_ushMapMode; if (MM_ISOTROPIC == ushMapMode) { diff --git a/DjVuFile/libdjvu/DjVuDocument.cpp b/DjVuFile/libdjvu/DjVuDocument.cpp index 0098f6b28f..ba89899d4b 100644 --- a/DjVuFile/libdjvu/DjVuDocument.cpp +++ b/DjVuFile/libdjvu/DjVuDocument.cpp @@ -1888,8 +1888,9 @@ DjVuDocument::writeDjVuXML(const GP &gstr_out,int flags) const void DjVuDocument::ReadPageInfo(int nPage, int& width, int& height, int& nDpi) { - width = 1000; - height = 1000; + width = 1; + height = 1; + nDpi = 96; try { diff --git a/EpubFile/CEpubFile.h b/EpubFile/CEpubFile.h index e74f65b43f..d37c723069 100644 --- a/EpubFile/CEpubFile.h +++ b/EpubFile/CEpubFile.h @@ -30,7 +30,7 @@ public: void SetTempDirectory(const std::wstring& stempDir); HRESULT Convert(const std::wstring& sInputFile, const std::wstring& sOutputFile, bool bIsOutCompress = true); void ShowMap(); - HRESULT FromHtml(const std::wstring& sHtmlFile, const std::wstring& sCoreFile, const std::wstring& sDstFile, const std::wstring& sInpTitle); + HRESULT FromHtml(const std::wstring& sHtmlFile, const std::wstring& sDstFile, const std::wstring& sInpTitle); }; #endif // CEPUBFILE_H diff --git a/EpubFile/src/CEpubFile.cpp b/EpubFile/src/CEpubFile.cpp index 89bec24b9e..a575fcbc97 100644 --- a/EpubFile/src/CEpubFile.cpp +++ b/EpubFile/src/CEpubFile.cpp @@ -196,7 +196,23 @@ void CEpubFile::ShowMap() std::wcout << oItem.m_sID << L" - " << m_mapRefs[oItem.m_sID].GetRef() << std::endl; } -HRESULT CEpubFile::FromHtml(const std::wstring& sHtmlFile, const std::wstring& sCoreFile, const std::wstring& sDstFile, const std::wstring& sInpTitle) +#define DocInfo(name, tag)\ +{\ + std::wstring sFind = L"", nFind);\ + if (nBegin != std::wstring::npos && nEnd != std::wstring::npos && nBegin + 9 < nEnd)\ + {\ + nBegin += 9;\ + std::wstring sRes = L"<"; sRes += tag; sRes += L'>'; sRes += sIndexHtml.substr(nBegin, nEnd - nBegin); sRes += L"";\ + oContentOpf.WriteStringUTF8(sRes);\ + }\ + }\ +} + +HRESULT CEpubFile::FromHtml(const std::wstring& sHtmlFile, const std::wstring& sDstFile, const std::wstring& sInpTitle) { NSDirectory::CreateDirectory(m_sTempDir + L"/META-INF"); NSDirectory::CreateDirectory(m_sTempDir + L"/OEBPS"); @@ -296,45 +312,27 @@ HRESULT CEpubFile::FromHtml(const std::wstring& sHtmlFile, const std::wstring& s oContentOpf.WriteStringUTF8(L""); // metadata bool bWasIdentifier = false; - XmlUtils::CXmlLiteReader oCoreReader; - oCoreReader.FromString(sCoreFile); - oCoreReader.ReadNextNode(); - int nDeath = oCoreReader.GetDepth(); - while (oCoreReader.ReadNextSiblingNode(nDeath)) + + size_t nFind; + if ((nFind = sIndexHtml.find(L"")) != std::wstring::npos) { - std::wstring sOut = oCoreReader.GetOuterXml(); - std::wstring sName = oCoreReader.GetName(); - if (sName == L"dc:identifier") + size_t nEnd = sIndexHtml.find(L"", nFind); + if (nEnd != std::wstring::npos) { - bWasIdentifier = true; - oContentOpf.WriteStringUTF8(sOut); + bWasTitle = true; + sTitle = sIndexHtml.substr(nFind + 7, nEnd - nFind - 7); + oContentOpf.WriteStringUTF8(L"" + sTitle + L""); } - else if (sName == L"dc:title") - { - std::wstring sInTitle = sOut; - size_t nBegin = sInTitle.find(L'>'); - if (nBegin == std::wstring::npos) - continue; - sInTitle.erase(0, nBegin + 1); - nBegin = sInTitle.find(L'<'); - if (nBegin == std::wstring::npos) - continue; - sInTitle.erase(nBegin); - if (!sInTitle.empty()) - { - bWasTitle = true; - sTitle = sInTitle; - oContentOpf.WriteStringUTF8(sOut); - } - } - else if (sName == L"dc:language") - { - bWasLanguage = true; - oContentOpf.WriteStringUTF8(sOut); - } - else - oContentOpf.WriteStringUTF8(sOut); } + DocInfo(L"identifier", L"dc:identifier"); + DocInfo(L"language", L"dc:language"); + DocInfo(L"creator", L"dc:creator"); + DocInfo(L"description", L"dc:description"); + DocInfo(L"subject", L"dc:subject"); + DocInfo(L"keywords", L"cp:keywords"); + bWasIdentifier = sIndexHtml.find(L"urn:uuid:"); diff --git a/EpubFile/test/main.cpp b/EpubFile/test/main.cpp index d7d2502ad6..f355fe236e 100644 --- a/EpubFile/test/main.cpp +++ b/EpubFile/test/main.cpp @@ -18,10 +18,10 @@ int main() bool bFromHtml = false; if (bFromHtml) { - std::wstring sFile = NSFile::GetProcessDirectory() + L"/../../../FromHtmlTest/test3"; + std::wstring sFile = NSFile::GetProcessDirectory() + L"/../../../Files/test.html"; CEpubFile oEpub; oEpub.SetTempDirectory(sTmp); - oEpub.FromHtml(sFile, sFile, sOutputDirectory + L"/res.epub", L""); + oEpub.FromHtml(sFile, sOutputDirectory + L"/res.epub", L""); NSDirectory::DeleteDirectory(sTmp); return 0; } diff --git a/EpubFile/test/test.pro b/EpubFile/test/test.pro index b556749409..971fa59427 100644 --- a/EpubFile/test/test.pro +++ b/EpubFile/test/test.pro @@ -11,8 +11,7 @@ DEFINES += EPUBFORMAT_USE_DYNAMIC_LIBRARY CORE_ROOT_DIR = $$PWD/../.. PWD_ROOT_DIR = $$PWD include($$CORE_ROOT_DIR/Common/base.pri) - -core_linux:include($$CORE_ROOT_DIR/Common/3dParty/icu/icu.pri) +include($$CORE_ROOT_DIR/Common/3dParty/icu/icu.pri) DESTDIR = $$PWD_ROOT_DIR/build/$$CORE_BUILDS_PLATFORM_PREFIX/$$CORE_BUILDS_CONFIGURATION_PREFIX diff --git a/Fb2File/Fb2File.cpp b/Fb2File/Fb2File.cpp index a9490acdd2..3c83685c97 100644 --- a/Fb2File/Fb2File.cpp +++ b/Fb2File/Fb2File.cpp @@ -1589,11 +1589,22 @@ HRESULT CFb2File::Open(const std::wstring& sPath, const std::wstring& sDirectory return S_OK; } -void readLi(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bUl, bool bWasP, bool bWasTable); -void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bWasP, bool bWasTable) +void replace_all(std::wstring& s, const std::wstring& s1, const std::wstring& s2) { - int nDeath = oIndexHtml.GetDepth(); - if (oIndexHtml.IsEmptyNode() || !oIndexHtml.ReadNextSiblingNode2(nDeath)) + size_t pos = s.find(s1); + size_t l = s2.length(); + while (pos != std::string::npos) + { + s.replace(pos, s1.length(), s2); + pos = s.find(s1, pos + l); + } +} + +void readLi(NSStringUtils::CStringBuilder& oXml, NSStringUtils::CStringBuilder& oTitleInfo, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bUl, bool bWasP, bool bWasTable); +void readStream(NSStringUtils::CStringBuilder& oXml, NSStringUtils::CStringBuilder& oTitleInfo, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bWasP, bool bWasTable) +{ + int nDepth = oIndexHtml.GetDepth(); + if (oIndexHtml.IsEmptyNode() || !oIndexHtml.ReadNextSiblingNode2(nDepth)) return; do { @@ -1604,15 +1615,48 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"

"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"

"); } + else if (sName == L"title") + oTitleInfo.WriteString(L"" + oIndexHtml.GetText2() + L""); + else if (sName == L"meta") + { + std::wstring sAtrName, sAtrContent; + while (oIndexHtml.MoveToNextAttribute()) + { + std::wstring sAtr = oIndexHtml.GetName(); + if (sAtr == L"name") + sAtrName = oIndexHtml.GetText(); + else if (sAtr == L"content") + sAtrContent = oIndexHtml.GetText(); + } + oIndexHtml.MoveToElement(); + + if (!sAtrName.empty()) + { + replace_all(sAtrContent, L"&", L"&"); + replace_all(sAtrContent, L"<", L"<"); + replace_all(sAtrContent, L">", L">"); + replace_all(sAtrContent, L"\"", L"""); + replace_all(sAtrContent, L"\'", L"'"); + + if (sAtrName == L"creator") + oTitleInfo.WriteString(L"" + sAtrContent + L""); + else if (sAtrName == L"description") + oTitleInfo.WriteString(L"

" + sAtrContent + L"

"); + else if (sAtrName == L"subject") + oTitleInfo.WriteString(L"" + sAtrContent + L""); + else if (sAtrName == L"keywords") + oTitleInfo.WriteString(L"" + sAtrContent + L""); + } + } else if (sName == L"h1") { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1620,7 +1664,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1628,7 +1672,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1636,7 +1680,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1644,7 +1688,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1652,7 +1696,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasP) oXml.WriteString(L"
<p>"); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"</p>
"); } @@ -1674,44 +1718,44 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o if (sAlign == L"super") { oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else if (sAlign == L"sub") { oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); } else - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); } else if (sName == L"s") { oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else if (sName == L"i") { oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else if (sName == L"b") { oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else if (sName == L"table") { if (!bWasTable) oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); if (!bWasTable) oXml.WriteString(L"
"); } @@ -1719,7 +1763,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o { if (!bWasTable) oXml.WriteString(L""); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); if (!bWasTable) oXml.WriteString(L""); } @@ -1738,7 +1782,7 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o oIndexHtml.MoveToElement(); oXml.WriteString(L">"); } - readStream(oXml, oIndexHtml, arrBinary, true, true); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, true); if (!bWasTable) oXml.WriteString(L""); } @@ -1757,13 +1801,13 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o oIndexHtml.MoveToElement(); oXml.WriteString(L">"); - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); oXml.WriteString(L""); } else if (sName == L"ul") - readLi(oXml, oIndexHtml, arrBinary, true, bWasP, bWasTable); + readLi(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasP, bWasTable); else if (sName == L"ol") - readLi(oXml, oIndexHtml, arrBinary, false, bWasP, bWasTable); + readLi(oXml, oTitleInfo, oIndexHtml, arrBinary, false, bWasP, bWasTable); else if (sName == L"img") { std::wstring sBinary; @@ -1780,8 +1824,8 @@ void readStream(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& o oXml.WriteString(L""); } else - readStream(oXml, oIndexHtml, arrBinary, bWasP, bWasTable); - } while (oIndexHtml.ReadNextSiblingNode2(nDeath)); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, bWasP, bWasTable); + } while (oIndexHtml.ReadNextSiblingNode2(nDepth)); } std::wstring ToUpperRoman(int number) @@ -1824,7 +1868,7 @@ std::wstring ToLowerRoman(int number) return L""; } -void readLi(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bUl, bool bWasP, bool bWasTable) +void readLi(NSStringUtils::CStringBuilder& oXml, NSStringUtils::CStringBuilder& oTitleInfo, XmlUtils::CXmlLiteReader& oIndexHtml, std::vector& arrBinary, bool bUl, bool bWasP, bool bWasTable) { int nNum = 1; while (oIndexHtml.MoveToNextAttribute()) @@ -1876,7 +1920,7 @@ void readLi(NSStringUtils::CStringBuilder& oXml, XmlUtils::CXmlLiteReader& oInde oXml.WriteString(sPoint); } oXml.WriteString(L" "); - readStream(oXml, oIndexHtml, arrBinary, true, bWasTable); + readStream(oXml, oTitleInfo, oIndexHtml, arrBinary, true, bWasTable); if (!bWasP) oXml.WriteString(L"

"); } @@ -1899,70 +1943,8 @@ std::wstring GenerateUUID() return sstream.str(); } -HRESULT CFb2File::FromHtml(const std::wstring& sHtmlFile, const std::wstring& sCoreFile, const std::wstring& sDst, const std::wstring& sInpTitle) +HRESULT CFb2File::FromHtml(const std::wstring& sHtmlFile, const std::wstring& sDst, const std::wstring& sInpTitle) { - NSStringUtils::CStringBuilder oDocument; - oDocument.WriteString(L""); - // description - // title-info - oDocument.WriteString(L""); - std::wstring sBookTitle = sInpTitle.empty() ? NSFile::GetFileName(sDst) : sInpTitle; - std::wstring sAuthor, sAnnotation, sKeywords, sGenre; - std::wstring sLanguage = L"en-EN", sVersion = L"1.0"; - std::wstring sIdentifier = GenerateUUID(); - XmlUtils::CXmlLiteReader oCoreReader; - oCoreReader.FromString(sCoreFile); - oCoreReader.ReadNextNode(); - int nDeath = oCoreReader.GetDepth(); - while (oCoreReader.ReadNextSiblingNode(nDeath)) - { - std::wstring sName = oCoreReader.GetName(); - std::wstring sText = oCoreReader.GetText2(); - if (!sText.empty()) - { - if (sName == L"dc:creator") - sAuthor = sText; - else if (sName == L"dc:title") - sBookTitle = sText; - else if (sName == L"dc:description") - sAnnotation = sText; - else if (sName == L"dc:subject") - sGenre = sText; - else if (sName == L"cp:keywords") - sKeywords = sText; - else if (sName == L"dc:identifier") - sIdentifier = sText; - else if (sName == L"dc:language") - sLanguage = sText; - else if (sName == L"cp:version") - sVersion = sText; - } - } - - oDocument.WriteString(L""); - oDocument.WriteString(sGenre); - oDocument.WriteString(L""); - oDocument.WriteString(sAuthor); - oDocument.WriteString(L""); - oDocument.WriteString(sBookTitle); - oDocument.WriteString(L""); - if (!sAnnotation.empty()) - oDocument.WriteString(L"

" + sAnnotation + L"

"); - if (!sKeywords.empty()) - oDocument.WriteString(L"" + sKeywords + L""); - oDocument.WriteString(L""); - oDocument.WriteString(sLanguage); - oDocument.WriteString(L"
"); - // document-info - oDocument.WriteString(sAuthor); - oDocument.WriteString(L""); - oDocument.WriteString(sIdentifier); - oDocument.WriteString(L""); - oDocument.WriteString(sVersion); - oDocument.WriteString(L""); - // body - oDocument.WriteString(L"
"); - BYTE* pData; DWORD nLength; if (!NSFile::CFileBinary::ReadAllBytes(sHtmlFile, &pData, nLength)) @@ -1985,30 +1967,46 @@ HRESULT CFb2File::FromHtml(const std::wstring& sHtmlFile, const std::wstring& sC RELEASEARRAYOBJECTS(pData); XmlUtils::CXmlLiteReader oIndexHtml; - std::vector arrBinary; std::wstring xhtml = htmlToXhtml(sContent, bNeedConvert); - if (oIndexHtml.FromString(xhtml)) - { - oIndexHtml.ReadNextNode(); // html - int nDepth = oIndexHtml.GetDepth(); - oIndexHtml.ReadNextSiblingNode(nDepth); // head - oIndexHtml.ReadNextSiblingNode(nDepth); // body - readStream(oDocument, oIndexHtml, arrBinary, false, false); - } - oDocument.WriteString(L"
"); + if (!oIndexHtml.FromString(xhtml)) + return S_FALSE; + + oIndexHtml.ReadNextNode(); // html + int nDepth = oIndexHtml.GetDepth(); + oIndexHtml.ReadNextSiblingNode(nDepth); // head + oIndexHtml.ReadNextSiblingNode(nDepth); // body + + std::vector arrBinary; + NSStringUtils::CStringBuilder oDocument; + NSStringUtils::CStringBuilder oTitleInfo; + readStream(oDocument, oTitleInfo, oIndexHtml, arrBinary, false, false); + + NSStringUtils::CStringBuilder oRes; + oRes.WriteString(L""); + // description title-info + oRes.WriteString(L""); + std::wstring sTitleInfo = oTitleInfo.GetData(); + if (sTitleInfo.find(L"") == std::wstring::npos) + oRes.WriteString(L"" + (sInpTitle.empty() ? NSFile::GetFileName(sDst) : sInpTitle) + L""); + oRes.WriteString(sTitleInfo); + oRes.WriteString(L""); + // body + oRes.WriteString(L"
"); + oRes.WriteString(oDocument.GetData()); + oRes.WriteString(L"
"); // binary for (size_t i = 0; i < arrBinary.size(); i++) { - oDocument.WriteString(L""); - oDocument.WriteString(arrBinary[i]); - oDocument.WriteString(L""); + oRes.WriteString(L""); + oRes.WriteString(arrBinary[i]); + oRes.WriteString(L""); } - oDocument.WriteString(L"
"); + oRes.WriteString(L"
"); // Запись в файл NSFile::CFileBinary oWriter; if (oWriter.CreateFileW(sDst)) { - oWriter.WriteStringUTF8(oDocument.GetData()); + oWriter.WriteStringUTF8(oRes.GetData()); oWriter.CloseFile(); } return S_OK; diff --git a/Fb2File/Fb2File.h b/Fb2File/Fb2File.h index 07e9cb701a..593df39aed 100644 --- a/Fb2File/Fb2File.h +++ b/Fb2File/Fb2File.h @@ -31,7 +31,7 @@ public: bool IsFb2File(const std::wstring& sFile); void SetTmpDirectory(const std::wstring& sFolder); HRESULT Open(const std::wstring& sPath, const std::wstring& sDirectory, CFb2Params* oParams = NULL); - HRESULT FromHtml(const std::wstring& sHtmlFile, const std::wstring& sCoreFile, const std::wstring& sDst, const std::wstring& sInpTitle); + HRESULT FromHtml(const std::wstring& sHtmlFile, const std::wstring& sDst, const std::wstring& sInpTitle); }; #endif // _FB2FILE_FB2FILE_H diff --git a/Fb2File/test/main.cpp b/Fb2File/test/main.cpp index 5ce34d4f6a..92ede2307c 100644 --- a/Fb2File/test/main.cpp +++ b/Fb2File/test/main.cpp @@ -16,7 +16,7 @@ void getDirectories(const std::wstring& sDirectory, std::vector& a int main() { bool bBatchMode = false; - bool bFromHtml = false; + bool bFromHtml = true; if (bBatchMode) { // Директория файлов @@ -98,11 +98,10 @@ int main() NSDirectory::DeleteDirectory(sOutputDirectory); NSDirectory::CreateDirectory(sOutputDirectory); - if (bFromHtml) { - sFile = NSFile::GetProcessDirectory() + L"/../../../examples/test3"; - oFile.FromHtml(sFile, sFile, sOutputDirectory + L"/res.fb2", L"Test Title"); + sFile = NSFile::GetProcessDirectory() + L"/../../../examples/test.html"; + oFile.FromHtml(sFile, sOutputDirectory + L"/res.fb2", L"Test Title"); return 0; } diff --git a/Fb2File/test/test.pro b/Fb2File/test/test.pro index 5302def068..5b246250e6 100644 --- a/Fb2File/test/test.pro +++ b/Fb2File/test/test.pro @@ -13,8 +13,7 @@ SOURCES += main.cpp CORE_ROOT_DIR = $$PWD/../../../core PWD_ROOT_DIR = $$PWD include($$CORE_ROOT_DIR/Common/base.pri) - -core_linux:include($$CORE_ROOT_DIR/Common/3dParty/icu/icu.pri) +include($$CORE_ROOT_DIR/Common/3dParty/icu/icu.pri) ADD_DEPENDENCY(kernel, Fb2File) diff --git a/MsBinaryFile/DocFile/CommentsMapping.cpp b/MsBinaryFile/DocFile/CommentsMapping.cpp index 09b1bedea3..c84604839a 100644 --- a/MsBinaryFile/DocFile/CommentsMapping.cpp +++ b/MsBinaryFile/DocFile/CommentsMapping.cpp @@ -121,7 +121,7 @@ namespace DocFileFormat { if ((m_document->AnnotationsReferencesEx) && (index < m_document->AnnotationsReferencesEx->m_ReferencesEx.size())) { - _paraId = XmlUtils::ToString(x++, L"%08X"); + _paraId = XmlUtils::ToString((unsigned int)(x++), L"%08X"); } cp = writeParagraph(cp, 0x7fffffff); } diff --git a/MsBinaryFile/DocFile/DocumentMapping.cpp b/MsBinaryFile/DocFile/DocumentMapping.cpp index 840a52ed5b..58bd8aabf7 100644 --- a/MsBinaryFile/DocFile/DocumentMapping.cpp +++ b/MsBinaryFile/DocFile/DocumentMapping.cpp @@ -733,9 +733,9 @@ namespace DocFileFormat if (oVmlMapper.m_isEmbedded) { - ole.isEquation = oVmlMapper.m_isEquation; - ole.isEmbedded = oVmlMapper.m_isEmbedded; - ole.emeddedData = oVmlMapper.m_embeddedData; + ole.isEquation = oVmlMapper.m_isEquation; + ole.isEmbedded = oVmlMapper.m_isEmbedded; + ole.embeddedData = oVmlMapper.m_embeddedData; } ole.Convert( &oleObjectMapping ); @@ -1037,9 +1037,9 @@ namespace DocFileFormat OleObject ole ( chpx, m_document); OleObjectMapping oleObjectMapping( &pictWriter, m_context, &oPicture, _caller, oVmlMapper.m_shapeId ); - ole.isEquation = oVmlMapper.m_isEquation; - ole.isEmbedded = oVmlMapper.m_isEmbedded; - ole.emeddedData = oVmlMapper.m_embeddedData; + ole.isEquation = oVmlMapper.m_isEquation; + ole.isEmbedded = oVmlMapper.m_isEmbedded; + ole.embeddedData = oVmlMapper.m_embeddedData; ole.Convert( &oleObjectMapping ); } diff --git a/MsBinaryFile/DocFile/OleObject.cpp b/MsBinaryFile/DocFile/OleObject.cpp index 670ee01f3f..99d42d74d8 100644 --- a/MsBinaryFile/DocFile/OleObject.cpp +++ b/MsBinaryFile/DocFile/OleObject.cpp @@ -37,7 +37,6 @@ namespace DocFileFormat { OleObject::OleObject( const CharacterPropertyExceptions* chpx, WordDocument* document) - : bLinked(false), updateMode(NoLink), isEquation(false), isEmbedded (false), oleStorage(NULL) { if (!document) return; if (!chpx) return; @@ -56,13 +55,14 @@ OleObject::OleObject( const CharacterPropertyExceptions* chpx, WordDocument* doc std::wstring name = L"ObjectPool/" + sObjectId + L"/"; bool bOle = processOleStream( name + L"Ole" ); - bool bCompObj = bLinked ? processLinkInfoStream( name + L"LinkInfo" ): + bool bCompObj = isLinked ? processLinkInfoStream( name + L"LinkInfo" ): processCompObjStream( name + L"CompObj" ); if (bOle || bCompObj) { processPICStream( name + L"PIC" ); processMETAStream( name + L"META" ); processEquationNativeStream( name + L"Equation Native" ); + processPackageStream(name + L"Package"); } else if (nWordVersion > 0) { @@ -98,16 +98,16 @@ OleObject::OleObject( const CharacterPropertyExceptions* chpx, WordDocument* doc //int lcb = 5000;//reader.ReadInt32(); int szHeader = reader.GetPosition() - pos; - int szData = reader.ReadInt32(); + size_t szData = reader.ReadInt32(); if (szData > lcb) { szData = szData >> 16; } - unsigned char* bytes = reader.ReadBytes( szData, true ); - if (bytes && szData < 0xffff) + char* bytes = (szData < 0xffff) ? (char*)reader.ReadBytes( szData, true ) : NULL; + if (bytes) { - emeddedData = std::string((char*)bytes, szData); - delete []bytes; + boost::shared_array buffer(bytes); + embeddedData = std::make_pair(buffer, szData); } } @@ -117,67 +117,89 @@ OleObject::OleObject( const CharacterPropertyExceptions* chpx, WordDocument* doc bool OleObject::processLinkInfoStream( const std::wstring& linkStream ) { + bool res = false; try { - POLE::Stream* pLinkStream = NULL; - HRESULT res = S_OK; + POLE::Stream* pLinkStream = new POLE::Stream(oleStorage, linkStream); - pLinkStream = new POLE::Stream(oleStorage, linkStream); - - if ( pLinkStream ) + if (( pLinkStream ) && (false == pLinkStream->fail())) { VirtualStreamReader reader( pLinkStream, 0, false); processLinkInfoStream(reader); delete pLinkStream; - return true; + res = true; } + if (pLinkStream) delete pLinkStream; } catch (...) { } - return false; + return res; } void OleObject::processEquationNativeStream( const std::wstring& eqStream ) { try { - POLE::Stream* pCompStream = NULL; - HRESULT res = S_OK; + POLE::Stream* pCompStream = new POLE::Stream(oleStorage, eqStream); - pCompStream = new POLE::Stream(oleStorage, eqStream); - - if ( pCompStream ) + if ((pCompStream) && (false == pCompStream->fail())) { - VirtualStreamReader reader( pCompStream, 0, false); + VirtualStreamReader reader(pCompStream, 0, false); - int sz = reader.GetSize(); + int sz = reader.GetSize(); - unsigned char *Buffer = reader.ReadBytes( sz, true ); + unsigned char *Buffer = reader.ReadBytes(sz, true); - if (Buffer && sz > 0) - { - isEquation = true; - delete []Buffer; - } - - delete pCompStream; + if (Buffer && sz > 0) + { + isEquation = true; + delete[]Buffer; + } } + if (pCompStream) delete pCompStream; } catch (...) { } } +bool OleObject::processPackageStream(const std::wstring& packageStream) +{ + bool res = true; + try + { + POLE::Stream* pPackageStream = new POLE::Stream(oleStorage, packageStream); + + if ((pPackageStream) && (false == pPackageStream->fail())) + { + VirtualStreamReader reader(pPackageStream, 0, false); + + size_t sz = reader.GetSize(); + + char* bytes = (sz < 0xffffff) ? (char*)reader.ReadBytes(sz, true) : NULL; + if (bytes) + { + boost::shared_array buffer(bytes); + embeddedData = std::make_pair(buffer, sz); + } + + isPackage = true; + } + if (pPackageStream) delete pPackageStream; + } + catch (...) + { + } + return res; +} void OleObject::processMETAStream( const std::wstring& metaStream ) { try { - HRESULT res = S_OK; - POLE::Stream* pMETAStream = new POLE::Stream(oleStorage, metaStream); - if ( pMETAStream ) + if (( pMETAStream ) && (false == pMETAStream->fail())) { pictureDesciptor.Type = wmf; VirtualStreamReader reader( pMETAStream, 0, false); @@ -190,6 +212,7 @@ void OleObject::processMETAStream( const std::wstring& metaStream ) pictureDesciptor.embeddedDataSize = reader.GetSize() - 8; pictureDesciptor.embeddedData = reader.ReadBytes( pictureDesciptor.embeddedDataSize, true ); } + if (pMETAStream) delete pMETAStream; } catch (...) { @@ -199,11 +222,9 @@ void OleObject::processPICStream( const std::wstring& picStream ) { try { - HRESULT res = S_OK; - POLE::Stream* pPICStream = new POLE::Stream(oleStorage, picStream); - if ( pPICStream ) + if ((pPICStream) && (false == pPICStream->fail())) { VirtualStreamReader reader( pPICStream, 0, false); @@ -266,26 +287,24 @@ void OleObject::processPICStream( const std::wstring& picStream ) bool OleObject::processCompObjStream( const std::wstring& compStream ) { + bool res = false; try { - HRESULT res = S_OK; - POLE::Stream* pCompStream = new POLE::Stream(oleStorage, compStream); - if ( (pCompStream) && (!pCompStream->fail()) ) + if ( (pCompStream) && (false == pCompStream->fail()) ) { VirtualStreamReader reader( pCompStream, 0, false); processCompObjStream(reader); - - delete pCompStream; - - return true; + + res = true; } + if (pCompStream) delete pCompStream; } catch (...) { } - return false; + return res; } bool OleObject::processOleStream( const std::wstring& oleStreamName ) @@ -316,12 +335,11 @@ bool OleObject::processOleStream( const std::wstring& oleStreamName ) void OleObject::processOleStream( VirtualStreamReader& reader ) { - //skip version - reader.ReadBytes( 4, false ); + reader.ReadBytes( 4, false ); //skip version //read the embedded/linked flag int flag = reader.ReadInt32(); - bLinked = FormatUtils::BitmaskToBool( flag, 0x1 ); + isLinked = FormatUtils::BitmaskToBool( flag, 0x1 ); //Link update option this->updateMode = (LinkUpdateOption)reader.ReadInt32(); diff --git a/MsBinaryFile/DocFile/OleObject.h b/MsBinaryFile/DocFile/OleObject.h index 5c3878117b..09d45ce983 100644 --- a/MsBinaryFile/DocFile/OleObject.h +++ b/MsBinaryFile/DocFile/OleObject.h @@ -49,7 +49,6 @@ namespace DocFileFormat OnCall = 3 }; int nWordVersion; - bool bLinked; // The the value is true, the object is a linked object std::wstring ObjectId; std::wstring ClassId; @@ -58,13 +57,15 @@ namespace DocFileFormat std::wstring ClipboardFormat; std::wstring Link; std::wstring Program; - LinkUpdateOption updateMode; + LinkUpdateOption updateMode = NoLink; std::wstring UpdateMode; - bool isEquation; - bool isEmbedded; + bool isLinked = false; + bool isEquation = false; + bool isEmbedded = false; + bool isPackage = false; - std::string emeddedData; + std::pair, size_t> embeddedData; PictureDescriptor pictureDesciptor; @@ -72,7 +73,7 @@ namespace DocFileFormat virtual ~OleObject() {} private: - POLE::Storage *oleStorage; + POLE::Storage *oleStorage = NULL; bool processLinkInfoStream ( const std::wstring& linkStream ); void processEquationNativeStream( const std::wstring& eqStream ); @@ -80,6 +81,7 @@ namespace DocFileFormat void processMETAStream ( const std::wstring& metaStream ); bool processCompObjStream ( const std::wstring& compStream ); bool processOleStream ( const std::wstring& oleStreamName ); + bool processPackageStream (const std::wstring& oleStreamName); void processOleStream ( VirtualStreamReader& reader ); void processLinkInfoStream ( VirtualStreamReader& reader ); diff --git a/MsBinaryFile/DocFile/OleObjectMapping.cpp b/MsBinaryFile/DocFile/OleObjectMapping.cpp index 0ee026de87..74356ae4f9 100644 --- a/MsBinaryFile/DocFile/OleObjectMapping.cpp +++ b/MsBinaryFile/DocFile/OleObjectMapping.cpp @@ -49,18 +49,18 @@ namespace DocFileFormat if ( ole != NULL ) { - if (ole->isEmbedded) + if (ole->isEmbedded || ole->isPackage) { - if (ole->isEquation) ole->ClipboardFormat = L"Equation"; - else ole->ClipboardFormat = L"MSWordDocx"; + if (ole->isEquation) ole->ClipboardFormat = L"Equation"; + else if (ole->ClipboardFormat.empty()) ole->ClipboardFormat = L"MSWordDocx"; - ole->Program = L"Word.Document"; + ole->Program = L"Word.Document"; } m_pXmlWriter->WriteNodeBegin( L"o:OLEObject", TRUE ); int relID = -1; - if ( ole->bLinked ) + if ( ole->isLinked) { relID = m_context->_docx->RegisterExternalOLEObject(_caller, ole->ClipboardFormat, ole->Link); @@ -69,7 +69,7 @@ namespace DocFileFormat } else { - if (ole->isEmbedded) + if (ole->isEmbedded || ole->isPackage) relID = m_context->_docx->RegisterPackage(_caller, ole->ClipboardFormat); else relID = m_context->_docx->RegisterOLEObject(_caller, ole->ClipboardFormat); @@ -162,9 +162,9 @@ namespace DocFileFormat object_descr.clsid = ole->ClipboardFormat; object_descr.bNativeOnly = true; } - if (ole->isEquation || ole->isEmbedded || ole->nWordVersion == 2) + if (ole->isEquation || ole->isEmbedded || ole->nWordVersion == 2 || ole->isPackage) { - object_descr.data = ole->emeddedData; + object_descr.data = ole->embeddedData; } m_context->_docx->OleObjectsList.push_back(object_descr); diff --git a/MsBinaryFile/DocFile/OpenXmlPackage.cpp b/MsBinaryFile/DocFile/OpenXmlPackage.cpp index 3562213bf1..8cb26b3a83 100644 --- a/MsBinaryFile/DocFile/OpenXmlPackage.cpp +++ b/MsBinaryFile/DocFile/OpenXmlPackage.cpp @@ -190,11 +190,11 @@ namespace DocFileFormat oStream2.flush(); //Ole10Native - size_t nativeDataSize = object.data.length(); + size_t nativeDataSize = object.data.second; POLE::Stream streamData(storageOut, L"\001Ole10Native", true, nativeDataSize + 4); streamData.write((BYTE*)&nativeDataSize, 4); - streamData.write((BYTE*)object.data.c_str(), nativeDataSize); + streamData.write((BYTE*)object.data.first.get(), nativeDataSize); streamData.flush(); storageOut->close(); @@ -205,7 +205,7 @@ namespace DocFileFormat { NSFile::CFileBinary file; file.CreateFileW(fileName); - file.WriteFile((BYTE*)object.data.c_str(), (_UINT32)object.data.size()); + file.WriteFile((BYTE*)object.data.first.get(), (_UINT32)object.data.second); file.CloseFile(); } return true; diff --git a/MsBinaryFile/DocFile/OpenXmlPackage.h b/MsBinaryFile/DocFile/OpenXmlPackage.h index 17cb3489ff..c38981156a 100644 --- a/MsBinaryFile/DocFile/OpenXmlPackage.h +++ b/MsBinaryFile/DocFile/OpenXmlPackage.h @@ -107,8 +107,8 @@ namespace DocFileFormat std::wstring ext; std::wstring objectID; std::wstring clsid; - - std::string data; + + std::pair, size_t> data; OleObjectFileStructure( const std::wstring& _ext, const std::wstring& _objectID, const std::wstring&/*REFCLSID*/ _clsid ): ext(_ext), objectID(_objectID), clsid(_clsid){} diff --git a/MsBinaryFile/DocFile/TableMapping.cpp b/MsBinaryFile/DocFile/TableMapping.cpp index 64a9b5313a..dde86009d8 100644 --- a/MsBinaryFile/DocFile/TableMapping.cpp +++ b/MsBinaryFile/DocFile/TableMapping.cpp @@ -314,8 +314,10 @@ namespace DocFileFormat { } - bool Table::IsCellMarker(int _cp) + bool Table::IsCellMarker(int _cp, bool & bBadMarker) { + bBadMarker = false; + if ( _cp > documentMapping->m_document->Text->size() - 1) return false; int fc = documentMapping->m_document->FindFileCharPos(_cp); @@ -337,7 +339,12 @@ namespace DocFileFormat ParagraphPropertyExceptions* papx_1 = documentMapping->findValidPapx(fc_1); ParagraphPropertyExceptions* papx_2 = documentMapping->findValidPapx(fc_2); - return (papx_1 != papx_2); + if (papx_1 == papx_2) + { + bBadMarker = true; + return false; + } + return true; } return false; @@ -379,8 +386,9 @@ namespace DocFileFormat TableInfo tai( papx, documentMapping->m_document->nWordVersion ); + bool bBadMarker = false; return ( ( tai.fInTable ) && ( documentMapping->m_document->Text->at( _cp ) == 0x000D ) && - ( !IsCellMarker( _cp ) ) && ( !IsRowMarker( _cp ) ) ); + ( !IsCellMarker( _cp, bBadMarker) ) && ( !IsRowMarker( _cp ) ) ); } Table::Table( DocumentMapping* _documentMapping, int _cp, unsigned int _depth ): @@ -434,7 +442,8 @@ namespace DocFileFormat } else { - if ( IsCellMarker( _cp ) ) + bool bBadMarker = false; + if ( IsCellMarker( _cp, bBadMarker) ) { lastCellCP = _cp; tableCell.SetCP( _cp ); @@ -465,12 +474,11 @@ namespace DocFileFormat tableRow.Clear(); paragraphBeginCP++; } - else if ( IsParagraphMarker( _cp ) ) + else if ( !bBadMarker && IsParagraphMarker( _cp ) ) { tableCell.AddItem( DocParagraph( documentMapping, paragraphBeginCP, _cp ) ); paragraphBeginCP = ( _cp + 1 ); } - _cp++; } } diff --git a/MsBinaryFile/DocFile/TableMapping.h b/MsBinaryFile/DocFile/TableMapping.h index 44a66ce81f..ea21d68f93 100644 --- a/MsBinaryFile/DocFile/TableMapping.h +++ b/MsBinaryFile/DocFile/TableMapping.h @@ -122,7 +122,7 @@ namespace DocFileFormat protected: - bool IsCellMarker( int _cp ); + bool IsCellMarker( int _cp, bool & bBadMarker); bool IsRowMarker( int _cp ); bool IsParagraphMarker( int _cp ); diff --git a/MsBinaryFile/DocFile/VMLPictureMapping.cpp b/MsBinaryFile/DocFile/VMLPictureMapping.cpp index 5e7c23fd11..d9f2585eca 100644 --- a/MsBinaryFile/DocFile/VMLPictureMapping.cpp +++ b/MsBinaryFile/DocFile/VMLPictureMapping.cpp @@ -163,9 +163,11 @@ namespace DocFileFormat return true; } - bool VMLPictureMapping::ParseEmbeddedEquation( const std::string & xmlString, std::wstring & newXmlString) + bool VMLPictureMapping::ParseEmbeddedEquation(std::pair, size_t> & data, std::wstring & xmlString) { - newXmlString.clear(); + xmlString.clear(); + + if (data.second == 0 || !data.first) return false; std::wstring sTempFolder = m_context->_doc->m_sTempFolder; if (sTempFolder.empty()) @@ -177,7 +179,7 @@ namespace DocFileFormat NSFile::CFileBinary file; file.CreateFileW(sTempXmlFile); - file.WriteFile((BYTE*)xmlString.c_str(), xmlString.size()); + file.WriteFile((BYTE*)data.first.get(), data.second); file.CloseFile(); OOX::CPath path(sTempXmlFile); @@ -190,13 +192,13 @@ namespace DocFileFormat { OOX::Logic::CParagraph *paragraph = dynamic_cast(*it); - for (std::vector::iterator jt = paragraph->m_arrItems.begin(); - (paragraph) && (jt != paragraph->m_arrItems.end()); jt++) + for (std::vector::iterator jt = paragraph->m_arrItems.begin(); + (paragraph) && (jt != paragraph->m_arrItems.end()); jt++) { if ((*jt)->getType() == OOX::et_m_oMath) { res = true; - newXmlString = (*jt)->toXML(); + xmlString = (*jt)->toXML(); break; } else if ((*jt)->getType() == OOX::et_m_oMathPara) @@ -209,7 +211,7 @@ namespace DocFileFormat if ((*kt)->getType() == OOX::et_m_oMath) { res = true; - newXmlString = (*kt)->toXML(); + xmlString = (*kt)->toXML(); break; } } @@ -240,11 +242,6 @@ namespace DocFileFormat m_caller = caller; m_isInlinePicture = isInlinePicture; m_inGroup = inGroup; - - m_isBullete = false; - m_isEquation = false; - m_isEmbedded = false; - m_isBlob = false; m_imageData = new XMLTools::XMLElement( L"v:imagedata" ); } diff --git a/MsBinaryFile/DocFile/VMLPictureMapping.h b/MsBinaryFile/DocFile/VMLPictureMapping.h index bb079d81ca..65e999ffde 100644 --- a/MsBinaryFile/DocFile/VMLPictureMapping.h +++ b/MsBinaryFile/DocFile/VMLPictureMapping.h @@ -57,7 +57,7 @@ namespace DocFileFormat /// Writes a border element void writePictureBorder (const std::wstring & name, const BorderCode* brc); void appendStyleProperty( std::wstring& style, const std::wstring& propName, const std::wstring& propValue ) const; - bool ParseEmbeddedEquation( const std::string & xmlString, std::wstring & newXmlString ); + bool ParseEmbeddedEquation(std::pair, size_t> & data, std::wstring & xmlString ); bool ParseEmbeddedBlob(const std::string & xmlString, std::wstring & newXmlString); std::wstring GetShapeID(const Shape* pShape) const; protected: @@ -70,25 +70,27 @@ namespace DocFileFormat static std::wstring GetTargetExt (Global::BlipType nType); static std::wstring GetContentType (Global::BlipType nType); - bool m_isBlob; - bool m_isBullete; - bool m_isEquation; - bool m_isEmbedded; - bool m_isPictureBroken; - std::string m_embeddedData; - std::wstring m_equationXml; - std::wstring m_blobXml; + bool m_isBlob = false; + bool m_isBullete = false; + bool m_isEquation = false; + bool m_isEmbedded = false; + bool m_isPictureBroken = false; - std::wstring m_shapeId; + std::pair, size_t> m_embeddedData; + + std::wstring m_equationXml; + std::wstring m_blobXml; + + std::wstring m_shapeId; private: ConversionContext* m_context; IMapping* m_caller; int m_nImageId; - bool m_isOlePreview; - bool m_isInlinePicture; - bool m_inGroup; + bool m_isOlePreview = false; + bool m_isInlinePicture = false; + bool m_inGroup = false; XMLTools::XMLElement* m_imageData; diff --git a/MsBinaryFile/DocFile/WordprocessingDocument.cpp b/MsBinaryFile/DocFile/WordprocessingDocument.cpp index 5c9b64aeb4..889fb37c31 100644 --- a/MsBinaryFile/DocFile/WordprocessingDocument.cpp +++ b/MsBinaryFile/DocFile/WordprocessingDocument.cpp @@ -168,7 +168,7 @@ namespace DocFileFormat { std::wstring fileName = pathObjects + FILE_SEPARATOR_STR + L"oleObject" + FormatUtils::IntToWideString(i++) + iter->ext; - if (!iter->data.empty()) + if (iter->data.second > 0) { SaveEmbeddedObject(fileName, *iter); } diff --git a/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.cpp b/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.cpp index 2276da36ba..a6f53717e6 100644 --- a/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.cpp +++ b/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.cpp @@ -35,44 +35,78 @@ namespace PPT { - namespace Intermediate - { - CRecordPP10SlideBinaryTagExtension* getPP10SlideBinaryTagExtension(CRecordSlide *pSlide) - { - CRecordSlideProgTagsContainer* progTag = pSlide->m_pSlideProgTagsContainer; - return progTag ? progTag->getPP10SlideBinaryTagExtension() : nullptr; - } - - std::vector getOldSlideAnimation(CRecordSlide *pSlide) - { - std::vector arrShapeCont; - pSlide->GetRecordsByType(&arrShapeCont, true); - - std::vector listOfRawAnimIC; - for (auto* pShapeCont : arrShapeCont) - { - std::vector shape; - pShapeCont->GetRecordsByType(&shape, true); - std::vector anim; - pShapeCont->GetRecordsByType(&anim, true); - SOldAnimation animIC; - if (!anim.empty() && !shape.empty()) - { - animIC.shapeId = shape[0]->m_nID; - animIC.anim = anim[0]; - listOfRawAnimIC.push_back(animIC); - } - } - - return listOfRawAnimIC; - } - SlideAnimation ParseSlideAnimation(CRecordSlide *pSlide) - { - SlideAnimation slideAnim; - slideAnim.arrAnim_1995 = getOldSlideAnimation(pSlide); - slideAnim.pAnim_2010 = getPP10SlideBinaryTagExtension(pSlide); - - return slideAnim; - } - } +namespace Intermediate +{ +CRecordPP10SlideBinaryTagExtension* getPP10SlideBinaryTagExtension(CRecordSlide *pSlide) +{ + CRecordSlideProgTagsContainer* progTag = pSlide->m_pSlideProgTagsContainer; + return progTag ? progTag->getPP10SlideBinaryTagExtension() : nullptr; +} + +std::vector getOldSlideAnimation(CRecordSlide *pSlide) +{ + std::vector arrShapeCont; + pSlide->GetRecordsByType(&arrShapeCont, true); + + std::vector listOfRawAnimIC; + for (auto* pShapeCont : arrShapeCont) + { + std::vector shape; + pShapeCont->GetRecordsByType(&shape, true); + std::vector anim; + pShapeCont->GetRecordsByType(&anim, true); + SOldAnimation animIC; + if (!anim.empty() && !shape.empty()) + { + animIC.shapeId = shape[0]->m_nID; + animIC.anim = anim[0]; + listOfRawAnimIC.push_back(animIC); + } + } + + return listOfRawAnimIC; +} + +void AddElementMetadataToSlideAnim(SlideAnimation& anim, CElementPtr element) +{ + if (!element) + return; + + auto id = element->m_lID; + anim.realShapesIds.insert(id); + + auto type = element->m_etType; + if (type == PPT::etPicture || type == PPT::etAudio || type == PPT::etVideo) + anim.nonTextShapes.insert(id); +} + +void ParseShapes(CSlide *pSlide, SlideAnimation& anim) +{ + CGroupElement *pGroupElement = !pSlide->m_arElements.empty() ? dynamic_cast(pSlide->m_arElements[0].get()) : NULL; + + size_t start_index = 0; + + if (pGroupElement) + { + for (size_t i = 0; i < pGroupElement->m_pChildElements.size(); ++i) + AddElementMetadataToSlideAnim(anim, pGroupElement->m_pChildElements[i]); + + start_index = 1; + } + + for (size_t i = start_index; i < pSlide->m_arElements.size(); ++i) + AddElementMetadataToSlideAnim(anim, pSlide->m_arElements[i]); + + return; +} +SlideAnimation ParseSlideAnimation(CRecordSlide *pSlideRecord, CSlide *pCSlide) +{ + SlideAnimation slideAnim; + slideAnim.arrAnim_1995 = getOldSlideAnimation(pSlideRecord); + slideAnim.pAnim_2010 = getPP10SlideBinaryTagExtension(pSlideRecord); + ParseShapes(pCSlide, slideAnim); + + return slideAnim; +} +} } diff --git a/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.h b/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.h index 780d2ed89c..939ffd6203 100644 --- a/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.h +++ b/MsBinaryFile/PptFile/Converter/Animation/AnimationParser.h @@ -36,7 +36,8 @@ namespace PPT { +class CSlide; namespace Intermediate { - SlideAnimation ParseSlideAnimation(CRecordSlide* pSlide); + SlideAnimation ParseSlideAnimation(CRecordSlide* pSlideRecord, CSlide* pCSlide); } } diff --git a/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.cpp b/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.cpp index 9d9d82f6d6..5ee6b5c7af 100644 --- a/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.cpp +++ b/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.cpp @@ -41,9 +41,8 @@ namespace PPT { namespace Converter { -Timing_2010::Timing_2010(CRecordPP10SlideBinaryTagExtension *pAnim_2010, const std::unordered_set &shapesID) : - pTagExtAnim(pAnim_2010), - slideShapes(shapesID) +Timing_2010::Timing_2010(const Intermediate::SlideAnimation &sldAnim) : + slideAnim(sldAnim) {} void Timing_2010::Convert(PPTX::Logic::Timing &timing, CExMedia *pExMedia, CRelsGenerator *pRels) @@ -52,6 +51,7 @@ void Timing_2010::Convert(PPTX::Logic::Timing &timing, CExMedia *pExMedia, CRels m_pRels = pRels; + auto* pTagExtAnim = slideAnim.pAnim_2010; if (pTagExtAnim == nullptr || pTagExtAnim->m_haveExtTime == false) return; @@ -76,8 +76,8 @@ void Timing_2010::ConvertBldLst(PPTX::Logic::Timing &timimg, CRecordBuildListCon PPTX::Logic::BuildNodeBase oBuildNodeBase; auto* pSub = dynamic_cast(pDBC); if (pSub == nullptr) - continue; - if (slideShapes.count(pSub->buildAtom.m_nShapeIdRef) == false) + throw TimingExeption("Cannot read BuildListSubContainer"); + if (IsCorrectAnimationSpId(pSub->buildAtom.m_nShapeIdRef) == false) continue; FillBuildNodeBase(pSub, oBuildNodeBase); @@ -396,33 +396,7 @@ void Timing_2010::FillCBhvr(CRecordTimeBehaviorContainer *pBhvr, PPTX::Logic::CB } } - if (pBhvr->m_oClientVisualElement.m_bVisualShapeAtom) - { - UINT spid = pBhvr-> - m_oClientVisualElement. - m_oVisualShapeAtom.m_nObjectIdRef; - - if (!oBhvr.tgtEl.spTgt.IsInit()) - { - oBhvr.tgtEl.spTgt = new PPTX::Logic::SpTgt; - oBhvr.tgtEl.spTgt->spid = std::to_wstring(spid); - } - - if (m_currentBldP) - { - m_currentBldP->spid = - oBhvr.tgtEl.spTgt->spid; - } - if (pBhvr->m_oClientVisualElement.m_oVisualShapeAtom.m_nData2 != 0xFFFFFFFF && - pBhvr->m_oClientVisualElement.m_oVisualShapeAtom.m_nData1 != 0xFFFFFFFF) - { - oBhvr.tgtEl.spTgt->txEl = new PPTX::Logic::TxEl; - oBhvr.tgtEl.spTgt->txEl->charRg = false; - oBhvr.tgtEl.spTgt->txEl->st = pBhvr->m_oClientVisualElement.m_oVisualShapeAtom.m_nData1; - oBhvr.tgtEl.spTgt->txEl->end = pBhvr->m_oClientVisualElement.m_oVisualShapeAtom.m_nData2; - } - } - + FillTgtEl(oBhvr.tgtEl, pBhvr->m_oClientVisualElement); if (pBhvr->m_pPropertyList == nullptr) return; @@ -464,6 +438,61 @@ void Timing_2010::FillCBhvr(CRecordTimeBehaviorContainer *pBhvr, PPTX::Logic::CB } } +bool Timing_2010::isTextShape(UINT spid) const +{ + return slideAnim.nonTextShapes.find(spid) == slideAnim.nonTextShapes.end(); +} + +void Timing_2010::FillTgtEl(PPTX::Logic::TgtEl &tgtEl, CRecordClientVisualElementContainer& clientVisualElement) +{ + if (!clientVisualElement.m_bVisualShapeAtom) + return; + + if (clientVisualElement.m_oVisualShapeAtom.m_RefType != TL_ET_ShapeType) + return; // todo insert next types here + + UINT spid = clientVisualElement. + m_oVisualShapeAtom.m_nObjectIdRef; + + if (!tgtEl.spTgt.IsInit()) + { + tgtEl.spTgt = new PPTX::Logic::SpTgt; + tgtEl.spTgt->spid = std::to_wstring(spid); + } + + if (m_currentBldP) + { + m_currentBldP->spid = + tgtEl.spTgt->spid; + } + + auto& vsa = clientVisualElement.m_oVisualShapeAtom; + if (vsa.m_Type == TL_TVET_TextRange && + vsa.m_nData1 != 0xffffffff && vsa.m_nData2 != 0xffffffff && + isTextShape(spid)) + { + tgtEl.spTgt->txEl = new PPTX::Logic::TxEl; + tgtEl.spTgt->txEl->charRg = false; + tgtEl.spTgt->txEl->st = clientVisualElement.m_oVisualShapeAtom.m_nData1; + tgtEl.spTgt->txEl->end = clientVisualElement.m_oVisualShapeAtom.m_nData2; + } else if (clientVisualElement.m_oVisualShapeAtom.m_Type == TL_TVET_ChartElement) + { + tgtEl.spTgt->type = new PPTX::Limit::TLChartSubElement; + std::wstring chartBA; + switch (clientVisualElement.m_oVisualShapeAtom.m_nData1) { + case 0: chartBA = L"gridLegend"; break; + case 1: chartBA = L"series"; break; + case 2: chartBA = L"category"; break; + case 3: chartBA = L"ptInSeries"; break; + case 4: chartBA = L"ptInCategory"; break; + case 5: chartBA = L"gridLegend"; break; + } + tgtEl.spTgt->type->set(chartBA); + if (clientVisualElement.m_oVisualShapeAtom.m_nData2) + tgtEl.spTgt->lvl = clientVisualElement.m_oVisualShapeAtom.m_nData2; + } +} + void Timing_2010::FillCBhvr(PPTX::Logic::CBhvr &oBhvr, int dur, UINT spid, std::wstring attrname, int delay) { oBhvr.cTn.id = cTnId++; @@ -621,15 +650,30 @@ void Timing_2010::FillCTnRecursive(CRecordExtTimeNodeContainer *pETNC, PPTX::Log bool Timing_2010::CheckAnimation5Level(const CRecordExtTimeNodeContainer *pETNC, const PPTX::Logic::CTn &oCTn) { auto anim_2010 = Intermediate::ParseExisting5Level_ETNC(pETNC); - bool isSlideShape = IsSlideSpId(anim_2010.spid); + bool isSlideShape = CheckSlideSpid(anim_2010.spid); + bool isSyncWithAnim95 = CheckMainSeqSyncWithAnim95(anim_2010.spid); + return isSlideShape && isSyncWithAnim95; +} + +bool Timing_2010::CheckSlideSpid(_INT32 spid) +{ + bool isSlideShape = IsSlideSpId(spid); if (isSlideShape) - InsertAnimationSpId(anim_2010.spid); + InsertAnimationSpId(spid); return isSlideShape; } bool Timing_2010::IsSlideSpId(_INT32 spid) const { - return slideShapes.find(spid) != slideShapes.end(); + return slideAnim.realShapesIds.find(spid) != slideAnim.realShapesIds.end(); +} + +bool Timing_2010::CheckMainSeqSyncWithAnim95(_INT32 spid) const +{ + if (!isMainSeq) + return true; + + return true; } bool Timing_2010::IsCorrectAnimationSpId(_INT32 spid) const @@ -787,7 +831,7 @@ void Timing_2010::ConvertCTnStCondLst(CRecordExtTimeNodeContainer *pETNC, PPTX:: void Timing_2010::FillCond(CRecordTimeConditionContainer *oldCond, PPTX::Logic::Cond &cond) { - if (oldCond->m_oTimeConditionAtom.m_nTimeDelay != -1) + if (oldCond->m_oTimeConditionAtom.m_nTimeDelay != 0xFFFFFFFF) cond.delay = std::to_wstring(oldCond->m_oTimeConditionAtom.m_nTimeDelay); else cond.delay = L"indefinite"; @@ -1111,7 +1155,7 @@ void Timing_2010::FillCTnHeadArgs(CRecordExtTimeNodeContainer *pETNC, PPTX::Logi // Write dur if (oTimeNodeAtom.m_fDurationProperty) { - if (oTimeNodeAtom.m_nDuration == -1) + if (oTimeNodeAtom.m_nDuration == 0xFFFFFFFF) oCTn.dur = L"indefinite"; else oCTn.dur = std::to_wstring(oTimeNodeAtom.m_nDuration); diff --git a/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.h b/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.h index 7f03f8c471..b1d001db79 100644 --- a/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.h +++ b/MsBinaryFile/PptFile/Converter/Animation/Timing_2010.h @@ -64,7 +64,7 @@ namespace PPT { class Timing_2010 { public: - Timing_2010(CRecordPP10SlideBinaryTagExtension* pAnim_2010, const std::unordered_set& shapesID); + Timing_2010(const Intermediate::SlideAnimation& sldAnim); void Convert(PPTX::Logic::Timing& timing, CExMedia* pExMedia, CRelsGenerator* pRels); public: @@ -100,6 +100,8 @@ namespace PPT { void FillCBhvr( CRecordTimeBehaviorContainer *pBhvr, PPTX::Logic::CBhvr &oBhvr); + bool isTextShape(UINT spid) const; + void FillTgtEl(PPTX::Logic::TgtEl& tgtEl, CRecordClientVisualElementContainer &clientVisualElement); void FillCBhvr( PPTX::Logic::CBhvr &oBhvr, int dur, UINT spid, std::wstring attrname, int delay); @@ -112,7 +114,9 @@ namespace PPT { void FillCTnRecursive(CRecordExtTimeNodeContainer *pETNC, PPTX::Logic::CTn &oCTn); bool CheckAnimation5Level(const CRecordExtTimeNodeContainer *pETNC, const PPTX::Logic::CTn &oCTn); - bool IsSlideSpId(_INT32 spid) const; + bool CheckSlideSpid(_INT32 spid); + bool IsSlideSpId(_INT32 spid) const; + bool CheckMainSeqSyncWithAnim95(_INT32 spid) const; bool IsCorrectAnimationSpId(_INT32 spid) const; void InsertAnimationSpId(_INT32 spid); void ConvertChildTnLst(CRecordExtTimeNodeContainer *pETNC, PPTX::Logic::CTn &oCTn); @@ -157,9 +161,8 @@ namespace PPT { PPTX::Logic::Video &oVideo); private: - CRecordPP10SlideBinaryTagExtension* pTagExtAnim = nullptr; - const std::unordered_set slideShapes; - std::unordered_set correctAnimatedShapes; + const Intermediate::SlideAnimation& slideAnim; + std::unordered_set correctAnimatedShapes; CExMedia *m_pExMedia = nullptr; CRelsGenerator *m_pRels = nullptr; bool isMainSeq = false; @@ -168,7 +171,7 @@ namespace PPT { PPTX::Logic::BldP *m_currentBldP = nullptr; int cTnId = 1; - int cTNLevel = TimeNodeLevel::zero; + int cTNLevel = TimeNodeLevel::zero; }; } diff --git a/MsBinaryFile/PptFile/Converter/Animation/intermediate_anim.h b/MsBinaryFile/PptFile/Converter/Animation/intermediate_anim.h index 782ba19ba3..c110ba4312 100644 --- a/MsBinaryFile/PptFile/Converter/Animation/intermediate_anim.h +++ b/MsBinaryFile/PptFile/Converter/Animation/intermediate_anim.h @@ -71,6 +71,7 @@ namespace PPT CRecordPP10SlideBinaryTagExtension* pAnim_2010 = nullptr; std::vector arrAnim_1995; std::unordered_set<_INT32> realShapesIds; + std::unordered_set<_INT32> nonTextShapes; }; } } diff --git a/MsBinaryFile/PptFile/Converter/timing.cpp b/MsBinaryFile/PptFile/Converter/timing.cpp index 18c40d53d6..fcd53ea390 100644 --- a/MsBinaryFile/PptFile/Converter/timing.cpp +++ b/MsBinaryFile/PptFile/Converter/timing.cpp @@ -40,9 +40,8 @@ using namespace PPT::Converter; -Timing::Timing(const PPT::Intermediate::SlideAnimation& slideAnim, const std::unordered_set &shapesID) : - slideAnim(slideAnim), - shapesID(shapesID) +Timing::Timing(const PPT::Intermediate::SlideAnimation& slideAnim) : + slideAnim(slideAnim) {} PPTX::Logic::Timing Timing::Convert(PPT::CExMedia *pExMedia, CRelsGenerator *pRels) @@ -72,7 +71,7 @@ bool Timing::TryToConvertTiming2010() { timing = PPTX::Logic::Timing(); try { - Timing_2010(slideAnim.pAnim_2010, shapesID). + Timing_2010(slideAnim). Convert(timing, pExMedia, pRels); } catch (const TimingExeption &ex) { return false; diff --git a/MsBinaryFile/PptFile/Converter/timing.h b/MsBinaryFile/PptFile/Converter/timing.h index 9b4a248157..3798bf2c4c 100644 --- a/MsBinaryFile/PptFile/Converter/timing.h +++ b/MsBinaryFile/PptFile/Converter/timing.h @@ -40,7 +40,7 @@ namespace PPT { class Timing { public: - Timing(const Intermediate::SlideAnimation& slideAnim, const std::unordered_set& shapesID); + Timing(const Intermediate::SlideAnimation& slideAnim); PPTX::Logic::Timing Convert(CExMedia* pExMedia, CRelsGenerator *pRels); bool HasAnimation() const; @@ -52,8 +52,7 @@ namespace PPT { private: const Intermediate::SlideAnimation& slideAnim; CExMedia* pExMedia; - CRelsGenerator* pRels; - const std::unordered_set shapesID; + CRelsGenerator* pRels; PPTX::Logic::Timing timing; }; } diff --git a/MsBinaryFile/PptFile/Drawing/Attributes.h b/MsBinaryFile/PptFile/Drawing/Attributes.h index 05a1374699..4ffe29f052 100644 --- a/MsBinaryFile/PptFile/Drawing/Attributes.h +++ b/MsBinaryFile/PptFile/Drawing/Attributes.h @@ -322,7 +322,7 @@ public: BYTE B; BYTE A; - LONG m_lSchemeIndex; + _INT32 m_lSchemeIndex; CColor() { @@ -382,7 +382,7 @@ public: if (lBGR & 0xFF000000) m_lSchemeIndex = R; } - void SetBGR(const LONG& lBGR) + void SetBGR(const _INT32& lBGR) { R = (BYTE)(lBGR); G = (BYTE)(lBGR >> 8); @@ -411,18 +411,18 @@ public: return ((color1.R == color2.R) && (color1.G == color2.G) && (color1.B == color2.B)); } - LONG GetLONG() const + _INT32 GetLONG() const { - LONG dwColor = 0; + _INT32 dwColor = 0; dwColor |= R; dwColor |= (G << 8); dwColor |= (B << 16); return dwColor; } - LONG GetLONG_RGB() const + _INT32 GetLONG_RGB() const { - LONG dwColor = 0; + _INT32 dwColor = 0; dwColor |= B; dwColor |= (G << 8); dwColor |= (R << 16); @@ -525,7 +525,7 @@ public: double DashOffset; - LONG Align; + _INT32 Align; double MiterLimit; CColor Color2; //backLine @@ -588,7 +588,7 @@ public: pRenderer->put_PenColor(Color.GetLONG()); else { - LONG lColor = Color.GetLONG(); + _INT32 lColor = Color.GetLONG(); lColor |= (0xFF000000 & ((Color.m_lSchemeIndex + 1 + 100) << 24)); pRenderer->put_PenColor(lColor); } @@ -703,7 +703,7 @@ public: std::vector> ColorsPosition; - inline LONG ConstantCompatible(LONG nConstant) + inline _INT32 ConstantCompatible(_INT32 nConstant) { if( c_BrushTypeDiagonal1_ == nConstant ) nConstant = c_BrushTypeDiagonal2_; @@ -873,7 +873,7 @@ public: pRenderer->put_BrushColor1(Color1.GetLONG()); else { - LONG lColor = Color1.GetLONG(); + _INT32 lColor = Color1.GetLONG(); lColor |= (0xFF000000 & ((Color1.m_lSchemeIndex + 1 + 100) << 24)); pRenderer->put_BrushColor1(lColor); } @@ -897,7 +897,7 @@ public: pRenderer->put_BrushColor1(Color1.GetLONG()); else { - LONG lColor = Color1.GetLONG(); + _INT32 lColor = Color1.GetLONG(); lColor |= (0xFF000000 & ((Color1.m_lSchemeIndex + 1 + 100) << 24)); pRenderer->put_BrushColor1(lColor); } @@ -945,9 +945,9 @@ public: (Bold == pFont->Bold) && (Italic == pFont->Italic)); } - LONG GetStyle() const + _INT32 GetStyle() const { - LONG lStyle = 0; + _INT32 lStyle = 0; if (Bold) lStyle |= 0x01; if (Italic) @@ -956,7 +956,7 @@ public: lStyle |= Strikeout << 7; return lStyle; } - void SetStyle(LONG const& lStyle) + void SetStyle(_INT32 const& lStyle) { Bold = (0x01 == (0x01 & lStyle)); Italic = (0x02 == (0x02 & lStyle)); diff --git a/MsBinaryFile/PptFile/Drawing/Structures.h b/MsBinaryFile/PptFile/Drawing/Structures.h index 62e8aa5c61..b07b359953 100644 --- a/MsBinaryFile/PptFile/Drawing/Structures.h +++ b/MsBinaryFile/PptFile/Drawing/Structures.h @@ -39,7 +39,7 @@ typedef std::vector vector_string; namespace ODRAW { - static void CorrectColorPPT(LONG& lSchemeIndex) + static void CorrectColorPPT(_INT32& lSchemeIndex) { //0x00 //Background color //0x01 //Text color @@ -102,24 +102,24 @@ namespace ODRAW struct SPointAtom { - LONG X; - LONG Y; + _INT32 X; + _INT32 Y; }; struct SRectAtom { - LONG Left; - LONG Top; - LONG Right; - LONG Bottom; + _INT32 Left; + _INT32 Top; + _INT32 Right; + _INT32 Bottom; }; struct SSmallRectAtom { - SHORT Left; - SHORT Top; - SHORT Right; - SHORT Bottom; + _INT16 Left; + _INT16 Top; + _INT16 Right; + _INT16 Bottom; }; struct SColorAtom diff --git a/MsBinaryFile/PptFile/PPTXWriter/Converter.cpp b/MsBinaryFile/PptFile/PPTXWriter/Converter.cpp index 5c69a4f92d..5512990e2a 100644 --- a/MsBinaryFile/PptFile/PPTXWriter/Converter.cpp +++ b/MsBinaryFile/PptFile/PPTXWriter/Converter.cpp @@ -670,6 +670,18 @@ bool CPPTXWriter::HasRoundTrips() const if (m_pDocument->m_pNotesMaster && arrRTNotes.empty()) return false; + if (m_pDocument->m_pHandoutMaster) + { + for (const auto& oIterSlide : m_pUserInfo->m_mapHandoutMasters) + { + std::vector arrRTTheme; + oIterSlide.second->GetRecordsByType(&arrRTTheme, false, true); + if (arrRTTheme.empty()) + return false; + } + } + + return arrRTTheme.size() && arrRTLayouts.size(); } @@ -1549,7 +1561,6 @@ void CPPTXWriter::WriteSlide(int nIndexSlide) CGroupElement *pGroupElement = !pSlide->m_arElements.empty() ? dynamic_cast(pSlide->m_arElements[0].get()) : NULL; size_t start_index = 0; - std::unordered_set realShapesId; // todo Wrap in context when code is restructured if (pGroupElement) { @@ -1557,8 +1568,6 @@ void CPPTXWriter::WriteSlide(int nIndexSlide) { auto& element = pGroupElement->m_pChildElements[i]; WriteElement(oWriter, oRels, element); - if (element) - realShapesId.insert(element->m_lID); } start_index = 1; @@ -1568,8 +1577,6 @@ void CPPTXWriter::WriteSlide(int nIndexSlide) { auto& element = pSlide->m_arElements[i]; WriteElement(oWriter, oRels, element); - if (element) - realShapesId.insert(element->m_lID); } oWriter.WriteString(std::wstring(L"")); @@ -1579,7 +1586,7 @@ void CPPTXWriter::WriteSlide(int nIndexSlide) WriteTransition(oWriter, pSlide->m_oSlideShow); // TODO write new method and class for timing - WriteTiming(oWriter, oRels, nIndexSlide, realShapesId); + WriteTiming(oWriter, oRels, nIndexSlide); oWriter.WriteString(std::wstring(L"")); @@ -1875,13 +1882,14 @@ void CPPTXWriter::WriteLayoutAfterTheme(CThemePtr pTheme, const int nIndexTheme, } -void CPPTXWriter::WriteTiming(CStringWriter& oWriter, CRelsGenerator &oRels, int nIndexSlide, const std::unordered_set& shapesID) +void CPPTXWriter::WriteTiming(CStringWriter& oWriter, CRelsGenerator &oRels, int nIndexSlide) { auto slide_iter = m_pUserInfo->m_mapSlides.find(m_pUserInfo->m_arrSlidesOrder[nIndexSlide]); - auto intermediateSlideAnimation = Intermediate::ParseSlideAnimation(slide_iter->second); - intermediateSlideAnimation.realShapesIds = shapesID; + CSlide* pCSlide = m_pDocument->m_arSlides[nIndexSlide]; + + auto intermediateSlideAnimation = Intermediate::ParseSlideAnimation(slide_iter->second, pCSlide); auto timing = - Converter::Timing(intermediateSlideAnimation, shapesID). + Converter::Timing(intermediateSlideAnimation). Convert(&(m_pUserInfo->m_oExMedia), &oRels); oWriter.WriteString(timing.toXML()); } diff --git a/MsBinaryFile/PptFile/PPTXWriter/Converter.h b/MsBinaryFile/PptFile/PPTXWriter/Converter.h index 7680f09b92..d7e203be71 100644 --- a/MsBinaryFile/PptFile/PPTXWriter/Converter.h +++ b/MsBinaryFile/PptFile/PPTXWriter/Converter.h @@ -88,8 +88,8 @@ namespace PPT void WriteLayout (CLayoutPtr pLayout, int nIndexLayout, int nStartLayout, int nIndexTheme); // void WriteRelsMaster (std::wstring path, int type, ) void WriteSlide (int nIndexSlide); - void WriteNotes (int nIndexNotes); - void WriteTiming (CStringWriter& oWriter, CRelsGenerator &oRels, int nIndexSlide, const std::unordered_set& shapesID); + void WriteNotes (int nIndexNotes); + void WriteTiming (CStringWriter& oWriter, CRelsGenerator &oRels, int nIndexSlide); void WriteTransition (CStringWriter& oWriter, CSlideShowInfo& oSSInfo); void WriteColorScheme (CStringWriter& oWriter, const std::wstring & name, const std::vector & colors, bool extra = false); diff --git a/MsBinaryFile/PptFile/Reader/Records.cpp b/MsBinaryFile/PptFile/Reader/Records.cpp index d3fa98dabe..9b9e4bb337 100644 --- a/MsBinaryFile/PptFile/Reader/Records.cpp +++ b/MsBinaryFile/PptFile/Reader/Records.cpp @@ -503,7 +503,7 @@ IRecord* CreateByType(SRecordHeader oHeader) CREATE_BY_TYPE(RT_HashCodeAtom, CRecordHashCode10Atom) CREATE_BY_TYPE(RT_BuildList, CRecordBuildListContainer) CREATE_BY_TYPE(RT_ParaBuild, CRecordParaBuildContainer) - CREATE_BY_TYPE(RT_ChartBuild, CRecordDiagramBuildAtom) + CREATE_BY_TYPE(RT_ChartBuild, CRecordChartBuildContainer) CREATE_BY_TYPE(RT_DiagramBuild, CRecordDiagramBuildContainer) CREATE_BY_TYPE(RT_ParaBuildAtom, CRecordParaBuildAtom) CREATE_BY_TYPE(RT_LevelInfoAtom, CRecordLevelInfoAtom) diff --git a/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.cpp b/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.cpp index e5aa6f740c..09c49eb3fb 100644 --- a/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.cpp +++ b/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.cpp @@ -40,7 +40,14 @@ CRecordParaBuildContainer::CRecordParaBuildContainer() CRecordParaBuildContainer::~CRecordParaBuildContainer() { - + for (size_t i = 0; i < rgParaBuildLevel.size(); ++i) + { + if (rgParaBuildLevel[i]) + { + delete rgParaBuildLevel[i]; + rgParaBuildLevel[i] = NULL; + } + } } void CRecordParaBuildContainer::ReadFromStream(SRecordHeader &header, POLE::Stream *pStream) @@ -60,12 +67,12 @@ void CRecordParaBuildContainer::ReadFromStream(SRecordHeader &header, POLE::Stre while (lCurLen < m_oHeader.RecLen ) { - CRecordParaBuildLevel buildLevel; - buildLevel.ReadFromStream(pStream); + CRecordParaBuildLevel* pLevel = new CRecordParaBuildLevel(); + pLevel->ReadFromStream(pStream); - rgParaBuildLevel.push_back(buildLevel); + rgParaBuildLevel.push_back(pLevel); - lCurLen += buildLevel.getRecordLen(); + lCurLen += pLevel->getRecordLen(); } StreamUtils::StreamSeek(lPos + m_oHeader.RecLen, pStream); diff --git a/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.h b/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.h index 71b770fb4f..9eb762ea0a 100644 --- a/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.h +++ b/MsBinaryFile/PptFile/Records/Animations/ParaBuildContainer.h @@ -49,6 +49,6 @@ public: public: CRecordParaBuildAtom m_oParaBuildAtom; - std::vector rgParaBuildLevel; + std::vector rgParaBuildLevel; }; } diff --git a/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.cpp b/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.cpp index 044c1f54fb..28d7c9395f 100644 --- a/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.cpp +++ b/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.cpp @@ -1016,15 +1016,15 @@ void PihlShape::ReadComplexData(IBinaryReader* reader) } void XmlString::ReadComplexData(IBinaryReader* reader) { - unsigned char* pData = reader->ReadBytes(op, true); - - data = std::string((char*)pData, op); - - delete []pData; + boost::shared_array buffer((char*)reader->ReadBytes(op, true)); + data = std::make_pair(buffer, op); } void XmlString::ReadComplexData(XLS::CFRecord& record) { - data = std::string(record.getCurData(), op); + boost::shared_array buffer(new char[op]); + memcpy(buffer.get(), record.getCurData(), op); + + data = std::make_pair(buffer, (size_t)op); record.skipNunBytes(op); } diff --git a/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.h b/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.h index 7289697ff6..7783ddabd3 100644 --- a/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.h +++ b/MsBinaryFile/XlsFile/Format/Logic/Biff_structures/ODRAW/OfficeArtFOPTE.h @@ -994,7 +994,7 @@ class XmlString : public OfficeArtFOPTE virtual void ReadComplexData(XLS::CFRecord& record); virtual void ReadComplexData(IBinaryReader* reader); - std::string data; //utf-8 + std::pair, size_t> data; }; class PathParser { diff --git a/OOXML/Base/Unit.cpp b/OOXML/Base/Unit.cpp index 798c1f9fe0..c520bcfbc1 100644 --- a/OOXML/Base/Unit.cpp +++ b/OOXML/Base/Unit.cpp @@ -621,15 +621,112 @@ namespace XmlUtils { return boost::lexical_cast(value); } - - std::wstring ToString( int value, const wchar_t* format ) + std::wstring ToString(BYTE value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(BYTE value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_INT16 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_INT16 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_UINT16 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_UINT16 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_INT32 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_INT32 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_UINT32 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_UINT32 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_INT64 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_INT64 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString(_UINT64 value, const wchar_t* format) + { + if (format == NULL) return L""; + std::wstringstream sstream; + sstream << boost::wformat(format) % value; + return sstream.str(); + } + std::string ToString(_UINT64 value, const char* format) + { + if (format == NULL) return ""; + std::stringstream sstream; + sstream << boost::format(format) % value; + return sstream.str(); + } + std::wstring ToString( double value, const wchar_t* format ) { if ( format == NULL ) return L""; std::wstringstream sstream; sstream << boost::wformat(format) % value; return sstream.str(); } - std::string ToString( int value, const char* format ) + std::string ToString(double value, const char* format ) { if ( format == NULL ) return ""; std::stringstream sstream; diff --git a/OOXML/Base/Unit.h b/OOXML/Base/Unit.h index 456be9df45..0839e641d9 100644 --- a/OOXML/Base/Unit.h +++ b/OOXML/Base/Unit.h @@ -30,8 +30,6 @@ * */ #pragma once -#ifndef _UNIT_INCLUDE_H_ -#define _UNIT_INCLUDE_H_ #include "Base.h" #include "../../DesktopEditor/common/Types.h" @@ -149,8 +147,27 @@ namespace XmlUtils std::wstring ToString(const int& value); std::wstring ToString(const long& value); std::wstring ToString(const unsigned long& value); - std::wstring ToString(int value, const wchar_t* format); - std::string ToString(int value, const char* format); + + std::wstring ToString(BYTE value, const wchar_t* format); + std::string ToString(BYTE value, const char* format); + + std::wstring ToString(_INT16 value, const wchar_t* format); + std::string ToString(_INT16 value, const char* format); + std::wstring ToString(_UINT16 value, const wchar_t* format); + std::string ToString(_UINT16 value, const char* format); + + std::wstring ToString(_INT64 value, const wchar_t* format); + std::string ToString(_INT64 value, const char* format); + std::wstring ToString(_UINT64 value, const wchar_t* format); + std::string ToString(_UINT64 value, const char* format); + + std::wstring ToString(_INT32 value, const wchar_t* format); + std::string ToString(_INT32 value, const char* format); + std::wstring ToString(_UINT32 value, const wchar_t* format); + std::string ToString(_UINT32 value, const char* format); + + std::wstring ToString(double value, const wchar_t* format); + std::string ToString(double value, const char* format); int Rand(); int GenerateInt(); @@ -163,4 +180,3 @@ namespace XmlUtils std::wstring EncodeXmlStringExtend(const std::wstring& data, bool bDeleteNoUnicode = true); } -#endif // _UNIT_INCLUDE_H_ diff --git a/OOXML/Binary/Document/BinReader/ReaderClasses.cpp b/OOXML/Binary/Document/BinReader/ReaderClasses.cpp index 05a05a345a..ad9c93c04e 100644 --- a/OOXML/Binary/Document/BinReader/ReaderClasses.cpp +++ b/OOXML/Binary/Document/BinReader/ReaderClasses.cpp @@ -457,7 +457,7 @@ namespace BinDocxRW { pCStringWriter->WriteString(CellPr); pCStringWriter->WriteString(L""); } - for(int i = 0, length = (int)TblStylePr.size(); i < length; ++i) + for(_INT32 i = 0, length = (_INT32)TblStylePr.size(); i < length; ++i) { pCStringWriter->WriteString(TblStylePr[i]); } @@ -486,7 +486,7 @@ namespace BinDocxRW { bBottom = false; } - docImg::docImg(int nDocPr) + docImg::docImg(_INT32 nDocPr) { m_nDocPr = nDocPr; bMediaId = false; @@ -505,8 +505,8 @@ namespace BinDocxRW { { if(bWidth && bHeight) { - __int64 nWidth = (__int64)(g_dKoef_mm_to_emu * Width); - __int64 nHeight = (__int64)(g_dKoef_mm_to_emu * Height); + _INT64 nWidth = (_INT64)(g_dKoef_mm_to_emu * Width); + _INT64 nHeight = (_INT64)(g_dKoef_mm_to_emu * Height); std::wstring sDrawing = L"bText) @@ -925,7 +925,7 @@ namespace BinDocxRW { } docANum::~docANum() { - for(int i = 0, length = (int)Lvls.size(); i < length; i++) + for (size_t i = 0, length = Lvls.size(); i < length; i++) { delete Lvls[i]; } @@ -945,7 +945,7 @@ namespace BinDocxRW { std::wstring sCorrectNumStyleLink = XmlUtils::EncodeXmlString(NumStyleLink); oWriterANum.WriteString(L""); } - for(int i = 0, length = (int)Lvls.size(); i < length; ++i) + for(size_t i = 0, length = Lvls.size(); i < length; ++i) { Lvls[i]->Write(oWriterANum); } @@ -1005,7 +1005,7 @@ namespace BinDocxRW { std::wstring sCurItem; bool bDQuot = false; - for(int i = 0, length = (int)fld.length(); i < length; ++i) + for(size_t i = 0, length = fld.length(); i < length; ++i) { wchar_t sCurLetter = fld[i]; if('\"' == sCurLetter) @@ -1029,7 +1029,7 @@ namespace BinDocxRW { if(sCurItem.length() > 0) aItems.push_back(sCurItem); - for(int i = 0, length = (int)aItems.size(); i < length; ++i) + for(size_t i = 0, length = aItems.size(); i < length; ++i) { std::wstring item = aItems[i]; if(bNextLink) @@ -1053,7 +1053,7 @@ namespace BinDocxRW { res = new WriteHyperlink(); boost::algorithm::trim(sLink); - int nAnchorIndex = (int)sLink.find(L"#"); + _INT32 nAnchorIndex = (_INT32)sLink.find(L"#"); if(-1 != nAnchorIndex) { res->href = sLink.substr(0, nAnchorIndex); @@ -1097,17 +1097,17 @@ namespace BinDocxRW { } } - IdCounter::IdCounter(int nStart) + IdCounter::IdCounter(_INT32 nStart) { m_nId = nStart; } - int IdCounter::getNextId(int nCount) + _INT32 IdCounter::getNextId(_INT32 nCount) { - int nRes = m_nId; + _INT32 nRes = m_nId; m_nId += nCount; return nRes; } - int IdCounter::getCurrentId() + _INT32 IdCounter::getCurrentId() { return m_nId; } @@ -1127,11 +1127,11 @@ namespace BinDocxRW { } replies.clear(); } - int CComment::getCount() + _INT32 CComment::getCount() { - return (int)replies.size() + 1; + return (_INT32)replies.size() + 1; } - void CComment::setFormatStart(int IdFormatStart) + void CComment::setFormatStart(_INT32 IdFormatStart) { bIdFormat = true; IdFormat = IdFormatStart; @@ -1140,7 +1140,7 @@ namespace BinDocxRW { { CComment* pComment = replies[i]; pComment->bIdFormat = true; - pComment->IdFormat = (int)(IdFormatStart + i + 1); + pComment->IdFormat = (_INT32)(IdFormatStart + i + 1); } } std::wstring CComment::writeRef(const std::wstring& sBefore, const std::wstring& sRef, const std::wstring& sAfter) @@ -1167,13 +1167,13 @@ namespace BinDocxRW { sRes += (sAfter); return sRes; } - void CComment::writeContentWritePart(CComment* pComment, std::wstring& sText, int nPrevIndex, int nCurIndex, std::wstring& sRes) + void CComment::writeContentWritePart(CComment* pComment, std::wstring& sText, _INT32 nPrevIndex, _INT32 nCurIndex, std::wstring& sRes) { std::wstring sPart; if(nPrevIndex < nCurIndex) sPart = XmlUtils::EncodeXmlString(sText.substr(nPrevIndex, nCurIndex - nPrevIndex)); - int nId = pComment->m_oParaIdCounter.getNextId(); + _INT32 nId = pComment->m_oParaIdCounter.getNextId(); pComment->sParaId = XmlUtils::ToString(nId, L"%08X"); sRes += L"sParaId + L"\" w14:textId=\"" + pComment->sParaId + L"\">"; @@ -1223,8 +1223,8 @@ namespace BinDocxRW { XmlUtils::replace_all(sText, L"\r", L""); - int nPrevIndex = 0; - for (int i = 0; i < (int)sText.length(); i++) + _INT32 nPrevIndex = 0; + for (size_t i = 0; i < sText.length(); i++) { wchar_t cToken = sText[i]; if('\n' == cToken) @@ -1233,7 +1233,7 @@ namespace BinDocxRW { nPrevIndex = i + 1; } } - writeContentWritePart(pComment, sText, nPrevIndex, (int)sText.length(), sRes); + writeContentWritePart(pComment, sText, nPrevIndex, (_INT32)sText.length(), sRes); } sRes += L""; return sRes; @@ -1313,7 +1313,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ } CComments::~CComments() { - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { delete it->second; } @@ -1334,22 +1334,22 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ if(false == pComment->UserName.empty() && false == pComment->UserId.empty()) m_mapAuthors[pComment->UserName] = pComment; } - CComment* CComments::get(int nInd) + CComment* CComments::get(_INT32 nInd) { CComment* pRes = NULL; - boost::unordered_map::const_iterator pair = m_mapComments.find(nInd); + boost::unordered_map<_INT32, CComment*>::const_iterator pair = m_mapComments.find(nInd); if(m_mapComments.end() != pair) pRes = pair->second; return pRes; } - int CComments::getNextId(int nCount) + _INT32 CComments::getNextId(_INT32 nCount) { return m_oFormatIdCounter.getNextId(nCount); } std::wstring CComments::writeContent() { std::wstring sRes; - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { sRes += CComment::writeContent(it->second); for(size_t i = 0; i < it->second->replies.size(); ++i) @@ -1360,7 +1360,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ std::wstring CComments::writeContentExt() { std::wstring sRes; - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { sRes += CComment::writeContentExt(it->second); for(size_t i = 0; i < it->second->replies.size(); ++i) @@ -1371,7 +1371,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ std::wstring CComments::writeContentExtensible() { std::wstring sRes; - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { sRes += CComment::writeContentExtensible(it->second); for(size_t i = 0; i < it->second->replies.size(); ++i) @@ -1382,7 +1382,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ std::wstring CComments::writeContentUserData() { std::wstring sRes; - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { sRes += CComment::writeContentUserData(it->second); for(size_t i = 0; i < it->second->replies.size(); ++i) @@ -1393,7 +1393,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ std::wstring CComments::writeContentsIds() { std::wstring sRes; - for (boost::unordered_map::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) + for (boost::unordered_map<_INT32, CComment*>::const_iterator it = m_mapComments.begin(); it != m_mapComments.end(); ++it) { sRes += CComment::writeContentsIds(it->second); for(size_t i = 0; i < it->second->replies.size(); ++i) @@ -1430,7 +1430,7 @@ w15:paraIdParent=\"" + pComment->sParaIdParent + L"\" w15:done=\"" + sDone + L"\ Points.clear(); } - CDrawingProperty::CDrawingProperty(int nDocPr) + CDrawingProperty::CDrawingProperty(_INT32 nDocPr) { m_nDocPr = nDocPr; @@ -1532,10 +1532,10 @@ distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">"; - __int64 emuX = 0; + _INT64 emuX = 0; if(bSimplePosX) emuX = SimplePosX; - __int64 emuY = 0; + _INT64 emuY = 0; if(bSimplePosY) emuY = SimplePosY; sXml += L""; @@ -1616,7 +1616,7 @@ allowOverlap=\"1\">"; } else if(bPositionHPctOffset) { - long pctOffset = (long)(1000 * PositionHPctOffset); + _INT32 pctOffset = (_INT32)(1000 * PositionHPctOffset); sContent = L"" + std::to_wstring(pctOffset) + L""; } sXml += L"" + sContent + L""; @@ -1653,7 +1653,7 @@ allowOverlap=\"1\">"; } else if(bPositionVPctOffset) { - long pctOffset = (long)(1000 * PositionVPctOffset); + _INT32 pctOffset = (_INT32)(1000 * PositionVPctOffset); sContent = L"" + std::to_wstring(pctOffset) + L""; } sXml += L"" + sContent + L""; @@ -1688,7 +1688,7 @@ allowOverlap=\"1\">"; else sXml += L""; - int nEdited = 0; + _INT32 nEdited = 0; if(DrawingPropertyWrap.bEdited && DrawingPropertyWrap.Edited) nEdited = 1; sXml += L""; diff --git a/OOXML/Binary/Document/BinReader/ReaderClasses.h b/OOXML/Binary/Document/BinReader/ReaderClasses.h index ec31c36a17..52ba0addf9 100644 --- a/OOXML/Binary/Document/BinReader/ReaderClasses.h +++ b/OOXML/Binary/Document/BinReader/ReaderClasses.h @@ -46,19 +46,19 @@ class SectPr { public: std::wstring sHeaderFooterReference; - long W; - long H; + _INT32 W; + _INT32 H; BYTE cOrientation; - long Left; - long Top; - long Right; - long Bottom; - long Header; - long Footer; + _INT32 Left; + _INT32 Top; + _INT32 Right; + _INT32 Bottom; + _INT32 Header; + _INT32 Footer; bool TitlePg; bool EvenAndOddHeaders; BYTE SectionType; - int PageNumStart; + _INT32 PageNumStart; std::wstring sectPrChange; std::wstring cols; std::wstring pgBorders; @@ -66,7 +66,7 @@ public: std::wstring endnotePr; std::wstring lineNum; bool RtlGutter; - long Gutter; + _INT32 Gutter; bool bW; bool bH; @@ -134,9 +134,9 @@ public: BYTE LineRule; double Line; - long LineTwips; - long After; - long Before; + _INT32 LineTwips; + _INT32 After; + _INT32 Before; bool AfterAuto; bool BeforeAuto; @@ -273,7 +273,7 @@ public: double Width; double Height; PaddingsToWriteMM Paddings; - int m_nDocPr; + _INT32 m_nDocPr; bool bMediaId; bool bType; @@ -284,7 +284,7 @@ public: bool bPaddings; std::wstring srId; - docImg(int nDocPr); + docImg(_INT32 nDocPr); void Write(NSStringUtils::CStringBuilder* pCStringWriter); }; @@ -362,24 +362,24 @@ public: class docLvl { public: - long ILvl; - long Format; + _INT32 ILvl; + _INT32 Format; std::wstring sFormat; BYTE Jc; std::wstring sJc; std::vector Text; - long Restart; - long Start; + _INT32 Restart; + _INT32 Start; BYTE Suff; NSStringUtils::CStringBuilder ParaPr; NSStringUtils::CStringBuilder TextPr; std::wstring PStyle; bool Tentative; - unsigned long Tplc; + _UINT32 Tplc; bool IsLgl; bool Legacy; - long LegacyIndent; - unsigned long LegacySpace; + _INT32 LegacyIndent; + _UINT32 LegacySpace; bool bILvl; bool bFormat; @@ -474,13 +474,13 @@ public: class IdCounter { private: - int m_nId; + _INT32 m_nId; public: - IdCounter(int nStart = 0); + IdCounter(_INT32 nStart = 0); - int getNextId(int nCount = 1); - int getCurrentId(); + _INT32 getNextId(_INT32 nCount = 1); + _INT32 getCurrentId(); }; class CComment { @@ -491,8 +491,8 @@ private: public: void *pBinary_DocumentTableReader; - int IdOpen; - int IdFormat; + _INT32 IdOpen; + _INT32 IdFormat; std::wstring UserName; std::wstring Initials; std::wstring UserId; @@ -502,7 +502,7 @@ public: std::wstring DateUtc; std::wstring UserData; bool Solved; - unsigned int DurableId; + _UINT32 DurableId; std::wstring Text; std::wstring sContent; @@ -519,14 +519,14 @@ public: CComment(IdCounter& oParaIdCounter, IdCounter& oFormatIdCounter); ~CComment(); - int getCount(); + _INT32 getCount(); - void setFormatStart(int IdFormatStart); + void setFormatStart(_INT32 IdFormatStart); std::wstring writeRef(const std::wstring& sBefore, const std::wstring& sRef, const std::wstring& sAfter); static std::wstring writeRef(CComment* pComment, const std::wstring& sBefore, const std::wstring& sRef, const std::wstring& sAfter); - static void writeContentWritePart(CComment* pComment, std::wstring& sText, int nPrevIndex, int nCurIndex, std::wstring& sRes); + static void writeContentWritePart(CComment* pComment, std::wstring& sText, _INT32 nPrevIndex, _INT32 nCurIndex, std::wstring& sRes); static std::wstring writeContent(CComment* pComment); static std::wstring writeContentExt(CComment* pComment); static std::wstring writeContentExtensible(CComment* pComment); @@ -536,7 +536,7 @@ public: }; class CComments { - boost::unordered_map m_mapComments; + boost::unordered_map<_INT32, CComment*> m_mapComments; boost::unordered_map m_mapAuthors; public: @@ -544,13 +544,13 @@ public: IdCounter m_oParaIdCounter; CComments(); - ~CComments(); + ~CComments(); void add(CComment* pComment); void addAuthor(CComment* pComment); - CComment* get(int nInd); - int getNextId(int nCount = 1); + CComment* get(_INT32 nInd); + _INT32 getNextId(_INT32 nCount = 1); std::wstring writeContent(); std::wstring writeContentExt(); @@ -563,8 +563,8 @@ public: class CDrawingPropertyWrapPoint { public: - __int64 X; - __int64 Y; + _INT64 X; + _INT64 Y; bool bX; bool bY; @@ -591,39 +591,39 @@ class CDrawingProperty public: bool bObject; std::wstring sObjectProgram; - unsigned int nObjectId; + _UINT32 nObjectId; BYTE nObjectType; - long DataPos; - long DataLength; + _INT32 DataPos; + _INT32 DataLength; BYTE Type; bool BehindDoc; - __int64 DistL; - __int64 DistT; - __int64 DistR; - __int64 DistB; + _INT64 DistL; + _INT64 DistT; + _INT64 DistR; + _INT64 DistB; bool LayoutInCell; - unsigned long RelativeHeight; + _UINT32 RelativeHeight; bool BSimplePos; - __int64 EffectExtentL; - __int64 EffectExtentT; - __int64 EffectExtentR; - __int64 EffectExtentB; - __int64 Width; - __int64 Height; + _INT64 EffectExtentL; + _INT64 EffectExtentT; + _INT64 EffectExtentR; + _INT64 EffectExtentB; + _INT64 Width; + _INT64 Height; BYTE PositionHRelativeFrom; BYTE PositionHAlign; - __int64 PositionHPosOffset; + _INT64 PositionHPosOffset; double PositionHPctOffset; BYTE PositionVRelativeFrom; BYTE PositionVAlign; - __int64 PositionVPosOffset; + _INT64 PositionVPosOffset; double PositionVPctOffset; - __int64 SimplePosX; - __int64 SimplePosY; + _INT64 SimplePosX; + _INT64 SimplePosY; std::wstring sSizeRelH; std::wstring sSizeRelV; - int m_nDocPr; + _INT32 m_nDocPr; std::wstring sGraphicFramePr; std::wstring sDocPr; @@ -660,7 +660,7 @@ public: bool bSimplePosY; bool bDrawingPropertyWrap; - CDrawingProperty(int nDocPr); + CDrawingProperty(_INT32 nDocPr); bool IsGraphicFrameContent(); std::wstring Write(); @@ -708,18 +708,18 @@ public: bool bYAlign; BYTE DropCap; - long H; + _INT32 H; BYTE HAnchor; BYTE HRule; - long HSpace; - long Lines; + _INT32 HSpace; + _INT32 Lines; BYTE VAnchor; - long VSpace; - long W; + _INT32 VSpace; + _INT32 W; BYTE Wrap; - long X; + _INT32 X; BYTE XAlign; - long Y; + _INT32 Y; BYTE YAlign; public: @@ -763,10 +763,10 @@ class TrackRevision public: std::wstring Author; std::wstring Date; - long* Id; + _INT32* Id; std::wstring UserId; - long* vMerge; - long* vMergeOrigin; + _INT32* vMerge; + _INT32* vMergeOrigin; OOX::Logic::CRunProperty* RPr; diff --git a/OOXML/Binary/Document/BinReader/Readers.cpp b/OOXML/Binary/Document/BinReader/Readers.cpp index 708be36dab..d43f0bd3f6 100644 --- a/OOXML/Binary/Document/BinReader/Readers.cpp +++ b/OOXML/Binary/Document/BinReader/Readers.cpp @@ -172,7 +172,7 @@ public: }\ else if(c_oSerProp_RevisionType::Id == type)\ {\ - poResult->Id = new long(m_oBufferedStream.GetLong());\ + poResult->Id = new _INT32(m_oBufferedStream.GetLong());\ }\ else if(c_oSerProp_RevisionType::UserId == type)\ {\ @@ -403,7 +403,7 @@ int Binary_HdrFtrTableReader::ReadHdrFtrItem(BYTE type, long length, void* poRes } m_oFileWriter.m_pDrawingConverter->SetDstContentRels(); - Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, poHdrFtrItem->Header); + Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, poHdrFtrItem->Header, false); READ1_DEF(length, res, this->ReadHdrFtrItemContent, &oBinary_DocumentTableReader); OOX::CPath fileRelsPath = m_oFileWriter.get_document_writer().m_sDir + FILE_SEPARATOR_STR + L"word" + @@ -2184,7 +2184,7 @@ int Binary_tblPrReader::Read_tblPr(BYTE type, long length, void* poResult) else if( c_oSerProp_tblPrType::Look == type ) { // - long nLook = m_oBufferedStream.GetLong(); + _INT32 nLook = m_oBufferedStream.GetLong(); int nFC = (0 == (nLook & 0x0080)) ? 0 : 1; int nFR = (0 == (nLook & 0x0020)) ? 0 : 1; int nLC = (0 == (nLook & 0x0100)) ? 0 : 1; @@ -2844,11 +2844,11 @@ int Binary_tblPrReader::ReadCellMerge(BYTE type, long length, void* poResult) READ1_TRACKREV(type, length, pTrackRevision) else if (c_oSerProp_RevisionType::VMerge == type) { - pTrackRevision->vMerge = new long(m_oBufferedStream.GetLong()); + pTrackRevision->vMerge = new _INT32(m_oBufferedStream.GetLong()); } else if (c_oSerProp_RevisionType::VMergeOrigin == type) { - pTrackRevision->vMergeOrigin = new long(m_oBufferedStream.GetLong()); + pTrackRevision->vMergeOrigin = new _INT32(m_oBufferedStream.GetLong()); } else res = c_oSerConstants::ReadUnknown; @@ -3646,7 +3646,7 @@ int Binary_CommentsTableReader::Read() m_oFileWriter.m_pDrawingConverter->SetDstContentRels(); Writers::ContentWriter oContentWriter; - Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, oContentWriter); + Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, oContentWriter, false); oBinary_DocumentTableReader.m_bUsedParaIdCounter = true; @@ -3757,7 +3757,7 @@ int Binary_CommentsTableReader::ReadCommentContent(BYTE type, long length, void* pComment->sContent = doc_reader->m_oDocumentWriter.m_oContent.GetData(); doc_reader->m_oDocumentWriter.m_oContent.Clear(); - int nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getCurrentId(); + _INT32 nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getCurrentId(); pComment->sParaId = XmlUtils::ToString(nId, L"%08X"); } @@ -4664,7 +4664,7 @@ int Binary_SettingsTableReader::ReadClrSchemeMapping(BYTE type, long length, voi }; -Binary_DocumentTableReader::Binary_DocumentTableReader(NSBinPptxRW::CBinaryFileReader& poBufferedStream, Writers::FileWriter& oFileWriter, Writers::ContentWriter& oDocumentWriter) +Binary_DocumentTableReader::Binary_DocumentTableReader(NSBinPptxRW::CBinaryFileReader& poBufferedStream, Writers::FileWriter& oFileWriter, Writers::ContentWriter& oDocumentWriter, bool bOFormRead) : Binary_CommonReader(poBufferedStream) , m_oDocumentWriter(oDocumentWriter) , m_oFileWriter(oFileWriter) @@ -4674,6 +4674,7 @@ Binary_DocumentTableReader::Binary_DocumentTableReader(NSBinPptxRW::CBinaryFileR , oBinary_pPrReader(poBufferedStream, oFileWriter) , oBinary_rPrReader(poBufferedStream, oFileWriter) , oBinary_tblPrReader(poBufferedStream, oFileWriter) + , m_bOFormRead(bOFormRead) { m_bUsedParaIdCounter = false; m_byteLastElemType = c_oSerParType::Content; @@ -4711,7 +4712,7 @@ int Binary_DocumentTableReader::ReadDocumentContent(BYTE type, long length, void if (m_bUsedParaIdCounter && m_oFileWriter.m_pComments) { - int nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getNextId(); + _INT32 nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getNextId(); std::wstring sParaId = XmlUtils::ToString(nId, L"%08X"); m_oDocumentWriter.m_oContent.WriteString(L""); @@ -8106,7 +8107,7 @@ int Binary_DocumentTableReader::ReadRunContent(BYTE type, long length, void* poR if (m_bUsedParaIdCounter && m_oFileWriter.m_pComments) { - int nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getNextId(); + _INT32 nId = m_oFileWriter.m_pComments->m_oParaIdCounter.getNextId(); std::wstring sParaId = XmlUtils::ToString(nId, L"%08X"); m_oDocumentWriter.m_oContent.WriteString(L""); @@ -8362,7 +8363,7 @@ int Binary_DocumentTableReader::Read_tblGridChange(BYTE type, long length, void* TrackRevision* pTrackRevision = static_cast(poResult); if(c_oSerProp_RevisionType::Id == type) { - pTrackRevision->Id = new long(m_oBufferedStream.GetLong()); + pTrackRevision->Id = new _INT32(m_oBufferedStream.GetLong()); } else if(c_oSerProp_RevisionType::tblGridChange == type) { @@ -8514,7 +8515,7 @@ int Binary_DocumentTableReader::ReadCell(BYTE type, long length, void* poResult) } else if( c_oSerDocTableType::Cell_Content == type ) { - Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, m_oDocumentWriter); + Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, m_oDocumentWriter, m_bOFormRead); READ1_DEF(length, res, this->ReadCellContent, &oBinary_DocumentTableReader); //Потому что если перед не идет

, то документ считается невалидным if(c_oSerParType::Par != oBinary_DocumentTableReader.m_byteLastElemType) @@ -9444,23 +9445,6 @@ int Binary_DocumentTableReader::ReadSdtPr(BYTE type, long length, void* poResult pSdtPr->m_oComplexFormPr.Init(); READ1_DEF(length, res, this->ReadSdtComplexFormPr, pSdtPr->m_oComplexFormPr.GetPointer()); } - else if (c_oSerSdt::OformMaster == type) - { - std::wstring pathOFormMaster = m_oBufferedStream.GetString3(length); - - if (false == pathOFormMaster.empty()) - { - XmlUtils::replace_all(pathOFormMaster, L"\\", L"/"); - - m_oFileWriter.m_pDrawingConverter->GetContentTypes()->Registration(L"oform/fieldMaster+xml", L"", pathOFormMaster.substr(3)); // del "../" - - unsigned int rId; - m_oFileWriter.m_pDrawingConverter->WriteRels(L"https://schemas.onlyoffice.com/relationships/oform-fieldMaster", pathOFormMaster, L"", &rId); - - pSdtPr->m_oOformRid.Init(); - pSdtPr->m_oOformRid->SetValue(L"rId" + std::to_wstring(rId)); - } - } else res = c_oSerConstants::ReadUnknown; return res; @@ -9710,6 +9694,23 @@ int Binary_DocumentTableReader::ReadSdtFormPr(BYTE type, long length, void* poRe pFormPr->m_oShd.Init(); READ2_DEF(length, res, oBinary_CommonReader2.ReadShdComplexType, pFormPr->m_oShd.GetPointer()); } + else if (c_oSerSdt::OformMaster == type) + { + std::wstring pathOFormMaster = m_oBufferedStream.GetString3(length); + + if (false == pathOFormMaster.empty() && m_bOFormRead) + { + XmlUtils::replace_all(pathOFormMaster, L"\\", L"/"); + + m_oFileWriter.m_pDrawingConverter->GetContentTypes()->Registration(L"oform/fieldMaster+xml", L"", pathOFormMaster.substr(3)); // del "../" + + unsigned int rId; + m_oFileWriter.m_pDrawingConverter->WriteRels(L"https://schemas.onlyoffice.com/relationships/oform-fieldMaster", pathOFormMaster, L"", &rId); + + pFormPr->m_oFieldRid.Init(); + pFormPr->m_oFieldRid->SetValue(L"rId" + std::to_wstring(rId)); + } + } else res = c_oSerConstants::ReadUnknown; return res; @@ -9835,7 +9836,7 @@ int Binary_NotesTableReader::Read() sFilename = m_oFileWriter.get_endnotes_writer().getFilename(); pContentWriter = &m_oFileWriter.get_endnotes_writer().m_oNotesWriter; } - Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, *pContentWriter); + Binary_DocumentTableReader oBinary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, *pContentWriter, false); int res = c_oSerConstants::ReadOk; READ_TABLE_DEF(res, this->ReadNotes, &oBinary_DocumentTableReader); @@ -9921,12 +9922,13 @@ int Binary_NotesTableReader::ReadNoteContent(BYTE type, long length, void* poRes }; -BinaryFileReader::BinaryFileReader(std::wstring& sFileInDir, NSBinPptxRW::CBinaryFileReader& oBufferedStream, Writers::FileWriter& oFileWriter, bool bMacro) +BinaryFileReader::BinaryFileReader(std::wstring& sFileInDir, NSBinPptxRW::CBinaryFileReader& oBufferedStream, Writers::FileWriter& oFileWriter, bool bMacro, bool bOForm) : m_sFileInDir(sFileInDir), m_oBufferedStream(oBufferedStream), m_oFileWriter(oFileWriter), - m_bMacro(bMacro) + m_bMacro(bMacro), + m_bOForm(bOForm) { } int BinaryFileReader::ReadFile() @@ -10143,31 +10145,35 @@ int BinaryFileReader::ReadMainTable() }break; case c_oSerTableTypes::OForm: { - _INT32 nDataSize = m_oBufferedStream.GetLong(); - - BYTE *pData = new BYTE[nDataSize]; - if (pData) + if (m_bOForm) { - m_oBufferedStream.GetArray(pData, nDataSize); - - std::wstring pathOFormDst = m_oFileWriter.get_document_writer().m_sDir + FILE_SEPARATOR_STR + L"oform"; - std::wstring sZipOformFile = NSFile::CFileBinary::CreateTempFileWithUniqueName(m_oFileWriter.get_document_writer().m_sDir, L"oform"); - - NSFile::CFileBinary zipOform; - if (zipOform.CreateFile(sZipOformFile) && NSDirectory::CreateDirectory(pathOFormDst)) + _INT32 nDataSize = m_oBufferedStream.GetLong(); + BYTE *pData = new BYTE[nDataSize]; + if (pData) { - zipOform.WriteFile(pData, nDataSize); - zipOform.CloseFile(); + m_oBufferedStream.GetArray(pData, nDataSize); + + std::wstring pathOFormDst = m_oFileWriter.get_document_writer().m_sDir + FILE_SEPARATOR_STR + L"oform"; + std::wstring sZipOformFile = NSFile::CFileBinary::CreateTempFileWithUniqueName(m_oFileWriter.get_document_writer().m_sDir, L"oform"); - COfficeUtils oCOfficeUtils(NULL); - if (S_OK == oCOfficeUtils.ExtractToDirectory(sZipOformFile, pathOFormDst, NULL, 0)) + NSFile::CFileBinary zipOform; + if (zipOform.CreateFile(sZipOformFile) && NSDirectory::CreateDirectory(pathOFormDst)) { - m_oFileWriter.m_pDrawingConverter->GetContentTypes()->Registration(L"oform/main+xml", L"/oform", L"main.xml"); + zipOform.WriteFile(pData, nDataSize); + zipOform.CloseFile(); + + COfficeUtils oCOfficeUtils(NULL); + if (S_OK == oCOfficeUtils.ExtractToDirectory(sZipOformFile, pathOFormDst, NULL, 0)) + { + m_oFileWriter.m_pDrawingConverter->GetContentTypes()->Registration(L"oform/main+xml", L"/oform", L"main.xml"); + } + NSFile::CFileBinary::Remove(sZipOformFile); } - NSFile::CFileBinary::Remove(sZipOformFile); + delete[]pData; } - delete[]pData; } + else + m_oBufferedStream.SkipRecord(); }break; case c_oSerTableTypes::Glossary: { @@ -10310,7 +10316,7 @@ int BinaryFileReader::ReadMainTable() m_oFileWriter.m_pDrawingConverter->WriteRels(OOX::FileTypes::CustomXml.RelationType(), sRelsPath, L"", &rId); } - res = Binary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, m_oFileWriter.get_document_writer()).Read(); + res = Binary_DocumentTableReader(m_oBufferedStream, m_oFileWriter, m_oFileWriter.get_document_writer(), m_bOForm).Read(); OOX::CPath fileRelsPath = m_oFileWriter.get_document_writer().m_sDir + FILE_SEPARATOR_STR + L"word" + (m_oFileWriter.m_bGlossaryMode ? (FILE_SEPARATOR_STR + std::wstring(L"glossary")) : L"") diff --git a/OOXML/Binary/Document/BinReader/Readers.h b/OOXML/Binary/Document/BinReader/Readers.h index e63947bff7..74dec7f67b 100644 --- a/OOXML/Binary/Document/BinReader/Readers.h +++ b/OOXML/Binary/Document/BinReader/Readers.h @@ -295,8 +295,9 @@ public: Writers::MediaWriter& m_oMediaWriter; bool m_bUsedParaIdCounter; + bool m_bOFormRead; - Binary_DocumentTableReader(NSBinPptxRW::CBinaryFileReader& poBufferedStream, Writers::FileWriter& oFileWriter, Writers::ContentWriter& oDocumentWriter); + Binary_DocumentTableReader(NSBinPptxRW::CBinaryFileReader& poBufferedStream, Writers::FileWriter& oFileWriter, Writers::ContentWriter& oDocumentWriter, bool bOFormRead); ~Binary_DocumentTableReader(); int Read(); @@ -506,8 +507,9 @@ private: std::wstring m_sFileInDir; bool m_bMacro = false; bool m_bMacroRead = false; + bool m_bOForm = false; public: - BinaryFileReader(std::wstring& sFileInDir, NSBinPptxRW::CBinaryFileReader& oBufferedStream, Writers::FileWriter& oFileWriter, bool bMacro = false); + BinaryFileReader(std::wstring& sFileInDir, NSBinPptxRW::CBinaryFileReader& oBufferedStream, Writers::FileWriter& oFileWriter, bool bMacro = false, bool bOForm = false); int ReadFile(); int ReadMainTable(); }; diff --git a/OOXML/Binary/Document/BinWriter/BinWriters.cpp b/OOXML/Binary/Document/BinWriter/BinWriters.cpp index 9684951160..4b13931b65 100644 --- a/OOXML/Binary/Document/BinWriter/BinWriters.cpp +++ b/OOXML/Binary/Document/BinWriter/BinWriters.cpp @@ -7831,16 +7831,6 @@ void BinaryDocumentTableWriter::WriteSdtPr(const OOX::Logic::CSdtPr& oStdPr) WriteSdtComplexFormPr(oStdPr.m_oComplexFormPr.get()); m_oBcw.WriteItemEnd(nCurPos); } - if (oStdPr.m_oOformRid.IsInit()) - { - smart_ptr pFile = m_oParamsDocumentWriter.m_pRels->Find(oStdPr.m_oOformRid->GetValue()); - if (pFile.IsInit()) - { - nCurPos = m_oBcw.WriteItemStart(c_oSerSdt::OformMaster); - m_oBcw.m_oStream.WriteStringW3(pFile->m_sOutputFilename); - m_oBcw.WriteItemEnd(nCurPos); - } - } } void BinaryDocumentTableWriter::WriteSdtPicture(const OOX::Logic::CSdtPicture& oSdtPicture) { @@ -8103,6 +8093,16 @@ void BinaryDocumentTableWriter::WriteSdtFormPr(const OOX::Logic::CFormPr& oFormP m_oBcw.WriteShd(oFormPr.m_oShd.get()); m_oBcw.WriteItemEnd(nCurPos); } + if (oFormPr.m_oFieldRid.IsInit()) + { + smart_ptr pFile = m_oParamsDocumentWriter.m_pRels->Find(oFormPr.m_oFieldRid->GetValue()); + if (pFile.IsInit()) + { + nCurPos = m_oBcw.WriteItemStart(c_oSerSdt::OformMaster); + m_oBcw.m_oStream.WriteStringW3(pFile->m_sOutputFilename); + m_oBcw.WriteItemEnd(nCurPos); + } + } } void BinaryDocumentTableWriter::WriteSdtTextFormPr(const OOX::Logic::CTextFormPr& oTextFormPr) { diff --git a/OOXML/Binary/Document/DocWrapper/DocxSerializer.cpp b/OOXML/Binary/Document/DocWrapper/DocxSerializer.cpp index b1419ba857..1f8953eaca 100644 --- a/OOXML/Binary/Document/DocWrapper/DocxSerializer.cpp +++ b/OOXML/Binary/Document/DocWrapper/DocxSerializer.cpp @@ -181,7 +181,7 @@ namespace BinDocxRW }; } -BinDocxRW::CDocxSerializer::CDocxSerializer() : m_bIsMacro(false), m_bIsNoBase64Save(false), m_bIsNoBase64(false) +BinDocxRW::CDocxSerializer::CDocxSerializer() : m_bIsMacro(false), m_bIsNoBase64Save(false), m_bIsNoBase64(false), m_bIsOForm(false) { m_pParamsWriter = NULL; m_pCurFileWriter = NULL; @@ -417,7 +417,7 @@ bool BinDocxRW::CDocxSerializer::loadFromFile(const std::wstring& sSrcFileName, oDrawingConverter.SetSrcPath(sFileInDir); - BinaryFileReader oBinaryFileReader(sFileInDir, oBufferedStream, *m_pCurFileWriter, m_bIsMacro); + BinaryFileReader oBinaryFileReader(sFileInDir, oBufferedStream, *m_pCurFileWriter, m_bIsMacro, m_bIsOForm); oBinaryFileReader.ReadFile(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //themes @@ -478,7 +478,7 @@ bool BinDocxRW::CDocxSerializer::getXmlContent(NSBinPptxRW::CBinaryFileReader& o { long nLength = oBufferedStream.GetLong(); Writers::ContentWriter oTempContentWriter; - BinDocxRW::Binary_DocumentTableReader oBinary_DocumentTableReader(oBufferedStream, *m_pCurFileWriter, oTempContentWriter); + BinDocxRW::Binary_DocumentTableReader oBinary_DocumentTableReader(oBufferedStream, *m_pCurFileWriter, oTempContentWriter, false); oBinary_DocumentTableReader.ReadDocumentContentOut(nLength); sOutputXml = oTempContentWriter.m_oContent.GetData(); @@ -566,7 +566,7 @@ bool BinDocxRW::CDocxSerializer::getXmlContentElem(OOX::EElementType eType, NSBi { long nLength = oBufferedStream.GetLong(); Writers::ContentWriter oTempContentWriter; - BinDocxRW::Binary_DocumentTableReader oBinary_DocumentTableReader(oBufferedStream, *m_pCurFileWriter, oTempContentWriter); + BinDocxRW::Binary_DocumentTableReader oBinary_DocumentTableReader(oBufferedStream, *m_pCurFileWriter, oTempContentWriter, m_bIsOForm); if(OOX::et_m_oMathPara == eType) { @@ -606,6 +606,10 @@ void BinDocxRW::CDocxSerializer::setMacroEnabled(bool val) { m_bIsMacro = val; } +void BinDocxRW::CDocxSerializer::setOFormEnabled(bool val) +{ + m_bIsOForm = val; +} bool BinDocxRW::CDocxSerializer::unpackageFile(const std::wstring& sSrcFileName, const std::wstring& sDstPath) { BinDocxRW::CPackageFile file; diff --git a/OOXML/Binary/Document/DocWrapper/DocxSerializer.h b/OOXML/Binary/Document/DocWrapper/DocxSerializer.h index b0ce507baa..1a90965a6a 100644 --- a/OOXML/Binary/Document/DocWrapper/DocxSerializer.h +++ b/OOXML/Binary/Document/DocWrapper/DocxSerializer.h @@ -55,6 +55,7 @@ namespace BinDocxRW bool m_bIsMacro; bool m_bIsNoBase64Save; bool m_bIsNoBase64; + bool m_bIsOForm; public: Writers::FileWriter* m_pCurFileWriter; ParamsWriter* m_pParamsWriter; @@ -82,5 +83,6 @@ namespace BinDocxRW void setIsNoBase64 (bool val); void setSaveChartAsImg (bool val); void setMacroEnabled (bool val); + void setOFormEnabled (bool val); }; } diff --git a/OOXML/Binary/Presentation/XmlWriter.cpp b/OOXML/Binary/Presentation/XmlWriter.cpp index 4f829e6918..5ab7301c3d 100644 --- a/OOXML/Binary/Presentation/XmlWriter.cpp +++ b/OOXML/Binary/Presentation/XmlWriter.cpp @@ -106,7 +106,7 @@ void CXmlWriter::WriteSIZET(const size_t& val) } void CXmlWriter::WriteDWORD_hex(const DWORD& val) { - m_oWriter.WriteString(XmlUtils::ToString(val, L"%x")); + m_oWriter.WriteString(XmlUtils::ToString((_UINT32)val, L"%x")); } void CXmlWriter::WriteBool(const bool& val) { diff --git a/OOXML/Binary/Sheets/Common/BinReaderWriterDefines.h b/OOXML/Binary/Sheets/Common/BinReaderWriterDefines.h index 996d59d4f6..c3e675a808 100644 --- a/OOXML/Binary/Sheets/Common/BinReaderWriterDefines.h +++ b/OOXML/Binary/Sheets/Common/BinReaderWriterDefines.h @@ -230,8 +230,8 @@ namespace BinXlsxRW SlicerCache = 20, Protection = 21, OleSize = 22, - ExternalFileId = 23, - ExternalPortalName = 24 + ExternalFileKey = 23, + ExternalInstanceId = 24 };} namespace c_oSerWorkbookProtection {enum c_oSerWorkbookProtection{ AlgorithmName = 0, diff --git a/OOXML/Binary/Sheets/Reader/BinaryWriter.cpp b/OOXML/Binary/Sheets/Reader/BinaryWriter.cpp index 238d969338..8769177400 100644 --- a/OOXML/Binary/Sheets/Reader/BinaryWriter.cpp +++ b/OOXML/Binary/Sheets/Reader/BinaryWriter.cpp @@ -2852,16 +2852,16 @@ void BinaryWorkbookTableWriter::WriteExternalReferences(const OOX::Spreadsheet:: int nCurPos2 = m_oBcw.WriteItemStart(c_oSerWorkbookTypes::ExternalReference); - if (pExternalLink->m_oFileId.IsInit()) + if (pExternalLink->m_oFileKey.IsInit()) { - int nCurPos = m_oBcw.WriteItemStart(c_oSerWorkbookTypes::ExternalFileId); - m_oBcw.m_oStream.WriteStringW3(*pExternalLink->m_oFileId); + int nCurPos = m_oBcw.WriteItemStart(c_oSerWorkbookTypes::ExternalFileKey); + m_oBcw.m_oStream.WriteStringW3(*pExternalLink->m_oFileKey); m_oBcw.WriteItemWithLengthEnd(nCurPos); } - if (pExternalLink->m_oPortalName.IsInit()) + if (pExternalLink->m_oInstanceId.IsInit()) { - int nCurPos = m_oBcw.WriteItemStart(c_oSerWorkbookTypes::ExternalPortalName); - m_oBcw.m_oStream.WriteStringW3(*pExternalLink->m_oPortalName); + int nCurPos = m_oBcw.WriteItemStart(c_oSerWorkbookTypes::ExternalInstanceId); + m_oBcw.m_oStream.WriteStringW3(*pExternalLink->m_oInstanceId); m_oBcw.WriteItemWithLengthEnd(nCurPos); } if (pExternalLink->m_oExternalBook.IsInit()) diff --git a/OOXML/Binary/Sheets/Writer/BinaryReader.cpp b/OOXML/Binary/Sheets/Writer/BinaryReader.cpp index f7036ffc25..e5a082d6b9 100644 --- a/OOXML/Binary/Sheets/Writer/BinaryReader.cpp +++ b/OOXML/Binary/Sheets/Writer/BinaryReader.cpp @@ -2730,13 +2730,13 @@ int BinaryWorkbookTableReader::ReadExternalReference(BYTE type, long length, voi externalLink->m_oDdeLink.Init(); READ1_DEF(length, res, this->ReadDdeLink, externalLink->m_oDdeLink.GetPointer()); } - else if (c_oSerWorkbookTypes::ExternalFileId == type) + else if (c_oSerWorkbookTypes::ExternalFileKey == type) { - externalLink->m_oFileId = m_oBufferedStream.GetString4(length); + externalLink->m_oFileKey = m_oBufferedStream.GetString4(length); } - else if (c_oSerWorkbookTypes::ExternalPortalName == type) + else if (c_oSerWorkbookTypes::ExternalInstanceId == type) { - externalLink->m_oPortalName = m_oBufferedStream.GetString4(length); + externalLink->m_oInstanceId = m_oBufferedStream.GetString4(length); } else res = c_oSerConstants::ReadUnknown; @@ -2748,7 +2748,7 @@ int BinaryWorkbookTableReader::ReadExternalReferences(BYTE type, long length, vo if (c_oSerWorkbookTypes::ExternalReference == type) { OOX::Spreadsheet::CExternalLink *extLink = new OOX::Spreadsheet::CExternalLink(NULL); - READ2_DEF_SPREADSHEET(length, res, this->ReadExternalReference, extLink); + READ1_DEF(length, res, this->ReadExternalReference, extLink); smart_ptr oCurFile(extLink); const OOX::RId oRId = m_oWorkbook.Add(oCurFile); @@ -2887,7 +2887,7 @@ int BinaryWorkbookTableReader::ReadExternalBook(BYTE type, long length, void* po { std::wstring sName(m_oBufferedStream.GetString3(length)); - OOX::Spreadsheet::ExternalLinkPath *link = new OOX::Spreadsheet::ExternalLinkPath(NULL, sName); + OOX::Spreadsheet::ExternalLinkPath *link = new OOX::Spreadsheet::ExternalLinkPath(NULL, OOX::CPath(sName, false)); smart_ptr oLinkFile(link); const OOX::RId oRIdLink = extLink->Add(oLinkFile); diff --git a/OOXML/DocxFormat/Document.cpp b/OOXML/DocxFormat/Document.cpp index fbfc3cd22b..2cfa2b60a5 100644 --- a/OOXML/DocxFormat/Document.cpp +++ b/OOXML/DocxFormat/Document.cpp @@ -323,7 +323,7 @@ namespace OOX else if (L"m:oMathPara" == sName ) pItem = new Logic::COMathPara( document ); else if (L"p" == sName ) - pItem = new Logic::CParagraph( document ); + pItem = new Logic::CParagraph( document, this ); else if (L"permEnd" == sName ) pItem = new Logic::CPermEnd( document ); else if (L"permStart" == sName ) @@ -382,14 +382,15 @@ namespace OOX else if (L"docParts" == sName && !oReader.IsEmptyNode()) { WritingElement *pItem = new OOX::Logic::CDocParts(WritingElement::m_pMainDocument); - m_arrItems.push_back(pItem); + pItem->fromXML(oReader); + m_arrItems.push_back(pItem); } if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Drawing/DrawingExt.cpp b/OOXML/DocxFormat/Drawing/DrawingExt.cpp index dab0533e71..a2c7bf2052 100644 --- a/OOXML/DocxFormat/Drawing/DrawingExt.cpp +++ b/OOXML/DocxFormat/Drawing/DrawingExt.cpp @@ -306,8 +306,8 @@ namespace OOX else if (sName == L"externalReference") { WritingElement_ReadAttributes_Start_No_NS(oReader) - WritingElement_ReadAttributes_Read_if(oReader, L"fileId", m_oFileId) - WritingElement_ReadAttributes_Read_else_if(oReader, L"portalName", m_oPortalName) + WritingElement_ReadAttributes_Read_if(oReader, L"fileKey", m_oFileKey) + WritingElement_ReadAttributes_Read_else_if(oReader, L"instanceId", m_oInstanceId) WritingElement_ReadAttributes_End_No_NS(oReader) } } @@ -456,14 +456,14 @@ namespace OOX m_oPivotCacheDefinitionExt->toXML(writer, L"x14:pivotCacheDefinition"); sResult += writer.GetData().c_str(); } - if (m_oFileId.IsInit() || m_oPortalName.IsInit()) + if (m_oFileKey.IsInit() || m_oInstanceId.IsInit()) { NSStringUtils::CStringBuilder writer; writer.StartNode(L"externalReference"); writer.StartAttributes(); - if (m_oFileId.IsInit()) writer.WriteAttribute(L"fileId", *m_oFileId); - if (m_oPortalName.IsInit()) writer.WriteAttribute(L"portalName", *m_oPortalName); + if (m_oFileKey.IsInit()) writer.WriteAttribute(L"fileKey", *m_oFileKey); + if (m_oInstanceId.IsInit()) writer.WriteAttribute(L"instanceId", *m_oInstanceId); writer.EndAttributes(); writer.EndNode(L"externalReference"); diff --git a/OOXML/DocxFormat/Drawing/DrawingExt.h b/OOXML/DocxFormat/Drawing/DrawingExt.h index 6fc1d99ab0..63dd8c0601 100644 --- a/OOXML/DocxFormat/Drawing/DrawingExt.h +++ b/OOXML/DocxFormat/Drawing/DrawingExt.h @@ -152,8 +152,8 @@ namespace OOX nullable m_oPresenceInfo; - nullable_string m_oFileId; - nullable_string m_oPortalName; + nullable_string m_oFileKey; + nullable_string m_oInstanceId; }; //-------------------------------------------------------------------------------- diff --git a/OOXML/DocxFormat/FileTypes.cpp b/OOXML/DocxFormat/FileTypes.cpp index 72f7a3fd5c..213661efb0 100644 --- a/OOXML/DocxFormat/FileTypes.cpp +++ b/OOXML/DocxFormat/FileTypes.cpp @@ -167,19 +167,19 @@ namespace OOX const FileType Image (L"media", L"image", L"", - L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", L"image", true, true); + L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", L"image", true); const FileType Audio (L"media", L"audio", L"", - L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio", L"audio", true, true); + L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio", L"audio", true); const FileType Video (L"media", L"video", L"", - L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/video", L"video", true, true); + L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/video", L"video", true); const FileType Media (L"media", L"media", L"", - L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/media", L"media", true, true); + L"http://schemas.openxmlformats.org/officeDocument/2006/relationships/media", L"media", true); const FileType DiagramData (L"diagrams", L"data.xml", L"application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml", diff --git a/OOXML/DocxFormat/HeaderFooter.cpp b/OOXML/DocxFormat/HeaderFooter.cpp index 279424fc2d..2097b85a8c 100644 --- a/OOXML/DocxFormat/HeaderFooter.cpp +++ b/OOXML/DocxFormat/HeaderFooter.cpp @@ -161,7 +161,7 @@ namespace OOX else if ( _T("m:oMathPara") == sName ) pItem = new Logic::COMathPara( document ); else if ( _T("w:p") == sName ) - pItem = new Logic::CParagraph( document ); + pItem = new Logic::CParagraph( document, this ); else if ( _T("w:permEnd") == sName ) pItem = new Logic::CPermEnd( document ); else if ( _T("w:permStart") == sName ) @@ -175,9 +175,8 @@ namespace OOX if ( pItem ) { - m_arrItems.push_back( pItem ); - pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Logic/DocParts.cpp b/OOXML/DocxFormat/Logic/DocParts.cpp index 590442cafb..7b5f628707 100644 --- a/OOXML/DocxFormat/Logic/DocParts.cpp +++ b/OOXML/DocxFormat/Logic/DocParts.cpp @@ -64,9 +64,9 @@ namespace OOX if (L"w:docPart" == sName) { CDocPart *pItem = new CDocPart(m_pMainDocument); - m_arrItems.push_back(pItem); - pItem->fromXML(oReader); + + m_arrItems.push_back(pItem); } } } @@ -221,6 +221,8 @@ namespace OOX if (oReader.IsEmptyNode()) return; + OOX::Document* document = WritingElement::m_pMainDocument; + int nParentDepth = oReader.GetDepth(); while (oReader.ReadNextSiblingNode(nParentDepth)) { @@ -287,7 +289,9 @@ namespace OOX AssignPtrXmlContent(pItem, CTbl, oReader) if (pItem) + { m_arrItems.push_back(pItem); + } } } std::wstring CDocPartBody::toXML() const diff --git a/OOXML/DocxFormat/Logic/FldSimple.cpp b/OOXML/DocxFormat/Logic/FldSimple.cpp index e41d85e43a..6767373d49 100644 --- a/OOXML/DocxFormat/Logic/FldSimple.cpp +++ b/OOXML/DocxFormat/Logic/FldSimple.cpp @@ -187,6 +187,8 @@ namespace OOX if ( oReader.IsEmptyNode() ) return; + OOX::Document* document = WritingElement::m_pMainDocument; + int nParentDepth = oReader.GetDepth(); while( oReader.ReadNextSiblingNode( nParentDepth ) ) { @@ -267,8 +269,10 @@ namespace OOX m_oFFData = oReader; } - if ( pItem ) - m_arrItems.push_back( pItem ); + if (pItem) + { + m_arrItems.push_back(pItem); + } } } std::wstring CFldSimple::toXML() const diff --git a/OOXML/DocxFormat/Logic/Hyperlink.cpp b/OOXML/DocxFormat/Logic/Hyperlink.cpp index a42c524421..621ae9d714 100644 --- a/OOXML/DocxFormat/Logic/Hyperlink.cpp +++ b/OOXML/DocxFormat/Logic/Hyperlink.cpp @@ -287,7 +287,7 @@ namespace OOX else if ( _T("w:proofErr") == sName ) pItem = new CProofErr( document ); else if ( _T("w:r") == sName ) - pItem = new CRun( document ); + pItem = new CRun( document, this ); else if ( _T("w:sdt") == sName ) pItem = new CSdt( document ); else if ( _T("w:smartTag") == sName ) @@ -297,8 +297,8 @@ namespace OOX if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Logic/Paragraph.cpp b/OOXML/DocxFormat/Logic/Paragraph.cpp index 21a6667f81..ae1dd6594f 100644 --- a/OOXML/DocxFormat/Logic/Paragraph.cpp +++ b/OOXML/DocxFormat/Logic/Paragraph.cpp @@ -32,6 +32,7 @@ #include "../DocxFlat.h" #include "../Comments.h" +#include "Table.h" #include "Paragraph.h" #include "Annotations.h" #include "Run.h" @@ -62,13 +63,15 @@ namespace OOX // CParagraph 17.3.1.22 (Part 1) //-------------------------------------------------------------------------------- - CParagraph::CParagraph(OOX::Document *pMain) : WritingElementWithChilds<>(pMain) + CParagraph::CParagraph(OOX::Document *pMain, WritingElement *parent) : WritingElementWithChilds<>(pMain) { m_oParagraphProperty = NULL; - } + m_oParent = parent; + } CParagraph::~CParagraph() { m_oParagraphProperty = NULL; + m_oParent = NULL; } const CParagraph& CParagraph::operator =(const XmlUtils::CXmlNode& oNode) { @@ -342,7 +345,7 @@ namespace OOX else if (L"proofErr" == sName ) pItem = new CProofErr( document ); else if (L"r" == sName ) - pItem = new CRun( document ); + pItem = new CRun( document, this ); else if (L"sdt" == sName ) pItem = new CSdt( document ); else if (L"smartTag" == sName ) @@ -364,10 +367,24 @@ namespace OOX int nWxSubSectDepth = oReader.GetDepth(); fromXML(nWxSubSectDepth, oReader); } + else if (L"tbl" == sName) + { + WritingElementWithChilds *parent = dynamic_cast(m_oParent); + if (parent) + { + WritingElement *pItemUpper = new CTbl(document); + if (pItemUpper) + { + pItemUpper->fromXML(oReader); + parent->m_arrItems.push_back(pItemUpper); + } + } + } + if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Logic/Paragraph.h b/OOXML/DocxFormat/Logic/Paragraph.h index 3f03122116..1b4e145db6 100644 --- a/OOXML/DocxFormat/Logic/Paragraph.h +++ b/OOXML/DocxFormat/Logic/Paragraph.h @@ -46,7 +46,7 @@ namespace OOX class CParagraph : public WritingElementWithChilds<> { public: - CParagraph(OOX::Document *pMain = NULL); + CParagraph(OOX::Document *pMain = NULL, WritingElement *parent = NULL); virtual ~CParagraph(); const CParagraph &operator =(const XmlUtils::CXmlNode& oNode); @@ -75,6 +75,7 @@ namespace OOX CParagraphProperty *m_oParagraphProperty; // копия того что в m_arrItems... - для быстрого доступа/анализа // по идее нужно сделать как в Drawing::Paragraph - то есть единственные подобъекты вынести отдельно + WritingElement *m_oParent = NULL; }; } // namespace Logic } // namespace OOX diff --git a/OOXML/DocxFormat/Logic/Run.cpp b/OOXML/DocxFormat/Logic/Run.cpp index c8ff1f9268..ec435c09fa 100644 --- a/OOXML/DocxFormat/Logic/Run.cpp +++ b/OOXML/DocxFormat/Logic/Run.cpp @@ -41,6 +41,8 @@ #include "../Drawing/Drawing.h" #include "../Comments.h" +#include "Table.h" +#include "Paragraph.h" #include "AlternateContent.h" #include "RunProperty.h" #include "RunContent.h" @@ -55,10 +57,11 @@ namespace OOX { namespace Logic { - CRun::CRun(OOX::Document *pMain) : WritingElementWithChilds<>(pMain) + CRun::CRun(OOX::Document *pMain, WritingElement *parent) : WritingElementWithChilds<>(pMain) { m_oRunProperty = NULL; - } + m_oParent = parent; + } CRun::~CRun() { ClearItems(); @@ -279,6 +282,22 @@ namespace OOX } pItem = pEndRef; } + else if (L"tbl" == sName) + {//ERP + CParagraph *paragraph = dynamic_cast(m_oParent); + WritingElementWithChilds *parent = paragraph ? dynamic_cast(paragraph->m_oParent) : NULL; + + if (!parent) parent = dynamic_cast(m_oParent); + if (parent) + { + WritingElement *pItemUpper = new CTbl(document); + if (pItemUpper) + { + pItemUpper->fromXML(oReader); + parent->m_arrItems.push_back(pItemUpper); + } + } + } else if ( L"endnoteRef" == sName ) pItem = new CEndnoteRef( document ); else if ( L"endnoteReference" == sName ) diff --git a/OOXML/DocxFormat/Logic/Run.h b/OOXML/DocxFormat/Logic/Run.h index 0910c4c061..3c724669b9 100644 --- a/OOXML/DocxFormat/Logic/Run.h +++ b/OOXML/DocxFormat/Logic/Run.h @@ -46,7 +46,8 @@ namespace OOX class CRun : public WritingElementWithChilds<> { public: - CRun(OOX::Document *pMain = NULL); + CRun(OOX::Document *pMain = NULL, WritingElement *parent = NULL); + virtual ~CRun(); const CRun &operator =(const XmlUtils::CXmlNode& oNode); @@ -73,6 +74,7 @@ namespace OOX nullable m_oRsidRPr; OOX::Logic::CRunProperty *m_oRunProperty; // копия того что в m_arrItems... - для быстрого доступа/анализа // по идее нужно сделать как в Drawing::Run - то есть единственные подобъекты вынести отдельно + WritingElement *m_oParent = NULL; }; } // namespace Logic } // namespace OOX diff --git a/OOXML/DocxFormat/Logic/RunContent.cpp b/OOXML/DocxFormat/Logic/RunContent.cpp index fcc6af5939..2fc4f0e0e0 100644 --- a/OOXML/DocxFormat/Logic/RunContent.cpp +++ b/OOXML/DocxFormat/Logic/RunContent.cpp @@ -44,6 +44,9 @@ namespace OOX CBr::~CBr() {} void CBr::fromXML(XmlUtils::CXmlNode &oNode) { + m_oClear.SetValue(SimpleTypes::brclearNone); + m_oType.SetValue(SimpleTypes::brtypeTextWrapping); + XmlMacroReadAttributeBase( oNode, _T("w:type"), m_oType ); XmlMacroReadAttributeBase( oNode, _T("w:clear"), m_oClear ); } diff --git a/OOXML/DocxFormat/Logic/Sdt.cpp b/OOXML/DocxFormat/Logic/Sdt.cpp index a4ccef8308..c6a9798981 100644 --- a/OOXML/DocxFormat/Logic/Sdt.cpp +++ b/OOXML/DocxFormat/Logic/Sdt.cpp @@ -529,6 +529,9 @@ namespace OOX return; int nParentDepth = oReader.GetDepth(); + + OOX::Document* document = WritingElement::m_pMainDocument; + while( oReader.ReadNextSiblingNode( nParentDepth ) ) { std::wstring sName = oReader.GetName(); @@ -603,7 +606,7 @@ namespace OOX else if ( L"w:smartTag" == sName ) AssignPtrXmlContent(pItem, CSmartTag, oReader) //else if ( L"w:subDoc" == sName ) - // pItem = new CSubDoc( oReader ); + // pItem = new CSubDoc( document ); else if ( L"w:tbl" == sName ) AssignPtrXmlContent(pItem, CTbl, oReader) else if ( L"w:tc" == sName ) @@ -611,8 +614,10 @@ namespace OOX else if ( L"w:tr" == sName ) AssignPtrXmlContent(pItem, CTr, oReader) - if ( pItem ) - m_arrItems.push_back( pItem ); + if (pItem) + { + m_arrItems.push_back(pItem); + } } } std::wstring CSdtContent::toXML() const @@ -673,6 +678,12 @@ namespace OOX m_oShd = oReader; else if (L"w:border" == sName) m_oBorder = oReader; + else if (L"w:field" == sName) + { + WritingElement_ReadAttributes_Start(oReader) + WritingElement_ReadAttributes_ReadSingle(oReader, L"r:id", m_oFieldRid) + WritingElement_ReadAttributes_End(oReader) + } } } std::wstring CFormPr::toXML() const @@ -707,6 +718,10 @@ namespace OOX WritingElement_WriteNode_1(L"ToString() + L"\"/>"; + } sResult += L""; return sResult; @@ -1476,12 +1491,6 @@ namespace OOX m_oFormPr = oReader; else if (L"w:textFormPr" == sName) m_oTextFormPr = oReader; - else if (L"w:oform" == sName) - { - WritingElement_ReadAttributes_Start(oReader) - WritingElement_ReadAttributes_ReadSingle(oReader, L"r:id", m_oOformRid) - WritingElement_ReadAttributes_End(oReader) - } else if (sdttypeUnknown == m_eType && L"w:text" == sName) { m_oText = oReader; @@ -1604,10 +1613,6 @@ namespace OOX WritingElement_WriteNode_2(m_oTextFormPr); WritingElement_WriteNode_2(m_oComplexFormPr); - if (m_oOformRid.IsInit()) - { - sResult += L"ToString() + L"\"/>"; - } return sResult; } std::wstring CSdtPr::toXMLEnd() const @@ -1776,15 +1781,27 @@ namespace OOX return; int nParentDepth = oReader.GetDepth(); + + OOX::Document* document = WritingElement::m_pMainDocument; + while( oReader.ReadNextSiblingNode( nParentDepth ) ) { std::wstring sName = oReader.GetName(); - if ( L"w:sdtContent" == sName ) - m_oSdtContent = oReader; - else if ( L"w:sdtEndPr" == sName ) - m_oSdtEndPr = oReader; - else if ( L"w:sdtPr" == sName ) - m_oSdtPr = oReader; + if (L"w:sdtContent" == sName) + { + m_oSdtContent = new CSdtContent(document); + m_oSdtContent->fromXML(oReader); + } + else if (L"w:sdtEndPr" == sName) + { + m_oSdtEndPr = new CSdtEndPr(document); + m_oSdtEndPr->fromXML(oReader); + } + else if (L"w:sdtPr" == sName) + { + m_oSdtPr = new CSdtPr(document); + m_oSdtPr->fromXML(oReader); + } } } std::wstring CSdt::toXML() const diff --git a/OOXML/DocxFormat/Logic/Sdt.h b/OOXML/DocxFormat/Logic/Sdt.h index 4a40f89336..474ddbd519 100644 --- a/OOXML/DocxFormat/Logic/Sdt.h +++ b/OOXML/DocxFormat/Logic/Sdt.h @@ -261,6 +261,7 @@ namespace OOX nullable m_oBorder; nullable m_oShd; + nullable m_oFieldRid; }; //Not from specification @@ -579,7 +580,6 @@ namespace OOX nullable m_oTextFormPr; //Not from specification nullable m_oPicture; //Not from specification nullable m_oComplexFormPr; // Not from specification - nullable m_oOformRid; // Not from specification }; //-------------------------------------------------------------------------------- diff --git a/OOXML/DocxFormat/Logic/Shape.cpp b/OOXML/DocxFormat/Logic/Shape.cpp index 9be3955bdd..84f29553bf 100644 --- a/OOXML/DocxFormat/Logic/Shape.cpp +++ b/OOXML/DocxFormat/Logic/Shape.cpp @@ -137,7 +137,7 @@ namespace OOX else if (L"m:oMathPara" == sName ) pItem = new COMathPara( document ); else if (L"w:p" == sName ) - pItem = new CParagraph( document ); + pItem = new CParagraph( document, this ); else if (L"w:permEnd" == sName ) pItem = new CPermEnd( document ); else if (L"w:permStart" == sName ) @@ -151,8 +151,8 @@ namespace OOX if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Logic/Table.cpp b/OOXML/DocxFormat/Logic/Table.cpp index 75700eac87..9e97c2bc27 100644 --- a/OOXML/DocxFormat/Logic/Table.cpp +++ b/OOXML/DocxFormat/Logic/Table.cpp @@ -503,8 +503,8 @@ namespace OOX if (pItem) { - m_arrItems.push_back(pItem); pItem->fromXML(oReader); + m_arrItems.push_back(pItem); } } } @@ -807,8 +807,8 @@ namespace OOX if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } m_nCountCell = nNumCol; @@ -1045,7 +1045,7 @@ namespace OOX else if ( _T("m:oMathPara") == sName ) pItem = new COMathPara( document ); else if ( _T("w:p") == sName ) - pItem = new CParagraph( document ); + pItem = new CParagraph( document, this ); else if ( _T("w:permEnd") == sName ) pItem = new CPermEnd( document ); else if ( _T("w:permStart") == sName ) @@ -1078,8 +1078,8 @@ namespace OOX } if ( pItem ) { - m_arrItems.push_back( pItem ); pItem->fromXML(oReader); + m_arrItems.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Logic/Vml.cpp b/OOXML/DocxFormat/Logic/Vml.cpp index 4e36d77ab3..d45e2c4c5f 100644 --- a/OOXML/DocxFormat/Logic/Vml.cpp +++ b/OOXML/DocxFormat/Logic/Vml.cpp @@ -191,8 +191,8 @@ namespace OOX if (NULL != pItem) { - m_arrItems.push_back(pItem); pItem->fromXML(oReader); + m_arrItems.push_back(pItem); } if ((image_data) && (image_data->m_rId.IsInit())) @@ -801,8 +801,8 @@ namespace OOX if ( NULL != pItem ) { - m_arrElements.push_back( pItem ); pItem->fromXML(oReader); + m_arrElements.push_back( pItem ); } } } diff --git a/OOXML/DocxFormat/Math/oMathBottomNodes.h b/OOXML/DocxFormat/Math/oMathBottomNodes.h index b5377cf2d8..e2a1aedc58 100644 --- a/OOXML/DocxFormat/Math/oMathBottomNodes.h +++ b/OOXML/DocxFormat/Math/oMathBottomNodes.h @@ -340,10 +340,12 @@ namespace OOX } CMathBottomNodesEx(XmlUtils::CXmlNode& oNode) { + CMathBottomNodes::m_eType = type; CMathBottomNodesExFromXML(*this, oNode); } CMathBottomNodesEx(XmlUtils::CXmlLiteReader& oReader) { + CMathBottomNodes::m_eType = type; CMathBottomNodesExFromXML(*this, oReader); } virtual EElementType getType() const diff --git a/OOXML/DocxFormat/Media/Media.cpp b/OOXML/DocxFormat/Media/Media.cpp index 27215e4c53..70c2554eb3 100644 --- a/OOXML/DocxFormat/Media/Media.cpp +++ b/OOXML/DocxFormat/Media/Media.cpp @@ -81,6 +81,9 @@ namespace OOX { m_filename = filename; m_bExist = NSFile::CFileBinary::Exists(m_filename.GetPath()); + + if (m_bExist) + m_sOutputFilename = filename.GetFilename(); } void Media::write(const CPath& filename, const CPath& directory, CContentTypes& content) const { diff --git a/OOXML/PPTXFormat/Logic/Runs/MathParaWrapper.cpp b/OOXML/PPTXFormat/Logic/Runs/MathParaWrapper.cpp index e19f7393da..7539383a8f 100644 --- a/OOXML/PPTXFormat/Logic/Runs/MathParaWrapper.cpp +++ b/OOXML/PPTXFormat/Logic/Runs/MathParaWrapper.cpp @@ -195,35 +195,29 @@ xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\">\ } LONG _end = pReader->GetPos() + pReader->GetRecordSize() + 4; std::wstring sXml; - if(NULL != pReader->m_pMainDocument) - { - pReader->m_pMainDocument->getXmlContentElem(eType, *pReader, m_oXml.get()); - } - else - { - BinDocxRW::CDocxSerializer oDocxSerializer; - NSBinPptxRW::CDrawingConverter oDrawingConverter; - - NSBinPptxRW::CImageManager2* pOldImageManager = oDrawingConverter.m_pImageManager; - NSBinPptxRW::CBinaryFileReader* pOldReader = oDrawingConverter.m_pReader; - - oDrawingConverter.m_pImageManager = pReader->m_pRels->m_pManager; - oDrawingConverter.m_pReader = pReader; - oDocxSerializer.m_pCurFileWriter = new Writers::FileWriter(L"", L"", true, BinDocxRW::g_nFormatVersion, &oDrawingConverter, L""); - oDocxSerializer.getXmlContentElem(eType, *pReader, sXml); + BinDocxRW::CDocxSerializer oDocxSerializer; + NSBinPptxRW::CDrawingConverter oDrawingConverter; + + NSBinPptxRW::CImageManager2* pOldImageManager = oDrawingConverter.m_pImageManager; + NSBinPptxRW::CBinaryFileReader* pOldReader = oDrawingConverter.m_pReader; + + oDrawingConverter.m_pImageManager = pReader->m_pRels->m_pManager; + oDrawingConverter.m_pReader = pReader; + + oDocxSerializer.m_pCurFileWriter = new Writers::FileWriter(L"", L"", true, BinDocxRW::g_nFormatVersion, &oDrawingConverter, L""); + oDocxSerializer.getXmlContentElem(eType, *pReader, sXml); + + oDrawingConverter.m_pReader = pOldReader; + oDrawingConverter.m_pImageManager = pOldImageManager; + RELEASEOBJECT(oDocxSerializer.m_pCurFileWriter); - oDrawingConverter.m_pReader = pOldReader; - oDrawingConverter.m_pImageManager = pOldImageManager; - RELEASEOBJECT(oDocxSerializer.m_pCurFileWriter); - } m_oXml = sXml; pReader->Seek(_end); } std::wstring MathParaWrapper::GetText() const { - //todo - return _T(""); + return L"math"; } void MathParaWrapper::FillParentPointersForChilds(){} } // namespace Logic diff --git a/OOXML/Projects/Windows/PPTXFormatLib/PPTXFormat.vcxproj.filters b/OOXML/Projects/Windows/PPTXFormatLib/PPTXFormat.vcxproj.filters index 0add27bd97..6e9a9129e1 100644 --- a/OOXML/Projects/Windows/PPTXFormatLib/PPTXFormat.vcxproj.filters +++ b/OOXML/Projects/Windows/PPTXFormatLib/PPTXFormat.vcxproj.filters @@ -494,19 +494,19 @@ Logic\Path2D - Logic\Run + Logic\Text - Logic\Run + Logic\Text - Logic\Run + Logic\Text - Logic\Run + Logic\Text - Logic\Run + Logic\Text Logic\Table @@ -949,9 +949,6 @@ Logic - - Logic - Logic @@ -1081,6 +1078,9 @@ Logic + + Logic\Text + @@ -1102,7 +1102,7 @@ Logic\Media - Logic\Run + Logic\Text Logic\Table @@ -1323,16 +1323,16 @@ Logic\Path2D - Logic\Run + Logic\Text - Logic\Run + Logic\Text - Logic\Run + Logic\Text - Logic\Run + Logic\Text Logic\Table @@ -1508,9 +1508,6 @@ Logic - - Logic - Logic @@ -2159,6 +2156,9 @@ Logic\Transition + + Logic\Text + @@ -2185,9 +2185,6 @@ {c3ea8511-a68e-47b3-8b84-b28c8cc782f5} - - {55fb0e4f-f959-4e64-ba5c-696a63abf2ae} - {2ff27397-b6ce-4764-94f7-d5948530c211} @@ -2209,5 +2206,8 @@ {79724603-f046-4794-939c-1fca08505a20} + + {55fb0e4f-f959-4e64-ba5c-696a63abf2ae} + \ No newline at end of file diff --git a/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.cpp b/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.cpp index 5eb7841212..8d82756bb2 100644 --- a/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.cpp +++ b/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.cpp @@ -1496,11 +1496,11 @@ namespace Spreadsheet for (size_t i = 0; (oExtLst.IsInit()) && (i < oExtLst->m_arrExt.size()); i++) { - if (oExtLst->m_arrExt[i]->m_oFileId.IsInit() || - oExtLst->m_arrExt[i]->m_oPortalName.IsInit()) + if (oExtLst->m_arrExt[i]->m_oFileKey.IsInit() || + oExtLst->m_arrExt[i]->m_oInstanceId.IsInit()) { - m_oFileId = oExtLst->m_arrExt[i]->m_oFileId; - m_oPortalName = oExtLst->m_arrExt[i]->m_oPortalName; + m_oFileKey = oExtLst->m_arrExt[i]->m_oFileKey; + m_oInstanceId = oExtLst->m_arrExt[i]->m_oInstanceId; break; } } @@ -1528,11 +1528,11 @@ namespace Spreadsheet { m_oDdeLink->toXML(sXml); } - if (m_oFileId.IsInit() || m_oPortalName.IsInit()) + if (m_oFileKey.IsInit() || m_oInstanceId.IsInit()) { OOX::Drawing::COfficeArtExtension oExt; - oExt.m_oFileId = m_oFileId; - oExt.m_oPortalName = m_oPortalName; + oExt.m_oFileKey = m_oFileKey; + oExt.m_oInstanceId = m_oInstanceId; oExt.m_sUri = L"{C3750BE0-5CA9-4D1C-82C7-79D762991C26}"; diff --git a/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.h b/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.h index 32dce2e7b3..21262fcb6a 100644 --- a/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.h +++ b/OOXML/XlsxFormat/ExternalLinks/ExternalLinks.h @@ -441,8 +441,8 @@ namespace OOX nullable m_oOleLink; nullable m_oDdeLink; - nullable_string m_oFileId; - nullable_string m_oPortalName; + nullable_string m_oFileKey; + nullable_string m_oInstanceId; private: CPath m_oReadPath; std::wstring m_rId; diff --git a/OOXML/XlsxFormat/Xlsx.cpp b/OOXML/XlsxFormat/Xlsx.cpp index ff849ad7ab..51db4a6b82 100644 --- a/OOXML/XlsxFormat/Xlsx.cpp +++ b/OOXML/XlsxFormat/Xlsx.cpp @@ -151,6 +151,7 @@ bool OOX::Spreadsheet::CXlsx::WriteNative(const CPath& oDirPath, OOX::CContentTy IFileContainer::Write(oDirPath / L"", OOX::CPath(_T("")), oContentTypes); oContentTypes.Write(oDirPath); + return true; } bool OOX::Spreadsheet::CXlsx::Write(const CPath& oDirPath, OOX::CContentTypes &oContentTypes) { diff --git a/OdfFile/Common/utils.cpp b/OdfFile/Common/utils.cpp index e65f86494b..9732cba898 100644 --- a/OdfFile/Common/utils.cpp +++ b/OdfFile/Common/utils.cpp @@ -64,15 +64,23 @@ namespace _graphics_utils_ if (file_size < 1) return false; bool result = false; - CBgraFrame image; - if (result = image.OpenFile(fileName, 0 )) - { - Width = image.get_Width(); - Height = image.get_Height(); + try + { + CBgraFrame image; + if (result = image.OpenFile(fileName, 0)) + { + Width = image.get_Width(); + Height = image.get_Height(); - result = true; - } - else + result = true; + } + } + catch (...) + { + result = false; + } + + if (!result) { #if defined(_WIN32) || defined(_WIN64) Gdiplus::GdiplusStartupInput gdiplusStartupInput; diff --git a/OdfFile/Formulas/formulasconvert_odf.cpp b/OdfFile/Formulas/formulasconvert_odf.cpp index 72ec4ad914..c90cb0d09b 100644 --- a/OdfFile/Formulas/formulasconvert_odf.cpp +++ b/OdfFile/Formulas/formulasconvert_odf.cpp @@ -577,7 +577,7 @@ namespace formulasconvert { replace_semicolons (workstr); replace_tilda (workstr); replace_vertical (workstr); - replace_apersand (workstr); + //replace_apersand (workstr); if (isFormula) { diff --git a/OdfFile/Reader/Converter/docx_conversion_context.cpp b/OdfFile/Reader/Converter/docx_conversion_context.cpp index 8973a4fd23..4571664be5 100644 --- a/OdfFile/Reader/Converter/docx_conversion_context.cpp +++ b/OdfFile/Reader/Converter/docx_conversion_context.cpp @@ -55,7 +55,7 @@ #include "../../../DesktopEditor/graphics/pro/Fonts.h" #include "../../../OOXML/Base/Unit.h" -static int current_id_changes = 0; +static int current_id_changes = 1; namespace cpdoccore { namespace oox { @@ -237,7 +237,7 @@ void docx_conversion_context::add_element_to_run(std::wstring parenStyleId) get_styles_context().start(); - if(( textProp) && (textProp->content_.r_style_))parenStyleId = _T(""); + if(( textProp) && (textProp->content_.r_style_)) parenStyleId = _T(""); textProp->content_.docx_convert(*this); } @@ -2375,23 +2375,27 @@ void docx_conversion_context::start_text_changes (const std::wstring &id) if (state_.in_paragraph_) { - std::wstring format_change = L" w:date=\"" + state.date + L"\"" + - L" w:author=\"" + state.author + L"\""; + std::wstring format_change = L" w:date=\"" + state.date + L"\" w:author=\"" + state.author + L"\""; finish_run(); - state.active = true; state.in_drawing = get_drawing_state_content(); - if (state.type == 1) + if (state.oox_id == 0) { - output_stream() << L""; + state.oox_id = current_id_changes++; + } + + if (state.type == 1 && !state.active) + { + output_stream() << L""; + state.active = true; } if (state.type == 2) { for (size_t i = 0; i < state.content.size(); i++) { - output_stream() << L""; + output_stream() << L""; output_stream() << state.content[i]; @@ -2429,7 +2433,12 @@ void docx_conversion_context::start_changes() std::wstring change_attr; change_attr += L" w:date=\"" + state.date + L"\""; change_attr += L" w:author=\"" + state.author + L"\""; - change_attr += L" w:id=\"" + std::to_wstring(current_id_changes++) + L"\""; + + if (state.oox_id == 0) + { + state.oox_id = current_id_changes++; + } + change_attr += L" w:id=\"" + std::to_wstring(state.oox_id) + L"\""; if (state.out_active) { diff --git a/OdfFile/Reader/Converter/docx_conversion_context.h b/OdfFile/Reader/Converter/docx_conversion_context.h index c000f64c1a..9119a0aa55 100644 --- a/OdfFile/Reader/Converter/docx_conversion_context.h +++ b/OdfFile/Reader/Converter/docx_conversion_context.h @@ -521,9 +521,11 @@ public: int type = 0; std::wstring style_name; std::vector content; //delete elements + bool active = false; bool in_drawing = false; bool out_active = false; + _UINT32 oox_id = 0; void clear() { @@ -535,6 +537,7 @@ public: content.clear(); active = false; in_drawing = false; + oox_id = 0; } }; std::wstring dumpPPr_; diff --git a/OdfFile/Reader/Converter/drawing_object_description.h b/OdfFile/Reader/Converter/drawing_object_description.h index c70e7311e1..999ef3e353 100644 --- a/OdfFile/Reader/Converter/drawing_object_description.h +++ b/OdfFile/Reader/Converter/drawing_object_description.h @@ -38,13 +38,13 @@ namespace oox { struct _rect { - _rect() : x(0), y(0), cx(0), cy(0) {} + _rect(){} _rect(double cx_, double cy_, double x_, double y_) : x(x_), y(y_), cx(cx_), cy(cy_) {} - double cx; - double cy; - double x; - double y; + double cx = 0; + double cy = 0; + double x = 0; + double y = 0; }; enum _anchor_rel { @@ -57,6 +57,7 @@ struct drawing_object_description bool bNotes_; oox::_rels_type type_; + bool bInner_; std::wstring name_; std::wstring descriptor_; diff --git a/OdfFile/Reader/Converter/pptx_slide_context.cpp b/OdfFile/Reader/Converter/pptx_slide_context.cpp index 5a2c1417b3..fbffa47703 100644 --- a/OdfFile/Reader/Converter/pptx_slide_context.cpp +++ b/OdfFile/Reader/Converter/pptx_slide_context.cpp @@ -224,6 +224,8 @@ void pptx_slide_context::set_transitionSpeed(std::wstring val) ///////////////////////////////////////////////////////////////////////////////////////////////// void pptx_slide_context::default_set() { + impl_->object_description_.bInner_ = false; + impl_->object_description_.type_ = typeUnknown; impl_->object_description_.xlink_href_ = L""; impl_->object_description_.name_ = L""; impl_->object_description_.descriptor_ = L""; @@ -373,6 +375,8 @@ void pptx_slide_context::set_name(std::wstring const & name) void pptx_slide_context::start_shape(int type) { + if (impl_->object_description_.bInner_) return; + impl_->object_description_.type_ = typeShape; impl_->object_description_.shape_type_ = type; //2,3... } @@ -509,9 +513,12 @@ void pptx_slide_context::set_image(const std::wstring & path) } } -void pptx_slide_context::start_frame() +bool pptx_slide_context::start_frame() { - impl_->object_description_.type_ = typeUnknown; + if (impl_->object_description_.type_ != typeUnknown) + impl_->object_description_.bInner_ = true; + + return impl_->object_description_.bInner_; } void pptx_slide_context::set_chart(const std::wstring & path) @@ -522,8 +529,13 @@ void pptx_slide_context::set_chart(const std::wstring & path) void pptx_slide_context::end_frame() { - impl_->objects_.push_back(impl_->object_description_); - default_set(); + if (impl_->object_description_.bInner_) + impl_->object_description_.bInner_ = false; + else + { + impl_->objects_.push_back(impl_->object_description_); + default_set(); + } } @@ -541,6 +553,10 @@ bool pptx_slide_context::empty() const { return impl_->empty(); } +bool pptx_slide_context::isDefault() +{ + return impl_->object_description_.type_ == typeUnknown; +} void pptx_slide_context::process_drawings() { diff --git a/OdfFile/Reader/Converter/pptx_slide_context.h b/OdfFile/Reader/Converter/pptx_slide_context.h index 179bb035b8..12e61d40dc 100644 --- a/OdfFile/Reader/Converter/pptx_slide_context.h +++ b/OdfFile/Reader/Converter/pptx_slide_context.h @@ -80,7 +80,7 @@ public: std::wstring add_hyperlink(std::wstring const & ref); - void start_frame(); + bool start_frame(); void set_image (const std::wstring & path); void set_chart (const std::wstring & path); void set_ms_object (const std::wstring & path, const std::wstring & progId); @@ -103,6 +103,7 @@ public: void set_use_image_replacement(); bool empty() const; + bool isDefault(); ////////////////////////////////////////////////////////////////////////////////////////////// void serialize_HeaderFooter (std::wostream & strm); diff --git a/OdfFile/Reader/Converter/pptx_text_context.cpp b/OdfFile/Reader/Converter/pptx_text_context.cpp index 2719793d2c..a9714d7efd 100644 --- a/OdfFile/Reader/Converter/pptx_text_context.cpp +++ b/OdfFile/Reader/Converter/pptx_text_context.cpp @@ -57,6 +57,7 @@ public: styles_context & get_styles_context() { return styles_context_; } void add_text(const std::wstring & text); + void add_paragraph(const std::wstring & para); void start_paragraph(const std::wstring & styleName); void end_paragraph (); @@ -148,7 +149,7 @@ private: pptx_text_context::Impl::Impl(odf_reader::odf_read_context & odf_contxt_, pptx_conversion_context & pptx_contxt_): odf_context_(odf_contxt_), pptx_context_(pptx_contxt_), - paragraphs_cout_(0),in_paragraph(false),in_span(false),in_comment(false),field_type_(none) + paragraphs_cout_(0), in_paragraph(false),in_span(false), in_comment(false), field_type_(none) { new_list_style_number_=0; local_styles_ptr_ = NULL; @@ -162,7 +163,10 @@ void pptx_text_context::Impl::add_text(const std::wstring & text) else text_ << text; } - +void pptx_text_context::Impl::add_paragraph(const std::wstring & para) +{ + paragraph_ << para; +} void pptx_text_context::Impl::set_local_styles_container(odf_reader::styles_container * local_styles_) { local_styles_ptr_= local_styles_; @@ -773,7 +777,10 @@ void pptx_text_context::set_local_styles_container(odf_reader::styles_container* { return impl_->set_local_styles_container(local_styles_); } - +void pptx_text_context::add_paragraph(const std::wstring & para) +{ + return impl_->add_paragraph(para); +} void pptx_text_context::add_text(const std::wstring & text) { return impl_->add_text(text); diff --git a/OdfFile/Reader/Converter/pptx_text_context.h b/OdfFile/Reader/Converter/pptx_text_context.h index bbdc2ef891..03bc323d29 100644 --- a/OdfFile/Reader/Converter/pptx_text_context.h +++ b/OdfFile/Reader/Converter/pptx_text_context.h @@ -60,8 +60,6 @@ enum field_type class pptx_text_context: boost::noncopyable { - - public: pptx_text_context(odf_reader::odf_read_context & odf_context_, pptx_conversion_context & pptx_contxt_); ~pptx_text_context(); @@ -69,6 +67,7 @@ public: void set_local_styles_container(odf_reader::styles_container* local_styles_); void add_text(const std::wstring & text); + void add_paragraph(const std::wstring & para); void start_paragraph(const std::wstring & styleName); void end_paragraph(); diff --git a/OdfFile/Reader/Converter/xlsx_drawing.cpp b/OdfFile/Reader/Converter/xlsx_drawing.cpp index 6268d1a300..99fd8021c8 100644 --- a/OdfFile/Reader/Converter/xlsx_drawing.cpp +++ b/OdfFile/Reader/Converter/xlsx_drawing.cpp @@ -351,75 +351,82 @@ void xml_serialize(std::wostream & strm, _xlsx_drawing & val, const std::wstring } -void _xlsx_drawing::serialize(std::wostream & strm, const std::wstring & ns) +void _xlsx_drawing::serialize(std::wostream & strm, const std::wstring & ns, bool local) { if (inGroup) return xml_serialize(strm, *this, ns); CP_XML_WRITER(strm) { - if (type_anchor == 1) + if (false == local) { - CP_XML_NODE(ns + L":twoCellAnchor") + if (type_anchor == 1) { - CP_XML_ATTR(L"editAs", L"oneCell");//"absolute");oneCell + CP_XML_NODE(ns + L":twoCellAnchor") + { + CP_XML_ATTR(L"editAs", L"oneCell");//"absolute");oneCell - from_.serialize (CP_XML_STREAM()); - to_.serialize (CP_XML_STREAM()); + from_.serialize(CP_XML_STREAM()); + to_.serialize(CP_XML_STREAM()); - xml_serialize (CP_XML_STREAM(), *this, ns); - CP_XML_NODE(ns + L":clientData"); + xml_serialize(CP_XML_STREAM(), *this, ns); + CP_XML_NODE(ns + L":clientData"); + } + } + else if (type_anchor == 2) + { + CP_XML_NODE(ns + L":absoluteAnchor") + { + CP_XML_NODE(ns + L":pos") + { + CP_XML_ATTR(L"x", x); + CP_XML_ATTR(L"y", y); + } + CP_XML_NODE(ns + L":ext") + { + CP_XML_ATTR(L"cx", cx); + CP_XML_ATTR(L"cy", cy); + } + xml_serialize(CP_XML_STREAM(), *this, ns); + CP_XML_NODE(ns + L":clientData"); + } + } + else if (type_anchor == 3) + { + CP_XML_NODE(ns + L":relSizeAnchor") + { + CP_XML_NODE(ns + L":from") + { + CP_XML_NODE(ns + L":x") + { + CP_XML_STREAM() << ((double)x / *owner_cx_); + } + CP_XML_NODE(ns + L":y") + { + CP_XML_STREAM() << ((double)y / *owner_cy_); + } + } + CP_XML_NODE(ns + L":to") + { + _INT32 x1 = x + cx; + _INT32 y1 = y + cy; + + CP_XML_NODE(ns + L":x") + { + CP_XML_STREAM() << ((double)x1 / *owner_cx_); + } + CP_XML_NODE(ns + L":y") + { + CP_XML_STREAM() << ((double)y1 / *owner_cy_); + } + } + xml_serialize(CP_XML_STREAM(), *this, ns); + } } } - else if (type_anchor == 2) + else { - CP_XML_NODE(ns + L":absoluteAnchor") - { - CP_XML_NODE(ns + L":pos") - { - CP_XML_ATTR(L"x", x); - CP_XML_ATTR(L"y", y); - } - CP_XML_NODE(ns + L":ext") - { - CP_XML_ATTR(L"cx", cx); - CP_XML_ATTR(L"cy", cy); - } - xml_serialize(CP_XML_STREAM(), *this, ns); - CP_XML_NODE(ns + L":clientData"); - } - } - else if (type_anchor == 3) - { - CP_XML_NODE(ns + L":relSizeAnchor") - { - CP_XML_NODE(ns + L":from") - { - CP_XML_NODE(ns + L":x") - { - CP_XML_STREAM() << ((double)x / *owner_cx_); - } - CP_XML_NODE(ns + L":y") - { - CP_XML_STREAM() << ((double)y / *owner_cy_); - } - } - CP_XML_NODE(ns + L":to") - { - _INT32 x1 = x + cx; - _INT32 y1 = y + cy; - - CP_XML_NODE(ns + L":x") - { - CP_XML_STREAM() << ((double)x1 / *owner_cx_); - } - CP_XML_NODE(ns + L":y") - { - CP_XML_STREAM() << ((double)y1 / *owner_cy_); - } - } - xml_serialize(CP_XML_STREAM(), *this, ns); - } + xml_serialize(strm, *this, ns); } } @@ -443,12 +450,13 @@ void _xlsx_drawing::serialize_object (std::wostream & strm) { CP_XML_ATTR(L"r:id", fill.bitmap->rId); } + CP_XML_NODE(L"anchor") { CP_XML_ATTR(L"moveWithCells", 1); - from_.serialize (CP_XML_STREAM(), L"", L""); - to_.serialize (CP_XML_STREAM(), L"", L""); + from_.serialize(CP_XML_STREAM(), L"", L""); + to_.serialize(CP_XML_STREAM(), L"", L""); } } } diff --git a/OdfFile/Reader/Converter/xlsx_drawing.h b/OdfFile/Reader/Converter/xlsx_drawing.h index f0be709537..e4ad2f791d 100644 --- a/OdfFile/Reader/Converter/xlsx_drawing.h +++ b/OdfFile/Reader/Converter/xlsx_drawing.h @@ -65,9 +65,11 @@ public: std::wstring content_group_; - virtual void serialize (std::wostream & strm) {return serialize(strm, L"xdr");} + std::vector<_xlsx_drawing> childs_; - void serialize (std::wostream & strm, const std::wstring & ns); + virtual void serialize (std::wostream & strm) { return serialize(strm, L"xdr", false); } + + void serialize (std::wostream & strm, const std::wstring & ns, bool local); void serialize_vml (std::wostream & strm); void serialize_object (std::wostream & strm); void serialize_control (std::wostream & strm); diff --git a/OdfFile/Reader/Converter/xlsx_drawing_context.cpp b/OdfFile/Reader/Converter/xlsx_drawing_context.cpp index 6cfe7b6eeb..e45eb6cd44 100644 --- a/OdfFile/Reader/Converter/xlsx_drawing_context.cpp +++ b/OdfFile/Reader/Converter/xlsx_drawing_context.cpp @@ -146,9 +146,9 @@ public: mediaitems_ptr & get_mediaitems() { return handle_->impl_->get_mediaitems(); } - void serialize(std::wostream & strm, const std::wstring & ns = L"xdr") + void serialize(std::wostream & strm, const std::wstring & ns, bool local) { - xlsx_drawings_->serialize(strm, ns); + xlsx_drawings_->serialize(strm, ns, local); } void serialize_vml(std::wostream & strm) { @@ -176,15 +176,17 @@ private: }; -xlsx_drawing_context::xlsx_drawing_context(xlsx_drawing_context_handle_ptr & h) +xlsx_drawing_context::xlsx_drawing_context(xlsx_drawing_context_handle_ptr & h, bool in_text) : impl_(new xlsx_drawing_context::Impl(h)) -{ +{ + in_text_ = in_text; hlinks_size_ = 0; clear(); } void xlsx_drawing_context::clear() { + impl_->object_description_.bInner_ = false; impl_->object_description_.type_ = typeUnknown; impl_->object_description_.in_group_ = false; impl_->object_description_.lined_ = false; @@ -273,12 +275,15 @@ void xlsx_drawing_context::end_group() impl_->current_level_ = &impl_->objects_; } } - +bool xlsx_drawing_context::isDefault() +{ + return impl_->object_description_.type_ == typeUnknown; +} void xlsx_drawing_context::start_drawing(std::wstring const & name) { impl_->object_description_.name_ = name; - if (impl_->groups_.size() > 0) + if (false == impl_->groups_.empty()) impl_->object_description_.in_group_ = true; } @@ -307,6 +312,7 @@ void xlsx_drawing_context::start_shape(int type) void xlsx_drawing_context::end_shape() { impl_->current_level_->push_back(impl_->object_description_); + clear(); } void xlsx_drawing_context::start_comment(int base_col, int base_row) { @@ -330,6 +336,7 @@ void xlsx_drawing_context::start_control(const std::wstring & ctrlPropId, int ty void xlsx_drawing_context::end_control() { impl_->current_level_->push_back(impl_->object_description_); + clear(); } void xlsx_drawing_context::set_use_image_replacement() { @@ -374,13 +381,22 @@ void xlsx_drawing_context::set_image(const std::wstring & path) impl_->object_description_.fill_.bitmap->xlink_href_ = path; } } -void xlsx_drawing_context::start_frame() +bool xlsx_drawing_context::start_frame() { - impl_->object_description_.type_ = typeUnknown; + if (impl_->object_description_.type_ != typeUnknown) + impl_->object_description_.bInner_ = true; + + return impl_->object_description_.bInner_; } void xlsx_drawing_context::end_frame() { - impl_->current_level_->push_back(impl_->object_description_); + if (impl_->object_description_.bInner_) + impl_->object_description_.bInner_ = false; + else + { + impl_->current_level_->push_back(impl_->object_description_); + } + clear(); } void xlsx_drawing_context::set_chart(const std::wstring & path) @@ -526,7 +542,7 @@ void xlsx_drawing_context::process_common_properties(drawing_object_description drawing.type_anchor = 2; // absolute } - if (drawing.type_anchor == 1) + if (drawing.type_anchor == 1 || obj.type_ == typeMsObject || obj.type_ == typeOleObject || obj.type_ == typeControl) { xlsx_table_position from, to; @@ -580,7 +596,7 @@ void xlsx_drawing_context::process_position_properties(drawing_object_descriptio if (obj.svg_rect_) { - x = obj.svg_rect_->x; + x = obj.svg_rect_->x; y = obj.svg_rect_->y; cx = obj.svg_rect_->cx; cy = obj.svg_rect_->cy; @@ -731,7 +747,12 @@ void xlsx_drawing_context::process_object(drawing_object_description & obj, xlsx } if (drawing.inGroup) - impl_->get_drawings()->add(isMediaInternal, drawing.objectId, ref, obj.type_, false, false); // не объект + {// не объекты + if (obj.type_ == typeControl || obj.type_ == typeComment) + impl_->get_drawings()->add(isMediaInternal, drawing.objectId, ref, obj.type_, false, false); + else + impl_->get_drawings()->add(isMediaInternal, drawing.objectId, ref, obj.type_, true, false); + } } void xlsx_drawing_context::process_shape(drawing_object_description & obj,_xlsx_drawing & drawing, xlsx_drawings_ptr xlsx_drawings_) { @@ -742,15 +763,17 @@ void xlsx_drawing_context::process_shape(drawing_object_description & obj,_xlsx_ xlsx_drawings_->add(drawing, isMediaInternal, rId, ref, obj.type_); } -void xlsx_drawing_context::process_group(drawing_object_description & obj, xlsx_table_metrics & table_metrics,_xlsx_drawing & drawing, xlsx_drawings_ptr xlsx_drawings_) +void xlsx_drawing_context::process_group(drawing_object_description & obj, xlsx_table_metrics & table_metrics, _xlsx_drawing & drawing, xlsx_drawings_ptr xlsx_drawings_) { xlsx_drawings_ptr xlsx_drawings_child(xlsx_drawings::create(true)); - process_group_objects ( obj.child_objects_, table_metrics, xlsx_drawings_child); + process_group_objects( obj.child_objects_, table_metrics, xlsx_drawings_child); + + drawing.childs_ = xlsx_drawings_child->get(); std::wstringstream strm; - xlsx_drawings_child->serialize(strm, L"xdr"); + xlsx_drawings_child->serialize(strm, L"xdr", in_text_); drawing.content_group_ = strm.str(); @@ -813,9 +836,9 @@ void xlsx_drawing_context::process_group_objects(std::vectorserialize(strm, ns); + impl_->serialize(strm, ns, local); } void xlsx_drawing_context::serialize_vml(std::wostream & strm) { diff --git a/OdfFile/Reader/Converter/xlsx_drawing_context.h b/OdfFile/Reader/Converter/xlsx_drawing_context.h index 28a05b6f1d..50fc1fdf09 100644 --- a/OdfFile/Reader/Converter/xlsx_drawing_context.h +++ b/OdfFile/Reader/Converter/xlsx_drawing_context.h @@ -86,9 +86,11 @@ typedef _CP_PTR(xlsx_drawing_context_handle) xlsx_drawing_context_handle_ptr; class xlsx_drawing_context { public: - xlsx_drawing_context(xlsx_drawing_context_handle_ptr & h); + xlsx_drawing_context(xlsx_drawing_context_handle_ptr & h, bool in_text = false); ~xlsx_drawing_context(); + bool isDefault(); + void set_odf_packet_path(std::wstring path){odf_packet_path_ = path;}//для анализа картинок void start_drawing (std::wstring const & name); @@ -100,7 +102,7 @@ public: void start_shape(int type); void end_shape(); - void start_frame(); + bool start_frame(); void set_image (const std::wstring & path); void set_chart (const std::wstring & path); void set_ole_object (const std::wstring & path, const std::wstring & progId); @@ -143,7 +145,7 @@ public: void clear(); - void serialize(std::wostream & strm, const std::wstring& ns = L"xdr"); + void serialize(std::wostream & strm, const std::wstring& ns = L"xdr", bool local = false); void serialize_vml(std::wostream & strm); std::wstring dump_path(std::vector & path, double w,double h); @@ -175,8 +177,11 @@ private: int hlinks_size_; std::wstring odf_packet_path_ ; float dpi_; + + bool in_text_ = false; }; +typedef _CP_PTR(xlsx_drawing_context) xlsx_drawing_context_ptr; } } diff --git a/OdfFile/Reader/Converter/xlsx_drawings.cpp b/OdfFile/Reader/Converter/xlsx_drawings.cpp index da6918d87e..a8096a0647 100644 --- a/OdfFile/Reader/Converter/xlsx_drawings.cpp +++ b/OdfFile/Reader/Converter/xlsx_drawings.cpp @@ -110,7 +110,7 @@ public: } } - void serialize(std::wostream & strm, const std::wstring & ns) + void serialize(std::wostream & strm, const std::wstring & ns, bool local) { if (drawings_.empty()) return; @@ -118,30 +118,40 @@ public: { for (size_t i = 0 ; i < drawings_.size(); i++) { - drawings_[i].serialize(strm, ns); + drawings_[i].serialize(strm, ns, local); } } else { CP_XML_WRITER(strm) { - CP_XML_NODE(ns + L":wsDr") + if (false == local) { - if (ns == L"xdr") + CP_XML_NODE(ns + L":wsDr") { - CP_XML_ATTR(L"xmlns:xdr", L"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); - } - if (ns == L"cdr") - { - CP_XML_ATTR(L"xmlns:cdr", L"http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"); - } - CP_XML_ATTR(L"xmlns:a" , L"http://schemas.openxmlformats.org/drawingml/2006/main"); - CP_XML_ATTR(L"xmlns:r" , L"http://schemas.openxmlformats.org/officeDocument/2006/relationships"); - CP_XML_ATTR(L"xmlns:a14", L"http://schemas.microsoft.com/office/drawing/2010/main"); + if (ns == L"xdr") + { + CP_XML_ATTR(L"xmlns:xdr", L"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); + } + if (ns == L"cdr") + { + CP_XML_ATTR(L"xmlns:cdr", L"http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"); + } + CP_XML_ATTR(L"xmlns:a", L"http://schemas.openxmlformats.org/drawingml/2006/main"); + CP_XML_ATTR(L"xmlns:r", L"http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + CP_XML_ATTR(L"xmlns:a14", L"http://schemas.microsoft.com/office/drawing/2010/main"); - for (size_t i = 0 ; i < drawings_.size(); i++) + for (size_t i = 0; i < drawings_.size(); i++) + { + drawings_[i].serialize(CP_XML_STREAM(), ns, false); + } + } + } + else + { + for (size_t i = 0; i < drawings_.size(); i++) { - drawings_[i].serialize(CP_XML_STREAM(), ns); + drawings_[i].serialize(strm, ns, true); } } } @@ -220,16 +230,12 @@ public: } } } - void serialize_objects(std::wostream & strm) - { - for (size_t i = 0 ; i < drawings_.size(); i++) - { - if (drawings_[i].type != typeOleObject && drawings_[i].type != typeMsObject) continue; - - drawings_[i].serialize_object(strm); - } - } - void serialize_controls(std::wostream & strm) + + void serialize_objects(std::wostream & strm) + { + serialize_objects(drawings_, strm); + } + void serialize_controls(std::wostream & strm) { for (size_t i = 0 ; i < vml_drawings_.size(); i++) { @@ -291,9 +297,25 @@ public: (xlsx_sheet_rels_[i].is_internal ? L"" : L"External")) ); } } - bool inGroup; - + std::vector<_xlsx_drawing> get() + { + return drawings_; + } + bool inGroup = false; private: + void serialize_objects(std::vector<_xlsx_drawing> & drawings, std::wostream & strm) + { + for (size_t i = 0; i < drawings.size(); i++) + { + if (drawings[i].type == typeGroupShape) + { + return serialize_objects(drawings[i].childs_, strm); + } + if (drawings[i].type != typeOleObject && drawings[i].type != typeMsObject) continue; + + drawings[i].serialize_object(strm); + } + } std::vector<_xlsx_drawing> drawings_; std::vector<_xlsx_drawing> vml_drawings_; @@ -311,7 +333,10 @@ xlsx_drawings::xlsx_drawings(bool inGroup_) : impl_( new xlsx_drawings::Impl() ) xlsx_drawings::~xlsx_drawings() { } - +std::vector<_xlsx_drawing> xlsx_drawings::get() +{ + return impl_->get(); +} void xlsx_drawings::add(_xlsx_drawing & d, bool isInternal, std::wstring const & rid, std::wstring const & ref, _rels_type type, bool sheet_rel) { @@ -323,9 +348,9 @@ void xlsx_drawings::add( bool isInternal, std::wstring const & rid, std::wstring impl_->add(isInternal, rid, ref, type, sheet_rel, vml_rel); } -void xlsx_drawings::serialize(std::wostream & strm, const std::wstring & ns) +void xlsx_drawings::serialize(std::wostream & strm, const std::wstring & ns, bool local) { - impl_->serialize(strm, ns); + impl_->serialize(strm, ns, local); } void xlsx_drawings::serialize_vml(std::wostream & strm) { diff --git a/OdfFile/Reader/Converter/xlsx_drawings.h b/OdfFile/Reader/Converter/xlsx_drawings.h index a14007c9d1..9c6c242c4b 100644 --- a/OdfFile/Reader/Converter/xlsx_drawings.h +++ b/OdfFile/Reader/Converter/xlsx_drawings.h @@ -73,10 +73,12 @@ public: void dump_rels_drawing (rels & Rels); void dump_rels_vml_drawing (rels & Rels); - void serialize (std::wostream & _Wostream, const std::wstring & ns); + void serialize (std::wostream & _Wostream, const std::wstring & ns, bool local); void serialize_vml (std::wostream & _Wostream); void serialize_objects (std::wostream & _Wostream); void serialize_controls (std::wostream & _Wostream); + + std::vector<_xlsx_drawing> get(); private: class Impl; _CP_SCOPED_PTR(Impl) impl_; diff --git a/OdfFile/Reader/Converter/xlsx_table_state.cpp b/OdfFile/Reader/Converter/xlsx_table_state.cpp index fbeb2045fa..a230755c19 100644 --- a/OdfFile/Reader/Converter/xlsx_table_state.cpp +++ b/OdfFile/Reader/Converter/xlsx_table_state.cpp @@ -631,18 +631,20 @@ void xlsx_table_state::serialize_table_format (std::wostream & strm) CP_XML_ATTR(L"xSplit", bXSplit ? nXSplit : 0); CP_XML_ATTR(L"ySplit", bYSplit ? nYSplit : 0); CP_XML_ATTR(L"topLeftCell", getCellAddress(nXSplit, nYSplit)); - CP_XML_ATTR(L"activePane", L"bottomLeft"); - CP_XML_ATTR(L"state", L"frozen"); + //CP_XML_ATTR(L"activePane", L"bottomLeft"); + CP_XML_ATTR(L"activePane", L"topLeft"); + CP_XML_ATTR(L"state", L"frozen"); } } if (col >= 0 && row >= 0) { CP_XML_NODE(L"selection") { - CP_XML_ATTR(L"activeCell", getCellAddress(col, row)); - CP_XML_ATTR(L"activeCellId", 0); - CP_XML_ATTR(L"pane", ((bXSplit || bYSplit) ? L"bottomLeft" : L"topLeft")); - CP_XML_ATTR(L"sqref", getCellAddress(col, row)); + CP_XML_ATTR(L"activeCell", getCellAddress(col, row)); + CP_XML_ATTR(L"activeCellId", 0); + //CP_XML_ATTR(L"pane", ((bXSplit || bYSplit) ? L"bottomLeft" : L"topLeft")); + CP_XML_ATTR(L"activePane", L"topLeft"); + CP_XML_ATTR(L"sqref", getCellAddress(col, row)); } } } diff --git a/OdfFile/Reader/Converter/xlsx_textcontext.cpp b/OdfFile/Reader/Converter/xlsx_textcontext.cpp index 757f955625..6d93810234 100644 --- a/OdfFile/Reader/Converter/xlsx_textcontext.cpp +++ b/OdfFile/Reader/Converter/xlsx_textcontext.cpp @@ -55,6 +55,7 @@ public: Impl(odf_reader::odf_read_context & odf_context); public: void add_text(const std::wstring & text); + void add_paragraph(const std::wstring & para); void start_paragraph(const std::wstring & styleName); void end_paragraph(); @@ -144,7 +145,10 @@ void xlsx_text_context::Impl::add_text(const std::wstring & text) if (!in_comment && !in_draw && !only_text) dump_run(); } - +void xlsx_text_context::Impl::add_paragraph(const std::wstring & para) +{ + paragraph_ << para; +} void xlsx_text_context::Impl::set_local_styles_container(odf_reader::styles_container * local_styles_) { local_styles_ptr_= local_styles_; @@ -599,18 +603,18 @@ void xlsx_text_context::set_local_styles_container(odf_reader::styles_container* { return impl_->set_local_styles_container(local_styles_); } - void xlsx_text_context::set_cell_text_properties(odf_reader::text_format_properties_content_ptr text_properties) { return impl_->set_cell_text_properties(text_properties); } - - void xlsx_text_context::add_text(const std::wstring & text) { return impl_->add_text(text); } - +void xlsx_text_context::add_paragraph(const std::wstring & para) +{ + return impl_->add_paragraph(para); +} void xlsx_text_context::start_paragraph(const std::wstring & styleName) { return impl_->start_paragraph(styleName); diff --git a/OdfFile/Reader/Converter/xlsx_textcontext.h b/OdfFile/Reader/Converter/xlsx_textcontext.h index 9d960824ec..d0f67169cc 100644 --- a/OdfFile/Reader/Converter/xlsx_textcontext.h +++ b/OdfFile/Reader/Converter/xlsx_textcontext.h @@ -86,6 +86,7 @@ public: void end_hyperlink(std::wstring hId); void add_text(const std::wstring & text); + void add_paragraph(const std::wstring & para); void serialize_shared_strings(std::wostream & strm); diff --git a/OdfFile/Reader/Converter/xlsxconversioncontext.cpp b/OdfFile/Reader/Converter/xlsxconversioncontext.cpp index b57fbde038..72a7fbd1cc 100644 --- a/OdfFile/Reader/Converter/xlsxconversioncontext.cpp +++ b/OdfFile/Reader/Converter/xlsxconversioncontext.cpp @@ -632,6 +632,18 @@ void xlsx_conversion_context::start_paragraph(const std::wstring & styleName) void xlsx_conversion_context::end_paragraph() { + if (xlsx_text_context_.is_drawing_context()) + { + get_drawing_context().process_objects(get_table_metrics()); + + if (false == get_drawing_context().empty()) + { + std::wstringstream strm; + get_drawing_context().serialize(strm, L"a", true); + + xlsx_text_context_.add_paragraph(strm.str()); + } + } xlsx_text_context_.end_paragraph(); } @@ -761,10 +773,22 @@ xlsx_table_metrics & xlsx_conversion_context::get_table_metrics() { return get_table_context().get_table_metrics(); } - +void xlsx_conversion_context::start_drawing_context() +{//todooo если делать множественную вложенность -> vector + if (xlsx_drawing_context_) return; + + xlsx_drawing_context_ = boost::shared_ptr(new xlsx_drawing_context(get_drawing_context_handle(), true)); +} +void xlsx_conversion_context::end_drawing_context() +{ + xlsx_drawing_context_.reset(); +} xlsx_drawing_context & xlsx_conversion_context::get_drawing_context() { - return get_table_context().get_drawing_context(); + if (xlsx_drawing_context_) + return *xlsx_drawing_context_; + else + return get_table_context().get_drawing_context(); } xlsx_conditionalFormatting_context & xlsx_conversion_context::get_conditionalFormatting_context() { @@ -811,7 +835,7 @@ void xlsx_conversion_context::end_hyperlink(std::wstring const & href) } else { - std::wstring hId = get_drawing_context().add_hyperlink(href); + std::wstring hId = get_table_context().get_drawing_context().add_hyperlink(href); // на внешний объект xlsx_text_context_.end_hyperlink(hId); xlsx_text_context_.end_span2(); diff --git a/OdfFile/Reader/Converter/xlsxconversioncontext.h b/OdfFile/Reader/Converter/xlsxconversioncontext.h index 76a2957a61..61784a8063 100644 --- a/OdfFile/Reader/Converter/xlsxconversioncontext.h +++ b/OdfFile/Reader/Converter/xlsxconversioncontext.h @@ -173,6 +173,9 @@ public: xlsx_comments_context_handle & get_comments_context_handle(); xlsx_conditionalFormatting_context & get_conditionalFormatting_context(); + void start_drawing_context(); + void end_drawing_context(); + xlsx_dataValidations_context & get_dataValidations_context() { return xlsx_dataValidations_context_;} xlsx_drawing_context_handle_ptr & get_drawing_context_handle(); @@ -214,6 +217,7 @@ private: xlsx_comments_context_handle xlsx_comments_context_handle_; xlsx_dataValidations_context xlsx_dataValidations_context_; xlsx_drawing_context_handle_ptr drawing_context_handle_; + xlsx_drawing_context_ptr xlsx_drawing_context_; math_context math_context_; forms_context forms_context_; diff --git a/OdfFile/Reader/Format/draw_frame_pptx.cpp b/OdfFile/Reader/Format/draw_frame_pptx.cpp index a08d7496aa..ba25d72a30 100644 --- a/OdfFile/Reader/Format/draw_frame_pptx.cpp +++ b/OdfFile/Reader/Format/draw_frame_pptx.cpp @@ -82,123 +82,126 @@ void draw_frame::pptx_convert_placeHolder(oox::pptx_conversion_context & Context } void draw_frame::pptx_convert(oox::pptx_conversion_context & Context) { - Context.get_slide_context().start_frame(); + bool bInnerFrame = Context.get_slide_context().start_frame(); - common_shape_draw_attlist &common_draw_attlist_ = common_draw_attlists_.shape_with_text_and_styles_.common_shape_draw_attlist_; - common_presentation_attlist &common_presentation_attlist_= common_draw_attlists_.shape_with_text_and_styles_.common_presentation_attlist_; - - const unsigned int z_index = common_draw_attlist_.draw_z_index_.get_value_or(0); - const std::wstring name = common_draw_attlist_.draw_name_.get_value_or(L""); - const std::wstring textStyleName = common_draw_attlist_.draw_text_style_name_.get_value_or(L""); - - Context.get_slide_context().set_name(name); -////////////////////////////////////////////////////////////////////////// - const _CP_OPT(length) svg_widthVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_width_; - const _CP_OPT(length) svg_heightVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_height_; - - double width_pt=0, height_pt =0; - if (svg_widthVal && svg_heightVal) + if (false == bInnerFrame) { - const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt); - const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt); + common_shape_draw_attlist &common_draw_attlist_ = common_draw_attlists_.shape_with_text_and_styles_.common_shape_draw_attlist_; + common_presentation_attlist &common_presentation_attlist_ = common_draw_attlists_.shape_with_text_and_styles_.common_presentation_attlist_; - double x_pt = common_draw_attlists_.position_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt); - double y_pt = common_draw_attlists_.position_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt); + const unsigned int z_index = common_draw_attlist_.draw_z_index_.get_value_or(0); + const std::wstring name = common_draw_attlist_.draw_name_.get_value_or(L""); + const std::wstring textStyleName = common_draw_attlist_.draw_text_style_name_.get_value_or(L""); - if (x_pt < 0) x_pt =0; - if (y_pt < 0) y_pt =0; + Context.get_slide_context().set_name(name); + ////////////////////////////////////////////////////////////////////////// + const _CP_OPT(length) svg_widthVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_width_; + const _CP_OPT(length) svg_heightVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_height_; - Context.get_slide_context().set_rect(width_pt, height_pt, x_pt, y_pt); + double width_pt = 0, height_pt = 0; + if (svg_widthVal && svg_heightVal) + { + const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt); + const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt); + + double x_pt = common_draw_attlists_.position_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt); + double y_pt = common_draw_attlists_.position_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt); + + if (x_pt < 0) x_pt = 0; + if (y_pt < 0) y_pt = 0; + + Context.get_slide_context().set_rect(width_pt, height_pt, x_pt, y_pt); + } + /////////////////////////////////////////////////////////////////////////////////////// + if (common_draw_attlist_.draw_transform_) + { + std::wstring transformStr = common_draw_attlist_.draw_transform_.get(); + pptx_convert_transforms(transformStr, Context); + } + //////////////////////////////////////// + std::wstring Anchor; + if (common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_cell_address_) + { + Anchor = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_cell_address_.get(); + const double a_x_pt = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_x_.get_value_or(length(0)).get_value_unit(length::pt); + const double a_y_pt = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_y_.get_value_or(length(0)).get_value_unit(length::pt); + + Context.get_slide_context().set_anchor(Anchor, a_x_pt, a_y_pt); + } + ////////////////////////////////////////////// + std::vector instances; + + const std::wstring grStyleName = common_draw_attlist_.draw_style_name_.get_value_or(L""); + const std::wstring baseStyleName = common_presentation_attlist_.presentation_style_name_.get_value_or(L""); + + odf_reader::style_instance* grStyleInst = + Context.root()->odf_context().styleContainer().style_by_name(grStyleName, odf_types::style_family::Graphic, Context.process_masters_); + + odf_reader::style_instance* baseStyleInst = + Context.root()->odf_context().styleContainer().style_by_name(baseStyleName, odf_types::style_family::Presentation, Context.process_masters_); + + if (baseStyleInst && ((!common_presentation_attlist_.presentation_user_transformed_) || + ((common_presentation_attlist_.presentation_user_transformed_) && + (common_presentation_attlist_.presentation_user_transformed_->get() == false))))//векторная фигура презентаций + { + style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Presentation); + if (defaultStyle)instances.push_back(defaultStyle); + instances.push_back(baseStyleInst); + } + else if (common_presentation_attlist_.presentation_class_) + { + instances.push_back(baseStyleInst); + } + if (grStyleInst)//обычная векторная фигура + { + style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic); + if (defaultStyle)instances.push_back(defaultStyle); + + instances.push_back(grStyleInst); + } + graphic_format_properties properties = calc_graphic_properties_content(instances); + + //////////////////////////////////////////////////////////////////// + properties.apply_to(Context.get_slide_context().get_properties()); + + oox::_oox_fill fill; + Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_, + Context.root()->odf_context().drawStyles(), fill); + if (properties.fo_clip_) + { + std::wstring strRectClip = properties.fo_clip_.get(); + Context.get_slide_context().set_clipping(strRectClip.substr(5, strRectClip.length() - 6)); + } + + Context.get_slide_context().set_fill(fill); + + Context.get_slide_context().set_property(odf_reader::_property(L"border_width_left", Compute_BorderWidth(properties, sideLeft))); + Context.get_slide_context().set_property(odf_reader::_property(L"border_width_top", Compute_BorderWidth(properties, sideTop))); + Context.get_slide_context().set_property(odf_reader::_property(L"border_width_right", Compute_BorderWidth(properties, sideRight))); + Context.get_slide_context().set_property(odf_reader::_property(L"border_width_bottom", Compute_BorderWidth(properties, sideBottom))); + + if (common_presentation_attlist_.presentation_class_) + { + Context.get_slide_context().set_placeHolder_type(common_presentation_attlist_.presentation_class_->get_type_ms()); + + if (idx_in_owner >= 0) + Context.get_slide_context().set_placeHolder_idx(idx_in_owner); + } + + if (!textStyleName.empty()) + { + odf_reader::style_instance* textStyleInst = + Context.root()->odf_context().styleContainer().style_by_name(textStyleName, odf_types::style_family::Paragraph, Context.process_masters_); + + paragraph_format_properties paragraph_properties = calc_paragraph_properties_content(textStyleInst); + } + + if (office_event_listeners_) office_event_listeners_->pptx_convert(Context); + + Context.get_text_context().start_base_style(baseStyleName, odf_types::style_family::Presentation); + + oox_drawing_ = oox_drawing_ptr(new oox::_pptx_drawing()); } -/////////////////////////////////////////////////////////////////////////////////////// - if (common_draw_attlist_.draw_transform_) - { - std::wstring transformStr = common_draw_attlist_.draw_transform_.get(); - pptx_convert_transforms(transformStr, Context); - } -//////////////////////////////////////// - std::wstring Anchor; - if (common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_cell_address_) - { - Anchor = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_cell_address_.get(); - const double a_x_pt = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_x_.get_value_or(length(0)).get_value_unit(length::pt); - const double a_y_pt = common_draw_attlists_.shape_with_text_and_styles_.common_shape_table_attlist_.table_end_y_.get_value_or(length(0)).get_value_unit(length::pt); - - Context.get_slide_context().set_anchor(Anchor, a_x_pt, a_y_pt); - } -////////////////////////////////////////////// - std::vector instances; - - const std::wstring grStyleName = common_draw_attlist_.draw_style_name_.get_value_or(L""); - const std::wstring baseStyleName = common_presentation_attlist_.presentation_style_name_.get_value_or(L""); - - odf_reader::style_instance* grStyleInst = - Context.root()->odf_context().styleContainer().style_by_name(grStyleName, odf_types::style_family::Graphic,Context.process_masters_); - - odf_reader::style_instance* baseStyleInst = - Context.root()->odf_context().styleContainer().style_by_name(baseStyleName, odf_types::style_family::Presentation,Context.process_masters_); - - if (baseStyleInst && ((!common_presentation_attlist_.presentation_user_transformed_) || - ((common_presentation_attlist_.presentation_user_transformed_) && - (common_presentation_attlist_.presentation_user_transformed_->get()== false))))//векторная фигура презентаций - { - style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Presentation); - if (defaultStyle)instances.push_back(defaultStyle); - instances.push_back(baseStyleInst); - } - else if (common_presentation_attlist_.presentation_class_) - { - instances.push_back(baseStyleInst); - } - if (grStyleInst)//обычная векторная фигура - { - style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic); - if (defaultStyle)instances.push_back(defaultStyle); - - instances.push_back(grStyleInst); - } - graphic_format_properties properties = calc_graphic_properties_content(instances); - -//////////////////////////////////////////////////////////////////// - properties.apply_to(Context.get_slide_context().get_properties()); - - oox::_oox_fill fill; - Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_, - Context.root()->odf_context().drawStyles(), fill); - if (properties.fo_clip_) - { - std::wstring strRectClip = properties.fo_clip_.get(); - Context.get_slide_context().set_clipping(strRectClip.substr(5, strRectClip.length() - 6)); - } - - Context.get_slide_context().set_fill(fill); - - Context.get_slide_context().set_property(odf_reader::_property(L"border_width_left", Compute_BorderWidth(properties, sideLeft))); - Context.get_slide_context().set_property(odf_reader::_property(L"border_width_top", Compute_BorderWidth(properties, sideTop))); - Context.get_slide_context().set_property(odf_reader::_property(L"border_width_right", Compute_BorderWidth(properties, sideRight))); - Context.get_slide_context().set_property(odf_reader::_property(L"border_width_bottom", Compute_BorderWidth(properties, sideBottom))); - - if (common_presentation_attlist_.presentation_class_) - { - Context.get_slide_context().set_placeHolder_type(common_presentation_attlist_.presentation_class_->get_type_ms()); - - if (idx_in_owner >= 0) - Context.get_slide_context().set_placeHolder_idx(idx_in_owner); - } - - if (!textStyleName.empty()) - { - odf_reader::style_instance* textStyleInst = - Context.root()->odf_context().styleContainer().style_by_name(textStyleName, odf_types::style_family::Paragraph, Context.process_masters_); - - paragraph_format_properties paragraph_properties = calc_paragraph_properties_content(textStyleInst); - } - - if (office_event_listeners_)office_event_listeners_->pptx_convert(Context); - - Context.get_text_context().start_base_style(baseStyleName ,odf_types::style_family::Presentation); -//////////////////////////////////////////////// - oox_drawing_ = oox_drawing_ptr(new oox::_pptx_drawing()); for (size_t i = 0; i < content_.size(); i++) { @@ -389,7 +392,11 @@ void draw_object::pptx_convert(oox::pptx_conversion_context & Context) } else if (objectBuild.object_type_ == 3) //math { - Context.get_slide_context().set_text_box(); + bool bNewObject = false; + if (bNewObject = Context.get_slide_context().isDefault()) + { + Context.get_slide_context().set_text_box(); + } objectBuild.pptx_convert(Context); @@ -404,8 +411,15 @@ void draw_object::pptx_convert(oox::pptx_conversion_context & Context) text_content += math_content; text_content += L""; - Context.get_slide_context().set_property(_property(L"fit-to-size", true)); - Context.get_slide_context().set_property(_property(L"text-content", text_content)); + if (bNewObject) + { + Context.get_slide_context().set_property(_property(L"fit-to-size", true)); + Context.get_slide_context().set_property(_property(L"text-content", text_content)); + } + else + { + Context.get_text_context().add_paragraph(text_content); + } } } else if (objectBuild.object_type_ == 4) //ods sheet diff --git a/OdfFile/Reader/Format/draw_frame_xlsx.cpp b/OdfFile/Reader/Format/draw_frame_xlsx.cpp index a91391cc3f..46c7255e9b 100644 --- a/OdfFile/Reader/Format/draw_frame_xlsx.cpp +++ b/OdfFile/Reader/Format/draw_frame_xlsx.cpp @@ -131,87 +131,93 @@ void draw_frame::xlsx_convert(oox::xlsx_conversion_context & Context) const std::wstring textStyleName = common_draw_attlist_.common_shape_draw_attlist_.draw_text_style_name_.get_value_or(L""); ////////////////////////////////////////////////////////////////////////// - Context.get_drawing_context().start_drawing( name); - Context.get_drawing_context().start_frame(); + if (Context.get_text_context().is_drawing_context()) + { + Context.get_drawing_context().set_text_box(); + } - const _CP_OPT(length) svg_widthVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_width_; - const _CP_OPT(length) svg_heightVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_height_; + bool bInnerFrame = Context.get_drawing_context().start_frame(); - const double x_pt = common_draw_attlists_.position_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt); - const double y_pt = common_draw_attlists_.position_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt); - - if (svg_widthVal && svg_heightVal) + if (false == bInnerFrame) { - const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt); - const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt); + Context.get_drawing_context().start_drawing(name); + const _CP_OPT(length) svg_widthVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_width_; + const _CP_OPT(length) svg_heightVal = common_draw_attlists_.rel_size_.common_draw_size_attlist_.svg_height_; - Context.get_drawing_context().set_rect(width_pt, height_pt, x_pt, y_pt); + const double x_pt = common_draw_attlists_.position_.svg_x_.get_value_or(length(0)).get_value_unit(length::pt); + const double y_pt = common_draw_attlists_.position_.svg_y_.get_value_or(length(0)).get_value_unit(length::pt); + + if (svg_widthVal && svg_heightVal) + { + const double width_pt = svg_widthVal.get_value_or(length(0)).get_value_unit(length::pt); + const double height_pt = svg_heightVal.get_value_or(length(0)).get_value_unit(length::pt); + + Context.get_drawing_context().set_rect(width_pt, height_pt, x_pt, y_pt); + } + /////////////////////////////////////////////////////////////////////////////////////// + if (common_draw_attlist_.common_shape_draw_attlist_.draw_transform_) + { + std::wstring transformStr = common_draw_attlist_.common_shape_draw_attlist_.draw_transform_.get(); + xlsx_convert_transforms(transformStr, Context); + } + //////////////////////////////////////// + if (common_draw_attlist_.common_shape_table_attlist_.table_end_cell_address_) + { + std::wstring end_Anchor = common_draw_attlist_.common_shape_table_attlist_.table_end_cell_address_.get(); + + const double end_x_pt = common_draw_attlist_.common_shape_table_attlist_.table_end_x_.get_value_or(length(0)).get_value_unit(length::pt); + const double end_y_pt = common_draw_attlist_.common_shape_table_attlist_.table_end_y_.get_value_or(length(0)).get_value_unit(length::pt); + + Context.get_drawing_context().set_anchor_end(end_Anchor, end_x_pt, end_y_pt); + } + else if (Context.in_table_cell()) + { + std::wstring Anchor = oox::getCellAddress(Context.current_table_column(), Context.current_table_row()); + Context.get_drawing_context().set_anchor_start(Anchor, x_pt, y_pt); + } + ////////////////////////////////////////////// + std::vector instances; + + odf_reader::style_instance* styleInst = + Context.root()->odf_context().styleContainer().style_by_name(styleName, odf_types::style_family::Graphic, false/*process_headers_footers_*/); + if (styleInst) + { + style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic); + if (defaultStyle)instances.push_back(defaultStyle); + + instances.push_back(styleInst); + } + graphic_format_properties properties = calc_graphic_properties_content(instances); + + //////////////////////////////////////////////////////////////////// + properties.apply_to(Context.get_drawing_context().get_properties()); + + Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_left", Compute_BorderWidth(properties, sideLeft))); + Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_top", Compute_BorderWidth(properties, sideTop))); + Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_right", Compute_BorderWidth(properties, sideRight))); + Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_bottom", Compute_BorderWidth(properties, sideBottom))); + + oox::_oox_fill fill; + Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_, + Context.root()->odf_context().drawStyles(), fill); + if (properties.fo_clip_) + { + std::wstring strRectClip = properties.fo_clip_.get(); + Context.get_drawing_context().set_clipping(strRectClip.substr(5, strRectClip.length() - 6)); + } + Context.get_drawing_context().set_fill(fill); + + oox_drawing_ = oox_drawing_ptr(new oox::_xlsx_drawing()); } -/////////////////////////////////////////////////////////////////////////////////////// - if (common_draw_attlist_.common_shape_draw_attlist_.draw_transform_) - { - std::wstring transformStr = common_draw_attlist_.common_shape_draw_attlist_.draw_transform_.get(); - xlsx_convert_transforms(transformStr, Context); - } -//////////////////////////////////////// - if (common_draw_attlist_.common_shape_table_attlist_.table_end_cell_address_) - { - std::wstring end_Anchor = common_draw_attlist_.common_shape_table_attlist_.table_end_cell_address_.get(); - - const double end_x_pt = common_draw_attlist_.common_shape_table_attlist_.table_end_x_.get_value_or(length(0)).get_value_unit(length::pt); - const double end_y_pt = common_draw_attlist_.common_shape_table_attlist_.table_end_y_.get_value_or(length(0)).get_value_unit(length::pt); - Context.get_drawing_context().set_anchor_end(end_Anchor, end_x_pt, end_y_pt); - } - else if (Context.in_table_cell()) - { - std::wstring Anchor = oox::getCellAddress(Context.current_table_column(), Context.current_table_row()); - Context.get_drawing_context().set_anchor_start(Anchor, x_pt, y_pt); - } -////////////////////////////////////////////// - std::vector instances; - - odf_reader::style_instance* styleInst = - Context.root()->odf_context().styleContainer().style_by_name(styleName, odf_types::style_family::Graphic,false/*process_headers_footers_*/); - if (styleInst) - { - style_instance * defaultStyle = Context.root()->odf_context().styleContainer().style_default_by_type(odf_types::style_family::Graphic); - if (defaultStyle)instances.push_back(defaultStyle); - - instances.push_back(styleInst); - } - graphic_format_properties properties = calc_graphic_properties_content(instances); - -//////////////////////////////////////////////////////////////////// - properties.apply_to(Context.get_drawing_context().get_properties()); - - Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_left", Compute_BorderWidth(properties, sideLeft))); - Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_top", Compute_BorderWidth(properties, sideTop))); - Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_right", Compute_BorderWidth(properties, sideRight))); - Context.get_drawing_context().set_property(odf_reader::_property(L"border_width_bottom", Compute_BorderWidth(properties, sideBottom))); - - oox::_oox_fill fill; - Compute_GraphicFill(properties.common_draw_fill_attlist_, properties.style_background_image_, - Context.root()->odf_context().drawStyles(), fill); - if (properties.fo_clip_) - { - std::wstring strRectClip = properties.fo_clip_.get(); - Context.get_drawing_context().set_clipping(strRectClip.substr(5, strRectClip.length() - 6)); - } - Context.get_drawing_context().set_fill(fill); - - oox_drawing_ = oox_drawing_ptr(new oox::_xlsx_drawing()); - -//////////////////////////////////////////////// for (size_t i = 0 ; i < content_.size(); i++) { office_element_ptr const & elm = content_[i]; elm->xlsx_convert(Context); } - Context.get_drawing_context().end_frame(); Context.get_drawing_context().end_drawing(); - Context.get_drawing_context().clear(); + Context.get_drawing_context().end_frame(); } void draw_image::xlsx_convert(oox::xlsx_conversion_context & Context) @@ -250,13 +256,15 @@ void draw_image::xlsx_convert(oox::xlsx_conversion_context & Context) Context.get_drawing_context().set_image(href); ////////////////////////////////////в принципе достаточно общая часть ... - Context.get_text_context().start_drawing_content();//... если в объекте есть текст он привяжется к объекту - иначе к ячейке + Context.get_text_context().start_drawing_content(); //... если в объекте есть текст он привяжется к объекту - иначе к ячейке + Context.start_drawing_context(); for (size_t i = 0 ; i < content_.size(); i++) { content_[i]->xlsx_convert(Context); } std::wstring text_content_ = Context.get_text_context().end_drawing_content(); + Context.end_drawing_context(); if (!text_content_.empty()) { @@ -295,6 +303,7 @@ void draw_text_box::xlsx_convert(oox::xlsx_conversion_context & Context) Context.get_drawing_context().set_text_box(); Context.get_text_context().start_drawing_content(); + Context.start_drawing_context(); for (size_t i = 0 ; i < content_.size(); i++) { @@ -302,6 +311,7 @@ void draw_text_box::xlsx_convert(oox::xlsx_conversion_context & Context) } std::wstring text_content_ = Context.get_text_context().end_drawing_content(); + Context.end_drawing_context(); if (!text_content_.empty()) { @@ -376,7 +386,11 @@ void draw_object::xlsx_convert(oox::xlsx_conversion_context & Context) } else if (objectBuild.object_type_ == 3) //мат формулы { - Context.get_drawing_context().set_text_box(); + bool bNewObject = false; + if (bNewObject = Context.get_drawing_context().isDefault()) + { + Context.get_drawing_context().set_text_box(); + } objectBuild.xlsx_convert(Context); @@ -391,8 +405,15 @@ void draw_object::xlsx_convert(oox::xlsx_conversion_context & Context) text_content += math_content; text_content += L""; - Context.get_drawing_context().set_property(_property(L"fit-to-size", true)); - Context.get_drawing_context().set_property(_property(L"text-content", text_content)); + if (bNewObject) + { + Context.get_drawing_context().set_property(_property(L"fit-to-size", true)); + Context.get_drawing_context().set_property(_property(L"text-content", text_content)); + } + else + { + Context.get_text_context().add_paragraph(text_content); + } } } else if (objectBuild.object_type_ == 4) // embedded sheet diff --git a/OdfFile/Reader/Format/draw_shapes_xlsx.cpp b/OdfFile/Reader/Format/draw_shapes_xlsx.cpp index c4e1f7282f..08fb06395d 100644 --- a/OdfFile/Reader/Format/draw_shapes_xlsx.cpp +++ b/OdfFile/Reader/Format/draw_shapes_xlsx.cpp @@ -145,6 +145,7 @@ void draw_shape::common_xlsx_convert(oox::xlsx_conversion_context & Context) ////////////////////////////////////////////////////////////////////////////////////// Context.get_text_context().start_drawing_content(); + Context.start_drawing_context(); if (word_art_) { @@ -156,6 +157,7 @@ void draw_shape::common_xlsx_convert(oox::xlsx_conversion_context & Context) content_[i]->xlsx_convert(Context); } std::wstring text_content_ = Context.get_text_context().end_drawing_content(); + Context.end_drawing_context(); if (!text_content_.empty()) { @@ -171,7 +173,6 @@ void draw_rect::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_ellipse::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -180,7 +181,6 @@ void draw_ellipse::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_circle::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -189,7 +189,6 @@ void draw_circle::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_line::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -200,7 +199,6 @@ void draw_line::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } @@ -213,7 +211,6 @@ void draw_path::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_connector::xlsx_convert(oox::xlsx_conversion_context & Context) @@ -234,7 +231,6 @@ void draw_connector::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_polygon::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -245,7 +241,6 @@ void draw_polygon::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_polyline::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -256,7 +251,6 @@ void draw_polyline::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_custom_shape::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -265,7 +259,6 @@ void draw_custom_shape::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_caption::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -276,7 +269,6 @@ void draw_caption::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void draw_enhanced_geometry::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -392,7 +384,6 @@ void dr3d_scene::xlsx_convert(oox::xlsx_conversion_context & Context) common_xlsx_convert(Context); Context.get_drawing_context().end_shape(); - Context.get_drawing_context().clear(); } void dr3d_light::xlsx_convert(oox::xlsx_conversion_context & Context) { @@ -519,8 +510,6 @@ void draw_control::xlsx_convert(oox::xlsx_conversion_context & Context) //_CP_OPT(odf_types::Bool) dropdown_; Context.get_drawing_context().end_control(); - Context.get_drawing_context().clear(); - } } diff --git a/OdfFile/Reader/Format/note.cpp b/OdfFile/Reader/Format/note.cpp index 4a432c3f60..9b6a8084c2 100644 --- a/OdfFile/Reader/Format/note.cpp +++ b/OdfFile/Reader/Format/note.cpp @@ -126,14 +126,16 @@ void note_body::docx_convert(oox::docx_conversion_context & Context) Context.set_stream_man( boost::shared_ptr( new oox::streams_man(*newXml) ) ); Context.set_process_headers_footers(true); - Context.reset_context_state(); + Context.start_comment_content(); // чтоб ins/del не отрабатывало for (size_t i = 0; i < content_.size(); i++) { content_[i]->docx_convert(Context); } - Context.set_process_headers_footers (false); + Context.end_comment_content(); + + Context.set_process_headers_footers (false); Context.back_context_state(); diff --git a/OdfFile/Reader/Format/paragraph_elements.cpp b/OdfFile/Reader/Format/paragraph_elements.cpp index f72bc8bdc8..fe3e7a1a6d 100644 --- a/OdfFile/Reader/Format/paragraph_elements.cpp +++ b/OdfFile/Reader/Format/paragraph_elements.cpp @@ -544,7 +544,7 @@ void span::docx_convert(oox::docx_conversion_context & Context) std::wstring parent = styleInst->parent_name(); if (false == parent.empty()) - { + { text_props->content_.r_style_ = Context.styles_map_.get(parent, styleInst->type()); } @@ -555,7 +555,8 @@ void span::docx_convert(oox::docx_conversion_context & Context) Context.get_styles_context().end_process_style(); addNewRun = true; - text_props->content_.r_style_ = boost::none; + if (text_props) + text_props->content_.r_style_ = boost::none; } } else diff --git a/OdfFile/Reader/Format/style_text_properties.cpp b/OdfFile/Reader/Format/style_text_properties.cpp index 6a90706724..ece72aa503 100644 --- a/OdfFile/Reader/Format/style_text_properties.cpp +++ b/OdfFile/Reader/Format/style_text_properties.cpp @@ -1668,7 +1668,10 @@ void text_format_properties_content::apply_from(const text_format_properties_con _CP_APPLY_PROP(style_text_overline_style_, Other.style_text_overline_style_); } - +void text_format_properties_content::set_r_style(const std::wstring & rStyle) +{ + r_style_ = rStyle; +} void text_format_properties_content::apply_to(std::vector<_property> & properties) { diff --git a/OdfFile/Reader/Format/style_text_properties.h b/OdfFile/Reader/Format/style_text_properties.h index 7b2ac41a0f..4228a40c61 100644 --- a/OdfFile/Reader/Format/style_text_properties.h +++ b/OdfFile/Reader/Format/style_text_properties.h @@ -82,9 +82,9 @@ public: void xlsx_serialize (std::wostream & strm, oox::xlsx_conversion_context & Context); - void apply_from (const text_format_properties_content & Other); - void apply_to (std::vector<_property> & properties); - void set_r_style (const std::wstring & rStyle) { r_style_ = rStyle; } + void apply_from (const text_format_properties_content & Other); + void apply_to (std::vector<_property> & properties); + void set_r_style(const std::wstring & rStyle); int process_font_size (const _CP_OPT(odf_types::font_size) & FontSize, const style_instance * currnetStyle, bool Complex = false, double Mul = 1.0); diff --git a/OdfFile/Writer/Converter/ConvertDrawing.cpp b/OdfFile/Writer/Converter/ConvertDrawing.cpp index e66475dc5d..a9dc87b355 100644 --- a/OdfFile/Writer/Converter/ConvertDrawing.cpp +++ b/OdfFile/Writer/Converter/ConvertDrawing.cpp @@ -1409,7 +1409,7 @@ void OoxConverter::convert(PPTX::Logic::UniColor * color, std::wstring & hexStri if (nARGB != 0) { - hexString = XmlUtils::ToString(nARGB & 0x00FFFFFF, L"#%06X"); + hexString = XmlUtils::ToString((unsigned int)(nARGB & 0x00FFFFFF), L"#%06X"); if ((nARGB >> 24) != 0xff) { @@ -1499,7 +1499,7 @@ void OoxConverter::convert(PPTX::Logic::Ln *oox_line_prop, DWORD ARGB, PPTX::Log { if (oox_line_prop->headEnd->len.IsInit() || oox_line_prop->headEnd->type.IsInit() || oox_line_prop->headEnd->w.IsInit()) { - int type = 1, w = 1, len = 1;//medium arrow + int type = 0, w = 1, len = 1;//medium arrow if (oox_line_prop->headEnd->len.IsInit()) len = oox_line_prop->headEnd->len->GetBYTECode(); if (oox_line_prop->headEnd->type.IsInit()) type = oox_line_prop->headEnd->type->GetBYTECode(); if (oox_line_prop->headEnd->w.IsInit()) w = oox_line_prop->headEnd->w->GetBYTECode(); @@ -2469,12 +2469,14 @@ void OoxConverter::convert(PPTX::Logic::MathParaWrapper *oox_math) { if (!oox_math) return; - odf_context()->math_context()->in_text_box_ = true; - + odf_context()->math_context()->in_text_box_ = false; + + odf_context()->start_drawing_context(); + convert(oox_math->m_oMathPara.GetPointer()); convert(oox_math->m_oMath.GetPointer()); - odf_context()->math_context()->in_text_box_ = false; + odf_context()->end_drawing_context(); } void OoxConverter::convert(PPTX::Logic::LineTo *oox_geom_path) { @@ -2515,7 +2517,25 @@ void OoxConverter::convert(PPTX::Logic::TxBody *oox_txBody, PPTX::Logic::ShapeSt convert(oox_txBody->lstStyle.GetPointer()); - for (size_t i = 0; i < oox_txBody->Paragrs.size(); i++) +//single math - либра не тянет сложные вложенности + bool bSingleMath = false; + if (odf_context()->drawing_context()->is_text_box() && + oox_txBody->Paragrs.size() == 1 && + oox_txBody->Paragrs[0].RunElems.size() == 1 && + oox_txBody->Paragrs[0].RunElems[0].getType() == OOX::et_p_MathPara) + { + bSingleMath = true; + + odf_context()->math_context()->in_text_box_ = true; + + PPTX::Logic::MathParaWrapper *oox_math = dynamic_cast(oox_txBody->Paragrs[0].RunElems[0].GetElem().GetPointer()); + convert(oox_math->m_oMathPara.GetPointer()); + convert(oox_math->m_oMath.GetPointer()); + + odf_context()->math_context()->in_text_box_ = false; + } +//---------------------------------------------------------------------------------------------- + for (size_t i = 0; !bSingleMath && i < oox_txBody->Paragrs.size(); i++) { convert(&oox_txBody->Paragrs[i], oox_txBody->lstStyle.GetPointer()); @@ -2577,7 +2597,7 @@ void OoxConverter::convert(PPTX::Logic::StyleRef *style_ref, int type) if (style_ref->idx.IsInit() == false) { - std::wstring hexColor = XmlUtils::ToString(nARGB & 0x00FFFFFF, L"#%06X"); + std::wstring hexColor = XmlUtils::ToString((unsigned int)(nARGB & 0x00FFFFFF), L"#%06X"); _CP_OPT(double) opacity; if ((nARGB >> 24) != 0xff) diff --git a/OdfFile/Writer/Converter/DocxConverter.cpp b/OdfFile/Writer/Converter/DocxConverter.cpp index 63bfcc6299..9fe5e67fd7 100644 --- a/OdfFile/Writer/Converter/DocxConverter.cpp +++ b/OdfFile/Writer/Converter/DocxConverter.cpp @@ -528,7 +528,7 @@ void DocxConverter::convert(OOX::Logic::CSdt *oox_sdt) if (false == id.empty()) { bForm = true; - odt_context->start_drawings(); + odt_context->start_drawing_context(); odt_context->drawing_context()->set_anchor(odf_types::anchor_type::AsChar); odt_context->drawing_context()->set_drawings_rect(x, y, width, height); //default @@ -672,7 +672,7 @@ void DocxConverter::convert(OOX::Logic::CSdt *oox_sdt) odt_context->drawing_context()->end_control(); odt_context->drawing_context()->end_drawing(); - odt_context->end_drawings(); + odt_context->end_drawing_context(); odt_context->controls_context()->end_control(); } } @@ -2220,7 +2220,7 @@ void DocxConverter::convert(OOX::Logic::CBgPict *oox_bg_pict, int type) odt_context->set_background(color, type); } - odt_context->start_drawings(); + odt_context->start_drawing_context(); odt_context->drawing_context()->start_drawing(); odt_context->drawing_context()->set_background_state(true); @@ -2232,7 +2232,7 @@ void DocxConverter::convert(OOX::Logic::CBgPict *oox_bg_pict, int type) odt_context->drawing_context()->end_drawing_background(current_layout_properties->attlist_.common_draw_fill_attlist_); odt_context->drawing_context()->set_background_state(false); - odt_context->end_drawings(); + odt_context->end_drawing_context(); } void DocxConverter::convert(OOX::Logic::CBackground *oox_background, int type) { @@ -2246,7 +2246,7 @@ void DocxConverter::convert(OOX::Logic::CBackground *oox_background, int type) odt_context->set_background(color, type); - odt_context->start_drawings(); + odt_context->start_drawing_context(); odt_context->drawing_context()->start_drawing(); odt_context->drawing_context()->set_background_state(true); @@ -2262,7 +2262,7 @@ void DocxConverter::convert(OOX::Logic::CBackground *oox_background, int type) odt_context->drawing_context()->end_drawing_background(current_layout_properties->attlist_.common_draw_fill_attlist_); odt_context->drawing_context()->set_background_state(false); - odt_context->end_drawings(); + odt_context->end_drawing_context(); } void DocxConverter::convert(ComplexTypes::Word::CFramePr *oox_frame_pr, odf_writer::style_paragraph_properties * paragraph_properties) @@ -3016,7 +3016,7 @@ void DocxConverter::convert(OOX::Logic::CPicture* oox_pic) { if (oox_pic == NULL) return; - odt_context->start_drawings(); + odt_context->start_drawing_context(); if (odt_context->table_context()->empty()) odf_context()->drawing_context()->set_anchor(anchor_type::Char);//default @@ -3029,13 +3029,13 @@ void DocxConverter::convert(OOX::Logic::CPicture* oox_pic) OoxConverter::convert(oox_pic->m_oShapeType.GetPointer()); OoxConverter::convert(oox_pic->m_oShapeElement.GetPointer()); - odt_context->end_drawings(); + odt_context->end_drawing_context(); } void DocxConverter::convert(OOX::Logic::CObject* oox_obj) { if (oox_obj == NULL) return; - odt_context->start_drawings(); + odt_context->start_drawing_context(); if (odt_context->table_context()->empty()) odf_context()->drawing_context()->set_anchor(odf_types::anchor_type::AsChar);//default @@ -3128,17 +3128,17 @@ void DocxConverter::convert(OOX::Logic::CObject* oox_obj) odf_context()->drawing_context()->end_drawing(); - odt_context->end_drawings(); + odt_context->end_drawing_context(); } /////////////////////////////////////////////// void DocxConverter::convert(OOX::Logic::CDrawing *oox_drawing) { if (oox_drawing == NULL) return; - odt_context->start_drawings(); + odt_context->start_drawing_context(); convert(oox_drawing->m_oAnchor.GetPointer()); convert(oox_drawing->m_oInline.GetPointer()); - odt_context->end_drawings(); + odt_context->end_drawing_context(); } void DocxConverter::convert(OOX::Drawing::CAnchor *oox_anchor) { @@ -3430,7 +3430,7 @@ void DocxConverter::convert(SimpleTypes::CHexColor *color, argb = HSL2RGB(dH, dS, dL); } - std::wstring strColor = XmlUtils::ToString(argb & 0x00FFFFFF, L"#%06X"); + std::wstring strColor = XmlUtils::ToString((unsigned int)(argb & 0x00FFFFFF), L"#%06X"); odf_color = odf_types::color(strColor); } } @@ -4455,7 +4455,7 @@ void DocxConverter::convert(OOX::Logic::CTbl *oox_table) odt_context->set_master_page_name(odt_context->page_layout_context()->last_master() ? odt_context->page_layout_context()->last_master()->get_name() : L""); } - odt_context->start_drawings(); + odt_context->start_drawing_context(); _CP_OPT(double) width, height, x, y ; if (oox_table->m_oTableProperties->m_oTblpPr->m_oTblpXSpec.IsInit()) @@ -4606,7 +4606,7 @@ void DocxConverter::convert(OOX::Logic::CTbl *oox_table) odt_context->drawing_context()->end_text_box(); odt_context->drawing_context()->end_drawing(); - odt_context->end_drawings(); + odt_context->end_drawing_context(); odt_context->text_context()->set_KeepNextParagraph(true); } diff --git a/OdfFile/Writer/Converter/MathConverter.cpp b/OdfFile/Writer/Converter/MathConverter.cpp index 29222acd50..9ee365c335 100644 --- a/OdfFile/Writer/Converter/MathConverter.cpp +++ b/OdfFile/Writer/Converter/MathConverter.cpp @@ -489,6 +489,7 @@ namespace Oox2Odf std::wstring OoxConverter::convert(OOX::Logic::CBegChr * oox_beg_chr) { if (!oox_beg_chr) return L"("; + if (false == oox_beg_chr->m_val.IsInit()) return L"("; std::wstring s_val = oox_beg_chr->m_val->GetValue(); @@ -500,6 +501,7 @@ namespace Oox2Odf std::wstring OoxConverter::convert(OOX::Logic::CEndChr * oox_end_chr) { if (!oox_end_chr) return L")"; + if (false == oox_end_chr->m_val.IsInit()) return L")"; std::wstring s_val = oox_end_chr->m_val->GetValue(); diff --git a/OdfFile/Writer/Converter/PptxConverter.cpp b/OdfFile/Writer/Converter/PptxConverter.cpp index d71323473c..cc1d4c5ea7 100644 --- a/OdfFile/Writer/Converter/PptxConverter.cpp +++ b/OdfFile/Writer/Converter/PptxConverter.cpp @@ -1451,7 +1451,7 @@ void PptxConverter::convert(PPTX::Logic::Bg *oox_background) odp_context->drawing_context()->end_drawing_background(page_props->content_.common_draw_fill_attlist_); odp_context->drawing_context()->set_background_state(false); - odp_context->end_drawings(); + odp_context->drawing_context()->clear(); } void PptxConverter::convert_slide(PPTX::Logic::CSld *oox_slide, PPTX::Logic::TxStyles* txStyles, bool bPlaceholders, bool bFillUp, _typePages type) diff --git a/OdfFile/Writer/Converter/XlsxConverter.cpp b/OdfFile/Writer/Converter/XlsxConverter.cpp index 234b7f859c..c491392499 100644 --- a/OdfFile/Writer/Converter/XlsxConverter.cpp +++ b/OdfFile/Writer/Converter/XlsxConverter.cpp @@ -2867,9 +2867,8 @@ void XlsxConverter::convert(OOX::Spreadsheet::CDrawing *oox_drawing, OOX::Spread continue; } } - ods_context->start_drawings(); - convert(oox_anchor); - ods_context->end_drawings(); + convert(oox_anchor); + ods_context->drawing_context()->clear(); } xlsx_current_container = old_container; @@ -2881,7 +2880,6 @@ void XlsxConverter::convert(OOX::Spreadsheet::COleObjects *oox_objects, OOX::Spr for (boost::unordered_map::const_iterator it = oox_objects->m_mapOleObjects.begin(); it != oox_objects->m_mapOleObjects.end(); ++it) { OOX::Spreadsheet::COleObject* object = it->second; - ods_context->start_drawings(); bool bAnchor = false; std::wstring odf_ref_object, odf_ref_image; @@ -2996,7 +2994,7 @@ void XlsxConverter::convert(OOX::Spreadsheet::COleObjects *oox_objects, OOX::Spr ods_context->drawing_context()->end_object_ole(); ods_context->drawing_context()->end_drawing(); - ods_context->end_drawings(); + ods_context->drawing_context()->clear(); } } @@ -3123,8 +3121,6 @@ void XlsxConverter::convert(OOX::Spreadsheet::CControls *oox_controls, OOX::Spre if (false == id.empty()) { - ods_context->start_drawings(); - { oox_table_position from = {}, to = {}; @@ -3272,7 +3268,7 @@ void XlsxConverter::convert(OOX::Spreadsheet::CControls *oox_controls, OOX::Spre ods_context->drawing_context()->end_control(); ods_context->drawing_context()->end_drawing(); - ods_context->end_drawings(); + ods_context->drawing_context()->clear(); ods_context->controls_context()->end_control(); } } diff --git a/OdfFile/Writer/Format/odf_conversion_context.cpp b/OdfFile/Writer/Format/odf_conversion_context.cpp index 0a17843037..a34764591d 100644 --- a/OdfFile/Writer/Format/odf_conversion_context.cpp +++ b/OdfFile/Writer/Format/odf_conversion_context.cpp @@ -308,6 +308,45 @@ void odf_conversion_context::end_chart() end_object(); chart_context_.set_styles_context(styles_context()); } +void odf_conversion_context::start_text_context() +{ + odf_text_context_ptr new_text_context_ = boost::shared_ptr(new odf_text_context(this, styles_context())); + if (!new_text_context_)return; + + text_context_.push_back(new_text_context_); +} +void odf_conversion_context::end_text_context() +{ + if (false == text_context_.empty()) + { + text_context_.pop_back(); + } +} +void odf_conversion_context::start_drawing_context() +{ + odf_drawing_context_ptr new_drawing_context_ = boost::shared_ptr(new odf_drawing_context(this)); + if (!new_drawing_context_)return; + + new_drawing_context_->set_styles_context(styles_context()); + + drawing_context_.push_back(new_drawing_context_); +} +void odf_conversion_context::end_drawing_context() +{ + if (drawing_context_.empty()) return; + + office_element_ptr & elm = drawing_context()->get_root_element(); + + if (elm) + { + text_context()->start_element(elm); + text_context()->end_element(); + } + + drawing_context()->clear(); + drawing_context_.pop_back(); +} + bool odf_conversion_context::start_math() { if (false == math_context_.isEmpty()) return false; diff --git a/OdfFile/Writer/Format/odf_conversion_context.h b/OdfFile/Writer/Format/odf_conversion_context.h index ea0e59d55a..4d59132a31 100644 --- a/OdfFile/Writer/Format/odf_conversion_context.h +++ b/OdfFile/Writer/Format/odf_conversion_context.h @@ -38,6 +38,7 @@ #include "odf_page_layout_context.h" +#include "odf_text_context.h" #include "odf_drawing_context.h" #include "odf_chart_context.h" #include "odf_math_context.h" @@ -115,9 +116,6 @@ public: virtual odf_text_context * text_context() = 0; virtual odf_controls_context * controls_context() = 0; - virtual void start_text_context() = 0; - virtual void end_text_context() = 0; - std::wstring add_image (const std::wstring & image_file_name); std::wstring add_media (const std::wstring & file_name); std::wstring add_oleobject (const std::wstring & ole_file_name); @@ -151,6 +149,12 @@ public: void create_object(bool bAddContentExt = true); void end_object(); + virtual void start_text_context(); + virtual void end_text_context(); + + virtual void start_drawing_context(); + virtual void end_drawing_context(); + std::wstring get_next_name_object(); office_element_ptr & get_current_object_element(); @@ -160,6 +164,11 @@ public: void calculate_font_metrix(std::wstring name, double size, bool italic, bool bold); double convert_symbol_width(double val); + +protected: + std::vector text_context_; + std::vector drawing_context_; + private: _font_metrix font_metrix_; diff --git a/OdfFile/Writer/Format/odf_drawing_context.cpp b/OdfFile/Writer/Format/odf_drawing_context.cpp index 7c1c20d3e7..8ae127ebe1 100644 --- a/OdfFile/Writer/Format/odf_drawing_context.cpp +++ b/OdfFile/Writer/Format/odf_drawing_context.cpp @@ -833,6 +833,13 @@ void odf_drawing_context::start_shape(int ooxDrawPreset) impl_->create_draw_base(drawCustom); } } +bool odf_drawing_context::is_text_box() +{ + if (impl_->current_drawing_state_.oox_shape_preset_ >= 2000 && impl_->current_drawing_state_.oox_shape_preset_ < 3000) + return true; + + return false; +} bool odf_drawing_context::is_wordart() { @@ -2289,7 +2296,7 @@ void odf_drawing_context::set_corner_radius (odf_types::length corner) std::wstring odf_drawing_context::add_marker_style(int type) { - if (type == 2) return L""; + if (type == 0) return L""; std::wstring str_types [] = {L"None", L"ArrowMarker", L"DiamondMarker", L"OvalMarker", L"StealthMarker", L"TriangleMarker"}; diff --git a/OdfFile/Writer/Format/odf_drawing_context.h b/OdfFile/Writer/Format/odf_drawing_context.h index cb36888bea..618e4e8f19 100644 --- a/OdfFile/Writer/Format/odf_drawing_context.h +++ b/OdfFile/Writer/Format/odf_drawing_context.h @@ -137,10 +137,11 @@ public: void start_image (std::wstring odf_file_path); void end_image (); - bool change_text_box_2_wordart (); - bool is_wordart (); + bool change_text_box_2_wordart(); + bool is_wordart(); + bool is_text_box(); - graphic_format_properties* get_graphic_properties(); + graphic_format_properties* get_graphic_properties(); void set_graphic_properties (style_graphic_properties *graphic_properties); void set_paragraph_properties (style_paragraph_properties *paragraph_properties); diff --git a/OdfFile/Writer/Format/odp_conversion_context.cpp b/OdfFile/Writer/Format/odp_conversion_context.cpp index 45d0f7adc3..5a0a0e0240 100644 --- a/OdfFile/Writer/Format/odp_conversion_context.cpp +++ b/OdfFile/Writer/Format/odp_conversion_context.cpp @@ -55,12 +55,19 @@ namespace odf_writer { odp_conversion_context::odp_conversion_context(package::odf_document * outputDocument) - : odf_conversion_context (PresentationDocument, outputDocument), root_presentation_(NULL), slide_context_(*this), text_context_(NULL), drawing_context_(this) + : odf_conversion_context (PresentationDocument, outputDocument), root_presentation_(NULL), slide_context_(*this) { } odf_text_context* odp_conversion_context::text_context() { - return text_context_; + if (false == text_context_.empty()) + { + return text_context_.back().get(); + } + else + { + return NULL; + } } odp_slide_context* odp_conversion_context::slide_context() { @@ -74,13 +81,17 @@ odf_controls_context* odp_conversion_context::controls_context() } odf_drawing_context* odp_conversion_context::drawing_context() { - if (slide_context_.page_state_list_.empty()) + if (false == drawing_context_.empty()) { - return &drawing_context_; + return drawing_context_.back().get(); + } + else if (false == slide_context_.page_state_list_.empty()) + { + return slide_context_.state().drawing_context(); } else { - return slide_context_.state().drawing_context(); + return NULL; } } odf_comment_context* odp_conversion_context::comment_context() @@ -95,8 +106,6 @@ void odp_conversion_context::start_document() start_presentation(); root_presentation_ = dynamic_cast(get_current_object_element().get()); - - drawing_context_.set_styles_context(styles_context()); } void odp_conversion_context::end_document() @@ -150,10 +159,7 @@ void odp_conversion_context::end_layout_slide() slide_context_.end_page(); slide_context_.set_styles_context(NULL); //возврат на базовый } -void odp_conversion_context::start_text_context() -{ - text_context_ = new odf_text_context(this, slide_context_.get_styles_context()); -} + odf_style_context* odp_conversion_context::styles_context() { odf_style_context* result = slide_context_.get_styles_context(); @@ -163,20 +169,6 @@ odf_style_context* odp_conversion_context::styles_context() return result; } -void odp_conversion_context::end_text_context() -{ - if (text_context_) - delete text_context_; - text_context_ = NULL; -} - -void odp_conversion_context::start_drawings() -{ -} -void odp_conversion_context::end_drawings() -{ - current_slide().drawing_context()->clear(); -} void odp_conversion_context::start_note(bool bMaster) { office_element_ptr note_elm; diff --git a/OdfFile/Writer/Format/odp_conversion_context.h b/OdfFile/Writer/Format/odp_conversion_context.h index ec48961b8a..02dbf786f8 100644 --- a/OdfFile/Writer/Format/odp_conversion_context.h +++ b/OdfFile/Writer/Format/odp_conversion_context.h @@ -72,8 +72,6 @@ public: odp_page_state & current_slide() { return slide_context_.state();} ///////////////////////////////////////////////////// - virtual void start_text_context(); - virtual void end_text_context(); virtual odf_drawing_context * drawing_context(); virtual odf_controls_context * controls_context(); @@ -83,9 +81,6 @@ public: virtual odf_style_context * styles_context(); - void start_drawings(); - void end_drawings(); - void start_comment (int oox_comment_id); void end_comment (); void start_comment_content (); @@ -97,9 +92,6 @@ public: std::map map_table_styles_; private: odp_slide_context slide_context_; - odf_drawing_context drawing_context_; - - odf_text_context* text_context_; office_presentation* root_presentation_; }; diff --git a/OdfFile/Writer/Format/ods_conversion_context.cpp b/OdfFile/Writer/Format/ods_conversion_context.cpp index e80eb60b34..4daf21b60e 100644 --- a/OdfFile/Writer/Format/ods_conversion_context.cpp +++ b/OdfFile/Writer/Format/ods_conversion_context.cpp @@ -48,9 +48,8 @@ namespace cpdoccore { namespace odf_writer { -ods_conversion_context::ods_conversion_context(package::odf_document * outputDocument) - : odf_conversion_context (SpreadsheetDocument, outputDocument), - table_context_(*this), current_text_context_(NULL) +ods_conversion_context::ods_conversion_context(package::odf_document* outputDocument) + : odf_conversion_context(SpreadsheetDocument, outputDocument), table_context_(*this) { } @@ -279,13 +278,13 @@ void ods_conversion_context::start_comment(int col, int row, std::wstring & auth office_element_ptr paragr_elm; create_element(L"text", L"p", paragr_elm, this); - current_text_context_->start_paragraph(paragr_elm); + text_context()->start_paragraph(paragr_elm); } void ods_conversion_context::end_comment() { - if (current_text_context_)current_text_context_->end_paragraph(); + if (text_context())text_context()->end_paragraph(); - current_table()->end_comment(current_text_context_); + current_table()->end_comment(text_context()); end_text_context(); } void ods_conversion_context::set_comment_color(const std::wstring & color) @@ -598,34 +597,46 @@ void ods_conversion_context::add_column(int start_column, int repeated, int leve current_table()->set_column_default_cell_style(style_cell_name); } } -void ods_conversion_context::start_text_context() -{ - current_text_context_ = new odf_text_context(this, styles_context()); -} -void ods_conversion_context::end_text_context() -{ - if (current_text_context_) - delete current_text_context_; - current_text_context_ = NULL; -} + void ods_conversion_context::add_text_content(const std::wstring & text) { - if (current_text_context_) + if (false == text_context_.empty()) { - current_text_context_->add_text_content(text); + text_context_.back()->add_text_content(text); + } +} +odf_drawing_context* ods_conversion_context::drawing_context() +{ + if (false == drawing_context_.empty()) + { + return drawing_context_.back().get(); + } + else + { + return current_table()->drawing_context(); + } +} +odf_text_context* ods_conversion_context::text_context() +{ + if (false == text_context_.empty()) + { + return text_context_.back().get(); + } + else + { + return NULL; } } - void ods_conversion_context::add_text(const std::wstring &text) { office_element_ptr paragr_elm; create_element(L"text", L"p", paragr_elm, this); - current_text_context_->start_paragraph(paragr_elm); + text_context()->start_paragraph(paragr_elm); - current_text_context_->add_text_content(text); + text_context()->add_text_content(text); - current_text_context_->end_paragraph(); + text_context()->end_paragraph(); } void ods_conversion_context::start_cell_text() @@ -635,7 +646,7 @@ void ods_conversion_context::start_cell_text() office_element_ptr paragr_elm; create_element(L"text", L"p", paragr_elm, this); - current_text_context_->start_paragraph(paragr_elm); + text_context()->start_paragraph(paragr_elm); if (current_table()->is_cell_hyperlink()) { @@ -650,29 +661,23 @@ void ods_conversion_context::start_cell_text() text_a_->common_xlink_attlist_.type_ = xlink_type(xlink_type::Simple); text_a_->common_xlink_attlist_.href_ = state.link; - current_text_context_->start_element(text_a_elm); // может быть стоит сделать собственый??? + text_context()->start_element(text_a_elm); // может быть стоит сделать собственый??? // libra дурит если в табличках будет вложенный span в гиперлинк ... оО (хотя это разрешено в спецификации!!!) - current_text_context_->single_paragraph_ = true; + text_context()->single_paragraph_ = true; } } void ods_conversion_context::end_cell_text() { - if (current_text_context_) + if (text_context()) { - if (current_table()->is_cell_hyperlink()) current_text_context_->end_element(); + if (current_table()->is_cell_hyperlink()) text_context()->end_element(); - current_text_context_->end_paragraph(); + text_context()->end_paragraph(); } } -void ods_conversion_context::start_drawings() -{ -} -void ods_conversion_context::end_drawings() -{ - current_table()->drawing_context()->clear(); -} + void ods_conversion_context::add_external_reference(const std::wstring & ref) { ods_external_state external; diff --git a/OdfFile/Writer/Format/ods_conversion_context.h b/OdfFile/Writer/Format/ods_conversion_context.h index d75b585190..b754facd82 100644 --- a/OdfFile/Writer/Format/ods_conversion_context.h +++ b/OdfFile/Writer/Format/ods_conversion_context.h @@ -100,16 +100,11 @@ public: //----------------------------------------------------------------------- ods_table_state_ptr & current_table() { return table_context_.state();} //----------------------------------------------------------------------- - virtual void start_text_context(); - virtual void end_text_context(); - virtual odf_drawing_context * drawing_context() {return current_table()->drawing_context();} - virtual odf_text_context * text_context() {return current_text_context_;} + virtual odf_drawing_context * drawing_context(); + virtual odf_text_context * text_context(); virtual odf_controls_context * controls_context(){return current_table()->controls_context();} - void start_drawings(); - void end_drawings(); - bool start_header(int type); bool start_footer(int type); void end_header_footer(); @@ -140,9 +135,7 @@ public: std::vector externals_; private: - ods_table_context table_context_; - - odf_text_context* current_text_context_; + ods_table_context table_context_; office_spreadsheet* root_spreadsheet_; }; diff --git a/OdfFile/Writer/Format/ods_table_state.cpp b/OdfFile/Writer/Format/ods_table_state.cpp index 5cb24b0535..8f75ec0bc9 100644 --- a/OdfFile/Writer/Format/ods_table_state.cpp +++ b/OdfFile/Writer/Format/ods_table_state.cpp @@ -1779,7 +1779,10 @@ void ods_table_state::set_conditional_time(int period) } void ods_table_state::set_conditional_text(const std::wstring &text) { + if (text.empty()) return; + calcext_condition* condition = dynamic_cast(current_level_.back().get()); + if (!condition) return; if ((condition->attr_.calcext_value_) && (std::wstring::npos != condition->attr_.calcext_value_->find(L"contains-text") || diff --git a/OdfFile/Writer/Format/odt_conversion_context.cpp b/OdfFile/Writer/Format/odt_conversion_context.cpp index a373985f3c..8f33037670 100644 --- a/OdfFile/Writer/Format/odt_conversion_context.cpp +++ b/OdfFile/Writer/Format/odt_conversion_context.cpp @@ -210,21 +210,7 @@ odf_text_context* odt_conversion_context::text_context() return main_text_context_; } } -void odt_conversion_context::start_text_context() -{ - odf_text_context_ptr new_text_context_ = boost::shared_ptr(new odf_text_context(this, /*odf_conversion_context::*/styles_context())); - //объекты с текстом в колонтитулах - if (!new_text_context_)return; - text_context_.push_back(new_text_context_); -} -void odt_conversion_context::end_text_context() -{ - if (text_context_.size() > 0) - { - text_context_.pop_back(); - } -} void odt_conversion_context::add_text_content(const std::wstring & text) { if (drop_cap_state_.enabled) @@ -258,31 +244,26 @@ void odt_conversion_context::add_to_root() odf_element_state & state = text_context()->current_level_.back(); current_root_elements_.push_back(state); } -void odt_conversion_context::start_drawings() +void odt_conversion_context::start_drawing_context() { - odf_drawing_context_ptr new_drawing_context_ = boost::shared_ptr(new odf_drawing_context(this)); - if (!new_drawing_context_)return; - - new_drawing_context_->set_styles_context(styles_context()); + odf_conversion_context::start_drawing_context(); - new_drawing_context_->set_footer_state(is_footer_); - new_drawing_context_->set_header_state(is_header_); - - drawing_context_.push_back(new_drawing_context_); + drawing_context()->set_footer_state(is_footer_); + drawing_context()->set_header_state(is_header_); } bool odt_conversion_context::start_math() { if (false == math_context()->isEmpty()) return false; - start_drawings(); + start_drawing_context(); return odf_conversion_context::start_math(); } void odt_conversion_context::end_math() { odf_conversion_context::end_math(); - end_drawings(); + end_drawing_context(); } -void odt_conversion_context::end_drawings() +void odt_conversion_context::end_drawing_context() { if (drawing_context_.empty()) return; diff --git a/OdfFile/Writer/Format/odt_conversion_context.h b/OdfFile/Writer/Format/odt_conversion_context.h index d613080ba2..1eee02ae9f 100644 --- a/OdfFile/Writer/Format/odt_conversion_context.h +++ b/OdfFile/Writer/Format/odt_conversion_context.h @@ -65,9 +65,6 @@ public: virtual void start_document(); virtual void end_document(); - virtual void start_text_context(); - virtual void end_text_context(); - virtual odf_drawing_context * drawing_context(); virtual odf_text_context * text_context(); virtual odf_controls_context * controls_context(); @@ -78,8 +75,9 @@ public: odf_table_context * table_context(); odf_notes_context * notes_context(); - void start_drawings (); - void end_drawings (); + + virtual void start_drawing_context(); + virtual void end_drawing_context(); virtual bool start_math(); virtual void end_math(); @@ -218,9 +216,6 @@ private: std::wstring current_master_page_; - std::vector drawing_context_; - std::vector text_context_; //for embedded - odf_controls_context controls_context_; std::vector current_root_elements_; // for section, if needed diff --git a/OdfFile/Writer/Format/office_forms.cpp b/OdfFile/Writer/Format/office_forms.cpp index 01ebc9a3c9..3c92115ff1 100644 --- a/OdfFile/Writer/Format/office_forms.cpp +++ b/OdfFile/Writer/Format/office_forms.cpp @@ -241,22 +241,22 @@ const wchar_t * form_element::name = L"element"; void form_element::serialize_attlist(CP_ATTR_NODE) { - CP_XML_ATTR_OPT(L"form:name", name_); + CP_XML_ATTR_OPT(L"form:name", name_); CP_XML_ATTR_OPT(L"form:control-implementation", control_implementation_); - CP_XML_ATTR_OPT(L"form:data-field", data_field_); - CP_XML_ATTR_OPT(L"form:linked-cell", linked_cell_); - CP_XML_ATTR_OPT(L"form:disabled", disabled_); - CP_XML_ATTR_OPT(L"form:id", id_); - CP_XML_ATTR_OPT(L"form:label", label_); - CP_XML_ATTR_OPT(L"form:printable", printable_); - CP_XML_ATTR_OPT(L"form:tab-index", tab_index_); - CP_XML_ATTR_OPT(L"form:tab-stop", tab_stop_); - CP_XML_ATTR_OPT(L"form:title", title_); - CP_XML_ATTR_OPT(L"form:value", value_); + CP_XML_ATTR_OPT(L"form:data-field", data_field_); + CP_XML_ATTR_OPT(L"form:linked-cell", linked_cell_); + CP_XML_ATTR_OPT(L"form:disabled", disabled_); + CP_XML_ATTR_OPT(L"form:id", id_); + CP_XML_ATTR_OPT_ENCODE_STRING(L"form:label", label_); + CP_XML_ATTR_OPT(L"form:printable", printable_); + CP_XML_ATTR_OPT(L"form:tab-index", tab_index_); + CP_XML_ATTR_OPT(L"form:tab-stop", tab_stop_); + CP_XML_ATTR_OPT_ENCODE_STRING(L"form:title", title_); + CP_XML_ATTR_OPT_ENCODE_STRING(L"form:value", value_); CP_XML_ATTR_OPT_ENCODE_STRING(L"form:current-value", current_value_); - CP_XML_ATTR_OPT(L"form:dropdown", dropdown_); - CP_XML_ATTR_OPT(L"xml:id", xml_id_); - CP_XML_ATTR_OPT(L"xforms:bind", xforms_bind_); + CP_XML_ATTR_OPT(L"form:dropdown", dropdown_); + CP_XML_ATTR_OPT(L"xml:id", xml_id_); + CP_XML_ATTR_OPT(L"xforms:bind", xforms_bind_); } void form_element::create_child_element(const std::wstring & Ns, const std::wstring & Name) { diff --git a/OdfFile/Writer/Format/style_text_properties.cpp b/OdfFile/Writer/Format/style_text_properties.cpp index 531643e63b..9916c796d3 100644 --- a/OdfFile/Writer/Format/style_text_properties.cpp +++ b/OdfFile/Writer/Format/style_text_properties.cpp @@ -63,7 +63,10 @@ std::wstring delete_apostroph_in_name(std::wstring value) } return value; } - +void text_format_properties_content::set_r_style(const std::wstring & rStyle) +{ + r_style_ = rStyle; +} void text_format_properties_content::apply_from(const text_format_properties_content & Other) { _CP_APPLY_PROP( r_style_, Other.r_style_); diff --git a/OdfFile/Writer/Format/style_text_properties.h b/OdfFile/Writer/Format/style_text_properties.h index 49289356ba..001f1c1823 100644 --- a/OdfFile/Writer/Format/style_text_properties.h +++ b/OdfFile/Writer/Format/style_text_properties.h @@ -73,10 +73,8 @@ class text_format_properties_content { public: void serialize(std::wostream & strm,const wchar_t * ns, const wchar_t * name ); - - void apply_from(const text_format_properties_content & Other); - - void set_r_style(const std::wstring & rStyle) { r_style_ = rStyle; } + void apply_from(const text_format_properties_content & Other); + void set_r_style(const std::wstring & rStyle); void clear(); diff --git a/OfficeCryptReader/Test/Test.cpp b/OfficeCryptReader/Test/Test.cpp index 2447fc4d60..eea58cadd8 100644 --- a/OfficeCryptReader/Test/Test.cpp +++ b/OfficeCryptReader/Test/Test.cpp @@ -31,8 +31,8 @@ int _tmain(int argc, _TCHAR* argv[]) ECMACryptFile crypt_file; bool result = false, bDataIntegrity = false; - std::wstring srcFileName = L"D:\\tests\\__53\\test123-1.rtf-my.docx"; - std::wstring dstFileName = srcFileName + L"-mycrypt.docx"; + std::wstring srcFileName = L"D:\\tests\\__63\\test-group-ole.ods-ms.xlsx"; + std::wstring dstFileName = srcFileName + L"-mycrypt.xlsx"; std::wstring dstFileName2 = dstFileName + L".oox"; //std::wstring dstFileName = srcFileName + L".oox"; @@ -45,19 +45,22 @@ int _tmain(int argc, _TCHAR* argv[]) //std::wstring dstFileName1 = srcFileName1 + L".oox"; //result = crypt_file.DecryptOfficeFile(srcFileName1, dstFileName1, password, bDataIntegrity); + result = crypt_file.EncryptOfficeFile(srcFileName, dstFileName, password, L"123456789"); //result = crypt_file.DecryptOfficeFile(dstFileName, dstFileName2, password, bDataIntegrity); - //std::wstring addit_name = L"11111111111111111111111111111"; - // - //std::string addit_info = crypt_file.ReadAdditional(srcFileName, addit_name); + std::wstring addit_name = L"11111111111111111111111111111"; - //std::wstring temp = NSFile::CFileBinary::CreateTempFileWithUniqueName(L"", L"asd"); - // - //addit_info += std::string(temp.begin(), temp.end()); + for (size_t i = 0; i < 100; ++i) + { + std::string addit_info = crypt_file.ReadAdditional(dstFileName, addit_name); - //crypt_file.WriteAdditional(srcFileName, addit_name, addit_info); - + std::wstring temp = NSFile::CFileBinary::CreateTempFileWithUniqueName(L"", L"asd"); + // + addit_info += std::string(temp.begin(), temp.end()); + + crypt_file.WriteAdditional(dstFileName, addit_name, addit_info); + } _CrtDumpMemoryLeaks(); return 0; } diff --git a/OfficeCryptReader/Test/Test.vcxproj b/OfficeCryptReader/Test/Test.vcxproj index 99a903ea7e..a4e29c7c91 100644 --- a/OfficeCryptReader/Test/Test.vcxproj +++ b/OfficeCryptReader/Test/Test.vcxproj @@ -87,12 +87,15 @@ + + - - + + + diff --git a/OfficeCryptReader/Test/Test.vcxproj.filters b/OfficeCryptReader/Test/Test.vcxproj.filters index 975d1188fe..b1846ffd9f 100644 --- a/OfficeCryptReader/Test/Test.vcxproj.filters +++ b/OfficeCryptReader/Test/Test.vcxproj.filters @@ -9,6 +9,8 @@ Common + + @@ -17,12 +19,9 @@ Common - - Common - - - Common - + + + \ No newline at end of file diff --git a/OfficeCryptReader/source/ECMACryptFile.cpp b/OfficeCryptReader/source/ECMACryptFile.cpp index 49fa702e91..84054babf8 100644 --- a/OfficeCryptReader/source/ECMACryptFile.cpp +++ b/OfficeCryptReader/source/ECMACryptFile.cpp @@ -1143,26 +1143,49 @@ std::string ECMACryptFile::ReadAdditional(const std::wstring &file_name, const s } bool ECMACryptFile::WriteAdditional(const std::wstring &file_name, const std::wstring &addit_name, const std::string &addit_info) { - POLE::Storage *pStorage = new POLE::Storage(file_name.c_str()); - - if (!pStorage)return false; - - if (!pStorage->open(true, false)) + try { + CFCPP::CompoundFile *pStorage = new CFCPP::CompoundFile(file_name, CFCPP::Update); + if (!pStorage)return false; + + std::shared_ptr pAddit = pStorage->RootStorage()->GetStream(addit_name); + + if (!pAddit) + { + pAddit = pStorage->RootStorage()->AddStream(addit_name); + } + + pAddit->Write(addit_info.c_str(), 0, addit_info.size()); + + pStorage->Save(file_name); + pStorage->Close(); delete pStorage; + } + catch (...) + { return false; } - POLE::Stream *pStream = new POLE::Stream(pStorage, addit_name, true, addit_info.size()); - - pStream->write((unsigned char*)addit_info.c_str(), addit_info.size()); - pStream->setSize(addit_info.size()); + //POLE::Storage *pStorage = new POLE::Storage(file_name.c_str()); + // + //if (!pStorage)return false; - pStream->flush(); - delete pStream; + //if (!pStorage->open(true, false)) + //{ + // delete pStorage; + // return false; + //} - pStorage->close(); - delete pStorage; + //POLE::Stream *pStream = new POLE::Stream(pStorage, addit_name, true, addit_info.size()); + // + //pStream->write((unsigned char*)addit_info.c_str(), addit_info.size()); + //pStream->setSize(addit_info.size()); + + //pStream->flush(); + //delete pStream; + + //pStorage->close(); + //delete pStorage; return true; } diff --git a/PdfFile/PdfFile.cpp b/PdfFile/PdfFile.cpp index 5e19b7ecba..3f11c7face 100644 --- a/PdfFile/PdfFile.cpp +++ b/PdfFile/PdfFile.cpp @@ -789,6 +789,7 @@ void CPdfFile::DrawPageOnRenderer(IRenderer* pRenderer, int nPageIndex, bool* pB { if (!m_pInternal->pReader) return; + pRenderer->CommandLong(c_nPenWidth0As1px, 1); m_pInternal->pReader->DrawPageOnRenderer(pRenderer, nPageIndex, pBreak); } std::wstring CPdfFile::GetInfo() diff --git a/PdfFile/PdfWriter.cpp b/PdfFile/PdfWriter.cpp index 3c99dfecae..64844d9386 100644 --- a/PdfFile/PdfWriter.cpp +++ b/PdfFile/PdfWriter.cpp @@ -166,19 +166,18 @@ void CPdfWriter::SetDocumentInfo(const std::wstring& wsTitle, const std::wstring if (!IsValid()) return; - std::string sTitle = U_TO_UTF8(wsTitle); - std::string sAuthor = U_TO_UTF8(wsCreator); - std::string sSubject = U_TO_UTF8(wsSubject); - std::string sKeywords = U_TO_UTF8(wsKeywords); - - if (!sTitle.empty()) - m_pDocument->SetTitle(sTitle); - if (!sAuthor.empty()) + if (!wsTitle.empty()) + m_pDocument->SetTitle(U_TO_UTF8(wsTitle)); + if (!wsCreator.empty()) + { + std::string sAuthor = U_TO_UTF8(wsCreator); + NSStringUtils::string_replaceA(sAuthor, ";", ", "); m_pDocument->SetAuthor(sAuthor); - if (!sSubject.empty()) - m_pDocument->SetSubject(sSubject); - if (!sKeywords.empty()) - m_pDocument->SetKeywords(sKeywords); + } + if (!wsSubject.empty()) + m_pDocument->SetSubject(U_TO_UTF8(wsSubject)); + if (!wsKeywords.empty()) + m_pDocument->SetKeywords(U_TO_UTF8(wsKeywords)); } std::wstring CPdfWriter::GetTempFile(const std::wstring& wsDirectory) { @@ -1600,10 +1599,13 @@ HRESULT CPdfWriter::DrawImageWith1bppMask(IGrObject* pImage, NSImages::CPixJbig2 if (!IsPageValid() || !pMaskBuffer || !pImage) return S_OK; + PdfWriter::CImageDict* pPdfImage = LoadImage((Aggplus::CImage*)pImage, 255); + if (!pPdfImage) + return S_OK; + m_pPage->GrSave(); UpdateTransform(); - PdfWriter::CImageDict* pPdfImage = LoadImage((Aggplus::CImage*)pImage, 255); - pPdfImage->LoadMask(pMaskBuffer, unMaskWidth, unMaskHeight); + pPdfImage->LoadMask(pMaskBuffer, unMaskWidth, unMaskHeight); m_pPage->DrawImage(pPdfImage, MM_2_PT(dX), MM_2_PT(m_dPageHeight - dY - dH), MM_2_PT(dW), MM_2_PT(dH)); m_pPage->GrRestore(); return S_OK; @@ -2013,16 +2015,34 @@ void CPdfWriter::UpdateBrush(NSFonts::IApplicationFonts* pAppFonts, const std::w _CXIMAGE_FORMAT_SVG == oImageFormat.eFileType) { // TODO: Реализовать отрисовку метафайлов по-нормальному - MetaFile::IMetaFile* pMeta = MetaFile::Create(pAppFonts); - pMeta->LoadFromFile(wsTexturePath.c_str()); + MetaFile::IMetaFile* pMeta = MetaFile::Create(pAppFonts); + pMeta->LoadFromFile(wsTexturePath.c_str()); double dL, dR, dT, dB; m_oPath.GetBounds(dL, dT, dR, dB); - double dNewW = std::max(10.0, dR - dL) / 72 * 300; + double dW = 300.0 * (dR - dL) / 72; + if (dW < 0) dW = -dW; + double dH = 300.0 * (dB - dT) / 72; + if (dH < 0) dH = -dH; - std::wstring wsTempFile = GetTempFile(wsTempDirectory); - pMeta->ConvertToRaster(wsTempFile.c_str(), _CXIMAGE_FORMAT_PNG, dNewW); + if (dW < 1) dW = 1; + if (dH < 1) dH = 1; + + double dMax = 2000; + double dMin = 10; + if (dW > dMax || dH > dMax) + { + double dMaxSrc = (dW > dH) ? dW : dH; + dW *= (dMax / dMaxSrc); + dH *= (dMax / dMaxSrc); + } + + if (dW < dMin) dW = dMin; + if (dH < dMin) dH = dMin; + + std::wstring wsTempFile = GetTempFile(wsTempDirectory); + pMeta->ConvertToRaster(wsTempFile.c_str(), _CXIMAGE_FORMAT_PNG, (int)dW, (int)dH); RELEASEOBJECT(pMeta); diff --git a/PdfFile/SrcReader/GfxClip.h b/PdfFile/SrcReader/GfxClip.h index 506274e74c..c4614cc927 100644 --- a/PdfFile/SrcReader/GfxClip.h +++ b/PdfFile/SrcReader/GfxClip.h @@ -8,6 +8,25 @@ #include "../lib/xpdf/GfxState.h" #include "MemoryUtils.h" +struct GfxClipMatrix +{ + double dA; + double dB; + double dC; + double dD; + double dE; + double dF; + + void FromDoublePointer(double* pMatrix) + { + dA = pMatrix[0]; + dB = pMatrix[1]; + dC = pMatrix[2]; + dD = pMatrix[3]; + dE = pMatrix[4]; + dF = pMatrix[5]; + } +}; class GfxTextClip { @@ -308,7 +327,8 @@ public: if (pPath && Matrix) { m_vPaths.push_back(pPath->copy()); - m_vMatrix.push_back(Matrix); + m_vMatrix.push_back(GfxClipMatrix()); + m_vMatrix.back().FromDoublePointer(Matrix); m_vPathsClipEo.push_back(bEo); } @@ -329,11 +349,6 @@ public: return m_vPathsClipEo[i]; } - double *GetMatrix(int i) - { - return m_vMatrix[i]; - } - bool IsChanged() { return m_bChanged; @@ -353,13 +368,12 @@ public: m_pTextClip = new GfxTextClip(c.GetTextClip()); }; - + std::vector m_vMatrix; private: std::vector m_vPaths; std::vector m_vPathsClipEo; - std::vector m_vMatrix; bool m_bChanged; GfxTextClip *m_pTextClip; }; diff --git a/PdfFile/SrcReader/RendererOutputDev.cpp b/PdfFile/SrcReader/RendererOutputDev.cpp index 3682ca5067..d1088106b5 100644 --- a/PdfFile/SrcReader/RendererOutputDev.cpp +++ b/PdfFile/SrcReader/RendererOutputDev.cpp @@ -535,8 +535,6 @@ namespace PdfReader m_bTransparentGroupSoftMask = false; m_bTransparentGroupSoftMaskEnd = false; - m_pSoftMask = NULL; - m_bDrawOnlyText = false; m_bClipChanged = true; @@ -632,7 +630,6 @@ namespace PdfReader // if (m_pBufferTextClip) tmpchange // delete m_pBufferTextClip; - RELEASEARRAYOBJECTS(m_pSoftMask); } void RendererOutputDev::startPage(int nPageIndex, GfxState *pGState) { @@ -647,7 +644,6 @@ namespace PdfReader m_bIsolatedTransparentGroup = false; m_bTransparentGroupSoftMask = false; m_bTransparentGroupSoftMaskEnd = false; - RELEASEARRAYOBJECTS(m_pSoftMask); if (c_nHtmlRendrerer2 == m_lRendererType) m_bDrawOnlyText = (S_OK == m_pRenderer->CommandLong(c_nCommandLongTypeOnlyText, 0)) ? true : false; @@ -668,8 +664,6 @@ namespace PdfReader } void RendererOutputDev::restoreState(GfxState *pGState) { - RELEASEARRAYOBJECTS(m_pSoftMask); - if (!m_sClip.empty()) m_sClip.pop_back(); m_bClipChanged = true; @@ -2937,7 +2931,7 @@ namespace PdfReader if (m_bDrawOnlyText) return; - if (m_bTransparentGroupSoftMask || (!m_arrTransparentGroupSoftMask.empty() && m_bTransparentGroupSoftMaskEnd) || m_pSoftMask) + if (m_bTransparentGroupSoftMask || (!m_arrTransparentGroupSoftMask.empty() && m_bTransparentGroupSoftMaskEnd)) return; DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); @@ -3327,7 +3321,7 @@ namespace PdfReader - DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); + DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); long brush; int alpha = pGState->getFillOpacity() * 255; @@ -3383,7 +3377,7 @@ namespace PdfReader if (m_bTransparentGroupSoftMask || (!m_arrTransparentGroupSoftMask.empty() && m_bTransparentGroupSoftMaskEnd)) return true; - DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); + DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); long brush; int alpha = pGState->getFillOpacity() * 255; @@ -3428,7 +3422,7 @@ namespace PdfReader if (m_bTransparentGroupSoftMask || (!m_arrTransparentGroupSoftMask.empty() && m_bTransparentGroupSoftMaskEnd)) return true; - DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); + DoPath(pGState, pGState->getPath(), pGState->getPageHeight(), pGState->getCTM()); long brush; int alpha = pGState->getFillOpacity() * 255; @@ -4078,10 +4072,12 @@ namespace PdfReader unsigned char *pBufferPtr = new unsigned char[nBufferSize]; if (!pBufferPtr) return; + /* RELEASEARRAYOBJECTS(m_pSoftMask); m_pSoftMask = pBufferPtr; m_nSoftMaskWidth = nWidth; m_nSoftMaskHeight = nHeight; + */ Aggplus::CImage oImage; oImage.Create(pBufferPtr, nWidth, nHeight, -4 * nWidth, true); @@ -4183,7 +4179,10 @@ namespace PdfReader ImageStream *pImageStream = new ImageStream(pStream, nWidth, nComponentsCount, pColorMap->getBits()); pImageStream->reset(); - unsigned char unAlpha = m_bTransparentGroup ? ((m_bIsolatedTransparentGroup && m_bTransparentGroupSoftMask) ? 0 : 255.0 * pGState->getFillOpacity()) : 255; + bool bTransperent = false; + for (const bool& b : m_arrTransparentGroupSoftMask) + bTransperent = b || bTransperent; + unsigned char unAlpha = m_bTransparentGroup ? ((m_bIsolatedTransparentGroup && bTransperent) ? 0 : 255.0 * pGState->getFillOpacity()) : 255; int nStride = pImageStream->getVals(); int nComps = pImageStream->getComps(); @@ -4699,7 +4698,7 @@ namespace PdfReader *pdDeviceX = dUserX * pMatrix[0] + dUserY * pMatrix[2] + pMatrix[4]; *pdDeviceY = dUserX * pMatrix[1] + dUserY * pMatrix[3] + pMatrix[5]; } - void RendererOutputDev::DoPath(GfxState *pGState, GfxPath *pPath, double dPageHeight, double *pCTM) + void RendererOutputDev::DoPath(GfxState *pGState, GfxPath *pPath, double dPageHeight, double *pCTM, GfxClipMatrix* pCTM2) { if (m_bDrawOnlyText) return; @@ -4715,6 +4714,15 @@ namespace PdfReader arrMatrix[3] = -pCTM[3]; arrMatrix[4] = pCTM[4]; arrMatrix[5] = -pCTM[5] + dPageHeight; + if (pCTM2) + { + arrMatrix[0] = pCTM2->dA; + arrMatrix[1] = -pCTM2->dB; + arrMatrix[2] = pCTM2->dC; + arrMatrix[3] = -pCTM2->dD; + arrMatrix[4] = pCTM2->dE; + arrMatrix[5] = -pCTM2->dF + dPageHeight; + } double dShiftX = 0, dShiftY = 0; DoTransform(arrMatrix, &dShiftX, &dShiftY); @@ -4722,9 +4730,7 @@ namespace PdfReader m_pRenderer->BeginCommand(c_nPathType); m_pRenderer->PathCommandEnd(); - int nSubPathCount = pPath->getNumSubpaths(); - - for (int nSubPathIndex = 0; nSubPathIndex < nSubPathCount; ++nSubPathIndex) + for (int nSubPathIndex = 0, nSubPathCount = pPath->getNumSubpaths(); nSubPathIndex < nSubPathCount; ++nSubPathIndex) { GfxSubpath *pSubpath = pPath->getSubpath(nSubPathIndex); int nPointsCount = pSubpath->getNumPoints(); @@ -4775,20 +4781,20 @@ namespace PdfReader if (m_sClip.empty()) return; - for (int i = m_sClip.size() - 1; i >= 0; i--) { - //for (int i = 0; i < m_sClip.size(); i++) { + //for (int i = m_sClip.size() - 1; i >= 0; i--) + for (int i = 0; i < m_sClip.size(); i++) + { for (int nIndex = 0; nIndex < m_sClip[i].GetPathNum(); nIndex++) { GfxPath *pPath = m_sClip[i].GetPath(nIndex); bool bFlag = m_sClip[i].GetClipEo(nIndex); - double *pMatrix = m_sClip[i].GetMatrix(nIndex); int nClipFlag = bFlag ? c_nClipRegionTypeEvenOdd : c_nClipRegionTypeWinding; nClipFlag |= c_nClipRegionIntersect; m_pRenderer->BeginCommand(c_nClipType); m_pRenderer->put_ClipMode(nClipFlag); - DoPath(pGState, pPath, pGState->getPageHeight(), pMatrix); + DoPath(pGState, pPath, pGState->getPageHeight(), pGState->getCTM(), &m_sClip[i].m_vMatrix[nIndex]); m_pRenderer->EndCommand(c_nPathType); m_pRenderer->EndCommand(c_nClipType); m_pRenderer->PathCommandEnd(); @@ -4847,9 +4853,6 @@ namespace PdfReader m_pRenderer->PathCommandEnd(); m_pRenderer->EndConvertCoordsToIdentity(); } - - if (m_sClip[i].GetPathNum() > 0) - break; } m_bClipChanged = false; diff --git a/PdfFile/SrcReader/RendererOutputDev.h b/PdfFile/SrcReader/RendererOutputDev.h index 4a08fa2d1b..2195678218 100644 --- a/PdfFile/SrcReader/RendererOutputDev.h +++ b/PdfFile/SrcReader/RendererOutputDev.h @@ -301,7 +301,7 @@ namespace PdfReader private: void Transform(double *pMatrix, double dUserX, double dUserY, double *pdDeviceX, double *pdDeviceY); - void DoPath(GfxState *pGState, GfxPath *pPath, double dPageHeight, double *pCTM); + void DoPath(GfxState *pGState, GfxPath *pPath, double dPageHeight, double *pCTM, GfxClipMatrix* pCTM2 = NULL); void ClipToText(const std::wstring& wsFontName, const std::wstring& wsFontPath, double dFontSize, int nFontStyle, double* pMatrix, const std::wstring& wsText, double dX, double dY, double dWidth = 0, double dHeight = 0, double dBaseLineOffset = 0); void updateClip(GfxState *pGState); void updateClipAttack(GfxState *pGState); @@ -330,9 +330,11 @@ namespace PdfReader bool m_bTransparentGroupSoftMaskEnd; std::vector m_arrTransparentGroupSoftMask; + /* unsigned char* m_pSoftMask; int m_nSoftMaskWidth; int m_nSoftMaskHeight; + */ bool m_bDrawOnlyText; // Special option for html-renderer diff --git a/PdfFile/SrcWriter/Document.cpp b/PdfFile/SrcWriter/Document.cpp index e8f200ab70..fc1743f684 100644 --- a/PdfFile/SrcWriter/Document.cpp +++ b/PdfFile/SrcWriter/Document.cpp @@ -144,7 +144,6 @@ namespace PdfWriter m_pInfo->SetInfo(InfoProducer, sCreatorA.c_str()); m_pInfo->SetInfo(InfoCreator, sCreatorA.c_str()); - CMetadata* pMetadata = m_pCatalog->AddMetadata(m_pXref, m_pInfo); if (IsPDFA()) { CArrayObject* pID = (CArrayObject*)m_pTrailer->Get("ID"); @@ -231,7 +230,7 @@ namespace PdfWriter } void CDocument::SaveToStream(CStream* pStream) { - unsigned long nRet = OK; + m_pCatalog->AddMetadata(m_pXref, m_pInfo); // Пишем заголовок if (IsPDFA()) diff --git a/PdfFile/SrcWriter/FontCidTT.cpp b/PdfFile/SrcWriter/FontCidTT.cpp index d1ec00d586..a29db0845e 100644 --- a/PdfFile/SrcWriter/FontCidTT.cpp +++ b/PdfFile/SrcWriter/FontCidTT.cpp @@ -143,19 +143,22 @@ namespace PdfWriter pFontDescriptor->Add("Flags", nFlags); - CArrayObject* pBBox = new CArrayObject(); - int* pFontBBox = m_pFontFile->GetBBox(); - pBBox->Add(pFontBBox[0]); - pBBox->Add(pFontBBox[1]); - pBBox->Add(pFontBBox[2]); - pBBox->Add(pFontBBox[3]); - pFontDescriptor->Add("FontBBox", pBBox); + if (m_pFontFile) + { + CArrayObject* pBBox = new CArrayObject(); + int* pFontBBox = m_pFontFile->GetBBox(); + pBBox->Add(pFontBBox[0]); + pBBox->Add(pFontBBox[1]); + pBBox->Add(pFontBBox[2]); + pBBox->Add(pFontBBox[3]); + pFontDescriptor->Add("FontBBox", pBBox); + } pFontDescriptor->Add("ItalicAngle", 0); - pFontDescriptor->Add("Ascent", m_pFontFile->GetAscent()); - pFontDescriptor->Add("Descent", m_pFontFile->GetDescent()); - pFontDescriptor->Add("CapHeight", m_pFontFile->GetCapHeight()); + pFontDescriptor->Add("Ascent", m_pFontFile ? m_pFontFile->GetAscent() : 1000); + pFontDescriptor->Add("Descent", m_pFontFile ? m_pFontFile->GetDescent() : -500); + pFontDescriptor->Add("CapHeight", m_pFontFile ? m_pFontFile->GetCapHeight() : 800); pFontDescriptor->Add("StemV", 0); - pFontDescriptor->Add("FontWeight", m_pFontFile->GetWeight()); + pFontDescriptor->Add("FontWeight", m_pFontFile ? m_pFontFile->GetWeight() : 400); m_pFontFileDict = new CDictObject(m_pXref); pFontDescriptor->Add("FontFile2", m_pFontFileDict); diff --git a/PdfFile/SrcWriter/FontTT.cpp b/PdfFile/SrcWriter/FontTT.cpp index ec0acd3029..6b62eb2002 100644 --- a/PdfFile/SrcWriter/FontTT.cpp +++ b/PdfFile/SrcWriter/FontTT.cpp @@ -185,10 +185,10 @@ namespace PdfWriter m_pFontDescriptor->Add("FontBBox", pBBox); m_pFontDescriptor->Add("Ascent", yMax); m_pFontDescriptor->Add("Descent", yMin); - m_pFontDescriptor->Add("CapHeight", (int)(unUnitsPerEm ? m_pFontFile->GetCapHeight() * dKoef : m_pFontFile->GetCapHeight())); + m_pFontDescriptor->Add("CapHeight", m_pFontFile ? (int)(unUnitsPerEm ? m_pFontFile->GetCapHeight() * dKoef : m_pFontFile->GetCapHeight()) : 800); m_pFontDescriptor->Add("ItalicAngle", 0); m_pFontDescriptor->Add("StemV", 80); - m_pFontDescriptor->Add("FontWeight", m_pFontFile->GetWeight()); + m_pFontDescriptor->Add("FontWeight", m_pFontFile ? m_pFontFile->GetWeight() : 400); // Сейчас мы этот класс используем для внедрения шрифтов, которые будут использоваться для заполнения // внутри форм. Если класс будет использоваться для чего-то другого, тогда надо задавать ограничения на внедрение diff --git a/PdfFile/SrcWriter/FontTTWriter.cpp b/PdfFile/SrcWriter/FontTTWriter.cpp index 90434b2fcf..fc48309663 100644 --- a/PdfFile/SrcWriter/FontTTWriter.cpp +++ b/PdfFile/SrcWriter/FontTTWriter.cpp @@ -261,6 +261,7 @@ namespace PdfWriter m_nAscent = 1000; m_nDescent = -500; m_nCapHeight = 800; + m_nWeight = 400; Parse(); } @@ -1227,10 +1228,14 @@ namespace PdfWriter if (-1 != nIndex && m_pTables[nIndex].nLen > 0) { unsigned int unOffset = m_pTables[nIndex].nOffset; + int nTableVersion = GetS16BE(unOffset, &m_bSuccess); m_nWeight = GetS16BE(unOffset + 4, &m_bSuccess); m_nAscent = GetS16BE(unOffset + 68, &m_bSuccess); m_nDescent = GetS16BE(unOffset + 70, &m_bSuccess); - m_nCapHeight = GetS16BE(unOffset + 88, &m_bSuccess); + + //https://learn.microsoft.com/en-us/typography/opentype/spec/os2#scapheight + if (nTableVersion >= 2) + m_nCapHeight = GetS16BE(unOffset + 88, &m_bSuccess); } } } diff --git a/PdfFile/SrcWriter/Metadata.cpp b/PdfFile/SrcWriter/Metadata.cpp index a9afe01388..ec8b9e1917 100644 --- a/PdfFile/SrcWriter/Metadata.cpp +++ b/PdfFile/SrcWriter/Metadata.cpp @@ -36,6 +36,15 @@ #include "../../DesktopEditor/common/SystemUtils.h" #include "../../OOXML/Base/Base.h" +void EscapeCharacters(std::string& s) +{ + NSStringUtils::string_replaceA(s, "&", "&"); + NSStringUtils::string_replaceA(s, "<", "<"); + NSStringUtils::string_replaceA(s, ">", ">"); + NSStringUtils::string_replaceA(s, "\"", """); + NSStringUtils::string_replaceA(s, "\'", "'"); +} + namespace PdfWriter { //---------------------------------------------------------------------------------------- @@ -59,11 +68,22 @@ namespace PdfWriter // Begin sXML += ("\n\n\n"); - // Producer sXML += "\n"; + // Producer sXML += ""; sXML += pInfo->GetInfo(InfoProducer); sXML += "\n"; + // Keywords + const char* sKeywords = pInfo->GetInfo(InfoKeyWords); + if (sKeywords) + { + std::string s = sKeywords; + EscapeCharacters(s); + + sXML += ""; + sXML += s; + sXML += "\n"; + } sXML += "\n"; // Creator Tool @@ -93,6 +113,43 @@ namespace PdfWriter sXML += "\n"; + // DC + const char* sTitle = pInfo->GetInfo(InfoTitle); + const char* sAuthor = pInfo->GetInfo(InfoAuthor); + const char* sSubject = pInfo->GetInfo(InfoSubject); + if (sTitle || sAuthor || sSubject) + { + sXML += "\n"; + sXML += "application/pdf"; + if (sSubject) + { + std::string s = sSubject; + EscapeCharacters(s); + + sXML += ""; + sXML += s; + sXML += "\n"; + } + if (sAuthor) + { + std::string s = sAuthor; + EscapeCharacters(s); + + sXML += ""; + sXML += s; + sXML += "\n"; + } + if (sTitle) + { + std::string s = sTitle; + EscapeCharacters(s); + + sXML += ""; + sXML += s; + sXML += "\n"; + } + sXML += "\n"; + } if (pXref->IsPDFA()) { diff --git a/RtfFile/Format/RtfGlobalTables.cpp b/RtfFile/Format/RtfGlobalTables.cpp index b337954e07..4527a0f187 100644 --- a/RtfFile/Format/RtfGlobalTables.cpp +++ b/RtfFile/Format/RtfGlobalTables.cpp @@ -152,7 +152,7 @@ bool RtfColorTable::GetColor( std::wstring sTheme, RtfColor& oColor) } return false; } -bool RtfColorTable::GetColor( RtfColor oColor , int & nId) +bool RtfColorTable::GetColor( RtfColor oColor , _INT32 & nId) { for (size_t i = 0; i < m_aArray.size(); i++ ) { diff --git a/RtfFile/Format/RtfGlobalTables.h b/RtfFile/Format/RtfGlobalTables.h index af2bac4b3b..d2977f0906 100644 --- a/RtfFile/Format/RtfGlobalTables.h +++ b/RtfFile/Format/RtfGlobalTables.h @@ -56,7 +56,7 @@ public: bool GetColor( int nId, RtfColor& oColor); bool GetColor( RtfColor::_ThemeColor oTheme, RtfColor& oColor); bool GetColor( std::wstring sTheme, RtfColor& oColor); - bool GetColor( RtfColor oColor , int & nId); + bool GetColor( RtfColor oColor , _INT32 & nId); std::wstring RenderToRtf(RenderParameter oRenderParameter); std::wstring RenderToOOX(RenderParameter oRenderParameter); diff --git a/RtfFile/Format/RtfMath.cpp b/RtfFile/Format/RtfMath.cpp index 0349fef57e..df643a7135 100644 --- a/RtfFile/Format/RtfMath.cpp +++ b/RtfFile/Format/RtfMath.cpp @@ -36,7 +36,7 @@ RtfMath::RtfMath( ) { m_bHeader = true; - m_bIsVal = m_bIsBool = false; + m_bIsVal = m_bIsChar = m_bIsBool = false; } RtfMath::RtfMath(const RtfMath& oMath ) { @@ -46,6 +46,7 @@ RtfMath& RtfMath::operator=(const RtfMath& oMath ) { m_bHeader = oMath.m_bHeader; m_bIsVal = oMath.m_bIsVal; + m_bIsChar = oMath.m_bIsChar; m_bIsBool = oMath.m_bIsBool; m_sRtfName = oMath.m_sRtfName; @@ -133,8 +134,15 @@ std::wstring RtfMath::RenderToRtf(RenderParameter oRenderParameter) if (m_bIsVal) { - oNewParameter.nType = RENDER_TO_RTF_PARAM_CHAR; - sVal = m_oVal.RenderToRtf( oNewParameter ) ; + if (false == m_bIsChar) + { + sVal += L" " + m_sVal; + } + else + { + oNewParameter.nType = RENDER_TO_RTF_PARAM_CHAR; + sVal = L" " + m_oVal.RenderToRtf(oNewParameter); + } } else { diff --git a/RtfFile/Format/RtfMath.h b/RtfFile/Format/RtfMath.h index 5ba8005639..d4e0a2912e 100644 --- a/RtfFile/Format/RtfMath.h +++ b/RtfFile/Format/RtfMath.h @@ -44,12 +44,15 @@ public: bool m_bHeader; //чтобы отличать заголовок от вложенных групп - bool m_bIsVal; - bool m_bIsBool; + bool m_bIsVal = false; + bool m_bIsChar = false; // for write + bool m_bIsBool = false; // for read RtfParagraph m_oVal; RtfShapePtr m_oPicture; + std::wstring m_sVal; + RtfMath( ); RtfMath(const RtfMath& oMath ); diff --git a/RtfFile/Format/RtfProperty.cpp b/RtfFile/Format/RtfProperty.cpp index b3257943c4..bceb98ec19 100644 --- a/RtfFile/Format/RtfProperty.cpp +++ b/RtfFile/Format/RtfProperty.cpp @@ -321,7 +321,7 @@ RtfColor::RtfColor() { SetDefault(); } -RtfColor::RtfColor(int nHex) +RtfColor::RtfColor(_UINT32 nHex) { SetHEX( nHex ); } @@ -384,7 +384,7 @@ const RtfColor& RtfColor::operator=( const RtfColor& oColor ) m_bAuto = oColor.m_bAuto; return (*this); } -void RtfColor::SetHEX(int color) +void RtfColor::SetHEX(_UINT32 color) { SetDefault(); @@ -392,11 +392,11 @@ void RtfColor::SetHEX(int color) m_byteGreen = (color&0xFF00) >> 8; m_byteBlue = (color&0xFF); } -int RtfColor::GetRGB()const +_UINT32 RtfColor::GetRGB()const { return (m_byteRed << 16) | (m_byteGreen << 8) | m_byteBlue; } -void RtfColor::SetRGB(unsigned int color) +void RtfColor::SetRGB(_UINT32 color) { SetDefault(); @@ -420,7 +420,7 @@ void RtfColor::SetHSL(double dH, double dS,double dL) { HSL2RGB(dH, dS, dL, m_byteRed, m_byteGreen, m_byteBlue); } -void RtfColor::SetRGBPercent(int nRedPer, int nGreenPer, int nBluePer) +void RtfColor::SetRGBPercent(_INT32 nRedPer, _INT32 nGreenPer, _INT32 nBluePer) { m_byteRed = (BYTE)(nRedPer * 255 / 100); m_byteGreen = (BYTE)(nGreenPer * 255 / 100); @@ -430,7 +430,7 @@ void RtfColor::SetHEXString(std::wstring hex) { if ( L"auto" != hex ) { - int color = Strings::ToColor(hex); + _UINT32 color = Strings::ToColor(hex); SetRGB(color); } @@ -460,7 +460,7 @@ std::wstring RtfColor::RenderToRtf(RenderParameter oRenderParameter ) } else { - int nColor; + _INT32 nColor; if( true == poRtfDocument->m_oColorTable.GetColor(*this, nColor) ) sResult += L"\\c" + std::to_wstring(nColor); //todo } diff --git a/RtfFile/Format/RtfProperty.h b/RtfFile/Format/RtfProperty.h index a4330a99ef..5a6848e4d0 100644 --- a/RtfFile/Format/RtfProperty.h +++ b/RtfFile/Format/RtfProperty.h @@ -135,16 +135,16 @@ public: FontTheme m_eFontTheme; FontFamily m_eFontFamily; std::wstring m_sPanose; - int m_nID; + _INT32 m_nID; std::wstring m_sName; std::wstring m_sAltName; - int m_nCharset; - int m_nCodePage; - int m_nPitch; + _INT32 m_nCharset; + _INT32 m_nCodePage; + _INT32 m_nPitch; RtfFont(); - int GetType(); + _INT32 GetType(); bool operator==( const RtfFont& oFont); bool IsValid(); @@ -171,11 +171,11 @@ public: BYTE m_byteTint; _ThemeColor m_eTheme; - int m_index; + _INT32 m_index; //-------------------------------------------------------- RtfColor(); - RtfColor(int nHex); + RtfColor(_UINT32 nHex); RtfColor(BYTE r, BYTE g, BYTE b); void SetDefaultRtf(); void SetDefaultOOX(); @@ -188,13 +188,13 @@ public: bool operator==(const RtfColor& oColor); const RtfColor& operator=( const RtfColor& oColor ); - void SetHEX(int color); - int GetRGB()const; - void SetRGB(unsigned int color); + void SetHEX(_UINT32 color); + _UINT32 GetRGB()const; + void SetRGB(_UINT32 color); void SetRGB(BYTE red, BYTE green, BYTE blue); void GetHSL(double &dH, double &dS,double &dL); void SetHSL(double dH, double dS,double dL); - void SetRGBPercent(int nRedPer, int nGreenPer, int nBluePer); + void SetRGBPercent(_INT32 nRedPer, _INT32 nGreenPer, _INT32 nBluePer); void SetHEXString(std::wstring hex); std::wstring ToHexColor(bool bBGR = false); @@ -245,15 +245,15 @@ public: st_clshdrawnil, //clshdrawnil Specifies a dark diagonal cross background pattern for the paragraph. } m_eType; - int m_nValue; - int m_nForeColor; - int m_nBackColor; + _INT32 m_nValue; + _INT32 m_nForeColor; + _INT32 m_nBackColor; RtfShading(); bool operator==( const RtfShading& oChar ); bool IsValid(); - int GetType(); + _INT32 GetType(); void SetDefaultRtf( ); void SetDefaultOOX( ); @@ -266,35 +266,35 @@ public: class RtfShadingPar : public RtfShading { public: - int GetType(); + _INT32 GetType(); std::wstring RenderToRtf(RenderParameter oRenderParameter); }; class RtfShadingChar : public RtfShading { public: - int GetType(); + _INT32 GetType(); std::wstring RenderToRtf(RenderParameter oRenderParameter); }; class RtfShadingCell : public RtfShading { public: - int GetType(); + _INT32 GetType(); std::wstring RenderToRtf(RenderParameter oRenderParameter); }; class RtfShadingRow : public RtfShading { public: - int GetType(); + _INT32 GetType(); std::wstring RenderToRtf(RenderParameter oRenderParameter); }; class RtfShadingTableStyle : public RtfShading { public: - int GetType(); + _INT32 GetType(); std::wstring RenderToRtf(RenderParameter oRenderParameter); }; @@ -335,15 +335,15 @@ public: bt_brdrengrave, //brdrengrave Engraved border. } m_eType; - int m_nWidth; - int m_nSpace; - int m_nColor; + _INT32 m_nWidth; + _INT32 m_nSpace; + _INT32 m_nColor; RtfBorder(); bool operator==( const RtfBorder& oChar ); bool IsValid(); - int GetType(); + _INT32 GetType(); void SetDefaultRtf( ); void SetDefaultOOX( ); @@ -380,7 +380,7 @@ public: tk_tqclear } m_eKind; - int m_nTab; //tbN or \txN Tab position in twips from the left margin. + _INT32 m_nTab; //tbN or \txN Tab position in twips from the left margin. RtfTab(); @@ -421,55 +421,55 @@ public: enum _UnderlineStyle {uls_none, uls_Single, uls_Dotted,uls_Dashed ,uls_Dash_dotted,uls_Dash_dot_dotted,uls_Double,uls_Heavy_wave,uls_Long_dashe,uls_Stops_all,uls_Thick,uls_Thick_dotted,uls_Thick_dashed,uls_Thick_dash_dotted,uls_Thick_dash_dot_dotted,uls_Thick_long_dashed,uls_Double_wave,uls_Word,uls_Wave}; - int m_nAnimated; //animtextN Animated text properties (note: Word 2007 ignores this control word): + _INT32 m_nAnimated; //animtextN Animated text properties (note: Word 2007 ignores this control word): - int m_bBold; //b* Bold. - int m_bCaps; //caps* All capitals. - int m_nScalex; //charscalexN Character scaling value. The N argument is a value representing a percentage (default is 100). - int m_nCharStyle; //csN Designates character style. If a character style is specified, style properties must be specified with the character run. N refers to an entry in the style table. - int m_nDown; //dnN Move down N half-points (default is 6). - int m_bEmbo; //embo* Emboss. - int m_nCharacterSpacing;//expndtwN Expansion or compression of the space between characters in twips; a negative value compresses. For backward compatibility, both \expndtwN and \expndN should be emitted. - int m_nFitText; //fittextN Fit the text in the current group in N twips. When N is set to -1 (\fittext-1), it indicates a continuation of the previous \fittextN run. In other words, {\fittext1000 Fit this} {\fittext-1 text} fits the string “Fit this text” in 1000 twips. - int m_nFont; //fN Font number. N refers to an entry in the font table. - int m_nFont2; - int m_nFont3; - int m_nFontSize; //fsN Font size in half-points (default is 24). - int m_bItalic; //i* Italic. - int m_bImprint; //impr* Engrave (imprint). - int m_nKerning; //kerningN Point size (in half-points) above which to kern character pairs. \kerning0 turns off kerning. - int m_bRightToLeft; //rtlch Character data following this control word is treated as a right-to-left run. - int m_nLanguage; - int m_nLanguageAsian; // for East Asian text - int m_nComplexScript; // 1 - means South East Asian complex script; 0 - means not South East Asian script - int m_bOutline; //outl* Outline. - int m_bScaps; //scaps* Small capitals. - int m_bShadow; //shad* Shadow. - int m_bStrike; //strike* Strikethrough. - int m_nStriked; //striked1 Double strikethrough. \striked0 turns it off. - int m_bSub; //sub Subscripts text and shrinks point size according to font information. - int m_bSuper; //super Superscripts text and shrinks point size according to font information. - int m_bHidden; //v* Hidden text. - int m_nHightlited; + _INT32 m_bBold; //b* Bold. + _INT32 m_bCaps; //caps* All capitals. + _INT32 m_nScalex; //charscalexN Character scaling value. The N argument is a value representing a percentage (default is 100). + _INT32 m_nCharStyle; //csN Designates character style. If a character style is specified, style properties must be specified with the character run. N refers to an entry in the style table. + _INT32 m_nDown; //dnN Move down N half-points (default is 6). + _INT32 m_bEmbo; //embo* Emboss. + _INT32 m_nCharacterSpacing;//expndtwN Expansion or compression of the space between characters in twips; a negative value compresses. For backward compatibility, both \expndtwN and \expndN should be emitted. + _INT32 m_nFitText; //fittextN Fit the text in the current group in N twips. When N is set to -1 (\fittext-1), it indicates a continuation of the previous \fittextN run. In other words, {\fittext1000 Fit this} {\fittext-1 text} fits the string “Fit this text” in 1000 twips. + _INT32 m_nFont; //fN Font number. N refers to an entry in the font table. + _INT32 m_nFont2; + _INT32 m_nFont3; + _INT32 m_nFontSize; //fsN Font size in half-points (default is 24). + _INT32 m_bItalic; //i* Italic. + _INT32 m_bImprint; //impr* Engrave (imprint). + _INT32 m_nKerning; //kerningN Point size (in half-points) above which to kern character pairs. \kerning0 turns off kerning. + _INT32 m_bRightToLeft; //rtlch Character data following this control word is treated as a right-to-left run. + _INT32 m_nLanguage; + _INT32 m_nLanguageAsian; // for East Asian text + _INT32 m_nComplexScript; // 1 - means South East Asian complex script; 0 - means not South East Asian script + _INT32 m_bOutline; //outl* Outline. + _INT32 m_bScaps; //scaps* Small capitals. + _INT32 m_bShadow; //shad* Shadow. + _INT32 m_bStrike; //strike* Strikethrough. + _INT32 m_nStriked; //striked1 Double strikethrough. \striked0 turns it off. + _INT32 m_bSub; //sub Subscripts text and shrinks point size according to font information. + _INT32 m_bSuper; //super Superscripts text and shrinks point size according to font information. + _INT32 m_bHidden; //v* Hidden text. + _INT32 m_nHightlited; - int m_nForeColor; + _INT32 m_nForeColor; - int m_nCrAuth; - int m_nCrDate; + _INT32 m_nCrAuth; + _INT32 m_nCrDate; - int m_nDeleted; - int m_nRevised; - int m_nRevauth; - int m_nRevdttm; - int m_nRevauthDel; - int m_nRevdttmDel; + _INT32 m_nDeleted; + _INT32 m_nRevised; + _INT32 m_nRevauth; + _INT32 m_nRevdttm; + _INT32 m_nRevauthDel; + _INT32 m_nRevdttmDel; - int m_nInsrsid; + _INT32 m_nInsrsid; -// int m_bUnderline; //ul* Continuous underline. \ul0 turns off all underlining. +// _INT32 m_bUnderline; //ul* Continuous underline. \ul0 turns off all underlining. _UnderlineStyle m_eUnderStyle; // - int m_nUnderlineColor; // - int m_nUp; //upN Move up N half-points (default is 6). + _INT32 m_nUnderlineColor; // + _INT32 m_nUp; //upN Move up N half-points (default is 6). RtfCharPropertyPtr m_pOldCharProp; RtfBorder m_poBorder; @@ -478,7 +478,7 @@ public: bool operator==( const RtfCharProperty& oChar ); RtfCharProperty(); - int GetType(); + _INT32 GetType(); void SetDefaultRtf(); void SetDefaultOOX(); @@ -493,23 +493,23 @@ public: class RtfListLevelProperty : IRenderableProperty { public: - int m_nLevel; ///OOX - int m_nNumberType; //levelnfcN \levelnfcnN Specifies the number type for the level - int m_bTentative; //lvltentative Specifies that a given numbering level was been saved by a producer but was not used in the parent document. This means that this numbering level may be redefined by a future consumer without changing the actual content of the document. - int m_nJustification; //leveljcN \leveljcnN 0 Left justified 1 Center justified 2 Right justified - int m_nFollow; //levelfollowN - int m_nStart; //levelstartatN N specifies the start-at value for the level. + _INT32 m_nLevel; ///OOX + _INT32 m_nNumberType; //levelnfcN \levelnfcnN Specifies the number type for the level + _INT32 m_bTentative; //lvltentative Specifies that a given numbering level was been saved by a producer but was not used in the parent document. This means that this numbering level may be redefined by a future consumer without changing the actual content of the document. + _INT32 m_nJustification; //leveljcN \leveljcnN 0 Left justified 1 Center justified 2 Right justified + _INT32 m_nFollow; //levelfollowN + _INT32 m_nStart; //levelstartatN N specifies the start-at value for the level. std::wstring m_sText; //как в rtf текст, но сдвинут от нуля на 1 // \'03\'00.\'01 -> ("%d%d%d",4,1,2) std::wstring m_sNumber; - int m_nNoRestart; //levelnorestartN 1 if this level does not restart its count each time a super ordinate level is incremented; 0 if this level does restart its count each time a super ordinate level is incremented. - int m_nLegal; //levellegalN 1 if any list numbers from previous levels should be converted to Arabic numbers; 0 if they should be left with the format specified by their own level’s definition. - int m_nPictureIndex; //levelpictureN Determines which picture bullet from the \listpicture destination should be applied. + _INT32 m_nNoRestart; //levelnorestartN 1 if this level does not restart its count each time a super ordinate level is incremented; 0 if this level does restart its count each time a super ordinate level is incremented. + _INT32 m_nLegal; //levellegalN 1 if any list numbers from previous levels should be converted to Arabic numbers; 0 if they should be left with the format specified by their own level’s definition. + _INT32 m_nPictureIndex; //levelpictureN Determines which picture bullet from the \listpicture destination should be applied. RtfTabs m_oTabs; //ParagraphProp - int m_nFirstIndent; - int m_nIndent; - int m_nIndentStart; - int m_nSpace; + _INT32 m_nFirstIndent; + _INT32 m_nIndent; + _INT32 m_nIndentStart; + _INT32 m_nSpace; RtfCharProperty m_oCharProp; //Char @@ -521,10 +521,10 @@ public: std::wstring RenderToRtf(RenderParameter oRenderParameter); std::wstring RenderToOOX(RenderParameter oRenderParameter); - std::wstring RenderToOOX2(RenderParameter oRenderParameter, int lvl = PROP_DEF); + std::wstring RenderToOOX2(RenderParameter oRenderParameter, _INT32 lvl = PROP_DEF); - static std::wstring GetFormat( int nNumFormat); - static int GetFormat( std::wstring sFormat); + static std::wstring GetFormat( _INT32 nNumFormat); + static _INT32 GetFormat( std::wstring sFormat); std::wstring GetLevelTextOOX(); void SetLevelTextOOX(std::wstring sText); @@ -533,10 +533,10 @@ public: class RtfListProperty : public IRenderableProperty, public ItemContainer { public: - int m_nID; //listidN Each list must have a unique list ID that should be randomly generated. N is a long integer. The list ID cannot be between –1 and –5. - int m_nTemplateId; //listtemplateidN Each list should have a unique template ID as well, which also should be randomly generated. The template ID –1 means the template ID is undefined. N is a long integer. - int m_nListSimple; //listsimpleN 1 if the list has one level; 0 (default) if the list has nine levels. - int m_bListHybrid; //listhybrid Present if the list has 9 levels, each of which is the equivalent of a simple list. Only one of \listsimpleN and \listhybrid should be present. Word 2000 and newer versions will write lists with the \listhybrid property. + _INT32 m_nID; //listidN Each list must have a unique list ID that should be randomly generated. N is a long integer. The list ID cannot be between –1 and –5. + _INT32 m_nTemplateId; //listtemplateidN Each list should have a unique template ID as well, which also should be randomly generated. The template ID –1 means the template ID is undefined. N is a long integer. + _INT32 m_nListSimple; //listsimpleN 1 if the list has one level; 0 (default) if the list has nine levels. + _INT32 m_bListHybrid; //listhybrid Present if the list has 9 levels, each of which is the equivalent of a simple list. Only one of \listsimpleN and \listhybrid should be present. Word 2000 and newer versions will write lists with the \listhybrid property. std::wstring m_sName; //listname The argument for \listname is a string that is the name of this list. Names allow ListNum fields to specify the list to which they belong. This is a destination control word. RtfListProperty(); @@ -557,8 +557,8 @@ public: class ListOverrideLevel { public: - int m_nLevelIndex; //listoverrideformat Number of list format override levels within this list override (should be either 1, 9, or missing, which means 0). - int m_nStart; //listoverridestartat Indicates an override of the start-at value. + _INT32 m_nLevelIndex; //listoverrideformat Number of list format override levels within this list override (should be either 1, 9, or missing, which means 0). + _INT32 m_nStart; //listoverridestartat Indicates an override of the start-at value. RtfListLevelProperty m_oLevel; ListOverrideLevel() { @@ -578,8 +578,8 @@ public: std::wstring RenderToOOX(RenderParameter oRenderParameter); }; - int m_nListID; //listidN Should exactly match the \listid of one of the lists in the List table. The value N is a long integer. - int m_nIndex; //lsN The (1-based) index of this \listoverride in the \listoverride table. This value should never be zero inside a \listoverride and must be unique for all \listoverride’s within a document. The valid values are from 1 to 2000. The value 0 means no list. + _INT32 m_nListID; //listidN Should exactly match the \listid of one of the lists in the List table. The value N is a long integer. + _INT32 m_nIndex; //lsN The (1-based) index of this \listoverride in the \listoverride table. This value should never be zero inside a \listoverride and must be unique for all \listoverride’s within a document. The valid values are from 1 to 2000. The value 0 means no list. ListOverrideLevels m_oOverrideLevels; @@ -602,27 +602,27 @@ public: _StyleType m_eType; std::wstring m_sName; - int m_nID; + _INT32 m_nID; std::wstring m_sID; - int m_bAdditive; - int m_nBasedOn; - int m_nNext; - int m_bHidden; - int m_nLink; - int m_bLocked; - int m_bPersonal; - int m_bCompose; - int m_bReply; - int m_nSemiHidden; - int m_bQFormat; - int m_nPriority; - int m_bUnhiddenWhenUse; + _INT32 m_bAdditive; + _INT32 m_nBasedOn; + _INT32 m_nNext; + _INT32 m_bHidden; + _INT32 m_nLink; + _INT32 m_bLocked; + _INT32 m_bPersonal; + _INT32 m_bCompose; + _INT32 m_bReply; + _INT32 m_nSemiHidden; + _INT32 m_bQFormat; + _INT32 m_nPriority; + _INT32 m_bUnhiddenWhenUse; RtfStyle(); bool IsValid(); - int GetType(); + _INT32 GetType(); void SetDefaultRtf(); void SetDefaultOOX(); @@ -678,12 +678,12 @@ public: vp_posyout //tposyout Position table outside within the vertical reference frame. }; - int m_bBidi; //taprtl Table direction is right to left. - int m_nAutoFit; //trautofitN AutoFit:0 No AutoFit (default).1 AutoFit is on for the row. Overridden by \clwWidthN and \trwWidthN in any table row - int m_nGraph; //trgaphN Half the space between the cells of a table row in twips. + _INT32 m_bBidi; //taprtl Table direction is right to left. + _INT32 m_nAutoFit; //trautofitN AutoFit:0 No AutoFit (default).1 AutoFit is on for the row. Overridden by \clwWidthN and \trwWidthN in any table row + _INT32 m_nGraph; //trgaphN Half the space between the cells of a table row in twips. - int nTableIndent; //tblindN - int eTableIndentUnit; // tblindtypeN + _INT32 nTableIndent; //tblindN + _INT32 eTableIndentUnit; // tblindtypeN enum _RowJust { @@ -693,43 +693,43 @@ public: rj_trqc //trqc Centers a table row with respect to its containing column. } m_eJust; - int m_nWrapLeft; //tdfrmtxtLeftN Distance in twips, between the left of the table and surrounding text (default is 0). - int m_nWrapRight; //tdfrmtxtRightN Distance in twips, between the right of the table and surrounding text (default is 0). - int m_nWrapTop; //tdfrmtxtTopN Distance in twips, between the top of the table and surrounding text (default is 0). - int m_nWrapBottom; //tdfrmtxtBottomN Distance in twips, between the bottom of the table and surrounding text (default is 0). - int m_bOverlap; //tabsnoovrlp Do not allow table to overlap with other tables or shapes with similar wrapping not contained within it. + _INT32 m_nWrapLeft; //tdfrmtxtLeftN Distance in twips, between the left of the table and surrounding text (default is 0). + _INT32 m_nWrapRight; //tdfrmtxtRightN Distance in twips, between the right of the table and surrounding text (default is 0). + _INT32 m_nWrapTop; //tdfrmtxtTopN Distance in twips, between the top of the table and surrounding text (default is 0). + _INT32 m_nWrapBottom; //tdfrmtxtBottomN Distance in twips, between the bottom of the table and surrounding text (default is 0). + _INT32 m_bOverlap; //tabsnoovrlp Do not allow table to overlap with other tables or shapes with similar wrapping not contained within it. _HRef m_eHRef; _VRef m_eVRef; _HPos m_eHPos; - int m_nHPos; //tposxN Position table N twips from the left edge of the horizontal reference frame. + _INT32 m_nHPos; //tposxN Position table N twips from the left edge of the horizontal reference frame. _VPos m_eVPos; - int m_nVPos; //tposyN Position table N twips from the top edge of the vertical reference frame. + _INT32 m_nVPos; //tposyN Position table N twips from the top edge of the vertical reference frame. - int m_nLeft; + _INT32 m_nLeft; - int m_nWidth; //trwWidthN Width of invisible cell at the end of the row. Used only when rows have different widths. - int m_eWidthUnit; //trftsWidthN Units for \trwWidthN: + _INT32 m_nWidth; //trwWidthN Width of invisible cell at the end of the row. Used only when rows have different widths. + _INT32 m_eWidthUnit; //trftsWidthN Units for \trwWidthN: - int m_nDefCellMarBottom; //trpaddbN Default bottom cell margin or padding for the row. - int m_nDefCellMarLeft; //trpaddlN Default left cell margin or padding for the row. - int m_nDefCellMarRight; //trpaddrN Default right cell margin or padding for the row. - int m_nDefCellMarTop; //trpaddtN Default top cell margin or padding for the row. + _INT32 m_nDefCellMarBottom; //trpaddbN Default bottom cell margin or padding for the row. + _INT32 m_nDefCellMarLeft; //trpaddlN Default left cell margin or padding for the row. + _INT32 m_nDefCellMarRight; //trpaddrN Default right cell margin or padding for the row. + _INT32 m_nDefCellMarTop; //trpaddtN Default top cell margin or padding for the row. - int m_eDefCellMarBottomUnit; //Units for \trpaddbN: 0 Null. Ignore \trpaddbN in favor of \trgaphN (Word 97 style padding). 3 Twips. - int m_eDefCellMarLeftUnit; - int m_eDefCellMarRightUnit; - int m_eDefCellMarTopUnit; + _INT32 m_eDefCellMarBottomUnit; //Units for \trpaddbN: 0 Null. Ignore \trpaddbN in favor of \trgaphN (Word 97 style padding). 3 Twips. + _INT32 m_eDefCellMarLeftUnit; + _INT32 m_eDefCellMarRightUnit; + _INT32 m_eDefCellMarTopUnit; - int m_nDefCellSpBottom; //trspdbN Default bottom cell spacing for the row. The total vertical spacing between adjacent cells is equal to the sum of \trspdtN from the bottom cell and \trspdbN from the top cell, both of which will have the same value when written by Word. - int m_nDefCellSpLeft; //trspdlN - int m_nDefCellSpRight; //trspdrN - int m_nDefCellSpTop; //trspdtN + _INT32 m_nDefCellSpBottom; //trspdbN Default bottom cell spacing for the row. The total vertical spacing between adjacent cells is equal to the sum of \trspdtN from the bottom cell and \trspdbN from the top cell, both of which will have the same value when written by Word. + _INT32 m_nDefCellSpLeft; //trspdlN + _INT32 m_nDefCellSpRight; //trspdrN + _INT32 m_nDefCellSpTop; //trspdtN - int m_eDefCellSpBottomUnit; //trspdfbN Units for \trspdbN: 0 Null. Ignore \trspdbN. 3 Twips. - int m_eDefCellSpLeftUnit; - int m_eDefCellSpRightUnit; - int m_eDefCellSpTopUnit; + _INT32 m_eDefCellSpBottomUnit; //trspdfbN Units for \trspdbN: 0 Null. Ignore \trspdbN. 3 Twips. + _INT32 m_eDefCellSpLeftUnit; + _INT32 m_eDefCellSpRightUnit; + _INT32 m_eDefCellSpTopUnit; RtfBorder m_oBorderLeft; RtfBorder m_oBorderRight; @@ -739,18 +739,18 @@ public: RtfBorder m_oBorderHor; RtfShadingRow m_oShading; - int m_nStyle; + _INT32 m_nStyle; //Autoformatting Flags - int m_bAutoFirstRow; //tbllkhdrrows Flag sets table autoformat to format the first (header) row. - int m_bAutoLastRow; //tbllklastrow Flag sets table autoformat to format the last row. - int m_bAutoFirstCol; //tbllkhdrcols Flag sets table autoformat to format the first (header) column. - int m_bAutoLastCol; //tbllklastcol Flag sets table autoformat to format the last column. - int m_bAutoNoRowBand; //tbllknorowband Specifies row banding conditional formatting shall not be applied. - int m_bAutoNoColBand; //tbllknocolband Specifies column banding conditional formatting shall not be applied. + _INT32 m_bAutoFirstRow; //tbllkhdrrows Flag sets table autoformat to format the first (header) row. + _INT32 m_bAutoLastRow; //tbllklastrow Flag sets table autoformat to format the last row. + _INT32 m_bAutoFirstCol; //tbllkhdrcols Flag sets table autoformat to format the first (header) column. + _INT32 m_bAutoLastCol; //tbllklastcol Flag sets table autoformat to format the last column. + _INT32 m_bAutoNoRowBand; //tbllknorowband Specifies row banding conditional formatting shall not be applied. + _INT32 m_bAutoNoColBand; //tbllknocolband Specifies column banding conditional formatting shall not be applied. - int m_nRowBandSize; //tscbandshN Count of rows in a row band - int m_nColBandSize; //tscbandsvN Count of cells in a cell band + _INT32 m_nRowBandSize; //tscbandshN Count of rows in a row band + _INT32 m_nColBandSize; //tscbandsvN Count of cells in a cell band RtfTableProperty(); @@ -811,21 +811,21 @@ public: }; - int m_nWidth; - int m_nHeight; + _INT32 m_nWidth; + _INT32 m_nHeight; _HRef m_eHRef; _VRef m_eVRef; _HPos m_eHPos; - int m_nHPos; + _INT32 m_nHPos; _VPos m_eVPos; - int m_nVPos; - int m_bLockAnchor; + _INT32 m_nVPos; + _INT32 m_bLockAnchor; _TextWrap m_eWrap; - int m_DropcapType; - int m_DropcapLines; - int m_nHorSpace; // dxfrtextN Distance in twips of a positioned paragraph from text in the main text flow in all directions. - int m_nVerSpace; // dfrmtxtxN N is the horizontal distance in twips from text on both sides of the frame. - int m_nAllSpace; // dfrmtxtyN N is the vertical distance in twips from text on both sides of the frame. + _INT32 m_DropcapType; + _INT32 m_DropcapLines; + _INT32 m_nHorSpace; // dxfrtextN Distance in twips of a positioned paragraph from text in the main text flow in all directions. + _INT32 m_nVerSpace; // dfrmtxtxN N is the horizontal distance in twips from text on both sides of the frame. + _INT32 m_nAllSpace; // dfrmtxtyN N is the vertical distance in twips from text on both sides of the frame. RtfFrame(); @@ -847,36 +847,36 @@ typedef boost::shared_ptr RtfCellPropertyPtr; class RtfCellProperty: public IRenderableProperty { public: - int m_bMergeFirst; //clmgf The first cell in a range of table cells to be merged. - int m_bMerge; //clmrg Contents of the table cell are merged with those of the preceding cell. - int m_bMergeFirstVertical; //clvmgf The first cell in a range of table cells to be vertically merged. - int m_bMergeVertical; //clvmrg Contents of the table cell are vertically merged with those of the preceding cell. + _INT32 m_bMergeFirst; //clmgf The first cell in a range of table cells to be merged. + _INT32 m_bMerge; //clmrg Contents of the table cell are merged with those of the preceding cell. + _INT32 m_bMergeFirstVertical; //clvmgf The first cell in a range of table cells to be vertically merged. + _INT32 m_bMergeVertical; //clvmrg Contents of the table cell are vertically merged with those of the preceding cell. - int m_bFitText; //clFitText Fit text in cell, compressing each paragraph to the width of the cell. - int m_bNoWrap; //clNoWrap Do not wrap text for the cell. Only has an effect if the table cell does not have a preferred \clwWidthN, which overrides \trautofitN. + _INT32 m_bFitText; //clFitText Fit text in cell, compressing each paragraph to the width of the cell. + _INT32 m_bNoWrap; //clNoWrap Do not wrap text for the cell. Only has an effect if the table cell does not have a preferred \clwWidthN, which overrides \trautofitN. - int m_nPaddingLeft; //clpadlN Left cell margin or padding. Overrides \trpaddlN. - int m_ePaddingLeftUnit; //clpadflN Units for \clpadlN: - int m_nPaddingRight; - int m_ePaddingRightUnit; - int m_nPaddingTop; - int m_ePaddingTopUnit; - int m_nPaddingBottom; - int m_ePaddingBottomUnit; + _INT32 m_nPaddingLeft; //clpadlN Left cell margin or padding. Overrides \trpaddlN. + _INT32 m_ePaddingLeftUnit; //clpadflN Units for \clpadlN: + _INT32 m_nPaddingRight; + _INT32 m_ePaddingRightUnit; + _INT32 m_nPaddingTop; + _INT32 m_ePaddingTopUnit; + _INT32 m_nPaddingBottom; + _INT32 m_ePaddingBottomUnit; - int m_nSpacingLeft; //clsplN Left cell margin or padding. Overrides \trspdlN. - int m_eSpacingLeftUnit; //clspflN Units for \clsplN: - int m_nSpacingRight; - int m_eSpacingRightUnit; - int m_nSpacingTop; - int m_eSpacingTopUnit; - int m_nSpacingBottom; - int m_eSpacingBottomUnit; + _INT32 m_nSpacingLeft; //clsplN Left cell margin or padding. Overrides \trspdlN. + _INT32 m_eSpacingLeftUnit; //clspflN Units for \clsplN: + _INT32 m_nSpacingRight; + _INT32 m_eSpacingRightUnit; + _INT32 m_nSpacingTop; + _INT32 m_eSpacingTopUnit; + _INT32 m_nSpacingBottom; + _INT32 m_eSpacingBottomUnit; - int m_nWidth; //clwWidthN Preferred cell width. Overrides \trautofitN. - int m_eWidthUnit; //clftsWidthN Units for \clwWidthN: + _INT32 m_nWidth; //clwWidthN Preferred cell width. Overrides \trautofitN. + _INT32 m_eWidthUnit; //clftsWidthN Units for \clwWidthN: - int m_bHideMark; //clhidemark This control word specifies whether the end of cell glyph shall influence the height of the given table row in the table. If it is specified, then only printing characters in this cell shall be used to determine the row height. + _INT32 m_bHideMark; //clhidemark This control word specifies whether the end of cell glyph shall influence the height of the given table row in the table. If it is specified, then only printing characters in this cell shall be used to determine the row height. RtfBorder m_oBorderDiagonalLR; RtfBorder m_oBorderDiagonalRL; @@ -888,14 +888,14 @@ public: RtfBorder m_oBorderInsideV; RtfShadingCell m_oShading; - int m_nShadingPctFrom; + _INT32 m_nShadingPctFrom; typedef enum{ ca_none, ca_Top, //clvertalt Text is top-aligned in cell (the default). ca_Center, //clvertalc Text is centered vertically in cell. ca_Bottom //clvertalb Text is bottom-aligned in cell. } CellAlign; - int m_eAlign; + _INT32 m_eAlign; typedef enum{ cf_none, cf_lrtb, //cltxlrtb Text in a cell flows from left to right and top to bottom (default). cf_tbrl, //cltxtbrl Text in a cell flows right to left and top to bottom. @@ -905,22 +905,22 @@ public: } CellFlow; CellFlow m_oCellFlow; - int m_nCellx; //cellxN Defines the right boundary of a table cell, including its half of the space between cells. - int m_nSpan; + _INT32 m_nCellx; //cellxN Defines the right boundary of a table cell, including its half of the space between cells. + _INT32 m_nSpan; //Table Style Specific - int m_bStyleFirstRow; // tscfirstrow This cell is in the first row. - int m_bStyleLastRow; // tsclastrow This cell is in the last row. - int m_bStyleFirstCol; // tscfirstcol This cell is in the first column. - int m_bStyleLastCol; // tsclastcol This cell is in the last column. - int m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. - int m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. - int m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. - int m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. - int m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). - int m_bStyleNECell; // tscnecell NE cell - int m_bStyleSWCell; // tscswcell SW cell. - int m_bStyleSECell; // tscsecell SE cell. + _INT32 m_bStyleFirstRow; // tscfirstrow This cell is in the first row. + _INT32 m_bStyleLastRow; // tsclastrow This cell is in the last row. + _INT32 m_bStyleFirstCol; // tscfirstcol This cell is in the first column. + _INT32 m_bStyleLastCol; // tsclastcol This cell is in the last column. + _INT32 m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. + _INT32 m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. + _INT32 m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. + _INT32 m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. + _INT32 m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). + _INT32 m_bStyleNECell; // tscnecell NE cell + _INT32 m_bStyleSWCell; // tscswcell SW cell. + _INT32 m_bStyleSECell; // tscsecell SE cell. RtfCellProperty(); @@ -944,41 +944,41 @@ typedef boost::shared_ptr RtfRowPropertyPtr; class RtfRowProperty: public RtfTableProperty, public ItemContainer< RtfCellProperty > { public: - int m_nRightToLeft; //bi direction - int m_nIndex; //irowN N is the row index of this row. - int m_nBandIndex; //irowbandN N is the row index of the row, adjusted to account for header rows. A header row has a value of –1. + _INT32 m_nRightToLeft; //bi direction + _INT32 m_nIndex; //irowN N is the row index of this row. + _INT32 m_nBandIndex; //irowbandN N is the row index of the row, adjusted to account for header rows. A header row has a value of –1. - int m_bLastRow; //lastrow Output if this is the last row in the table. + _INT32 m_bLastRow; //lastrow Output if this is the last row in the table. - int m_bIsHeader; //trhdr Table row header. This row should appear at the top of every page on which the current table appears. - int m_bKeep; //trkeep Keep table row together. This row cannot be split by a page break. This property is assumed to be off unless the control word is present. + _INT32 m_bIsHeader; //trhdr Table row header. This row should appear at the top of every page on which the current table appears. + _INT32 m_bKeep; //trkeep Keep table row together. This row cannot be split by a page break. This property is assumed to be off unless the control word is present. - int m_nHeight; //trrhN Height of a table row in twips. When 0, the height is sufficient for all the text in the line; when positive, the height is guaranteed to be at least the specified height; when negative, the absolute value of the height is used, regardless of the height of the text in the line. + _INT32 m_nHeight; //trrhN Height of a table row in twips. When 0, the height is sufficient for all the text in the line; when positive, the height is guaranteed to be at least the specified height; when negative, the absolute value of the height is used, regardless of the height of the text in the line. - int m_nWidthStartInvCell; //trwWidthBN Width of invisible cell at the beginning of the row. Used only in cases where rows have different widths. - int m_eWidthStartInvCellUnit; //trftsWidthBN Units for \trwWidthBN: + _INT32 m_nWidthStartInvCell; //trwWidthBN Width of invisible cell at the beginning of the row. Used only in cases where rows have different widths. + _INT32 m_eWidthStartInvCellUnit; //trftsWidthBN Units for \trwWidthBN: - int m_nWidthEndInvCell; //trwWidthAN Width of invisible cell at the end of the row. Used only when rows have different widths. - int m_eWidthEndInvCellUnit; //trftsWidthAN Units for \trwWidthAN: + _INT32 m_nWidthEndInvCell; //trwWidthAN Width of invisible cell at the end of the row. Used only when rows have different widths. + _INT32 m_eWidthEndInvCellUnit; //trftsWidthAN Units for \trwWidthAN: - int m_nGridBefore; //для oox - int m_nGridAfter; //для oox + _INT32 m_nGridBefore; //для oox + _INT32 m_nGridAfter; //для oox - int m_bStyleFirstRow; // tscfirstrow This cell is in the first row. - int m_bStyleLastRow; // tsclastrow This cell is in the last row. - int m_bStyleFirstCol; // tscfirstcol This cell is in the first column. - int m_bStyleLastCol; // tsclastcol This cell is in the last column. - int m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. - int m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. - int m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. - int m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. - int m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). - int m_bStyleNECell; // tscnecell NE cell - int m_bStyleSWCell; // tscswcell SW cell. - int m_bStyleSECell; // tscsecell SE cell. + _INT32 m_bStyleFirstRow; // tscfirstrow This cell is in the first row. + _INT32 m_bStyleLastRow; // tsclastrow This cell is in the last row. + _INT32 m_bStyleFirstCol; // tscfirstcol This cell is in the first column. + _INT32 m_bStyleLastCol; // tsclastcol This cell is in the last column. + _INT32 m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. + _INT32 m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. + _INT32 m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. + _INT32 m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. + _INT32 m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). + _INT32 m_bStyleNECell; // tscnecell NE cell + _INT32 m_bStyleSWCell; // tscswcell SW cell. + _INT32 m_bStyleSECell; // tscsecell SE cell. - int m_nTrAuth; - int m_nTrDate; + _INT32 m_nTrAuth; + _INT32 m_nTrDate; RtfRowPropertyPtr m_pOldRowProperty; @@ -1007,14 +1007,14 @@ public: bool m_bOldList; RtfParagraphPropertyPtr m_pOldParagraphProp; //------------- - int m_bAutoHyphenation; //hyphpar Switches automatic hyphenation for the paragraph. Append 1 or nothing to toggle property on; append 0 to turn it off. - int m_bInTable; //intbl Paragraph is part of a table. - int m_nItap; //itapN Paragraph nesting level, where 0 is the main document, 1 is a table cell, 2 is a nested table cell, 3 is a doubly nested table cell, and so forth (default is 1). - int m_bKeep; //keep Keep paragraph intact (completely on one page if possible). - int m_bKeepNext; //keepn Keep paragraph with the next paragraph. - int m_bPageBB; //pagebb Break page before the paragraph. - int m_nOutlinelevel; // outlinelevelN Outline level of paragraph. The N argument is a value from 0 to 8 representing the outline level of the paragraph. In the default case, no outline level is specified (same as body text). - int m_nStyle; //sN Designates paragraph style. If a paragraph style is specified, style properties must be specified with the paragraph. N references an entry in the style sheet. + _INT32 m_bAutoHyphenation; //hyphpar Switches automatic hyphenation for the paragraph. Append 1 or nothing to toggle property on; append 0 to turn it off. + _INT32 m_bInTable; //intbl Paragraph is part of a table. + _INT32 m_nItap; //itapN Paragraph nesting level, where 0 is the main document, 1 is a table cell, 2 is a nested table cell, 3 is a doubly nested table cell, and so forth (default is 1). + _INT32 m_bKeep; //keep Keep paragraph intact (completely on one page if possible). + _INT32 m_bKeepNext; //keepn Keep paragraph with the next paragraph. + _INT32 m_bPageBB; //pagebb Break page before the paragraph. + _INT32 m_nOutlinelevel; // outlinelevelN Outline level of paragraph. The N argument is a value from 0 to 8 representing the outline level of the paragraph. In the default case, no outline level is specified (same as body text). + _INT32 m_nStyle; //sN Designates paragraph style. If a paragraph style is specified, style properties must be specified with the paragraph. N references an entry in the style sheet. typedef enum { @@ -1029,7 +1029,7 @@ public: pa_qk20, } ParagraphAlign; - int m_eAlign; + _INT32 m_eAlign; typedef enum { @@ -1044,27 +1044,27 @@ public: FontAlign m_eFontAlign; - int m_nIndFirstLine; //fiN First-line indent in twips (default is 0). - int m_nIndLeft; //liN Left indent in twips (default is 0). - int m_nIndRight; //riN Right indent in twips (default is 0). - int m_nIndStart; //linN Left indent for left-to-right paragraphs; right indent for right-to-left paragraphs (default is 0). \linN defines space before the paragraph. - int m_nIndEnd; //rinN Right indent for left-to-right paragraphs; left indent for right-to-left paragraphs (default is 0). \rinN defines space after the paragraph. - int m_bIndRightAuto; //adjustright Automatically adjust right indent when document grid is defined. - int m_bIndMirror; //indmirror... + _INT32 m_nIndFirstLine; //fiN First-line indent in twips (default is 0). + _INT32 m_nIndLeft; //liN Left indent in twips (default is 0). + _INT32 m_nIndRight; //riN Right indent in twips (default is 0). + _INT32 m_nIndStart; //linN Left indent for left-to-right paragraphs; right indent for right-to-left paragraphs (default is 0). \linN defines space before the paragraph. + _INT32 m_nIndEnd; //rinN Right indent for left-to-right paragraphs; left indent for right-to-left paragraphs (default is 0). \rinN defines space after the paragraph. + _INT32 m_bIndRightAuto; //adjustright Automatically adjust right indent when document grid is defined. + _INT32 m_bIndMirror; //indmirror... - int m_nSpaceBefore; //sbN Space before in twips (default is 0). - int m_nSpaceAfter; //saN Space after in twips (default is 0). - int m_nSpaceBeforeAuto; //sbautoN Auto spacing before: - int m_nSpaceAfterAuto; //saautoN Auto spacing after: - int m_nSpaceBeforeLine; //lisbN Space before in hundredths of a character unit. Overrides \sbN, although they should both be emitted with equivalent values. - int m_nSpaceAfterLine; //lisaN Space after in hundredths of a character unit. Overrides \saN, although they should both be emitted with equivalent values. - int m_nSpaceBetween; //slN Space between lines. If this control word is missing or if \sl0 is used, the line spacing is automatically determined by the tallest character in the line. If N is a positive value, this size is used only if it is taller than the tallest character (otherwise, the tallest character is used); if N is a negative value, the absolute value of N is used, even if it is shorter than the tallest character. - int m_nSpaceMultiLine; //slmultN - int m_bContextualSpacing; //contextualspace + _INT32 m_nSpaceBefore; //sbN Space before in twips (default is 0). + _INT32 m_nSpaceAfter; //saN Space after in twips (default is 0). + _INT32 m_nSpaceBeforeAuto; //sbautoN Auto spacing before: + _INT32 m_nSpaceAfterAuto; //saautoN Auto spacing after: + _INT32 m_nSpaceBeforeLine; //lisbN Space before in hundredths of a character unit. Overrides \sbN, although they should both be emitted with equivalent values. + _INT32 m_nSpaceAfterLine; //lisaN Space after in hundredths of a character unit. Overrides \saN, although they should both be emitted with equivalent values. + _INT32 m_nSpaceBetween; //slN Space between lines. If this control word is missing or if \sl0 is used, the line spacing is automatically determined by the tallest character in the line. If N is a positive value, this size is used only if it is taller than the tallest character (otherwise, the tallest character is used); if N is a negative value, the absolute value of N is used, even if it is shorter than the tallest character. + _INT32 m_nSpaceMultiLine; //slmultN + _INT32 m_bContextualSpacing; //contextualspace - int m_bRtl; //rtlpar Text in this paragraph will display with right-to-left precedence. - int m_bNoWordWrap; //nowwrap - int m_bSnapToGrid; //nosnaplinegrid Disable snap line to grid. + _INT32 m_bRtl; //rtlpar Text in this paragraph will display with right-to-left precedence. + _INT32 m_bNoWordWrap; //nowwrap + _INT32 m_bSnapToGrid; //nosnaplinegrid Disable snap line to grid. enum _TextBoxWrap { @@ -1075,8 +1075,8 @@ public: tbw_txbxtwfirst, //txbxtwfirst tbw_txbxtwlast, //txbxtwlast } m_eTextBoxWrap; - int m_nListId; //lsN Should exactly match the \lsN for one of the list overrides in the List Override table. - int m_nListLevel; //ilvlN The 0-based level of the list to which the paragraph belongs. For all simple lists, N should always be 0. For multilevel lists, it can be 0 through 8. The value 9 is never used. The values 10 through 12 have the special meanings for documents generated by Word 6: 10 = ilvlBullet (a bulleted paragraph in Word 6), 11 = ilvlList (a numbered paragraph in Word 6), 12 = ilvlContinue (a paragraph that was not itself numbered, but took its indenting scheme from its numbering properties and did not “break” numbering (that in Word 6 required otherwise contiguous paragraphs). + _INT32 m_nListId; //lsN Should exactly match the \lsN for one of the list overrides in the List Override table. + _INT32 m_nListLevel; //ilvlN The 0-based level of the list to which the paragraph belongs. For all simple lists, N should always be 0. For multilevel lists, it can be 0 through 8. The value 9 is never used. The values 10 through 12 have the special meanings for documents generated by Word 6: 10 = ilvlBullet (a bulleted paragraph in Word 6), 11 = ilvlList (a numbered paragraph in Word 6), 12 = ilvlContinue (a paragraph that was not itself numbered, but took its indenting scheme from its numbering properties and did not “break” numbering (that in Word 6 required otherwise contiguous paragraphs). RtfShadingPar m_oShading; @@ -1088,7 +1088,7 @@ public: RtfBorder m_oBorderBar; RtfFrame m_oFrame; - int m_bOverlap; //1\absnoovrlpN Allow overlap with other frames or objects with similar wrapping: + _INT32 m_bOverlap; //1\absnoovrlpN Allow overlap with other frames or objects with similar wrapping: enum _TextFollow { tf_none, @@ -1101,22 +1101,22 @@ public: RtfTabs m_oTabs; //Table Style Specific - int m_nTableStyle; // ytsN Designates the table style handle that was applied to the row/cell. - int m_bStyleFirstRow; // tscfirstrow This cell is in the first row. - int m_bStyleLastRow; // tsclastrow This cell is in the last row. - int m_bStyleFirstCollumn; // tscfirstcol This cell is in the first column. - int m_bStyleLastCollumn; // tsclastcol This cell is in the last column. - int m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. - int m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. - int m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. - int m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. - int m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). - int m_bStyleNECell; // tscnecell NE cell. - int m_bStyleSWCell; // tscswcell SW cell. - int m_bStyleSECell; // tscsecell SE cell. + _INT32 m_nTableStyle; // ytsN Designates the table style handle that was applied to the row/cell. + _INT32 m_bStyleFirstRow; // tscfirstrow This cell is in the first row. + _INT32 m_bStyleLastRow; // tsclastrow This cell is in the last row. + _INT32 m_bStyleFirstCollumn; // tscfirstcol This cell is in the first column. + _INT32 m_bStyleLastCollumn; // tsclastcol This cell is in the last column. + _INT32 m_bStyleOddRowBand; // tscbandhorzodd This cell is in the odd row band. + _INT32 m_bStyleEvenRowBand; // tscbandhorzeven This cell is in the even row band. + _INT32 m_bStyleOddColBand; // tscbandvertodd This cell is in the odd column band. + _INT32 m_bStyleEvenColBand; // tscbandverteven This cell is in the even column band. + _INT32 m_bStyleNWCell; // tscnwcell This is the NW (north west) cell in the table (upper left). + _INT32 m_bStyleNECell; // tscnecell NE cell. + _INT32 m_bStyleSWCell; // tscswcell SW cell. + _INT32 m_bStyleSECell; // tscsecell SE cell. - int m_nPrAuth; - int m_nPrDate; + _INT32 m_nPrAuth; + _INT32 m_nPrDate; RtfCharProperty m_oCharProperty; @@ -1169,12 +1169,12 @@ public: class RtfTime: public IRenderableProperty { public: - int m_nYear; - int m_nMonth; - int m_nDay; - int m_nHour; - int m_nMin; - int m_nSecond; + _INT32 m_nYear; + _INT32 m_nMonth; + _INT32 m_nDay; + _INT32 m_nHour; + _INT32 m_nMin; + _INT32 m_nSecond; RtfTime(); bool IsValid(); @@ -1209,15 +1209,15 @@ public: RtfTime m_oPrintTime; RtfTime m_oBackupTime; - int m_nVersion; - int m_nInternalVersion; - int m_nEndingTime; + _INT32 m_nVersion; + _INT32 m_nInternalVersion; + _INT32 m_nEndingTime; - int m_nNumberOfPages; - int m_nNumberOfWords; - int m_nNumberOfCharactersWithSpace; - int m_nNumberOfCharactersWithoutSpace; - int m_nInternalId; + _INT32 m_nNumberOfPages; + _INT32 m_nNumberOfWords; + _INT32 m_nNumberOfCharactersWithSpace; + _INT32 m_nNumberOfCharactersWithoutSpace; + _INT32 m_nInternalId; RtfInformation(); bool IsValid(); @@ -1237,7 +1237,7 @@ public: RtfCharStyle(); - int GetType(); + _INT32 GetType(); void Merge( RtfStylePtr oStyle ); std::wstring RenderToRtf(RenderParameter oRenderParameter); @@ -1251,7 +1251,7 @@ public: RtfParagraphStyle(); - int GetType(); + _INT32 GetType(); void Merge( RtfStylePtr oStyle ); std::wstring RenderToRtf(RenderParameter oRenderParameter); @@ -1286,7 +1286,7 @@ public: RtfTableStyle(); void SetDefault(); - int GetType(); + _INT32 GetType(); void Merge( RtfStylePtr oStyle ); std::wstring RenderToRtf(RenderParameter oRenderParameter); diff --git a/RtfFile/Format/Utils.cpp b/RtfFile/Format/Utils.cpp index 9307d12e5b..fe639aff3e 100644 --- a/RtfFile/Format/Utils.cpp +++ b/RtfFile/Format/Utils.cpp @@ -34,16 +34,18 @@ //------------------------------------------------------------------------------------------------------ -std::wstring Convert::ToString(int i) +std::wstring Convert::ToString(_INT32 i) { return std::to_wstring( i ); } -std::wstring Convert::ToStringHex( int i, int nLen ) +std::wstring Convert::ToStringHex(_INT32 i, size_t nLen ) { std::wstring result = XmlUtils::ToString(i, L"%X"); - for(int i = (int)result.length(); i < nLen; i++ ) - result.insert( result.begin() , '0' ); + for (size_t i = result.length(); i < nLen; i++) + { + result.insert(result.begin(), '0'); + } return result; } int Convert::ToInt32(std::wstring str, int base) diff --git a/RtfFile/Format/Utils.h b/RtfFile/Format/Utils.h index fb702e7e1e..918cb08302 100644 --- a/RtfFile/Format/Utils.h +++ b/RtfFile/Format/Utils.h @@ -82,12 +82,12 @@ namespace Strings return 0; } - static int ToColor(const std::wstring& strValue) + static _UINT32 ToColor(const std::wstring& strValue) { // variables - int blue = 0; - int green = 0; - int red = 0; + _UINT32 blue = 0; + _UINT32 green = 0; + _UINT32 red = 0; std::wstring color = strValue; //color = color.Trim(); @@ -136,7 +136,7 @@ class Convert { public: static std::wstring ToString(int i); - static std::wstring ToStringHex( int i, int nLen ); + static std::wstring ToStringHex(_INT32 i, size_t nLen ); static int ToInt32(std::wstring str, int base = 10); }; diff --git a/RtfFile/OOXml/Reader/OOXMathReader.cpp b/RtfFile/OOXml/Reader/OOXMathReader.cpp index 8abe0c32fe..61e7bd599c 100644 --- a/RtfFile/OOXml/Reader/OOXMathReader.cpp +++ b/RtfFile/OOXml/Reader/OOXMathReader.cpp @@ -602,6 +602,7 @@ bool OOXMathReader::ParseElement(ReaderParameter oParam , OOX::WritingElement * oSubMath.reset(); if (ParseElement(oParam, ooxSubMath->m_oSubHide.GetPointer(), oSubMath)) rtfMath->AddItem(oSubMath); + oSubMath.reset(); if (ParseElement(oParam, ooxSubMath->m_oSupHide.GetPointer(), oSubMath)) rtfMath->AddItem(oSubMath); @@ -932,10 +933,14 @@ bool OOXMathReader::ParseElement(ReaderParameter oParam , OOX::WritingElement * OOX::WritingElementWithChilds* ooxElemArray = dynamic_cast*>(ooxMath); //---------------------------------- - nullable sVal; + nullable_string sVal; - if ((ooxElemBool) && (ooxElemBool->m_val.IsInit())) sVal = ooxElemBool->m_val->ToString2(SimpleTypes::onofftostringOn); - else if ((ooxElemChar) && (ooxElemChar->m_val.IsInit())) sVal = ooxElemChar->m_val->GetValue(); + if ((ooxElemChar) && (ooxElemChar->m_val.IsInit())) + { + rtfMath->m_bIsChar = true; + sVal = ooxElemChar->m_val->GetValue(); + } + else if ((ooxElemBool) && (ooxElemBool->m_val.IsInit())) sVal = ooxElemBool->m_val->ToString2(SimpleTypes::onofftostringOn); else if ((ooxElemMeasure) && (ooxElemMeasure->m_val.IsInit())) sVal = ooxElemMeasure->m_val->ToString(); else if ((ooxElemInt255) && (ooxElemInt255->m_val.IsInit())) sVal = ooxElemInt255->m_val->ToString(); else if ((ooxElemLim) && (ooxElemLim->m_val.IsInit())) sVal = ooxElemLim->m_val->ToString(); @@ -962,13 +967,17 @@ bool OOXMathReader::ParseElement(ReaderParameter oParam , OOX::WritingElement * } else if (sVal.IsInit()) { - rtfMath->m_bIsVal = true; - - RtfCharPtr oChar = RtfCharPtr(new RtfChar); - if (!sVal->empty()) - oChar->setText( L" " + *sVal ); - - rtfMath->m_oVal.AddItem( oChar ); + rtfMath->m_bIsVal = true; + rtfMath->m_sVal = *sVal; + + if (rtfMath->m_bIsChar) + { + RtfCharPtr oChar = RtfCharPtr(new RtfChar); + if (!sVal->empty()) + oChar->setText(*sVal); + + rtfMath->m_oVal.AddItem(oChar); + } } else { diff --git a/RtfFile/OOXml/Writer/OOXWriter.h b/RtfFile/OOXml/Writer/OOXWriter.h index 40fb0489b9..309ef7ec4b 100644 --- a/RtfFile/OOXml/Writer/OOXWriter.h +++ b/RtfFile/OOXml/Writer/OOXWriter.h @@ -45,7 +45,7 @@ public: int m_nCurTrackChangesId; int m_nFormFieldId; - long int m_nextParaId; + _INT64 m_nextParaId; OOXRelsWriter m_oDocRels; OOXRelsWriter m_oRels; diff --git a/Test/Applications/x2tTester/x2tTester.cpp b/Test/Applications/x2tTester/x2tTester.cpp index 7c60a117dc..e85c4a5d5d 100644 --- a/Test/Applications/x2tTester/x2tTester.cpp +++ b/Test/Applications/x2tTester/x2tTester.cpp @@ -198,12 +198,6 @@ std::vector CFormatsList::AllFormats() const return all_formats; } -void WaitFile(const std::wstring& path, const bool& exist_check = true) -{ - while (exist_check != NSFile::CFileBinary::Exists(path)) - NSThreads::Sleep(10); -} - Cx2tTester::Cx2tTester(const std::wstring& configPath) { m_bIsUseSystemFonts = true; @@ -216,7 +210,23 @@ Cx2tTester::Cx2tTester(const std::wstring& configPath) m_inputFormatsList.SetDefault(); m_outputFormatsList.SetOutput(); SetConfig(configPath); - m_errorsXmlDirectory = m_outputDirectory + L"/_errors"; + m_errorsXmlDirectory = m_outputDirectory + FILE_SEPARATOR_STR + L"_errors"; + + // CorrectPathW works strange with directories starts with "./" + if(m_outputDirectory.find(L"./") == 0) + m_outputDirectory.erase(0, 2); + + // no slash at the end + if(m_outputDirectory.size() > 2 && m_outputDirectory[m_outputDirectory.size() - 1] == L'/') + m_outputDirectory.erase(m_outputDirectory.size() - 1, 1); + + // on linux the backslash can be part of the filename +#ifdef WIN32 + + if(m_outputDirectory.size() > 2 && m_outputDirectory[m_outputDirectory.size() - 1] == L'\\') + m_outputDirectory.erase(m_outputDirectory.size() - 1, 1); + +#endif if(m_bIsTimestamp) { @@ -353,7 +363,7 @@ void Cx2tTester::Start() m_timeStart = NSTimers::GetTickCount(); // check fonts - std::wstring fonts_directory = NSFile::GetProcessDirectory() + L"/fonts"; + std::wstring fonts_directory = NSFile::GetProcessDirectory() + FILE_SEPARATOR_STR + L"fonts"; CApplicationFontsWorker fonts_worker; fonts_worker.m_sDirectory = fonts_directory; if (!NSDirectory::Exists(fonts_worker.m_sDirectory)) @@ -365,7 +375,7 @@ void Cx2tTester::Start() { std::wstring sFolder = *i; if (0 == sFolder.find(L".")) - sFolder = NSFile::GetProcessDirectory() + L"/" + sFolder; + sFolder = NSFile::GetProcessDirectory() + FILE_SEPARATOR_STR + sFolder; fonts_worker.m_arAdditionalFolders.push_back(sFolder); } @@ -373,6 +383,9 @@ void Cx2tTester::Start() NSFonts::IApplicationFonts* pFonts = fonts_worker.Check(); RELEASEINTERFACE(pFonts); + m_outputDirectory = CorrectPathW(m_outputDirectory); + m_errorsXmlDirectory = CorrectPathW(m_errorsXmlDirectory); + // setup & clear output folder if(NSDirectory::Exists(m_outputDirectory)) NSDirectory::DeleteDirectory(m_outputDirectory); @@ -417,18 +430,12 @@ void Cx2tTester::Start() int input_format = COfficeFileFormatChecker::GetFormatByExtension(input_ext); std::wstring input_file_directory = NSFile::GetDirectoryName(input_file); - std::wstring output_files_directory = m_outputDirectory; // takes full directory after input folder std::wstring input_subfolders = input_file_directory.substr(m_inputDirectory.size(), input_file_directory.size() - m_inputDirectory.size()); - output_files_directory += input_subfolders; - // setup & clear output subfolder - while(!NSDirectory::Exists(output_files_directory)) - NSDirectory::CreateDirectories(output_files_directory); - - output_files_directory += L'/' + NSFile::GetFileName(input_file); + std::wstring output_files_directory = m_outputDirectory + input_subfolders + FILE_SEPARATOR_STR + input_filename; // setup output_formats for file std::vector output_file_formats; @@ -456,6 +463,13 @@ void Cx2tTester::Start() } } + if(output_file_formats.empty()) + continue; + + // setup & clear output subfolder + while(!NSDirectory::Exists(output_files_directory)) + NSDirectory::CreateDirectories(output_files_directory); + std::wstring csvTxtEncodingS = m_defaultCsvTxtEndcoding; std::wstring csvDelimiter = m_defaultCsvDelimiter; @@ -488,16 +502,11 @@ void Cx2tTester::Start() csvDelimiter = (wchar_t)std::stoi(input_filename.substr(pos1 + find_str.size(), pos2 - pos1 - find_str.size()), nullptr, 16); } - // setup folder for output files - if(NSDirectory::Exists(output_files_directory)) - NSDirectory::DeleteDirectory(output_files_directory); - - NSDirectory::CreateDirectory(output_files_directory); - // waiting... do + { NSThreads::Sleep(50); - while(IsAllBusy()); + }while(IsAllBusy()); m_coresCS.Enter(); @@ -685,6 +694,14 @@ DWORD CConverter::ThreadProc() bool is_all_ok = true; +#ifdef WIN32 + + // x2t cannot work with normalized paths in xml + if(m_outputFilesDirectory.find(L"\\\\?\\") == 0) + m_outputFilesDirectory.erase(0, 4); + +#endif // WIN32 + // input_format in many output exts for(int i = 0; i < m_outputFormats.size(); i++) { @@ -692,13 +709,16 @@ DWORD CConverter::ThreadProc() std::wstring output_ext = checker.GetExtensionByType(output_format); std::wstring xml_params_filename = input_filename + L"_" + output_ext + L".xml"; - std::wstring xml_params_file = m_outputFilesDirectory + L"/" + xml_params_filename; + std::wstring xml_params_file = m_outputFilesDirectory + FILE_SEPARATOR_STR + xml_params_filename; std::wstring output_file = m_outputFilesDirectory - + L"/" + input_filename_no_ext + output_ext; + + FILE_SEPARATOR_STR + input_filename_no_ext + output_ext; std::wstring output_filename = NSFile::GetFileName(output_file); + xml_params_file = CorrectPathW(xml_params_file); + + // creating temporary xml file with params NSStringUtils::CStringBuilder builder; builder.WriteString(L""); @@ -724,7 +744,7 @@ DWORD CConverter::ThreadProc() builder.WriteString(L"true"); builder.WriteString(L""); - builder.WriteEncodeXmlString(m_fontsDirectory + L"/AllFonts.js"); + builder.WriteEncodeXmlString(m_fontsDirectory + FILE_SEPARATOR_STR + L"AllFonts.js"); builder.WriteString(L""); builder.WriteString(L""); @@ -757,16 +777,30 @@ DWORD CConverter::ThreadProc() builder.WriteString(L""); } - builder.WriteString(L"{"spreadsheetLayout":{"gridLines":true,"headings":true,"fitToHeight":1,"fitToWidth":1,"orientation":"landscape"}}"); - builder.WriteString(L""); std::wstring xml_params = builder.GetData(); - NSFile::CFileBinary::SaveToFile(xml_params_file, xml_params, true); - // waiting - WaitFile(xml_params_file); + NSFile::CFileBinary o_xml_file; + bool is_created = o_xml_file.CreateFileW(xml_params_file); + if(!is_created) + { + m_internal->m_outputCS.Enter(); + std::cout << "Error creating XML conversion file!" << std::endl; + m_internal->m_outputCS.Leave(); + continue; + } + o_xml_file.WriteStringUTF8(xml_params, true); + o_xml_file.CloseFile(); + +#ifdef WIN32 + + // x2t cannot work with normalized paths in xml + if(xml_params_file.find(L"\\\\?\\") == 0) + xml_params_file.erase(0, 4); + +#endif // WIN32 int exit_code = NSX2T::Convert(NSFile::GetDirectoryName(m_x2tPath), xml_params_file); @@ -812,7 +846,8 @@ DWORD CConverter::ThreadProc() // save param xml of error conversion if(exit_code || !exist) { - std::wstring err_xml_file = m_errorsXmlDirectory + L"/" + xml_params_filename; + std::wstring err_xml_file = m_errorsXmlDirectory + FILE_SEPARATOR_STR + xml_params_filename; + err_xml_file = CorrectPathW(err_xml_file); NSFile::CFileBinary::SaveToFile(err_xml_file, xml_params, true); } diff --git a/X2tConverter/src/ASCConverters.cpp b/X2tConverter/src/ASCConverters.cpp index 4d02377b20..744e28bc06 100644 --- a/X2tConverter/src/ASCConverters.cpp +++ b/X2tConverter/src/ASCConverters.cpp @@ -455,11 +455,13 @@ namespace NExtractTools BinDocxRW::CDocxSerializer m_oCDocxSerializer; + m_oCDocxSerializer.setOFormEnabled(params.m_nFormatTo && ( *params.m_nFormatTo == AVS_OFFICESTUDIO_FILE_DOCUMENT_OFORM || + *params.m_nFormatTo == AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCXF)); m_oCDocxSerializer.setMacroEnabled(params.m_bMacro); m_oCDocxSerializer.setIsNoBase64(params.getIsNoBase64()); m_oCDocxSerializer.setFontDir(params.getFontPath()); - std::wstring sXmlOptions = _T(""); + std::wstring sXmlOptions; std::wstring sThemePath; // will be filled by 'CreateDocxFolders' method std::wstring sMediaPath; // will be filled by 'CreateDocxFolders' method std::wstring sEmbedPath; // will be filled by 'CreateDocxFolders' method @@ -1614,6 +1616,7 @@ namespace NExtractTools CPdfFile pdfWriter(pApplicationFonts); pdfWriter.CreatePdf(params.getIsPDFA()); pdfWriter.SetTempDirectory(sTemp); + pdfWriter.DocInfo(params.getTitle(), L"", L"", L""); CConvertFromBinParams oBufferParams; oBufferParams.m_sThemesDirectory = sThemeDir; @@ -1771,7 +1774,7 @@ namespace NExtractTools std::wstring sEpubTemp = sTemp + FILE_SEPARATOR_STR + L"tmp"; NSDirectory::CreateDirectory(sEpubTemp); oFile.SetTempDirectory(sEpubTemp); - if (S_FALSE == oFile.FromHtml(sHtmlFile, sResult, sTo, params.m_sTitle ? *params.m_sTitle : L"")) + if (S_FALSE == oFile.FromHtml(sHtmlFile, sTo, params.m_sTitle ? *params.m_sTitle : L"")) nRes = AVS_FILEUTILS_ERROR_CONVERT; } return nRes; @@ -1799,7 +1802,7 @@ namespace NExtractTools { CFb2File fb2File; fb2File.SetTmpDirectory(sTemp); - if (S_FALSE == fb2File.FromHtml(sHtmlFile, sResult, sTo, params.m_sTitle ? *params.m_sTitle : L"")) + if (S_FALSE == fb2File.FromHtml(sHtmlFile, sTo, params.m_sTitle ? *params.m_sTitle : L"")) nRes = AVS_FILEUTILS_ERROR_CONVERT; } return nRes; @@ -1879,6 +1882,7 @@ namespace NExtractTools CPdfFile pdfWriter(pApplicationFonts); pdfWriter.CreatePdf(params.getIsPDFA()); pdfWriter.SetTempDirectory(sTemp); + pdfWriter.DocInfo(params.getTitle(), L"", L"", L""); CConvertFromBinParams oBufferParams; oBufferParams.m_sThemesDirectory = sThemeDir; @@ -1892,9 +1896,6 @@ namespace NExtractTools if (false == password.empty()) pdfWriter.SetPassword(password); -// if (false == sResult.empty()) -// pdfWriter.SetCore(sResult); - int nReg = (bPaid == false) ? 0 : 1; nRes = (S_OK == pdfWriter.OnlineWordToPdfFromBinary(sPdfBinFile, sTo, &oBufferParams)) ? nRes : AVS_FILEUTILS_ERROR_CONVERT; RELEASEOBJECT(pApplicationFonts); @@ -3555,6 +3556,7 @@ namespace NExtractTools CPdfFile pdfWriter(pApplicationFonts); pdfWriter.CreatePdf(params.getIsPDFA()); pdfWriter.SetTempDirectory(sTemp); + pdfWriter.DocInfo(params.getTitle(), L"", L"", L""); CConvertFromBinParams oBufferParams; oBufferParams.m_sThemesDirectory = sThemeDir; @@ -3567,9 +3569,6 @@ namespace NExtractTools if (false == password.empty()) pdfWriter.SetPassword(password); -// if (false == sResult.empty()) -// pdfWriter.SetCore(sResult); - int nReg = (bPaid == false) ? 0 : 1; nRes = (S_OK == pdfWriter.OnlineWordToPdfFromBinary(sFilePathIn, sFilePathOut, &oBufferParams)) ? 0 : AVS_FILEUTILS_ERROR_CONVERT; RELEASEOBJECT(pApplicationFonts); @@ -4886,6 +4885,7 @@ namespace NExtractTools CPdfFile pdfWriter(pApplicationFonts); pdfWriter.CreatePdf(params.getIsPDFA()); pdfWriter.SetTempDirectory(sTemp); + pdfWriter.DocInfo(params.getTitle(), L"", L"", L""); std::wstring documentID = params.getDocumentID(); if (false == documentID.empty()) diff --git a/X2tConverter/src/cextracttools.h b/X2tConverter/src/cextracttools.h index d3afc6933d..9e5cba9e7e 100644 --- a/X2tConverter/src/cextracttools.h +++ b/X2tConverter/src/cextracttools.h @@ -1192,6 +1192,10 @@ namespace NExtractTools RELEASEOBJECT(m_bFromChanges); m_bFromChanges = new bool(bVal); } + std::wstring getTitle() const + { + return (NULL != m_sTitle) ? (*m_sTitle) : L""; + } }; static std::wstring string_replaceAll(std::wstring str, const std::wstring& from, const std::wstring& to) diff --git a/X2tConverter/test/win32Test/X2tConverter_win_test.sln b/X2tConverter/test/win32Test/X2tConverter_win_test.sln index e9530c6b4d..7219aaa8fc 100644 --- a/X2tConverter/test/win32Test/X2tConverter_win_test.sln +++ b/X2tConverter/test/win32Test/X2tConverter_win_test.sln @@ -46,6 +46,9 @@ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Oox2OdfConverter", "..\..\..\OdfFile\Projects\Windows\Oox2OdfConverter.vcxproj", "{BEE01B53-244A-44E6-8947-ED9342D9247E}" EndProject Global + GlobalSection(Performance) = preSolution + HasPerformanceSessions = true + EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64