diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b451356 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +test export-ignore diff --git a/.gitignore b/.gitignore index c49977f..13e1fba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,10 @@ +imageBuild +poppler-data +buildScripts/reSourceVersionEnvs +brewFormula +fontforge +*.tar.* +poppler build compile_commands.json CMakeCache.txt @@ -7,19 +14,19 @@ CTestTestfile.cmake gmon.out install_manifest.txt Makefile -pdf2htmlEX -pdf2htmlEX.1 +pdf2htmlEX/build +pdf2htmlEX/pdf2htmlEX.1 *.pyc -share/base.css -share/base.min.css -share/fancy.css -share/fancy.min.css -share/pdf2htmlEX.js -share/pdf2htmlEX.min.js -src/pdf2htmlEX-config.h -src/util/css_const.h -test export-ignore +pdf2htmlEX/share/base.css +pdf2htmlEX/share/base.min.css +pdf2htmlEX/share/fancy.css +pdf2htmlEX/share/fancy.min.css +pdf2htmlEX/share/pdf2htmlEX.js +pdf2htmlEX/share/pdf2htmlEX.min.js +pdf2htmlEX/src/pdf2htmlEX-config.h +pdf2htmlEX/src/util/css_const.h Testing/* DartConfiguration.tcl -test/test.py +pdf2htmlEX/test/test.py +pdf2htmlEX/test/geckodriver.log *.swp diff --git a/.travis.yml b/.travis.yml index bff2be1..24e0ff6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,88 +1,28 @@ language: cpp -sudo: true +# NOTE: Since we do not have direct access to either MacOS or Windows +# machines on which to develop WE DO NOT support building on MacOS or +# Windows. -os: - - linux -# - osx - -dist: bionic - -env: - global: - - POPPLER_SOURCE="https://gitlab.freedesktop.org/poppler/poppler.git" - matrix: - - PDF2HTMLEX_RELEASE="v0.18.7-poppler-0.81.0" POPPLER_RELEASE="poppler-0.81.0" - - PDF2HTMLEX_RELEASE="v0.18.0-poppler-0.74.0-ubuntu-19.04" POPPLER_RELEASE="poppler-0.74.0" - - PDF2HTMLEX_RELEASE="v0.16.0-poppler-0.62.0-ubuntu-18.04" POPPLER_RELEASE="poppler-0.62.0" +# For Windows, it is known that the more recent Windows 10 versions are +# able to use either the debian archive OR AppImage (as Windows 10 now +# allows FUSE). compiler: gcc -addons: - apt: - update: true - packages: - - build-essential - - autoconf - - git - - pkg-config - - cmake - - make - - gcc - - g++ - # - ca-certificates - # - libfreetype6-dev - # Poppler-specific packages - - libfontforge-dev - - libfontconfig-dev - - libjpeg-dev - - libpng-dev - - libnss3-dev - # pdf2htmlEX-specific packages - - default-jre - - libcairo-dev - - libspiro-dev - - libpango1.0-dev - - poppler-data -# homebrew: -# packages: -# - autoconf -# - pkg-config -# - git -# - cmake -# - freetype -# # Poppler-specific packages -# - fontconfig -# - jpeg -# - nss -# # libuninameslist-specific packages -# - automake -# - libtool -# # fontforge-specific packages -# - python -# - glib -# - xml2 -# - libspiro -# - gettext -# # pdf2htmlEX-specific packages -# - cairo -# - pango -# sauce_connect: true +branches: + except: # do not build tags that we create using the upload.sh script + - /^(?i:continuous.*)$/ -matrix: +jobs: fast_finish: true -# allow_failures: -# - os: osx # Until the build passes, then re-enable. - -before_install: - - ./.travisScripts/copyScriptsToBin - - $HOME/bin/buildPoppler.sh - - $HOME/bin/installPoppler.sh - #- $HOME/setupTests.sh - -script: - - git checkout ${PDF2HTMLEX_RELEASE} - - git branch - - $HOME/bin/dobuild - - $HOME/bin/doinstall --noWait - - /usr/local/bin/pdf2htmlEX -v + include: + - os: linux + dist: bionic + env: DOCKER_FROM="ubuntu:18.04" + services: + - docker + addons: + firefox: latest + script: + - ./buildScripts/travisLinuxDoItAll diff --git a/.travis.yml.orig20190930 b/.travis.yml.orig20190930 deleted file mode 100644 index c48cdd9..0000000 --- a/.travis.yml.orig20190930 +++ /dev/null @@ -1,130 +0,0 @@ -language: cpp - -sudo: true - -os: - - linux - - osx - -env: - global: - - POPPLER_NAME="poppler-0.63.0" - - POPPLER_SOURCE="https://gitlab.freedesktop.org/poppler/poppler.git" - - FONTFORGE_SOURCE="https://github.com/fontforge/fontforge.git" - - LIBUNINAMESLIST_SOURCE="https://github.com/fontforge/libuninameslist.git" - - -compiler: gcc - -addons: - apt: - update: true - packages: - - build-essential - - autoconf - - gcc - - pkg-config - - git - - cmake - - ca-certificates - - libfreetype6-dev - # Poppler-specific packages - - libfontconfig1-dev - - libjpeg-dev - - libnss3-dev - # libuninameslist-specific packages - - automake - - libtool - # fontforge-specific packages - - libltdl-dev - - python-dev - - libglib2.0-dev - - libxml2-dev - - libspiro-dev - - gettext - # pdf2htmlEX-specific packages - - default-jre - - libcairo2-dev - - libpango1.0-dev - homebrew: - packages: - - autoconf - - pkg-config - - git - - cmake - - freetype - # Poppler-specific packages - - fontconfig - - jpeg - - nss - # libuninameslist-specific packages - - automake - - libtool - # fontforge-specific packages - - python - - glib - - xml2 - - libspiro - - gettext - # pdf2htmlEX-specific packages - - cairo - - pango - sauce_connect: true - -matrix: - fast_finish: true - allow_failures: - - os: osx # Until the build passes, then re-enable. - -before_install: -# Clone and build poppler - - git clone ${POPPLER_SOURCE} - - cd poppler; - git checkout tags/${POPPLER_NAME} -b poppler-local; - cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=${TRAVIS_BUILD_DIR}/usr -DENABLE_XPDF_HEADERS=ON -DENABLE_LIBOPENJPEG=none .; - make; - make install - - cd ${TRAVIS_BUILD_DIR} - -# Install libuninameslist - - git clone ${LIBUNINAMESLIST_SOURCE} - - cd libuninameslist; - git checkout tags/20180701 -b libuninameslist-local; - autoreconf -i; - automake; - ./configure --prefix=${TRAVIS_BUILD_DIR}/usr; - make; - make install - - cd ${TRAVIS_BUILD_DIR} - -# Install fontforge - - git clone ${FONTFORGE_SOURCE} - - cd fontforge; - git checkout tags/20170731 -b fontforge-local; - ./bootstrap; - ./configure --disable-programs --disable-python-extension --disable-python-scripting --prefix=${TRAVIS_BUILD_DIR}/usr; - make; - make install; - sudo ldconfig - - cd ${TRAVIS_BUILD_DIR} - -# Test setup - - pip install --user Pillow selenium sauceclient - - export DISPLAY=:99.0 - - test/start_xvfb.sh - - pushd / - - python -m SimpleHTTPServer 8000 >/dev/null 2>&1 & - - popd - - sleep 5 - -before_script: - - export LD_LIBRARY_PATH=${TRAVIS_BUILD_DIR}/usr/lib:$LD_LIBRARY_PATH - - export PKG_CONFIG_PATH=${TRAVIS_BUILD_DIR}/usr/lib/pkgconfig:$PKG_CONFIG_PATH - - patch < CMakeLists.txt.patch - - mkdir build && cd build && cmake -DENABLE_SVG=ON -DCMAKE_INSTALL_PREFIX=${TRAVIS_BUILD_DIR}/usr .. - -script: - - make - - P2H_TEST_REMOTE=1 ctest --output-on-failure --verbose - - make install - - ${TRAVIS_BUILD_DIR}/usr/bin/pdf2htmlEX -v diff --git a/.travisScripts/buildPoppler.sh b/.travisScripts/buildPoppler.sh deleted file mode 100755 index f0a0924..0000000 --- a/.travisScripts/buildPoppler.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# This bash script clones and builds the specified poppler release - -# See: https://github.com/pdf2htmlEX/buildAndPackagingTools/blob/master/building/awsEC2/scripts/dobuildPoppler - -# Clone and build poppler -git clone ${POPPLER_SOURCE} - -cd poppler - -git checkout tags/${POPPLER_RELEASE} - -git branch - -mkdir build - -cd build - -cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr \ - -DENABLE_XPDF_HEADERS=ON -DENABLE_LIBOPENJPEG=none .. - -make - - diff --git a/.travisScripts/copyScriptsToBin b/.travisScripts/copyScriptsToBin deleted file mode 100755 index ec882bd..0000000 --- a/.travisScripts/copyScriptsToBin +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -# This bash script copies the various scripts in the .travisScripts to the -# /home/travis/bin directory to ensure the current scripts are not lost -# when we checkout different versions of pdf2htmlEX - -cp .travisScripts/* $HOME/bin - -cp dobuild $HOME/bin -cp doinstall $HOME/bin - diff --git a/.travisScripts/installPoppler.sh b/.travisScripts/installPoppler.sh deleted file mode 100755 index 4d97481..0000000 --- a/.travisScripts/installPoppler.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -# This bash scripts **installs** poppler - -# See: https://github.com/pdf2htmlEX/buildAndPackagingTools/blob/master/building/awsEC2/scripts/doinstallPoppler - -pushd poppler/build - -sudo make install - -popd - -sudo mkdir -p /usr/include/poppler -sudo cp poppler/poppler/*.h /usr/include/poppler - -sudo mkdir -p /usr/include/poppler/goo -sudo cp poppler/goo/*.h /usr/include/poppler/goo - -sudo mkdir -p /usr/include/poppler/fofi -sudo cp poppler/fofi/*.h /usr/include/poppler/fofi - -sudo mkdir -p /usr/include/poppler/splash -sudo cp poppler/splash/*.h /usr/include/poppler/splash - -sudo cp poppler/build/poppler/poppler-config.h \ - /usr/include/poppler - - diff --git a/.travisScripts/setupTests.sh b/.travisScripts/setupTests.sh deleted file mode 100755 index 8c0eac1..0000000 --- a/.travisScripts/setupTests.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# This bash script sets up the test environment - -# Test setup -pip install --user Pillow selenium sauceclient -export DISPLAY=:99.0 -test/start_xvfb.sh -pushd / -python -m SimpleHTTPServer 8000 >/dev/null 2>&1 & -popd -sleep 5 - diff --git a/3rdparty/poppler/COPYING3 b/3rdparty/poppler/COPYING3 deleted file mode 100644 index 94a9ed0..0000000 --- a/3rdparty/poppler/COPYING3 +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/3rdparty/poppler/git/CairoFontEngine.cc b/3rdparty/poppler/git/CairoFontEngine.cc deleted file mode 100644 index 3a479e4..0000000 --- a/3rdparty/poppler/git/CairoFontEngine.cc +++ /dev/null @@ -1,856 +0,0 @@ -//======================================================================== -// -// CairoFontEngine.cc -// -// Copyright 2003 Glyph & Cog, LLC -// Copyright 2004 Red Hat, Inc -// -//======================================================================== - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2005-2007 Jeff Muizelaar -// Copyright (C) 2005, 2006 Kristian Høgsberg -// Copyright (C) 2005 Martin Kretzschmar -// Copyright (C) 2005, 2009, 2012, 2013, 2015, 2017-2019 Albert Astals Cid -// Copyright (C) 2006, 2007, 2010, 2011 Carlos Garcia Campos -// Copyright (C) 2007 Koji Otani -// Copyright (C) 2008, 2009 Chris Wilson -// Copyright (C) 2008, 2012, 2014, 2016, 2017 Adrian Johnson -// Copyright (C) 2009 Darren Kenny -// Copyright (C) 2010 Suzuki Toshiya -// Copyright (C) 2010 Jan Kümmel -// Copyright (C) 2012 Hib Eris -// Copyright (C) 2013 Thomas Freitag -// Copyright (C) 2015, 2016 Jason Crain -// Copyright (C) 2018 Adam Reichold -// Copyright (C) 2019 Christian Persch -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - -#include - -#include -#include "CairoFontEngine.h" -#include "CairoOutputDev.h" -#include "GlobalParams.h" -#include -#include -#include "goo/gfile.h" -#include "Error.h" -#include "XRef.h" -#include "Gfx.h" -#include "Page.h" - -#if defined(HAVE_FCNTL_H) && defined(HAVE_SYS_MMAN_H) && defined(HAVE_SYS_STAT_H) -#include -#include -#include -#define CAN_CHECK_OPEN_FACES 1 -#endif - -//------------------------------------------------------------------------ -// CairoFont -//------------------------------------------------------------------------ - -CairoFont::CairoFont(Ref refA, - cairo_font_face_t *cairo_font_faceA, - int *codeToGIDA, - unsigned int codeToGIDLenA, - bool substituteA, - bool printingA) : ref(refA), - cairo_font_face(cairo_font_faceA), - codeToGID(codeToGIDA), - codeToGIDLen(codeToGIDLenA), - substitute(substituteA), - printing(printingA) { } - -CairoFont::~CairoFont() { - cairo_font_face_destroy (cairo_font_face); - gfree(codeToGID); -} - -bool -CairoFont::matches(Ref &other, bool printingA) { - return (other == ref); -} - -cairo_font_face_t * -CairoFont::getFontFace(void) { - return cairo_font_face; -} - -unsigned long -CairoFont::getGlyph(CharCode code, - Unicode *u, int uLen) { - FT_UInt gid; - - if (codeToGID && code < codeToGIDLen) { - gid = (FT_UInt)codeToGID[code]; - } else { - gid = (FT_UInt)code; - } - return gid; -} - -double -CairoFont::getSubstitutionCorrection(GfxFont *gfxFont) -{ - double w1, w2, w3; - CharCode code; - const char *name; - - // for substituted fonts: adjust the font matrix -- compare the - // width of 'm' in the original font and the substituted font - if (isSubstitute() && !gfxFont->isCIDFont()) { - for (code = 0; code < 256; ++code) { - if ((name = ((Gfx8BitFont *)gfxFont)->getCharName(code)) && - name[0] == 'm' && name[1] == '\0') { - break; - } - } - if (code < 256) { - w1 = ((Gfx8BitFont *)gfxFont)->getWidth(code); - { - cairo_matrix_t m; - cairo_matrix_init_identity(&m); - cairo_font_options_t *options = cairo_font_options_create(); - cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_NONE); - cairo_font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_OFF); - cairo_scaled_font_t *scaled_font = cairo_scaled_font_create(cairo_font_face, &m, &m, options); - - cairo_text_extents_t extents; - cairo_scaled_font_text_extents(scaled_font, "m", &extents); - - cairo_scaled_font_destroy(scaled_font); - cairo_font_options_destroy(options); - w2 = extents.x_advance; - } - w3 = ((Gfx8BitFont *)gfxFont)->getWidth(0); - if (!gfxFont->isSymbolic() && w2 > 0 && w1 > w3) { - // if real font is substantially narrower than substituted - // font, reduce the font size accordingly - if (w1 > 0.01 && w1 < 0.9 * w2) { - w1 /= w2; - return w1; - } - } - } - } - return 1.0; -} - -//------------------------------------------------------------------------ -// CairoFreeTypeFont -//------------------------------------------------------------------------ - -static cairo_user_data_key_t _ft_cairo_key; - -static void -_ft_done_face_uncached (void *closure) -{ - FT_Face face = (FT_Face) closure; - FT_Done_Face (face); -} - -static bool -_ft_new_face_uncached (FT_Library lib, - const char *filename, - char *font_data, - int font_data_len, - FT_Face *face_out, - cairo_font_face_t **font_face_out) -{ - FT_Face face; - cairo_font_face_t *font_face; - - if (font_data == nullptr) { - if (FT_New_Face (lib, filename, 0, &face)) - return false; - } else { - if (FT_New_Memory_Face (lib, (unsigned char *)font_data, font_data_len, 0, &face)) - return false; - } - - font_face = cairo_ft_font_face_create_for_ft_face (face, - FT_LOAD_NO_HINTING | - FT_LOAD_NO_BITMAP); - if (cairo_font_face_set_user_data (font_face, - &_ft_cairo_key, - face, - _ft_done_face_uncached)) - { - _ft_done_face_uncached (face); - cairo_font_face_destroy (font_face); - return false; - } - - *face_out = face; - *font_face_out = font_face; - return true; -} - -#ifdef CAN_CHECK_OPEN_FACES -static struct _ft_face_data { - struct _ft_face_data *prev, *next, **head; - - int fd; - unsigned long hash; - size_t size; - unsigned char *bytes; - - FT_Library lib; - FT_Face face; - cairo_font_face_t *font_face; -} *_ft_open_faces; - -static unsigned long -_djb_hash (const unsigned char *bytes, size_t len) -{ - unsigned long hash = 5381; - while (len--) { - unsigned char c = *bytes++; - hash *= 33; - hash ^= c; - } - return hash; -} - -static bool -_ft_face_data_equal (struct _ft_face_data *a, struct _ft_face_data *b) -{ - if (a->lib != b->lib) - return false; - if (a->size != b->size) - return false; - if (a->hash != b->hash) - return false; - - return memcmp (a->bytes, b->bytes, a->size) == 0; -} - -static void -_ft_done_face (void *closure) -{ - struct _ft_face_data *data = (struct _ft_face_data *) closure; - - if (data->next) - data->next->prev = data->prev; - if (data->prev) - data->prev->next = data->next; - else - _ft_open_faces = data->next; - - if (data->fd != -1) { -#if defined(__SUNPRO_CC) && defined(__sun) && defined(__SVR4) - munmap ((char*)data->bytes, data->size); -#else - munmap (data->bytes, data->size); -#endif - close (data->fd); - } else { - gfree (data->bytes); - } - - FT_Done_Face (data->face); - gfree (data); -} - -static bool -_ft_new_face (FT_Library lib, - const char *filename, - char *font_data, - int font_data_len, - FT_Face *face_out, - cairo_font_face_t **font_face_out) -{ - struct _ft_face_data *l; - struct stat st; - struct _ft_face_data tmpl; - - tmpl.fd = -1; - - if (font_data == nullptr) { - /* if we fail to mmap the file, just pass it to FreeType instead */ - tmpl.fd = openFileDescriptor (filename, O_RDONLY); - if (tmpl.fd == -1) - return _ft_new_face_uncached (lib, filename, font_data, font_data_len, face_out, font_face_out); - - if (fstat (tmpl.fd, &st) == -1) { - close (tmpl.fd); - return _ft_new_face_uncached (lib, filename, font_data, font_data_len, face_out, font_face_out); - } - - tmpl.bytes = (unsigned char *) mmap (nullptr, st.st_size, - PROT_READ, MAP_PRIVATE, - tmpl.fd, 0); - if (tmpl.bytes == MAP_FAILED) { - close (tmpl.fd); - return _ft_new_face_uncached (lib, filename, font_data, font_data_len, face_out, font_face_out); - } - tmpl.size = st.st_size; - } else { - tmpl.bytes = (unsigned char*) font_data; - tmpl.size = font_data_len; - } - - /* check to see if this is a duplicate of any of the currently open fonts */ - tmpl.lib = lib; - tmpl.hash = _djb_hash (tmpl.bytes, tmpl.size); - - for (l = _ft_open_faces; l; l = l->next) { - if (_ft_face_data_equal (l, &tmpl)) { - if (tmpl.fd != -1) { -#if defined(__SUNPRO_CC) && defined(__sun) && defined(__SVR4) - munmap ((char*)tmpl.bytes, tmpl.size); -#else - munmap (tmpl.bytes, tmpl.size); -#endif - close (tmpl.fd); - } else { - gfree (tmpl.bytes); - } - *face_out = l->face; - *font_face_out = cairo_font_face_reference (l->font_face); - return true; - } - } - - /* not a dup, open and insert into list */ - if (FT_New_Memory_Face (lib, - (FT_Byte *) tmpl.bytes, tmpl.size, - 0, &tmpl.face)) - { - if (tmpl.fd != -1) { -#if defined(__SUNPRO_CC) && defined(__sun) && defined(__SVR4) - munmap ((char*)tmpl.bytes, tmpl.size); -#else - munmap (tmpl.bytes, tmpl.size); -#endif - - close (tmpl.fd); - } - return false; - } - - l = (struct _ft_face_data *) gmallocn (1, sizeof (struct _ft_face_data)); - *l = tmpl; - l->prev = nullptr; - l->next = _ft_open_faces; - if (_ft_open_faces) - _ft_open_faces->prev = l; - _ft_open_faces = l; - - l->font_face = cairo_ft_font_face_create_for_ft_face (tmpl.face, - FT_LOAD_NO_HINTING | - FT_LOAD_NO_BITMAP); - if (cairo_font_face_set_user_data (l->font_face, - &_ft_cairo_key, - l, - _ft_done_face)) - { - cairo_font_face_destroy (l->font_face); - _ft_done_face (l); - return false; - } - - *face_out = l->face; - *font_face_out = l->font_face; - return true; -} -#else -#define _ft_new_face _ft_new_face_uncached -#endif - -CairoFreeTypeFont::CairoFreeTypeFont(Ref refA, - cairo_font_face_t *cairo_font_faceA, - int *codeToGIDA, - unsigned int codeToGIDLenA, - bool substituteA) : CairoFont(refA, - cairo_font_faceA, - codeToGIDA, - codeToGIDLenA, - substituteA, - true) { } - -CairoFreeTypeFont::~CairoFreeTypeFont() { } - -CairoFreeTypeFont *CairoFreeTypeFont::create(GfxFont *gfxFont, XRef *xref, - FT_Library lib, bool useCIDs) { - GooString *fileName; - const char *fileNameC; - char *font_data; - int font_data_len; - int i, n; - GfxFontType fontType; - GfxFontLoc *fontLoc; - char **enc; - const char *name; - FoFiTrueType *ff; - FoFiType1C *ff1c; - Ref ref; - FT_Face face; - cairo_font_face_t *font_face; - - int *codeToGID; - unsigned int codeToGIDLen; - - codeToGID = nullptr; - codeToGIDLen = 0; - font_data = nullptr; - font_data_len = 0; - fileName = nullptr; - fileNameC = nullptr; - - bool substitute = false; - - ref = *gfxFont->getID(); - fontType = gfxFont->getType(); - - if (!(fontLoc = gfxFont->locateFont(xref, nullptr))) { - error(errSyntaxError, -1, "Couldn't find a font for '{0:s}'", - gfxFont->getName() ? gfxFont->getName()->c_str() - : "(unnamed)"); - goto err2; - } - - // embedded font - if (fontLoc->locType == gfxFontLocEmbedded) { - font_data = gfxFont->readEmbFontFile(xref, &font_data_len); - if (nullptr == font_data) - goto err2; - - // external font - } else { // gfxFontLocExternal - fileName = fontLoc->path; - fontType = fontLoc->fontType; - substitute = true; - } - - if (fileName != nullptr) { - fileNameC = fileName->c_str(); - } - - switch (fontType) { - case fontType1: - case fontType1C: - case fontType1COT: - if (! _ft_new_face (lib, fileNameC, font_data, font_data_len, &face, &font_face)) { - error(errSyntaxError, -1, "could not create type1 face"); - goto err2; - } - - enc = ((Gfx8BitFont *)gfxFont)->getEncoding(); - - codeToGID = (int *)gmallocn(256, sizeof(int)); - codeToGIDLen = 256; - for (i = 0; i < 256; ++i) { - codeToGID[i] = 0; - if ((name = enc[i])) { - codeToGID[i] = FT_Get_Name_Index(face, (char*)name); - if (codeToGID[i] == 0) { - Unicode u; - u = globalParams->mapNameToUnicodeText (name); - codeToGID[i] = FT_Get_Char_Index (face, u); - } - if (codeToGID[i] == 0) { - name = GfxFont::getAlternateName(name); - if (name) { - codeToGID[i] = FT_Get_Name_Index(face, (char*)name); - } - } - } - } - break; - case fontCIDType2: - case fontCIDType2OT: - codeToGID = nullptr; - n = 0; - if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { - n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); - if (n) { - codeToGID = (int *)gmallocn(n, sizeof(int)); - memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), - n * sizeof(int)); - } - } else { - if (font_data != nullptr) { - ff = FoFiTrueType::make(font_data, font_data_len); - } else { - ff = FoFiTrueType::load(fileNameC); - } - if (! ff) - goto err2; - codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n); - delete ff; - } - codeToGIDLen = n; - /* Fall through */ - case fontTrueType: - case fontTrueTypeOT: - if (font_data != nullptr) { - ff = FoFiTrueType::make(font_data, font_data_len); - } else { - ff = FoFiTrueType::load(fileNameC); - } - if (! ff) { - error(errSyntaxError, -1, "failed to load truetype font\n"); - goto err2; - } - /* This might be set already for the CIDType2 case */ - if (fontType == fontTrueType || fontType == fontTrueTypeOT) { - codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff); - codeToGIDLen = 256; - } - delete ff; - if (! _ft_new_face (lib, fileNameC, font_data, font_data_len, &face, &font_face)) { - error(errSyntaxError, -1, "could not create truetype face\n"); - goto err2; - } - break; - - case fontCIDType0: - case fontCIDType0C: - - codeToGID = nullptr; - codeToGIDLen = 0; - - if (!useCIDs) - { - if (font_data != nullptr) { - ff1c = FoFiType1C::make(font_data, font_data_len); - } else { - ff1c = FoFiType1C::load(fileNameC); - } - if (ff1c) { - codeToGID = ff1c->getCIDToGIDMap((int *)&codeToGIDLen); - delete ff1c; - } - } - - if (! _ft_new_face (lib, fileNameC, font_data, font_data_len, &face, &font_face)) { - error(errSyntaxError, -1, "could not create cid face\n"); - goto err2; - } - break; - - case fontCIDType0COT: - codeToGID = nullptr; - n = 0; - if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { - n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); - if (n) { - codeToGID = (int *)gmallocn(n, sizeof(int)); - memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), - n * sizeof(int)); - } - } - codeToGIDLen = n; - - if (!codeToGID) { - if (!useCIDs) { - if (font_data != nullptr) { - ff = FoFiTrueType::make(font_data, font_data_len); - } else { - ff = FoFiTrueType::load(fileNameC); - } - if (ff) { - if (ff->isOpenTypeCFF()) { - codeToGID = ff->getCIDToGIDMap((int *)&codeToGIDLen); - } - delete ff; - } - } - } - if (! _ft_new_face (lib, fileNameC, font_data, font_data_len, &face, &font_face)) { - error(errSyntaxError, -1, "could not create cid (OT) face\n"); - goto err2; - } - break; - - default: - fprintf (stderr, "font type %d not handled\n", (int)fontType); - goto err2; - break; - } - - delete fontLoc; - return new CairoFreeTypeFont(ref, - font_face, - codeToGID, codeToGIDLen, - substitute); - - err2: - /* hmm? */ - delete fontLoc; - gfree (codeToGID); - gfree (font_data); - fprintf (stderr, "some font thing failed\n"); - return nullptr; -} - -//------------------------------------------------------------------------ -// CairoType3Font -//------------------------------------------------------------------------ - -static const cairo_user_data_key_t type3_font_key = {0}; - -typedef struct _type3_font_info { - GfxFont *font; - PDFDoc *doc; - CairoFontEngine *fontEngine; - bool printing; - XRef *xref; -} type3_font_info_t; - -static void -_free_type3_font_info(void *closure) -{ - type3_font_info_t *info = (type3_font_info_t *) closure; - - info->font->decRefCnt(); - free (info); -} - -static cairo_status_t -_init_type3_glyph (cairo_scaled_font_t *scaled_font, - cairo_t *cr, - cairo_font_extents_t *extents) -{ - type3_font_info_t *info; - GfxFont *font; - - info = (type3_font_info_t *) - cairo_font_face_get_user_data (cairo_scaled_font_get_font_face (scaled_font), - &type3_font_key); - font = info->font; - const double *mat = font->getFontBBox(); - extents->ascent = mat[3]; /* y2 */ - extents->descent = -mat[3]; /* -y1 */ - extents->height = extents->ascent + extents->descent; - extents->max_x_advance = mat[2] - mat[1]; /* x2 - x1 */ - extents->max_y_advance = 0; - - return CAIRO_STATUS_SUCCESS; -} - -static cairo_status_t -_render_type3_glyph (cairo_scaled_font_t *scaled_font, - unsigned long glyph, - cairo_t *cr, - cairo_text_extents_t *metrics) -{ - Dict *charProcs; - Object charProc; - CairoOutputDev *output_dev; - cairo_matrix_t matrix, invert_y_axis; - const double *mat; - double wx, wy; - PDFRectangle box; - type3_font_info_t *info; - GfxFont *font; - Dict *resDict; - Gfx *gfx; - - info = (type3_font_info_t *) - cairo_font_face_get_user_data (cairo_scaled_font_get_font_face (scaled_font), - &type3_font_key); - - font = info->font; - resDict = ((Gfx8BitFont *)font)->getResources(); - charProcs = ((Gfx8BitFont *)(info->font))->getCharProcs(); - if (!charProcs) - return CAIRO_STATUS_USER_FONT_ERROR; - - if ((int)glyph >= charProcs->getLength()) - return CAIRO_STATUS_USER_FONT_ERROR; - - mat = font->getFontMatrix(); - matrix.xx = mat[0]; - matrix.yx = mat[1]; - matrix.xy = mat[2]; - matrix.yy = mat[3]; - matrix.x0 = mat[4]; - matrix.y0 = mat[5]; - cairo_matrix_init_scale (&invert_y_axis, 1, -1); - cairo_matrix_multiply (&matrix, &matrix, &invert_y_axis); - cairo_transform (cr, &matrix); - - output_dev = new CairoOutputDev(); - output_dev->setCairo(cr); - output_dev->setPrinting(info->printing); - - mat = font->getFontBBox(); - box.x1 = mat[0]; - box.y1 = mat[1]; - box.x2 = mat[2]; - box.y2 = mat[3]; - gfx = new Gfx(info->doc, output_dev, resDict, &box, nullptr); - output_dev->startDoc(info->doc, info->fontEngine); - output_dev->startPage (1, gfx->getState(), gfx->getXRef()); - output_dev->setInType3Char(true); - charProc = charProcs->getVal(glyph); - gfx->display(&charProc); - - output_dev->getType3GlyphWidth (&wx, &wy); - cairo_matrix_transform_distance (&matrix, &wx, &wy); - metrics->x_advance = wx; - metrics->y_advance = wy; - if (output_dev->hasType3GlyphBBox()) { - double *bbox = output_dev->getType3GlyphBBox(); - - cairo_matrix_transform_point (&matrix, &bbox[0], &bbox[1]); - cairo_matrix_transform_point (&matrix, &bbox[2], &bbox[3]); - metrics->x_bearing = bbox[0]; - metrics->y_bearing = bbox[1]; - metrics->width = bbox[2] - bbox[0]; - metrics->height = bbox[3] - bbox[1]; - } - - delete gfx; - delete output_dev; - - return CAIRO_STATUS_SUCCESS; -} - - -CairoType3Font *CairoType3Font::create(GfxFont *gfxFont, PDFDoc *doc, - CairoFontEngine *fontEngine, - bool printing, XRef *xref) { - type3_font_info_t *info; - cairo_font_face_t *font_face; - Ref ref; - int *codeToGID; - unsigned int codeToGIDLen; - int i, j; - char **enc; - Dict *charProcs; - char *name; - - charProcs = ((Gfx8BitFont *)gfxFont)->getCharProcs(); - info = (type3_font_info_t *) malloc(sizeof(*info)); - ref = *gfxFont->getID(); - font_face = cairo_user_font_face_create(); - cairo_user_font_face_set_init_func (font_face, _init_type3_glyph); - cairo_user_font_face_set_render_glyph_func (font_face, _render_type3_glyph); - gfxFont->incRefCnt(); - info->font = gfxFont; - info->doc = doc; - info->fontEngine = fontEngine; - info->printing = printing; - info->xref = xref; - - cairo_font_face_set_user_data (font_face, &type3_font_key, (void *) info, _free_type3_font_info); - - enc = ((Gfx8BitFont *)gfxFont)->getEncoding(); - codeToGID = (int *)gmallocn(256, sizeof(int)); - codeToGIDLen = 256; - for (i = 0; i < 256; ++i) { - codeToGID[i] = 0; - if (charProcs && (name = enc[i])) { - for (j = 0; j < charProcs->getLength(); j++) { - if (strcmp(name, charProcs->getKey(j)) == 0) { - codeToGID[i] = j; - } - } - } - } - - return new CairoType3Font(ref, font_face, codeToGID, codeToGIDLen, printing, xref); -} - -CairoType3Font::CairoType3Font(Ref refA, - cairo_font_face_t *cairo_font_faceA, - int *codeToGIDA, - unsigned int codeToGIDLenA, - bool printingA, XRef *xref) : CairoFont(refA, - cairo_font_faceA, - codeToGIDA, - codeToGIDLenA, - false, - printingA) -{ } - -CairoType3Font::~CairoType3Font() { } - -bool -CairoType3Font::matches(Ref &other, bool printingA) { - return (other == ref && printing == printingA); -} - - -//------------------------------------------------------------------------ -// CairoFontEngine -//------------------------------------------------------------------------ - -#define fontEngineLocker() std::unique_lock locker(mutex) - -CairoFontEngine::CairoFontEngine(FT_Library libA) { - int i; - - lib = libA; - for (i = 0; i < cairoFontCacheSize; ++i) { - fontCache[i] = nullptr; - } - - FT_Int major, minor, patch; - // as of FT 2.1.8, CID fonts are indexed by CID instead of GID - FT_Library_Version(lib, &major, &minor, &patch); - useCIDs = major > 2 || - (major == 2 && (minor > 1 || (minor == 1 && patch > 7))); -} - -CairoFontEngine::~CairoFontEngine() { - int i; - - for (i = 0; i < cairoFontCacheSize; ++i) { - if (fontCache[i]) - delete fontCache[i]; - } -} - -CairoFont * -CairoFontEngine::getFont(GfxFont *gfxFont, PDFDoc *doc, bool printing, XRef *xref) { - int i, j; - Ref ref; - CairoFont *font; - GfxFontType fontType; - - fontEngineLocker(); - ref = *gfxFont->getID(); - - for (i = 0; i < cairoFontCacheSize; ++i) { - font = fontCache[i]; - if (font && font->matches(ref, printing)) { - for (j = i; j > 0; --j) { - fontCache[j] = fontCache[j-1]; - } - fontCache[0] = font; - return font; - } - } - - fontType = gfxFont->getType(); - if (fontType == fontType3) - font = CairoType3Font::create (gfxFont, doc, this, printing, xref); - else - font = CairoFreeTypeFont::create (gfxFont, xref, lib, useCIDs); - - //XXX: if font is null should we still insert it into the cache? - if (fontCache[cairoFontCacheSize - 1]) { - delete fontCache[cairoFontCacheSize - 1]; - } - for (j = cairoFontCacheSize - 1; j > 0; --j) { - fontCache[j] = fontCache[j-1]; - } - fontCache[0] = font; - return font; -} diff --git a/3rdparty/poppler/git/CairoFontEngine.h b/3rdparty/poppler/git/CairoFontEngine.h deleted file mode 100644 index 2a55af1..0000000 --- a/3rdparty/poppler/git/CairoFontEngine.h +++ /dev/null @@ -1,128 +0,0 @@ -//======================================================================== -// -// CairoFontEngine.h -// -// Copyright 2003 Glyph & Cog, LLC -// Copyright 2004 Red Hat, Inc -// -//======================================================================== - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2005, 2006 Kristian Høgsberg -// Copyright (C) 2005, 2018 Albert Astals Cid -// Copyright (C) 2006, 2007 Jeff Muizelaar -// Copyright (C) 2006, 2010 Carlos Garcia Campos -// Copyright (C) 2008, 2017 Adrian Johnson -// Copyright (C) 2013 Thomas Freitag -// Copyright (C) 2018 Adam Reichold -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - -#ifndef CAIROFONTENGINE_H -#define CAIROFONTENGINE_H - -#include - -#include "poppler-config.h" -#include - -#include "GfxFont.h" -#include "PDFDoc.h" - -class CairoFontEngine; - -class CairoFont { -public: - CairoFont(Ref ref, - cairo_font_face_t *face, - int *codeToGID, - unsigned int codeToGIDLen, - bool substitute, - bool printing); - virtual ~CairoFont(); - CairoFont(const CairoFont &) = delete; - CairoFont& operator=(const CairoFont &other) = delete; - - virtual bool matches(Ref &other, bool printing); - cairo_font_face_t *getFontFace(void); - unsigned long getGlyph(CharCode code, Unicode *u, int uLen); - double getSubstitutionCorrection(GfxFont *gfxFont); - - bool isSubstitute() { return substitute; } -protected: - Ref ref; - cairo_font_face_t *cairo_font_face; - - int *codeToGID; - unsigned int codeToGIDLen; - - bool substitute; - bool printing; -}; - -//------------------------------------------------------------------------ - -class CairoFreeTypeFont : public CairoFont { -public: - static CairoFreeTypeFont *create(GfxFont *gfxFont, XRef *xref, FT_Library lib, bool useCIDs); - ~CairoFreeTypeFont(); - -private: - CairoFreeTypeFont(Ref ref, cairo_font_face_t *cairo_font_face, - int *codeToGID, unsigned int codeToGIDLen, bool substitute); -}; - -//------------------------------------------------------------------------ - -class CairoType3Font : public CairoFont { -public: - static CairoType3Font *create(GfxFont *gfxFont, PDFDoc *doc, - CairoFontEngine *fontEngine, - bool printing, XRef *xref); - ~CairoType3Font(); - - bool matches(Ref &other, bool printing) override; - -private: - CairoType3Font(Ref ref, - cairo_font_face_t *cairo_font_face, - int *codeToGID, unsigned int codeToGIDLen, - bool printing, XRef *xref); -}; - -//------------------------------------------------------------------------ - -#define cairoFontCacheSize 64 - -//------------------------------------------------------------------------ -// CairoFontEngine -//------------------------------------------------------------------------ - -class CairoFontEngine { -public: - - // Create a font engine. - CairoFontEngine(FT_Library libA); - ~CairoFontEngine(); - CairoFontEngine(const CairoFontEngine &) = delete; - CairoFontEngine& operator=(const CairoFontEngine &other) = delete; - - CairoFont *getFont(GfxFont *gfxFont, PDFDoc *doc, bool printing, XRef *xref); - -private: - CairoFont *fontCache[cairoFontCacheSize]; - FT_Library lib; - bool useCIDs; - mutable std::recursive_mutex mutex; -}; - -#endif diff --git a/3rdparty/poppler/git/CairoOutputDev.cc b/3rdparty/poppler/git/CairoOutputDev.cc deleted file mode 100644 index 846c81a..0000000 --- a/3rdparty/poppler/git/CairoOutputDev.cc +++ /dev/null @@ -1,3574 +0,0 @@ -//======================================================================== -// -// CairoOutputDev.cc -// -// Copyright 2003 Glyph & Cog, LLC -// Copyright 2004 Red Hat, Inc -// -//======================================================================== - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2005-2008 Jeff Muizelaar -// Copyright (C) 2005, 2006 Kristian Høgsberg -// Copyright (C) 2005, 2009, 2012, 2017-2019 Albert Astals Cid -// Copyright (C) 2005 Nickolay V. Shmyrev -// Copyright (C) 2006-2011, 2013, 2014, 2017, 2018 Carlos Garcia Campos -// Copyright (C) 2008 Carl Worth -// Copyright (C) 2008-2018 Adrian Johnson -// Copyright (C) 2008 Michael Vrable -// Copyright (C) 2008, 2009 Chris Wilson -// Copyright (C) 2008, 2012 Hib Eris -// Copyright (C) 2009, 2010 David Benjamin -// Copyright (C) 2011-2014 Thomas Freitag -// Copyright (C) 2012 Patrick Pfeifer -// Copyright (C) 2012, 2015, 2016 Jason Crain -// Copyright (C) 2015 Suzuki Toshiya -// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, . Work sponsored by the LiMux project of the city of Munich -// Copyright (C) 2018 Adam Reichold -// Copyright (C) 2019 Marek Kasik -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - -#include - -#include -#include -#include -#include -#include - -#include "goo/gfile.h" -#include "GlobalParams.h" -#include "Error.h" -#include "Object.h" -#include "Gfx.h" -#include "GfxState.h" -#include "GfxFont.h" -#include "Page.h" -#include "Link.h" -#include "FontEncodingTables.h" -#include "PDFDocEncoding.h" -#include -#include -#include "CairoOutputDev.h" -#include "CairoFontEngine.h" -#include "CairoRescaleBox.h" -#include "UnicodeMap.h" -#include "JBIG2Stream.h" -//------------------------------------------------------------------------ - -// #define LOG_CAIRO - -// To limit memory usage and improve performance when printing, limit -// cairo images to this size. 8192 is sufficient for an A2 sized -// 300ppi image. -#define MAX_PRINT_IMAGE_SIZE 8192 - -#ifdef LOG_CAIRO -#define LOG(x) (x) -#else -#define LOG(x) -#endif - - -#define MIN(a,b) (((a) < (b)) ? (a) : (b)) -#define MAX(a,b) (((a) > (b)) ? (a) : (b)) - - -//------------------------------------------------------------------------ -// CairoImage -//------------------------------------------------------------------------ - -CairoImage::CairoImage (double x1A, double y1A, double x2A, double y2A) { - image = nullptr; - x1 = x1A; - y1 = y1A; - x2 = x2A; - y2 = y2A; -} - -CairoImage::~CairoImage () { - if (image) - cairo_surface_destroy (image); -} - -void CairoImage::setImage (cairo_surface_t *i) { - if (image) - cairo_surface_destroy (image); - image = cairo_surface_reference (i); -} - -//------------------------------------------------------------------------ -// CairoOutputDev -//------------------------------------------------------------------------ - -// We cannot tie the lifetime of an FT_Library object to that of -// CairoOutputDev, since any FT_Faces created with it may end up with a -// reference by Cairo which can be held long after the CairoOutputDev is -// deleted. The simplest way to avoid problems is to never tear down the -// FT_Library instance; to avoid leaks, just use a single global instance -// initialized the first time it is needed. -FT_Library CairoOutputDev::ft_lib; -bool CairoOutputDev::ft_lib_initialized = false; - -CairoOutputDev::CairoOutputDev() { - doc = nullptr; - - if (!ft_lib_initialized) { - FT_Init_FreeType(&ft_lib); - ft_lib_initialized = true; - } - - fontEngine = nullptr; - fontEngine_owner = false; - glyphs = nullptr; - fill_pattern = nullptr; - fill_color.r = fill_color.g = fill_color.b = 0; - stroke_pattern = nullptr; - stroke_color.r = stroke_color.g = stroke_color.b = 0; - stroke_opacity = 1.0; - fill_opacity = 1.0; - textClipPath = nullptr; - strokePathClip = nullptr; - cairo = nullptr; - currentFont = nullptr; -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) - prescaleImages = false; -#else - prescaleImages = true; -#endif - printing = true; - use_show_text_glyphs = false; - inUncoloredPattern = false; - inType3Char = false; - t3_glyph_has_bbox = false; - text_matrix_valid = true; - antialias = CAIRO_ANTIALIAS_DEFAULT; - - groupColorSpaceStack = nullptr; - maskStack = nullptr; - group = nullptr; - mask = nullptr; - shape = nullptr; - cairo_shape = nullptr; - knockoutCount = 0; - - textPage = nullptr; - actualText = nullptr; - - // the SA parameter supposedly defaults to false, but Acrobat - // apparently hardwires it to true - stroke_adjust = true; - align_stroke_coords = false; - adjusted_stroke_width = false; - xref = nullptr; -} - -CairoOutputDev::~CairoOutputDev() { - if (fontEngine_owner && fontEngine) { - delete fontEngine; - } - - if (cairo) - cairo_destroy (cairo); - cairo_pattern_destroy (stroke_pattern); - cairo_pattern_destroy (fill_pattern); - if (group) - cairo_pattern_destroy (group); - if (mask) - cairo_pattern_destroy (mask); - if (shape) - cairo_pattern_destroy (shape); - if (textPage) - textPage->decRefCnt(); - if (actualText) - delete actualText; -} - -void CairoOutputDev::setCairo(cairo_t *c) -{ - if (cairo != nullptr) { - cairo_status_t status = cairo_status (cairo); - if (status) { - error(errInternal, -1, "cairo context error: {0:s}\n", cairo_status_to_string(status)); - } - cairo_destroy (cairo); - assert(!cairo_shape); - } - if (c != nullptr) { - cairo = cairo_reference (c); - /* save the initial matrix so that we can use it for type3 fonts. */ - //XXX: is this sufficient? could we miss changes to the matrix somehow? - cairo_get_matrix(cairo, &orig_matrix); - setContextAntialias(cairo, antialias); - } else { - cairo = nullptr; - cairo_shape = nullptr; - } -} - -void CairoOutputDev::setTextPage(TextPage *text) -{ - if (textPage) - textPage->decRefCnt(); - if (actualText) - delete actualText; - if (text) { - textPage = text; - textPage->incRefCnt(); - actualText = new ActualText(text); - } else { - textPage = nullptr; - actualText = nullptr; - } -} - -void CairoOutputDev::setAntialias(cairo_antialias_t a) -{ - antialias = a; - if (cairo) - setContextAntialias (cairo, antialias); - if (cairo_shape) - setContextAntialias (cairo_shape, antialias); -} - -void CairoOutputDev::setContextAntialias(cairo_t *cr, cairo_antialias_t antialias) -{ - cairo_font_options_t *font_options; - cairo_set_antialias (cr, antialias); - font_options = cairo_font_options_create (); - cairo_get_font_options (cr, font_options); - cairo_font_options_set_antialias (font_options, antialias); - cairo_set_font_options (cr, font_options); - cairo_font_options_destroy (font_options); -} - -void CairoOutputDev::startDoc(PDFDoc *docA, - CairoFontEngine *parentFontEngine) { - doc = docA; - if (parentFontEngine) { - fontEngine = parentFontEngine; - } else { - if (fontEngine) { - delete fontEngine; - } - fontEngine = new CairoFontEngine(ft_lib); - fontEngine_owner = true; - } - xref = doc->getXRef(); -} - -void CairoOutputDev::startPage(int pageNum, GfxState *state, XRef *xrefA) { - /* set up some per page defaults */ - cairo_pattern_destroy(fill_pattern); - cairo_pattern_destroy(stroke_pattern); - - fill_pattern = cairo_pattern_create_rgb(0., 0., 0.); - fill_color.r = fill_color.g = fill_color.b = 0; - stroke_pattern = cairo_pattern_reference(fill_pattern); - stroke_color.r = stroke_color.g = stroke_color.b = 0; - - if (textPage) - textPage->startPage(state); - if (xrefA != nullptr) { - xref = xrefA; - } -} - -void CairoOutputDev::endPage() { - if (textPage) { - textPage->endPage(); - textPage->coalesce(true, 0, false); - } -} - -void CairoOutputDev::saveState(GfxState *state) { - LOG(printf ("save\n")); - cairo_save (cairo); - if (cairo_shape) - cairo_save (cairo_shape); - - MaskStack *ms = new MaskStack; - ms->mask = cairo_pattern_reference(mask); - ms->mask_matrix = mask_matrix; - ms->next = maskStack; - maskStack = ms; - - if (strokePathClip) - strokePathClip->ref_count++; -} - -void CairoOutputDev::restoreState(GfxState *state) { - LOG(printf ("restore\n")); - cairo_restore (cairo); - if (cairo_shape) - cairo_restore (cairo_shape); - - text_matrix_valid = true; - - /* These aren't restored by cairo_restore() since we keep them in - * the output device. */ - updateFillColor(state); - updateStrokeColor(state); - updateFillOpacity(state); - updateStrokeOpacity(state); - updateBlendMode(state); - - MaskStack* ms = maskStack; - if (ms) { - if (mask) - cairo_pattern_destroy(mask); - mask = ms->mask; - mask_matrix = ms->mask_matrix; - maskStack = ms->next; - delete ms; - } - - if (strokePathClip && --strokePathClip->ref_count == 0) { - delete strokePathClip->path; - if (strokePathClip->dashes) - gfree (strokePathClip->dashes); - gfree (strokePathClip); - strokePathClip = nullptr; - } -} - -void CairoOutputDev::updateAll(GfxState *state) { - updateLineDash(state); - updateLineJoin(state); - updateLineCap(state); - updateLineWidth(state); - updateFlatness(state); - updateMiterLimit(state); - updateFillColor(state); - updateStrokeColor(state); - updateFillOpacity(state); - updateStrokeOpacity(state); - updateBlendMode(state); - needFontUpdate = true; - if (textPage) - textPage->updateFont(state); -} - -void CairoOutputDev::setDefaultCTM(const double *ctm) { - cairo_matrix_t matrix; - matrix.xx = ctm[0]; - matrix.yx = ctm[1]; - matrix.xy = ctm[2]; - matrix.yy = ctm[3]; - matrix.x0 = ctm[4]; - matrix.y0 = ctm[5]; - - cairo_transform (cairo, &matrix); - if (cairo_shape) - cairo_transform (cairo_shape, &matrix); - - OutputDev::setDefaultCTM(ctm); -} - -void CairoOutputDev::updateCTM(GfxState *state, double m11, double m12, - double m21, double m22, - double m31, double m32) { - cairo_matrix_t matrix, invert_matrix; - matrix.xx = m11; - matrix.yx = m12; - matrix.xy = m21; - matrix.yy = m22; - matrix.x0 = m31; - matrix.y0 = m32; - - /* Make sure the matrix is invertible before setting it. - * cairo will blow up if we give it a matrix that's not - * invertible, so we need to check before passing it - * to cairo_transform. Ignoring it is likely to give better - * results than not rendering anything at all. See #14398 - * - * Ideally, we could do the cairo_transform - * and then check if anything went wrong and fix it then - * instead of having to invert the matrix. */ - invert_matrix = matrix; - if (cairo_matrix_invert(&invert_matrix)) { - error(errSyntaxWarning, -1, "matrix not invertible\n"); - return; - } - - cairo_transform (cairo, &matrix); - if (cairo_shape) - cairo_transform (cairo_shape, &matrix); - updateLineDash(state); - updateLineJoin(state); - updateLineCap(state); - updateLineWidth(state); -} - -void CairoOutputDev::updateLineDash(GfxState *state) { - double *dashPattern; - int dashLength; - double dashStart; - - state->getLineDash(&dashPattern, &dashLength, &dashStart); - cairo_set_dash (cairo, dashPattern, dashLength, dashStart); - if (cairo_shape) - cairo_set_dash (cairo_shape, dashPattern, dashLength, dashStart); -} - -void CairoOutputDev::updateFlatness(GfxState *state) { - // cairo_set_tolerance (cairo, state->getFlatness()); -} - -void CairoOutputDev::updateLineJoin(GfxState *state) { - switch (state->getLineJoin()) { - case 0: - cairo_set_line_join (cairo, CAIRO_LINE_JOIN_MITER); - break; - case 1: - cairo_set_line_join (cairo, CAIRO_LINE_JOIN_ROUND); - break; - case 2: - cairo_set_line_join (cairo, CAIRO_LINE_JOIN_BEVEL); - break; - } - if (cairo_shape) - cairo_set_line_join (cairo_shape, cairo_get_line_join(cairo)); -} - -void CairoOutputDev::updateLineCap(GfxState *state) { - switch (state->getLineCap()) { - case 0: - cairo_set_line_cap (cairo, CAIRO_LINE_CAP_BUTT); - break; - case 1: - cairo_set_line_cap (cairo, CAIRO_LINE_CAP_ROUND); - break; - case 2: - cairo_set_line_cap (cairo, CAIRO_LINE_CAP_SQUARE); - break; - } - if (cairo_shape) - cairo_set_line_cap (cairo_shape, cairo_get_line_cap(cairo)); -} - -void CairoOutputDev::updateMiterLimit(GfxState *state) { - cairo_set_miter_limit (cairo, state->getMiterLimit()); - if (cairo_shape) - cairo_set_miter_limit (cairo_shape, state->getMiterLimit()); -} - -void CairoOutputDev::updateLineWidth(GfxState *state) { - LOG(printf ("line width: %f\n", state->getLineWidth())); - adjusted_stroke_width = false; - double width = state->getLineWidth(); - if (stroke_adjust && !printing) { - double x, y; - x = y = width; - - /* find out line width in device units */ - cairo_user_to_device_distance(cairo, &x, &y); - if (fabs(x) <= 1.0 && fabs(y) <= 1.0) { - /* adjust width to at least one device pixel */ - x = y = 1.0; - cairo_device_to_user_distance(cairo, &x, &y); - width = MIN(fabs(x),fabs(y)); - adjusted_stroke_width = true; - } - } else if (width == 0.0) { - /* Cairo does not support 0 line width == 1 device pixel. Find out - * how big pixels (device unit) are in the x and y - * directions. Choose the smaller of the two as our line width. - */ - double x = 1.0, y = 1.0; - if (printing) { - // assume printer pixel size is 1/600 inch - x = 72.0/600; - y = 72.0/600; - } - cairo_device_to_user_distance(cairo, &x, &y); - width = MIN(fabs(x),fabs(y)); - } - cairo_set_line_width (cairo, width); - if (cairo_shape) - cairo_set_line_width (cairo_shape, cairo_get_line_width (cairo)); -} - -void CairoOutputDev::updateFillColor(GfxState *state) { - GfxRGB color = fill_color; - - if (inUncoloredPattern) - return; - - state->getFillRGB(&fill_color); - if (cairo_pattern_get_type (fill_pattern) != CAIRO_PATTERN_TYPE_SOLID || - color.r != fill_color.r || - color.g != fill_color.g || - color.b != fill_color.b) - { - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_rgba(colToDbl(fill_color.r), - colToDbl(fill_color.g), - colToDbl(fill_color.b), - fill_opacity); - - LOG(printf ("fill color: %d %d %d\n", - fill_color.r, fill_color.g, fill_color.b)); - } -} - -void CairoOutputDev::updateStrokeColor(GfxState *state) { - GfxRGB color = stroke_color; - - if (inUncoloredPattern) - return; - - state->getStrokeRGB(&stroke_color); - if (cairo_pattern_get_type (fill_pattern) != CAIRO_PATTERN_TYPE_SOLID || - color.r != stroke_color.r || - color.g != stroke_color.g || - color.b != stroke_color.b) - { - cairo_pattern_destroy(stroke_pattern); - stroke_pattern = cairo_pattern_create_rgba(colToDbl(stroke_color.r), - colToDbl(stroke_color.g), - colToDbl(stroke_color.b), - stroke_opacity); - - LOG(printf ("stroke color: %d %d %d\n", - stroke_color.r, stroke_color.g, stroke_color.b)); - } -} - -void CairoOutputDev::updateFillOpacity(GfxState *state) { - double opacity = fill_opacity; - - if (inUncoloredPattern) - return; - - fill_opacity = state->getFillOpacity(); - if (opacity != fill_opacity) { - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_rgba(colToDbl(fill_color.r), - colToDbl(fill_color.g), - colToDbl(fill_color.b), - fill_opacity); - - LOG(printf ("fill opacity: %f\n", fill_opacity)); - } -} - -void CairoOutputDev::updateStrokeOpacity(GfxState *state) { - double opacity = stroke_opacity; - - if (inUncoloredPattern) - return; - - stroke_opacity = state->getStrokeOpacity(); - if (opacity != stroke_opacity) { - cairo_pattern_destroy(stroke_pattern); - stroke_pattern = cairo_pattern_create_rgba(colToDbl(stroke_color.r), - colToDbl(stroke_color.g), - colToDbl(stroke_color.b), - stroke_opacity); - - LOG(printf ("stroke opacity: %f\n", stroke_opacity)); - } -} - -void CairoOutputDev::updateFillColorStop(GfxState *state, double offset) { - if (inUncoloredPattern) - return; - - state->getFillRGB(&fill_color); - - cairo_pattern_add_color_stop_rgba(fill_pattern, offset, - colToDbl(fill_color.r), - colToDbl(fill_color.g), - colToDbl(fill_color.b), - fill_opacity); - LOG(printf ("fill color stop: %f (%d, %d, %d)\n", - offset, fill_color.r, fill_color.g, fill_color.b)); -} - -void CairoOutputDev::updateBlendMode(GfxState *state) { - switch (state->getBlendMode()) { - default: - case gfxBlendNormal: - cairo_set_operator (cairo, CAIRO_OPERATOR_OVER); - break; - case gfxBlendMultiply: - cairo_set_operator (cairo, CAIRO_OPERATOR_MULTIPLY); - break; - case gfxBlendScreen: - cairo_set_operator (cairo, CAIRO_OPERATOR_SCREEN); - break; - case gfxBlendOverlay: - cairo_set_operator (cairo, CAIRO_OPERATOR_OVERLAY); - break; - case gfxBlendDarken: - cairo_set_operator (cairo, CAIRO_OPERATOR_DARKEN); - break; - case gfxBlendLighten: - cairo_set_operator (cairo, CAIRO_OPERATOR_LIGHTEN); - break; - case gfxBlendColorDodge: - cairo_set_operator (cairo, CAIRO_OPERATOR_COLOR_DODGE); - break; - case gfxBlendColorBurn: - cairo_set_operator (cairo, CAIRO_OPERATOR_COLOR_BURN); - break; - case gfxBlendHardLight: - cairo_set_operator (cairo, CAIRO_OPERATOR_HARD_LIGHT); - break; - case gfxBlendSoftLight: - cairo_set_operator (cairo, CAIRO_OPERATOR_SOFT_LIGHT); - break; - case gfxBlendDifference: - cairo_set_operator (cairo, CAIRO_OPERATOR_DIFFERENCE); - break; - case gfxBlendExclusion: - cairo_set_operator (cairo, CAIRO_OPERATOR_EXCLUSION); - break; - case gfxBlendHue: - cairo_set_operator (cairo, CAIRO_OPERATOR_HSL_HUE); - break; - case gfxBlendSaturation: - cairo_set_operator (cairo, CAIRO_OPERATOR_HSL_SATURATION); - break; - case gfxBlendColor: - cairo_set_operator (cairo, CAIRO_OPERATOR_HSL_COLOR); - break; - case gfxBlendLuminosity: - cairo_set_operator (cairo, CAIRO_OPERATOR_HSL_LUMINOSITY); - break; - } - LOG(printf ("blend mode: %d\n", (int)state->getBlendMode())); -} - -void CairoOutputDev::updateFont(GfxState *state) { - cairo_font_face_t *font_face; - cairo_matrix_t matrix, invert_matrix; - - LOG(printf ("updateFont() font=%s\n", state->getFont()->getName()->c_str())); - - needFontUpdate = false; - - //FIXME: use cairo font engine? - if (textPage) - textPage->updateFont(state); - - currentFont = fontEngine->getFont (state->getFont(), doc, printing, xref); - - if (!currentFont) - return; - - font_face = currentFont->getFontFace(); - cairo_set_font_face (cairo, font_face); - - use_show_text_glyphs = state->getFont()->hasToUnicodeCMap() && - cairo_surface_has_show_text_glyphs (cairo_get_target (cairo)); - - double fontSize = state->getFontSize(); - const double *m = state->getTextMat(); - /* NOTE: adjusting by a constant is hack. The correct solution - * is probably to use user-fonts and compute the scale on a per - * glyph basis instead of for the entire font */ - double w = currentFont->getSubstitutionCorrection(state->getFont()); - matrix.xx = m[0] * fontSize * state->getHorizScaling() * w; - matrix.yx = m[1] * fontSize * state->getHorizScaling() * w; - matrix.xy = -m[2] * fontSize; - matrix.yy = -m[3] * fontSize; - matrix.x0 = 0; - matrix.y0 = 0; - - LOG(printf ("font matrix: %f %f %f %f\n", matrix.xx, matrix.yx, matrix.xy, matrix.yy)); - - /* Make sure the font matrix is invertible before setting it. cairo - * will blow up if we give it a matrix that's not invertible, so we - * need to check before passing it to cairo_set_font_matrix. Ignoring it - * is likely to give better results than not rendering anything at - * all. See #18254. - */ - invert_matrix = matrix; - if (cairo_matrix_invert(&invert_matrix)) { - error(errSyntaxWarning, -1, "font matrix not invertible"); - text_matrix_valid = false; - return; - } - - cairo_set_font_matrix (cairo, &matrix); - text_matrix_valid = true; -} - -/* Tolerance in pixels for checking if strokes are horizontal or vertical - * lines in device space */ -#define STROKE_COORD_TOLERANCE 0.5 - -/* Align stroke coordinate i if the point is the start or end of a - * horizontal or vertical line */ -void CairoOutputDev::alignStrokeCoords(GfxSubpath *subpath, int i, double *x, double *y) -{ - double x1, y1, x2, y2; - bool align = false; - - x1 = subpath->getX(i); - y1 = subpath->getY(i); - cairo_user_to_device (cairo, &x1, &y1); - - // Does the current coord and prev coord form a horiz or vert line? - if (i > 0 && !subpath->getCurve(i - 1)) { - x2 = subpath->getX(i - 1); - y2 = subpath->getY(i - 1); - cairo_user_to_device (cairo, &x2, &y2); - if (fabs(x2 - x1) < STROKE_COORD_TOLERANCE || fabs(y2 - y1) < STROKE_COORD_TOLERANCE) - align = true; - } - - // Does the current coord and next coord form a horiz or vert line? - if (i < subpath->getNumPoints() - 1 && !subpath->getCurve(i + 1)) { - x2 = subpath->getX(i + 1); - y2 = subpath->getY(i + 1); - cairo_user_to_device (cairo, &x2, &y2); - if (fabs(x2 - x1) < STROKE_COORD_TOLERANCE || fabs(y2 - y1) < STROKE_COORD_TOLERANCE) - align = true; - } - - *x = subpath->getX(i); - *y = subpath->getY(i); - if (align) { - /* see http://www.cairographics.org/FAQ/#sharp_lines */ - cairo_user_to_device (cairo, x, y); - *x = floor(*x) + 0.5; - *y = floor(*y) + 0.5; - cairo_device_to_user (cairo, x, y); - } -} - -#undef STROKE_COORD_TOLERANCE - -void CairoOutputDev::doPath(cairo_t *c, GfxState *state, GfxPath *path) { - GfxSubpath *subpath; - int i, j; - double x, y; - cairo_new_path (c); - for (i = 0; i < path->getNumSubpaths(); ++i) { - subpath = path->getSubpath(i); - if (subpath->getNumPoints() > 0) { - if (align_stroke_coords) { - alignStrokeCoords(subpath, 0, &x, &y); - } else { - x = subpath->getX(0); - y = subpath->getY(0); - } - cairo_move_to (c, x, y); - j = 1; - while (j < subpath->getNumPoints()) { - if (subpath->getCurve(j)) { - if (align_stroke_coords) { - alignStrokeCoords(subpath, j + 2, &x, &y); - } else { - x = subpath->getX(j+2); - y = subpath->getY(j+2); - } - cairo_curve_to( c, - subpath->getX(j), subpath->getY(j), - subpath->getX(j+1), subpath->getY(j+1), - x, y); - - j += 3; - } else { - if (align_stroke_coords) { - alignStrokeCoords(subpath, j, &x, &y); - } else { - x = subpath->getX(j); - y = subpath->getY(j); - } - cairo_line_to (c, x, y); - ++j; - } - } - if (subpath->isClosed()) { - LOG (printf ("close\n")); - cairo_close_path (c); - } - } - } -} - -void CairoOutputDev::stroke(GfxState *state) { - if (inType3Char) { - GfxGray gray; - state->getFillGray(&gray); - if (colToDbl(gray) > 0.5) - return; - } - - if (adjusted_stroke_width) - align_stroke_coords = true; - doPath (cairo, state, state->getPath()); - align_stroke_coords = false; - cairo_set_source (cairo, stroke_pattern); - LOG(printf ("stroke\n")); - if (strokePathClip) { - cairo_push_group (cairo); - cairo_stroke (cairo); - cairo_pop_group_to_source (cairo); - fillToStrokePathClip (state); - } else { - cairo_stroke (cairo); - } - if (cairo_shape) { - doPath (cairo_shape, state, state->getPath()); - cairo_stroke (cairo_shape); - } -} - -void CairoOutputDev::fill(GfxState *state) { - if (inType3Char) { - GfxGray gray; - state->getFillGray(&gray); - if (colToDbl(gray) > 0.5) - return; - } - - doPath (cairo, state, state->getPath()); - cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_WINDING); - cairo_set_source (cairo, fill_pattern); - LOG(printf ("fill\n")); - //XXX: how do we get the path - if (mask) { - cairo_save (cairo); - cairo_clip (cairo); - if (strokePathClip) { - cairo_push_group (cairo); - fillToStrokePathClip (state); - cairo_pop_group_to_source (cairo); - } - cairo_set_matrix (cairo, &mask_matrix); - cairo_mask (cairo, mask); - cairo_restore (cairo); - } else if (strokePathClip) { - fillToStrokePathClip(state); - } else { - cairo_fill (cairo); - } - if (cairo_shape) { - cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_WINDING); - doPath (cairo_shape, state, state->getPath()); - cairo_fill (cairo_shape); - } -} - -void CairoOutputDev::eoFill(GfxState *state) { - doPath (cairo, state, state->getPath()); - cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_EVEN_ODD); - cairo_set_source (cairo, fill_pattern); - LOG(printf ("fill-eo\n")); - - if (mask) { - cairo_save (cairo); - cairo_clip (cairo); - cairo_set_matrix (cairo, &mask_matrix); - cairo_mask (cairo, mask); - cairo_restore (cairo); - } else { - cairo_fill (cairo); - } - if (cairo_shape) { - cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_EVEN_ODD); - doPath (cairo_shape, state, state->getPath()); - cairo_fill (cairo_shape); - } - -} - -bool CairoOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *cat, Object *str, - const double *pmat, int paintType, int /*tilingType*/, Dict *resDict, - const double *mat, const double *bbox, - int x0, int y0, int x1, int y1, - double xStep, double yStep) -{ - PDFRectangle box; - Gfx *gfx; - cairo_pattern_t *pattern; - cairo_surface_t *surface; - cairo_matrix_t matrix; - cairo_matrix_t pattern_matrix; - cairo_t *old_cairo; - double xMin, yMin, xMax, yMax; - double width, height; - double scaleX, scaleY; - int surface_width, surface_height; - StrokePathClip *strokePathTmp; - bool adjusted_stroke_width_tmp; - cairo_pattern_t *maskTmp; - - width = bbox[2] - bbox[0]; - height = bbox[3] - bbox[1]; - - if (xStep != width || yStep != height) - return false; - /* TODO: implement the other cases here too */ - - // Find the width and height of the transformed pattern - cairo_get_matrix (cairo, &matrix); - cairo_matrix_init (&pattern_matrix, mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]); - cairo_matrix_multiply (&matrix, &matrix, &pattern_matrix); - - double widthX = width, widthY = 0; - cairo_matrix_transform_distance (&matrix, &widthX, &widthY); - surface_width = ceil (sqrt (widthX * widthX + widthY * widthY)); - - double heightX = 0, heightY = height; - cairo_matrix_transform_distance (&matrix, &heightX, &heightY); - surface_height = ceil (sqrt (heightX * heightX + heightY * heightY)); - scaleX = surface_width / width; - scaleY = surface_height / height; - - surface = cairo_surface_create_similar (cairo_get_target (cairo), - CAIRO_CONTENT_COLOR_ALPHA, - surface_width, surface_height); - if (cairo_surface_status (surface)) - return false; - - old_cairo = cairo; - cairo = cairo_create (surface); - cairo_surface_destroy (surface); - setContextAntialias(cairo, antialias); - - box.x1 = bbox[0]; box.y1 = bbox[1]; - box.x2 = bbox[2]; box.y2 = bbox[3]; - cairo_scale (cairo, scaleX, scaleY); - cairo_translate (cairo, -box.x1, -box.y1); - - strokePathTmp = strokePathClip; - strokePathClip = nullptr; - adjusted_stroke_width_tmp = adjusted_stroke_width; - maskTmp = mask; - mask = nullptr; - gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA); - if (paintType == 2) - inUncoloredPattern = true; - gfx->display(str); - if (paintType == 2) - inUncoloredPattern = false; - delete gfx; - strokePathClip = strokePathTmp; - adjusted_stroke_width = adjusted_stroke_width_tmp; - mask = maskTmp; - - pattern = cairo_pattern_create_for_surface (cairo_get_target (cairo)); - cairo_destroy (cairo); - cairo = old_cairo; - if (cairo_pattern_status (pattern)) - return false; - - state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax); - cairo_rectangle (cairo, xMin, yMin, xMax - xMin, yMax - yMin); - - cairo_matrix_init_scale (&matrix, scaleX, scaleY); - cairo_matrix_translate (&matrix, -box.x1, -box.y1); - cairo_pattern_set_matrix (pattern, &matrix); - - cairo_transform (cairo, &pattern_matrix); - cairo_set_source (cairo, pattern); - cairo_pattern_set_extend (pattern, CAIRO_EXTEND_REPEAT); - if (strokePathClip) { - fillToStrokePathClip(state); - } else { - cairo_fill (cairo); - } - - cairo_pattern_destroy (pattern); - - return true; -} - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) -bool CairoOutputDev::functionShadedFill(GfxState *state, GfxFunctionShading *shading) -{ - // Function shaded fills are subdivided to rectangles that are the - // following size in device space. Note when printing this size is - // in points. - const int subdivide_pixels = 10; - - double x_begin, x_end, x1, x2; - double y_begin, y_end, y1, y2; - double x_step; - double y_step; - GfxColor color; - GfxRGB rgb; - cairo_matrix_t mat; - - const double *matrix = shading->getMatrix(); - mat.xx = matrix[0]; - mat.yx = matrix[1]; - mat.xy = matrix[2]; - mat.yy = matrix[3]; - mat.x0 = matrix[4]; - mat.y0 = matrix[5]; - if (cairo_matrix_invert(&mat)) { - error(errSyntaxWarning, -1, "matrix not invertible\n"); - return false; - } - - // get cell size in pattern space - x_step = y_step = subdivide_pixels; - cairo_matrix_transform_distance (&mat, &x_step, &y_step); - - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_mesh (); - cairo_pattern_set_matrix(fill_pattern, &mat); - shading->getDomain(&x_begin, &y_begin, &x_end, &y_end); - - for (x1 = x_begin; x1 < x_end; x1 += x_step) { - x2 = x1 + x_step; - if (x2 > x_end) - x2 = x_end; - - for (y1 = y_begin; y1 < y_end; y1 += y_step) { - y2 = y1 + y_step; - if (y2 > y_end) - y2 = y_end; - - cairo_mesh_pattern_begin_patch (fill_pattern); - cairo_mesh_pattern_move_to (fill_pattern, x1, y1); - cairo_mesh_pattern_line_to (fill_pattern, x2, y1); - cairo_mesh_pattern_line_to (fill_pattern, x2, y2); - cairo_mesh_pattern_line_to (fill_pattern, x1, y2); - - shading->getColor(x1, y1, &color); - shading->getColorSpace()->getRGB(&color, &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, 0, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - - shading->getColor(x2, y1, &color); - shading->getColorSpace()->getRGB(&color, &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, 1, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - - shading->getColor(x2, y2, &color); - shading->getColorSpace()->getRGB(&color, &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, 2, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - - shading->getColor(x1, y2, &color); - shading->getColorSpace()->getRGB(&color, &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, 3, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - - cairo_mesh_pattern_end_patch (fill_pattern); - } - } - - double xMin, yMin, xMax, yMax; - // get the clip region bbox - state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax); - state->moveTo(xMin, yMin); - state->lineTo(xMin, yMax); - state->lineTo(xMax, yMax); - state->lineTo(xMax, yMin); - state->closePath(); - fill(state); - state->clearPath(); - - return true; -} -#endif /* CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) */ - -bool CairoOutputDev::axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax) { - double x0, y0, x1, y1; - double dx, dy; - - shading->getCoords(&x0, &y0, &x1, &y1); - dx = x1 - x0; - dy = y1 - y0; - - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_linear (x0 + tMin * dx, y0 + tMin * dy, - x0 + tMax * dx, y0 + tMax * dy); - if (!shading->getExtend0() && !shading->getExtend1()) - cairo_pattern_set_extend (fill_pattern, CAIRO_EXTEND_NONE); - else - cairo_pattern_set_extend (fill_pattern, CAIRO_EXTEND_PAD); - - LOG (printf ("axial-sh\n")); - - // TODO: use the actual stops in the shading in the case - // of linear interpolation (Type 2 Exponential functions with N=1) - return false; -} - -bool CairoOutputDev::axialShadedSupportExtend(GfxState *state, GfxAxialShading *shading) -{ - return (shading->getExtend0() == shading->getExtend1()); -} - -bool CairoOutputDev::radialShadedFill(GfxState *state, GfxRadialShading *shading, double sMin, double sMax) { - double x0, y0, r0, x1, y1, r1; - double dx, dy, dr; - cairo_matrix_t matrix; - double scale; - - shading->getCoords(&x0, &y0, &r0, &x1, &y1, &r1); - dx = x1 - x0; - dy = y1 - y0; - dr = r1 - r0; - - // Cairo/pixman do not work well with a very large or small scaled - // matrix. See cairo bug #81657. - // - // As a workaround, scale the pattern by the average of the vertical - // and horizontal scaling of the current transformation matrix. - cairo_get_matrix(cairo, &matrix); - scale = (sqrt(matrix.xx * matrix.xx + matrix.yx * matrix.yx) - + sqrt(matrix.xy * matrix.xy + matrix.yy * matrix.yy)) / 2; - cairo_matrix_init_scale(&matrix, scale, scale); - - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_radial ((x0 + sMin * dx) * scale, - (y0 + sMin * dy) * scale, - (r0 + sMin * dr) * scale, - (x0 + sMax * dx) * scale, - (y0 + sMax * dy) * scale, - (r0 + sMax * dr) * scale); - cairo_pattern_set_matrix(fill_pattern, &matrix); - if (shading->getExtend0() && shading->getExtend1()) - cairo_pattern_set_extend (fill_pattern, CAIRO_EXTEND_PAD); - else - cairo_pattern_set_extend (fill_pattern, CAIRO_EXTEND_NONE); - - LOG (printf ("radial-sh\n")); - - return false; -} - -bool CairoOutputDev::radialShadedSupportExtend(GfxState *state, GfxRadialShading *shading) -{ - return (shading->getExtend0() == shading->getExtend1()); -} - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) -bool CairoOutputDev::gouraudTriangleShadedFill(GfxState *state, GfxGouraudTriangleShading *shading) -{ - double x0, y0, x1, y1, x2, y2; - GfxColor color[3]; - int i, j; - GfxRGB rgb; - - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_mesh (); - - for (i = 0; i < shading->getNTriangles(); i++) { - if (shading->isParameterized()) { - double color0, color1, color2; - shading->getTriangle(i, &x0, &y0, &color0, - &x1, &y1, &color1, - &x2, &y2, &color2); - shading->getParameterizedColor(color0, &color[0]); - shading->getParameterizedColor(color1, &color[1]); - shading->getParameterizedColor(color2, &color[2]); - } else { - shading->getTriangle(i, - &x0, &y0, &color[0], - &x1, &y1, &color[1], - &x2, &y2, &color[2]); - - } - - cairo_mesh_pattern_begin_patch (fill_pattern); - - cairo_mesh_pattern_move_to (fill_pattern, x0, y0); - cairo_mesh_pattern_line_to (fill_pattern, x1, y1); - cairo_mesh_pattern_line_to (fill_pattern, x2, y2); - - for (j = 0; j < 3; j++) { - shading->getColorSpace()->getRGB(&color[j], &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, j, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - } - - cairo_mesh_pattern_end_patch (fill_pattern); - } - - double xMin, yMin, xMax, yMax; - // get the clip region bbox - state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax); - state->moveTo(xMin, yMin); - state->lineTo(xMin, yMax); - state->lineTo(xMax, yMax); - state->lineTo(xMax, yMin); - state->closePath(); - fill(state); - state->clearPath(); - - return true; -} - -bool CairoOutputDev::patchMeshShadedFill(GfxState *state, GfxPatchMeshShading *shading) -{ - int i, j, k; - - cairo_pattern_destroy(fill_pattern); - fill_pattern = cairo_pattern_create_mesh (); - - for (i = 0; i < shading->getNPatches(); i++) { - const GfxPatch *patch = shading->getPatch(i); - GfxColor color; - GfxRGB rgb; - - cairo_mesh_pattern_begin_patch (fill_pattern); - - cairo_mesh_pattern_move_to (fill_pattern, patch->x[0][0], patch->y[0][0]); - cairo_mesh_pattern_curve_to (fill_pattern, - patch->x[0][1], patch->y[0][1], - patch->x[0][2], patch->y[0][2], - patch->x[0][3], patch->y[0][3]); - - cairo_mesh_pattern_curve_to (fill_pattern, - patch->x[1][3], patch->y[1][3], - patch->x[2][3], patch->y[2][3], - patch->x[3][3], patch->y[3][3]); - - cairo_mesh_pattern_curve_to (fill_pattern, - patch->x[3][2], patch->y[3][2], - patch->x[3][1], patch->y[3][1], - patch->x[3][0], patch->y[3][0]); - - cairo_mesh_pattern_curve_to (fill_pattern, - patch->x[2][0], patch->y[2][0], - patch->x[1][0], patch->y[1][0], - patch->x[0][0], patch->y[0][0]); - - cairo_mesh_pattern_set_control_point (fill_pattern, 0, patch->x[1][1], patch->y[1][1]); - cairo_mesh_pattern_set_control_point (fill_pattern, 1, patch->x[1][2], patch->y[1][2]); - cairo_mesh_pattern_set_control_point (fill_pattern, 2, patch->x[2][2], patch->y[2][2]); - cairo_mesh_pattern_set_control_point (fill_pattern, 3, patch->x[2][1], patch->y[2][1]); - - for (j = 0; j < 4; j++) { - int u, v; - - switch (j) { - case 0: - u = 0; v = 0; - break; - case 1: - u = 0; v = 1; - break; - case 2: - u = 1; v = 1; - break; - case 3: - u = 1; v = 0; - break; - } - - if (shading->isParameterized()) { - shading->getParameterizedColor (patch->color[u][v].c[0], &color); - } else { - for (k = 0; k < shading->getColorSpace()->getNComps(); k++) { - // simply cast to the desired type; that's all what is needed. - color.c[k] = GfxColorComp (patch->color[u][v].c[k]); - } - } - - shading->getColorSpace()->getRGB(&color, &rgb); - cairo_mesh_pattern_set_corner_color_rgb (fill_pattern, j, - colToDbl(rgb.r), - colToDbl(rgb.g), - colToDbl(rgb.b)); - } - cairo_mesh_pattern_end_patch (fill_pattern); - } - - double xMin, yMin, xMax, yMax; - // get the clip region bbox - state->getUserClipBBox(&xMin, &yMin, &xMax, &yMax); - state->moveTo(xMin, yMin); - state->lineTo(xMin, yMax); - state->lineTo(xMax, yMax); - state->lineTo(xMax, yMin); - state->closePath(); - fill(state); - state->clearPath(); - - return true; -} -#endif /* CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) */ - -void CairoOutputDev::clip(GfxState *state) { - doPath (cairo, state, state->getPath()); - cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_WINDING); - cairo_clip (cairo); - LOG (printf ("clip\n")); - if (cairo_shape) { - doPath (cairo_shape, state, state->getPath()); - cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_WINDING); - cairo_clip (cairo_shape); - } -} - -void CairoOutputDev::eoClip(GfxState *state) { - doPath (cairo, state, state->getPath()); - cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_EVEN_ODD); - cairo_clip (cairo); - LOG (printf ("clip-eo\n")); - if (cairo_shape) { - doPath (cairo_shape, state, state->getPath()); - cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_EVEN_ODD); - cairo_clip (cairo_shape); - } - -} - -void CairoOutputDev::clipToStrokePath(GfxState *state) { - LOG(printf("clip-to-stroke-path\n")); - strokePathClip = (StrokePathClip*)gmalloc (sizeof(*strokePathClip)); - strokePathClip->path = state->getPath()->copy(); - cairo_get_matrix (cairo, &strokePathClip->ctm); - strokePathClip->line_width = cairo_get_line_width (cairo); - strokePathClip->dash_count = cairo_get_dash_count (cairo); - if (strokePathClip->dash_count) { - strokePathClip->dashes = (double*) gmallocn (sizeof(double), strokePathClip->dash_count); - cairo_get_dash (cairo, strokePathClip->dashes, &strokePathClip->dash_offset); - } else { - strokePathClip->dashes = nullptr; - } - strokePathClip->cap = cairo_get_line_cap (cairo); - strokePathClip->join = cairo_get_line_join (cairo); - strokePathClip->miter = cairo_get_miter_limit (cairo); - strokePathClip->ref_count = 1; -} - -void CairoOutputDev::fillToStrokePathClip(GfxState *state) { - cairo_save (cairo); - - cairo_set_matrix (cairo, &strokePathClip->ctm); - cairo_set_line_width (cairo, strokePathClip->line_width); - cairo_set_dash (cairo, strokePathClip->dashes, strokePathClip->dash_count, strokePathClip->dash_offset); - cairo_set_line_cap (cairo, strokePathClip->cap); - cairo_set_line_join (cairo, strokePathClip->join); - cairo_set_miter_limit (cairo, strokePathClip->miter); - doPath (cairo, state, strokePathClip->path); - cairo_stroke (cairo); - - cairo_restore (cairo); -} - -void CairoOutputDev::beginString(GfxState *state, const GooString *s) -{ - int len = s->getLength(); - - if (needFontUpdate) - updateFont(state); - - if (!currentFont) - return; - - glyphs = (cairo_glyph_t *) gmallocn (len, sizeof (cairo_glyph_t)); - glyphCount = 0; - if (use_show_text_glyphs) { - clusters = (cairo_text_cluster_t *) gmallocn (len, sizeof (cairo_text_cluster_t)); - clusterCount = 0; - utf8Max = len*2; // start with twice the number of glyphs. we will realloc if we need more. - utf8 = (char *) gmalloc (utf8Max); - utf8Count = 0; - } -} - -void CairoOutputDev::drawChar(GfxState *state, double x, double y, - double dx, double dy, - double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen) -{ - if (currentFont) { - glyphs[glyphCount].index = currentFont->getGlyph (code, u, uLen); - glyphs[glyphCount].x = x - originX; - glyphs[glyphCount].y = y - originY; - glyphCount++; - if (use_show_text_glyphs) { - GooString enc("UTF-8"); - UnicodeMap *utf8Map = globalParams->getUnicodeMap(&enc); - if (utf8Max - utf8Count < uLen*6) { - // utf8 encoded characters can be up to 6 bytes - if (utf8Max > uLen*6) - utf8Max *= 2; - else - utf8Max += 2*uLen*6; - utf8 = (char *) grealloc (utf8, utf8Max); - } - clusters[clusterCount].num_bytes = 0; - for (int i = 0; i < uLen; i++) { - int size = utf8Map->mapUnicode(u[i], utf8 + utf8Count, utf8Max - utf8Count); - utf8Count += size; - clusters[clusterCount].num_bytes += size; - } - clusters[clusterCount].num_glyphs = 1; - clusterCount++; - } - } - - if (!textPage) - return; - actualText->addChar (state, x, y, dx, dy, code, nBytes, u, uLen); -} - -void CairoOutputDev::endString(GfxState *state) -{ - int render; - - if (!currentFont) - return; - - // endString can be called without a corresponding beginString. If this - // happens glyphs will be null so don't draw anything, just return. - // XXX: OutputDevs should probably not have to deal with this... - if (!glyphs) - return; - - // ignore empty strings and invisible text -- this is used by - // Acrobat Capture - render = state->getRender(); - if (render == 3 || glyphCount == 0 || !text_matrix_valid) { - goto finish; - } - - if (!(render & 1)) { - LOG (printf ("fill string\n")); - cairo_set_source (cairo, fill_pattern); - if (use_show_text_glyphs) - cairo_show_text_glyphs (cairo, utf8, utf8Count, glyphs, glyphCount, clusters, clusterCount, (cairo_text_cluster_flags_t)0); - else - cairo_show_glyphs (cairo, glyphs, glyphCount); - if (cairo_shape) - cairo_show_glyphs (cairo_shape, glyphs, glyphCount); - } - - // stroke - if ((render & 3) == 1 || (render & 3) == 2) { - LOG (printf ("stroke string\n")); - cairo_set_source (cairo, stroke_pattern); - cairo_glyph_path (cairo, glyphs, glyphCount); - cairo_stroke (cairo); - if (cairo_shape) { - cairo_glyph_path (cairo_shape, glyphs, glyphCount); - cairo_stroke (cairo_shape); - } - } - - // clip - if ((render & 4)) { - LOG (printf ("clip string\n")); - // append the glyph path to textClipPath. - - // set textClipPath as the currentPath - if (textClipPath) { - cairo_append_path (cairo, textClipPath); - if (cairo_shape) { - cairo_append_path (cairo_shape, textClipPath); - } - cairo_path_destroy (textClipPath); - } - - // append the glyph path - cairo_glyph_path (cairo, glyphs, glyphCount); - - // move the path back into textClipPath - // and clear the current path - textClipPath = cairo_copy_path (cairo); - cairo_new_path (cairo); - if (cairo_shape) { - cairo_new_path (cairo_shape); - } - } - -finish: - gfree (glyphs); - glyphs = nullptr; - if (use_show_text_glyphs) { - gfree (clusters); - clusters = nullptr; - gfree (utf8); - utf8 = nullptr; - } -} - - -bool CairoOutputDev::beginType3Char(GfxState *state, double x, double y, - double dx, double dy, - CharCode code, Unicode *u, int uLen) { - - cairo_save (cairo); - cairo_matrix_t matrix; - - const double *ctm = state->getCTM(); - matrix.xx = ctm[0]; - matrix.yx = ctm[1]; - matrix.xy = ctm[2]; - matrix.yy = ctm[3]; - matrix.x0 = ctm[4]; - matrix.y0 = ctm[5]; - /* Restore the original matrix and then transform to matrix needed for the - * type3 font. This is ugly but seems to work. Perhaps there is a better way to do it?*/ - cairo_set_matrix(cairo, &orig_matrix); - cairo_transform(cairo, &matrix); - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_set_matrix(cairo_shape, &orig_matrix); - cairo_transform(cairo_shape, &matrix); - } - cairo_pattern_destroy(stroke_pattern); - cairo_pattern_reference(fill_pattern); - stroke_pattern = fill_pattern; - return false; -} - -void CairoOutputDev::endType3Char(GfxState *state) { - cairo_restore (cairo); - if (cairo_shape) { - cairo_restore (cairo_shape); - } -} - -void CairoOutputDev::type3D0(GfxState *state, double wx, double wy) { - t3_glyph_wx = wx; - t3_glyph_wy = wy; -} - -void CairoOutputDev::type3D1(GfxState *state, double wx, double wy, - double llx, double lly, double urx, double ury) { - t3_glyph_wx = wx; - t3_glyph_wy = wy; - t3_glyph_bbox[0] = llx; - t3_glyph_bbox[1] = lly; - t3_glyph_bbox[2] = urx; - t3_glyph_bbox[3] = ury; - t3_glyph_has_bbox = true; -} - -void CairoOutputDev::beginTextObject(GfxState *state) { -} - -void CairoOutputDev::endTextObject(GfxState *state) { - if (textClipPath) { - // clip the accumulated text path - cairo_append_path (cairo, textClipPath); - cairo_clip (cairo); - if (cairo_shape) { - cairo_append_path (cairo_shape, textClipPath); - cairo_clip (cairo_shape); - } - cairo_path_destroy (textClipPath); - textClipPath = nullptr; - } -} - -void CairoOutputDev::beginActualText(GfxState *state, const GooString *text) -{ - if (textPage) - actualText->begin(state, text); -} - -void CairoOutputDev::endActualText(GfxState *state) -{ - if (textPage) - actualText->end(state); -} - -static inline int splashRound(SplashCoord x) { - return (int)floor(x + 0.5); -} - -static inline int splashCeil(SplashCoord x) { - return (int)ceil(x); -} - -static inline int splashFloor(SplashCoord x) { - return (int)floor(x); -} - -static -cairo_surface_t *cairo_surface_create_similar_clip (cairo_t *cairo, cairo_content_t content) -{ - cairo_pattern_t *pattern; - cairo_surface_t *surface = nullptr; - - cairo_push_group_with_content (cairo, content); - pattern = cairo_pop_group (cairo); - cairo_pattern_get_surface (pattern, &surface); - cairo_surface_reference (surface); - cairo_pattern_destroy (pattern); - return surface; -} - - - -void CairoOutputDev::beginTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/, - GfxColorSpace * blendingColorSpace, - bool /*isolated*/, bool knockout, - bool forSoftMask) { - /* push color space */ - ColorSpaceStack* css = new ColorSpaceStack; - css->cs = blendingColorSpace; - css->knockout = knockout; - cairo_get_matrix(cairo, &css->group_matrix); - css->next = groupColorSpaceStack; - groupColorSpaceStack = css; - - LOG(printf ("begin transparency group. knockout: %s\n", knockout ? "yes":"no")); - - if (knockout) { - knockoutCount++; - if (!cairo_shape) { - /* create a surface for tracking the shape */ - cairo_surface_t *cairo_shape_surface = cairo_surface_create_similar_clip (cairo, CAIRO_CONTENT_ALPHA); - cairo_shape = cairo_create (cairo_shape_surface); - cairo_surface_destroy (cairo_shape_surface); - setContextAntialias(cairo_shape, antialias); - - /* the color doesn't matter as long as it is opaque */ - cairo_set_source_rgb (cairo_shape, 0, 0, 0); - cairo_matrix_t matrix; - cairo_get_matrix (cairo, &matrix); - cairo_set_matrix (cairo_shape, &matrix); - } - } - if (groupColorSpaceStack->next && groupColorSpaceStack->next->knockout) { - /* we need to track the shape */ - cairo_push_group (cairo_shape); - } - if (0 && forSoftMask) - cairo_push_group_with_content (cairo, CAIRO_CONTENT_ALPHA); - else - cairo_push_group (cairo); - - /* push_group has an implicit cairo_save() */ - if (knockout) { - /*XXX: let's hope this matches the semantics needed */ - cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE); - } else { - cairo_set_operator(cairo, CAIRO_OPERATOR_OVER); - } -} - -void CairoOutputDev::endTransparencyGroup(GfxState * /*state*/) { - if (group) - cairo_pattern_destroy(group); - group = cairo_pop_group (cairo); - - LOG(printf ("end transparency group\n")); - - if (groupColorSpaceStack->next && groupColorSpaceStack->next->knockout) { - if (shape) - cairo_pattern_destroy(shape); - shape = cairo_pop_group (cairo_shape); - } -} - -void CairoOutputDev::paintTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/) { - LOG(printf ("paint transparency group\n")); - - cairo_save (cairo); - cairo_set_matrix (cairo, &groupColorSpaceStack->group_matrix); - - if (shape) { - /* OPERATOR_SOURCE w/ a mask is defined as (src IN mask) ADD (dest OUT mask) - * however our source has already been clipped to mask so we only need to - * do ADD and OUT */ - - /* clear the shape mask */ - cairo_set_source (cairo, shape); - cairo_set_operator (cairo, CAIRO_OPERATOR_DEST_OUT); - cairo_paint (cairo); - cairo_set_operator (cairo, CAIRO_OPERATOR_ADD); - } - cairo_set_source (cairo, group); - - if (!mask) { - cairo_paint_with_alpha (cairo, fill_opacity); - cairo_status_t status = cairo_status(cairo); - if (status) - printf("BAD status: %s\n", cairo_status_to_string(status)); - } else { - if (fill_opacity < 1.0) { - cairo_push_group(cairo); - } - cairo_save(cairo); - cairo_set_matrix(cairo, &mask_matrix); - cairo_mask(cairo, mask); - cairo_restore(cairo); - if (fill_opacity < 1.0) { - cairo_pop_group_to_source(cairo); - cairo_paint_with_alpha (cairo, fill_opacity); - } - cairo_pattern_destroy(mask); - mask = nullptr; - } - - if (shape) { - if (cairo_shape) { - cairo_set_source (cairo_shape, shape); - cairo_paint (cairo_shape); - cairo_set_source_rgb (cairo_shape, 0, 0, 0); - } - cairo_pattern_destroy (shape); - shape = nullptr; - } - - popTransparencyGroup(); - cairo_restore(cairo); -} - -static int luminocity(uint32_t x) -{ - int r = (x >> 16) & 0xff; - int g = (x >> 8) & 0xff; - int b = (x >> 0) & 0xff; - // an arbitrary integer approximation of .3*r + .59*g + .11*b - int y = (r*19661+g*38666+b*7209 + 32829)>>16; - return y; -} - - -/* XXX: do we need to deal with shape here? */ -void CairoOutputDev::setSoftMask(GfxState * state, const double * bbox, bool alpha, - Function * transferFunc, GfxColor * backdropColor) { - cairo_pattern_destroy(mask); - - LOG(printf ("set softMask\n")); - - if (!alpha || transferFunc) { - /* We need to mask according to the luminocity of the group. - * So we paint the group to an image surface convert it to a luminocity map - * and then use that as the mask. */ - - /* Get clip extents in device space */ - double x1, y1, x2, y2, x_min, y_min, x_max, y_max; - cairo_clip_extents(cairo, &x1, &y1, &x2, &y2); - cairo_user_to_device(cairo, &x1, &y1); - cairo_user_to_device(cairo, &x2, &y2); - x_min = MIN(x1, x2); - y_min = MIN(y1, y2); - x_max = MAX(x1, x2); - y_max = MAX(y1, y2); - cairo_clip_extents(cairo, &x1, &y1, &x2, &y2); - cairo_user_to_device(cairo, &x1, &y2); - cairo_user_to_device(cairo, &x2, &y1); - x_min = MIN(x_min,MIN(x1, x2)); - y_min = MIN(y_min,MIN(y1, y2)); - x_max = MAX(x_max,MAX(x1, x2)); - y_max = MAX(y_max,MAX(y1, y2)); - - int width = (int)(ceil(x_max) - floor(x_min)); - int height = (int)(ceil(y_max) - floor(y_min)); - - /* Get group device offset */ - double x_offset, y_offset; - if (cairo_get_group_target(cairo) == cairo_get_target(cairo)) { - cairo_surface_get_device_offset(cairo_get_group_target(cairo), &x_offset, &y_offset); - } else { - cairo_surface_t *pats; - cairo_pattern_get_surface(group, &pats); - cairo_surface_get_device_offset(pats, &x_offset, &y_offset); - } - - /* Adjust extents by group offset */ - x_min += x_offset; - y_min += y_offset; - - cairo_surface_t *source = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); - cairo_t *maskCtx = cairo_create(source); - setContextAntialias(maskCtx, antialias); - - //XXX: hopefully this uses the correct color space */ - if (!alpha && groupColorSpaceStack->cs) { - GfxRGB backdropColorRGB; - groupColorSpaceStack->cs->getRGB(backdropColor, &backdropColorRGB); - /* paint the backdrop */ - cairo_set_source_rgb(maskCtx, - colToDbl(backdropColorRGB.r), - colToDbl(backdropColorRGB.g), - colToDbl(backdropColorRGB.b)); - } - cairo_paint(maskCtx); - - /* Copy source ctm to mask ctm and translate origin so that the - * mask appears it the same location on the source surface. */ - cairo_matrix_t mat, tmat; - cairo_matrix_init_translate(&tmat, -x_min, -y_min); - cairo_get_matrix(cairo, &mat); - cairo_matrix_multiply(&mat, &mat, &tmat); - cairo_set_matrix(maskCtx, &mat); - - /* make the device offset of the new mask match that of the group */ - cairo_surface_set_device_offset(source, x_offset, y_offset); - - /* paint the group */ - cairo_set_source(maskCtx, group); - cairo_paint(maskCtx); - - /* XXX status = cairo_status(maskCtx); */ - cairo_destroy(maskCtx); - - /* convert to a luminocity map */ - uint32_t *source_data = reinterpret_cast(cairo_image_surface_get_data(source)); - /* get stride in units of 32 bits */ - ptrdiff_t stride = cairo_image_surface_get_stride(source)/4; - for (int y=0; ytransform(&lum_in, &lum_out); - lum = (int)(lum_out * 255.0 + 0.5); - } - source_data[y*stride + x] = lum << 24; - } - } - cairo_surface_mark_dirty (source); - - /* setup the new mask pattern */ - mask = cairo_pattern_create_for_surface(source); - cairo_get_matrix(cairo, &mask_matrix); - - if (cairo_get_group_target(cairo) == cairo_get_target(cairo)) { - cairo_pattern_set_matrix(mask, &mat); - } else { - cairo_matrix_t patMatrix; - cairo_pattern_get_matrix(group, &patMatrix); - /* Apply x_min, y_min offset to it appears in the same location as source. */ - cairo_matrix_multiply(&patMatrix, &patMatrix, &tmat); - cairo_pattern_set_matrix(mask, &patMatrix); - } - - cairo_surface_destroy(source); - } else if (alpha) { - mask = cairo_pattern_reference(group); - cairo_get_matrix(cairo, &mask_matrix); - } - - popTransparencyGroup(); -} - -void CairoOutputDev::popTransparencyGroup() { - /* pop color space */ - ColorSpaceStack *css = groupColorSpaceStack; - if (css->knockout) { - knockoutCount--; - if (!knockoutCount) { - /* we don't need to track the shape anymore because - * we are not above any knockout groups */ - cairo_destroy(cairo_shape); - cairo_shape = nullptr; - } - } - groupColorSpaceStack = css->next; - delete css; -} - - -void CairoOutputDev::clearSoftMask(GfxState * /*state*/) { - if (mask) - cairo_pattern_destroy(mask); - mask = nullptr; -} - -/* Taken from cairo/doc/tutorial/src/singular.c */ -static void -get_singular_values (const cairo_matrix_t *matrix, - double *major, - double *minor) -{ - double xx = matrix->xx, xy = matrix->xy; - double yx = matrix->yx, yy = matrix->yy; - - double a = xx*xx+yx*yx; - double b = xy*xy+yy*yy; - double k = xx*xy+yx*yy; - - double f = (a+b) * .5; - double g = (a-b) * .5; - double delta = sqrt (g*g + k*k); - - if (major) - *major = sqrt (f + delta); - if (minor) - *minor = sqrt (f - delta); -} - -void CairoOutputDev::getScaledSize(const cairo_matrix_t *matrix, - int orig_width, - int orig_height, - int *scaledWidth, - int *scaledHeight) -{ - double xScale; - double yScale; - if (orig_width > orig_height) - get_singular_values (matrix, &xScale, &yScale); - else - get_singular_values (matrix, &yScale, &xScale); - - int tx, tx2, ty, ty2; /* the integer co-ordinates of the resulting image */ - if (xScale >= 0) { - tx = splashRound(matrix->x0 - 0.01); - tx2 = splashRound(matrix->x0 + xScale + 0.01) - 1; - } else { - tx = splashRound(matrix->x0 + 0.01) - 1; - tx2 = splashRound(matrix->x0 + xScale - 0.01); - } - *scaledWidth = abs(tx2 - tx) + 1; - //scaledWidth = splashRound(fabs(xScale)); - if (*scaledWidth == 0) { - // technically, this should draw nothing, but it generally seems - // better to draw a one-pixel-wide stripe rather than throwing it - // away - *scaledWidth = 1; - } - if (yScale >= 0) { - ty = splashFloor(matrix->y0 + 0.01); - ty2 = splashCeil(matrix->y0 + yScale - 0.01); - } else { - ty = splashCeil(matrix->y0 - 0.01); - ty2 = splashFloor(matrix->y0 + yScale + 0.01); - } - *scaledHeight = abs(ty2 - ty); - if (*scaledHeight == 0) { - *scaledHeight = 1; - } -} - -cairo_filter_t -CairoOutputDev::getFilterForSurface(cairo_surface_t *image, - bool interpolate) -{ - if (interpolate) - return CAIRO_FILTER_GOOD; - - int orig_width = cairo_image_surface_get_width (image); - int orig_height = cairo_image_surface_get_height (image); - if (orig_width == 0 || orig_height == 0) - return CAIRO_FILTER_NEAREST; - - /* When printing, don't change the interpolation. */ - if (printing) - return CAIRO_FILTER_NEAREST; - - cairo_matrix_t matrix; - cairo_get_matrix(cairo, &matrix); - int scaled_width, scaled_height; - getScaledSize (&matrix, orig_width, orig_height, &scaled_width, &scaled_height); - - /* When scale factor is >= 400% we don't interpolate. See bugs #25268, #9860 */ - if (scaled_width / orig_width >= 4 || scaled_height / orig_height >= 4) - return CAIRO_FILTER_NEAREST; - - return CAIRO_FILTER_GOOD; -} - -void CairoOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool interpolate, bool inlineImg) { - - /* FIXME: Doesn't the image mask support any colorspace? */ - cairo_set_source (cairo, fill_pattern); - - /* work around a cairo bug when scaling 1x1 surfaces */ - if (width == 1 && height == 1) { - ImageStream *imgStr; - unsigned char pix; - int invert_bit; - - imgStr = new ImageStream(str, width, 1, 1); - imgStr->reset(); - imgStr->getPixel(&pix); - imgStr->close(); - delete imgStr; - - invert_bit = invert ? 1 : 0; - if (pix ^ invert_bit) - return; - - cairo_save (cairo); - cairo_rectangle (cairo, 0., 0., width, height); - cairo_fill (cairo); - cairo_restore (cairo); - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_rectangle (cairo_shape, 0., 0., width, height); - cairo_fill (cairo_shape); - cairo_restore (cairo_shape); - } - return; - } - - /* shape is 1.0 for painted areas, 0.0 for unpainted ones */ - - cairo_matrix_t matrix; - cairo_get_matrix (cairo, &matrix); - //XXX: it is possible that we should only do sub pixel positioning if - // we are rendering fonts */ - if (!printing && prescaleImages - /* not rotated */ - && matrix.xy == 0 && matrix.yx == 0 - /* axes not flipped / not 180 deg rotated */ - && matrix.xx > 0 && (upsideDown() ? -1 : 1) * matrix.yy > 0) { - drawImageMaskPrescaled(state, ref, str, width, height, invert, interpolate, inlineImg); - } else { - drawImageMaskRegular(state, ref, str, width, height, invert, interpolate, inlineImg); - } - -} - -void CairoOutputDev::setSoftMaskFromImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool inlineImg, double *baseMatrix) { - - /* FIXME: Doesn't the image mask support any colorspace? */ - cairo_set_source (cairo, fill_pattern); - - /* work around a cairo bug when scaling 1x1 surfaces */ - if (width == 1 && height == 1) { - ImageStream *imgStr; - unsigned char pix; - int invert_bit; - - imgStr = new ImageStream(str, width, 1, 1); - imgStr->reset(); - imgStr->getPixel(&pix); - imgStr->close(); - delete imgStr; - - invert_bit = invert ? 1 : 0; - if (!(pix ^ invert_bit)) { - cairo_save (cairo); - cairo_rectangle (cairo, 0., 0., width, height); - cairo_fill (cairo); - cairo_restore (cairo); - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_rectangle (cairo_shape, 0., 0., width, height); - cairo_fill (cairo_shape); - cairo_restore (cairo_shape); - } - } - } else { - cairo_push_group_with_content (cairo, CAIRO_CONTENT_ALPHA); - - /* shape is 1.0 for painted areas, 0.0 for unpainted ones */ - - cairo_matrix_t matrix; - cairo_get_matrix (cairo, &matrix); - //XXX: it is possible that we should only do sub pixel positioning if - // we are rendering fonts */ - if (!printing && prescaleImages && matrix.xy == 0.0 && matrix.yx == 0.0) { - drawImageMaskPrescaled(state, ref, str, width, height, invert, false, inlineImg); - } else { - drawImageMaskRegular(state, ref, str, width, height, invert, false, inlineImg); - } - - if (state->getFillColorSpace()->getMode() == csPattern) { - cairo_set_source_rgb (cairo, 1, 1, 1); - cairo_set_matrix (cairo, &mask_matrix); - cairo_mask (cairo, mask); - } - - if (mask) - cairo_pattern_destroy (mask); - mask = cairo_pop_group (cairo); - } - - saveState(state); - double bbox[4] = {0,0,1,1}; // dummy - beginTransparencyGroup(state, bbox, state->getFillColorSpace(), - true, false, false); -} - -void CairoOutputDev::unsetSoftMaskFromImageMask(GfxState *state, double *baseMatrix) { - double bbox[4] = {0,0,1,1}; // dummy - - endTransparencyGroup(state); - restoreState(state); - paintTransparencyGroup(state, bbox); - clearSoftMask(state); -} - -void CairoOutputDev::drawImageMaskRegular(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool interpolate, bool inlineImg) { - unsigned char *buffer; - unsigned char *dest; - cairo_surface_t *image; - cairo_pattern_t *pattern; - int x, y, i, bit; - ImageStream *imgStr; - unsigned char *pix; - cairo_matrix_t matrix; - int invert_bit; - ptrdiff_t row_stride; - cairo_filter_t filter; - - /* TODO: Do we want to cache these? */ - imgStr = new ImageStream(str, width, 1, 1); - imgStr->reset(); - - image = cairo_image_surface_create (CAIRO_FORMAT_A1, width, height); - if (cairo_surface_status (image)) - goto cleanup; - - buffer = cairo_image_surface_get_data (image); - row_stride = cairo_image_surface_get_stride (image); - - invert_bit = invert ? 1 : 0; - - for (y = 0; y < height; y++) { - pix = imgStr->getLine(); - dest = buffer + y * row_stride; - i = 0; - bit = 0; - for (x = 0; x < width; x++) { - if (bit == 0) - dest[i] = 0; - if (!(pix[x] ^ invert_bit)) { -#ifdef WORDS_BIGENDIAN - dest[i] |= (1 << (7 - bit)); -#else - dest[i] |= (1 << bit); -#endif - } - bit++; - if (bit > 7) { - bit = 0; - i++; - } - } - } - - filter = getFilterForSurface (image, interpolate); - - cairo_surface_mark_dirty (image); - pattern = cairo_pattern_create_for_surface (image); - cairo_surface_destroy (image); - if (cairo_pattern_status (pattern)) - goto cleanup; - - LOG (printf ("drawImageMask %dx%d\n", width, height)); - - cairo_pattern_set_filter (pattern, filter); - - cairo_matrix_init_translate (&matrix, 0, height); - cairo_matrix_scale (&matrix, width, -height); - cairo_pattern_set_matrix (pattern, &matrix); - if (cairo_pattern_status (pattern)) { - cairo_pattern_destroy (pattern); - goto cleanup; - } - - if (state->getFillColorSpace()->getMode() == csPattern) { - mask = cairo_pattern_reference (pattern); - cairo_get_matrix (cairo, &mask_matrix); - } else if (!printing) { - cairo_save (cairo); - cairo_rectangle (cairo, 0., 0., 1., 1.); - cairo_clip (cairo); - if (strokePathClip) { - cairo_push_group (cairo); - fillToStrokePathClip (state); - cairo_pop_group_to_source (cairo); - } - cairo_mask (cairo, pattern); - cairo_restore (cairo); - } else { - cairo_mask (cairo, pattern); - } - - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_set_source (cairo_shape, pattern); - if (!printing) { - cairo_rectangle (cairo_shape, 0., 0., 1., 1.); - cairo_fill (cairo_shape); - } else { - cairo_mask (cairo_shape, pattern); - } - cairo_restore (cairo_shape); - } - - cairo_pattern_destroy (pattern); - -cleanup: - imgStr->close(); - delete imgStr; -} - - -void CairoOutputDev::drawImageMaskPrescaled(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool interpolate, bool inlineImg) { - unsigned char *buffer; - cairo_surface_t *image; - cairo_pattern_t *pattern; - ImageStream *imgStr; - unsigned char *pix; - cairo_matrix_t matrix; - int invert_bit; - ptrdiff_t row_stride; - - /* cairo does a very poor job of scaling down images so we scale them ourselves */ - - LOG (printf ("drawImageMaskPrescaled %dx%d\n", width, height)); - - /* this scaling code is adopted from the splash image scaling code */ - cairo_get_matrix(cairo, &matrix); -#if 0 - printf("[%f %f], [%f %f], %f %f\n", matrix.xx, matrix.xy, matrix.yx, matrix.yy, matrix.x0, matrix.y0); -#endif - /* this whole computation should be factored out */ - double xScale = matrix.xx; - double yScale = matrix.yy; - int tx, tx2, ty, ty2; /* the integer co-ordinates of the resulting image */ - int scaledHeight; - int scaledWidth; - if (xScale >= 0) { - tx = splashRound(matrix.x0 - 0.01); - tx2 = splashRound(matrix.x0 + xScale + 0.01) - 1; - } else { - tx = splashRound(matrix.x0 + 0.01) - 1; - tx2 = splashRound(matrix.x0 + xScale - 0.01); - } - scaledWidth = abs(tx2 - tx) + 1; - //scaledWidth = splashRound(fabs(xScale)); - if (scaledWidth == 0) { - // technically, this should draw nothing, but it generally seems - // better to draw a one-pixel-wide stripe rather than throwing it - // away - scaledWidth = 1; - } - if (yScale >= 0) { - ty = splashFloor(matrix.y0 + 0.01); - ty2 = splashCeil(matrix.y0 + yScale - 0.01); - } else { - ty = splashCeil(matrix.y0 - 0.01); - ty2 = splashFloor(matrix.y0 + yScale + 0.01); - } - scaledHeight = abs(ty2 - ty); - if (scaledHeight == 0) { - scaledHeight = 1; - } -#if 0 - printf("xscale: %g, yscale: %g\n", xScale, yScale); - printf("width: %d, height: %d\n", width, height); - printf("scaledWidth: %d, scaledHeight: %d\n", scaledWidth, scaledHeight); -#endif - - /* compute the required padding */ - /* Padding is used to preserve the aspect ratio. - We compute total_pad to make (height+total_pad)/scaledHeight as close to height/yScale as possible */ - int head_pad = 0; - int tail_pad = 0; - int total_pad = splashRound(height*(scaledHeight/fabs(yScale)) - height); - - /* compute the two pieces of padding */ - if (total_pad > 0) { - //XXX: i'm not positive fabs() is correct - float tail_error = fabs(matrix.y0 - ty); - float head_error = fabs(ty2 - (matrix.y0 + yScale)); - float tail_fraction = tail_error/(tail_error + head_error); - tail_pad = splashRound(total_pad*tail_fraction); - head_pad = total_pad - tail_pad; - } else { - tail_pad = 0; - head_pad = 0; - } - int origHeight = height; - height += tail_pad; - height += head_pad; -#if 0 - printf("head_pad: %d tail_pad: %d\n", head_pad, tail_pad); - printf("origHeight: %d height: %d\n", origHeight, height); - printf("ty: %d, ty2: %d\n", ty, ty2); -#endif - - /* TODO: Do we want to cache these? */ - imgStr = new ImageStream(str, width, 1, 1); - imgStr->reset(); - - invert_bit = invert ? 1 : 0; - - image = cairo_image_surface_create (CAIRO_FORMAT_A8, scaledWidth, scaledHeight); - if (cairo_surface_status (image)) { - imgStr->close(); - delete imgStr; - return; - } - - buffer = cairo_image_surface_get_data (image); - row_stride = cairo_image_surface_get_stride (image); - - int yp = height / scaledHeight; - int yq = height % scaledHeight; - int xp = width / scaledWidth; - int xq = width % scaledWidth; - int yt = 0; - int origHeight_c = origHeight; - /* use MIN() because yp might be > origHeight because of padding */ - unsigned char *pixBuf = (unsigned char *)malloc(MIN(yp+1, origHeight)*width); - int lastYStep = 1; - int total = 0; - for (int y = 0; y < scaledHeight; y++) { - // y scale Bresenham - int yStep = yp; - yt += yq; - - if (yt >= scaledHeight) { - yt -= scaledHeight; - ++yStep; - } - - // read row (s) from image ignoring the padding as appropriate - { - int n = (yp > 0) ? yStep : lastYStep; - total += n; - if (n > 0) { - unsigned char *p = pixBuf; - int head_pad_count = head_pad; - int origHeight_count = origHeight; - int tail_pad_count = tail_pad; - for (int i=0; igetLine(); - for (int j=0; j 0 ? yStep : 1; - int origN = n; - - /* compute the size of padding and pixels that will be used for this row */ - int head_pad_size = MIN(n, head_pad); - n -= head_pad_size; - head_pad -= MIN(head_pad_size, yStep); - - int pix_size = MIN(n, origHeight); - n -= pix_size; - origHeight -= MIN(pix_size, yStep); - - int tail_pad_size = MIN(n, tail_pad); - n -= tail_pad_size; - tail_pad -= MIN(tail_pad_size, yStep); - if (n != 0) { - printf("n = %d (%d %d %d)\n", n, head_pad_size, pix_size, tail_pad_size); - assert(n == 0); - } - - for (int x = 0; x < scaledWidth; ++x) { - int xStep = xp; - xt += xq; - if (xt >= scaledWidth) { - xt -= scaledWidth; - ++xStep; - } - int m = xStep > 0 ? xStep : 1; - float pixAcc0 = 0; - /* could m * head_pad_size * tail_pad_size overflow? */ - if (invert_bit) { - pixAcc0 += m * head_pad_size * tail_pad_size * 255; - } else { - pixAcc0 += m * head_pad_size * tail_pad_size * 0; - } - /* Accumulate all of the source pixels for the destination pixel */ - for (int i = 0; i < pix_size; ++i) { - for (int j = 0; j< m; ++j) { - if (xSrc + i*width + j > MIN(yp + 1, origHeight_c)*width) { - printf("%d > %d (%d %d %d %d) (%d %d %d)\n", xSrc + i*width + j, MIN(yp + 1, origHeight_c)*width, xSrc, i , width, j, yp, origHeight_c, width); - printf("%d %d %d\n", head_pad_size, pix_size, tail_pad_size); - assert(0 && "bad access\n"); - } - pixAcc0 += pixBuf[xSrc + i*width + j]; - } - } - buffer[y * row_stride + x] = splashFloor(pixAcc0 / (origN*m)); - xSrc += xStep; - x1 += 1; - } - - } - free(pixBuf); - - cairo_surface_mark_dirty (image); - pattern = cairo_pattern_create_for_surface (image); - cairo_surface_destroy (image); - if (cairo_pattern_status (pattern)) { - imgStr->close(); - delete imgStr; - return; - } - - /* we should actually be using CAIRO_FILTER_NEAREST here. However, - * cairo doesn't yet do minifaction filtering causing scaled down - * images with CAIRO_FILTER_NEAREST to look really bad */ - cairo_pattern_set_filter (pattern, - interpolate ? CAIRO_FILTER_GOOD : CAIRO_FILTER_FAST); - - if (state->getFillColorSpace()->getMode() == csPattern) { - cairo_matrix_init_translate (&matrix, 0, scaledHeight); - cairo_matrix_scale (&matrix, scaledWidth, -scaledHeight); - cairo_pattern_set_matrix (pattern, &matrix); - if (cairo_pattern_status (pattern)) { - cairo_pattern_destroy (pattern); - imgStr->close(); - delete imgStr; - return; - } - - mask = cairo_pattern_reference (pattern); - cairo_get_matrix (cairo, &mask_matrix); - } else { - cairo_save (cairo); - - /* modify our current transformation so that the prescaled image - * goes where it is supposed to */ - cairo_get_matrix(cairo, &matrix); - cairo_scale(cairo, 1.0/matrix.xx, 1.0/matrix.yy); - // get integer co-ords - cairo_translate (cairo, tx - matrix.x0, ty2 - matrix.y0); - if (yScale > 0) - cairo_scale(cairo, 1, -1); - - cairo_rectangle (cairo, 0., 0., scaledWidth, scaledHeight); - cairo_clip (cairo); - if (strokePathClip) { - cairo_push_group (cairo); - fillToStrokePathClip (state); - cairo_pop_group_to_source (cairo); - } - cairo_mask (cairo, pattern); - - //cairo_get_matrix(cairo, &matrix); - //printf("mask at: [%f %f], [%f %f], %f %f\n\n", matrix.xx, matrix.xy, matrix.yx, matrix.yy, matrix.x0, matrix.y0); - cairo_restore(cairo); - } - - if (cairo_shape) { - cairo_save (cairo_shape); - - /* modify our current transformation so that the prescaled image - * goes where it is supposed to */ - cairo_get_matrix(cairo_shape, &matrix); - cairo_scale(cairo_shape, 1.0/matrix.xx, 1.0/matrix.yy); - // get integer co-ords - cairo_translate (cairo_shape, tx - matrix.x0, ty2 - matrix.y0); - if (yScale > 0) - cairo_scale(cairo_shape, 1, -1); - - cairo_rectangle (cairo_shape, 0., 0., scaledWidth, scaledHeight); - cairo_fill (cairo_shape); - - cairo_restore(cairo_shape); - } - - cairo_pattern_destroy (pattern); - - imgStr->close(); - delete imgStr; -} - -void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, - Stream *str, int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, int maskWidth, - int maskHeight, bool maskInvert, - bool maskInterpolate) -{ - ImageStream *maskImgStr, *imgStr; - ptrdiff_t row_stride; - unsigned char *maskBuffer, *buffer; - unsigned char *maskDest; - unsigned int *dest; - cairo_surface_t *maskImage, *image; - cairo_pattern_t *maskPattern, *pattern; - cairo_matrix_t matrix; - cairo_matrix_t maskMatrix; - unsigned char *pix; - int x, y; - int invert_bit; - cairo_filter_t filter; - cairo_filter_t maskFilter; - - maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); - maskImgStr->reset(); - - maskImage = cairo_image_surface_create (CAIRO_FORMAT_A8, maskWidth, maskHeight); - if (cairo_surface_status (maskImage)) { - maskImgStr->close(); - delete maskImgStr; - return; - } - - maskBuffer = cairo_image_surface_get_data (maskImage); - row_stride = cairo_image_surface_get_stride (maskImage); - - invert_bit = maskInvert ? 1 : 0; - - for (y = 0; y < maskHeight; y++) { - pix = maskImgStr->getLine(); - maskDest = maskBuffer + y * row_stride; - for (x = 0; x < maskWidth; x++) { - if (pix[x] ^ invert_bit) - *maskDest++ = 0; - else - *maskDest++ = 255; - } - } - - maskImgStr->close(); - delete maskImgStr; - - maskFilter = getFilterForSurface (maskImage, maskInterpolate); - - cairo_surface_mark_dirty (maskImage); - maskPattern = cairo_pattern_create_for_surface (maskImage); - cairo_surface_destroy (maskImage); - if (cairo_pattern_status (maskPattern)) - return; - -#if 0 - /* ICCBased color space doesn't do any color correction - * so check its underlying color space as well */ - int is_identity_transform; - is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || - (colorMap->getColorSpace()->getMode() == csICCBased && - ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); -#endif - - /* TODO: Do we want to cache these? */ - imgStr = new ImageStream(str, width, - colorMap->getNumPixelComps(), - colorMap->getBits()); - imgStr->reset(); - - image = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height); - if (cairo_surface_status (image)) - goto cleanup; - - buffer = cairo_image_surface_get_data (image); - row_stride = cairo_image_surface_get_stride (image); - for (y = 0; y < height; y++) { - dest = reinterpret_cast(buffer + y * row_stride); - pix = imgStr->getLine(); - colorMap->getRGBLine (pix, dest, width); - } - - filter = getFilterForSurface (image, interpolate); - - cairo_surface_mark_dirty (image); - pattern = cairo_pattern_create_for_surface (image); - cairo_surface_destroy (image); - if (cairo_pattern_status (pattern)) - goto cleanup; - - LOG (printf ("drawMaskedImage %dx%d\n", width, height)); - - cairo_pattern_set_filter (pattern, filter); - cairo_pattern_set_filter (maskPattern, maskFilter); - - if (!printing) { - cairo_pattern_set_extend (pattern, CAIRO_EXTEND_PAD); - cairo_pattern_set_extend (maskPattern, CAIRO_EXTEND_PAD); - } - - cairo_matrix_init_translate (&matrix, 0, height); - cairo_matrix_scale (&matrix, width, -height); - cairo_pattern_set_matrix (pattern, &matrix); - if (cairo_pattern_status (pattern)) { - cairo_pattern_destroy (pattern); - cairo_pattern_destroy (maskPattern); - goto cleanup; - } - - cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); - cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); - cairo_pattern_set_matrix (maskPattern, &maskMatrix); - if (cairo_pattern_status (maskPattern)) { - cairo_pattern_destroy (maskPattern); - cairo_pattern_destroy (pattern); - goto cleanup; - } - - if (!printing) { - cairo_save (cairo); - cairo_set_source (cairo, pattern); - cairo_rectangle (cairo, 0., 0., 1., 1.); - cairo_clip (cairo); - cairo_mask (cairo, maskPattern); - cairo_restore (cairo); - } else { - cairo_set_source (cairo, pattern); - cairo_mask (cairo, maskPattern); - } - - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_set_source (cairo_shape, pattern); - if (!printing) { - cairo_rectangle (cairo_shape, 0., 0., 1., 1.); - cairo_fill (cairo_shape); - } else { - cairo_mask (cairo_shape, pattern); - } - cairo_restore (cairo_shape); - } - - cairo_pattern_destroy (maskPattern); - cairo_pattern_destroy (pattern); - -cleanup: - imgStr->close(); - delete imgStr; -} - - -//XXX: is this affect by AIS(alpha is shape)? -void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - GfxImageColorMap *maskColorMap, - bool maskInterpolate) -{ - ImageStream *maskImgStr, *imgStr; - ptrdiff_t row_stride; - unsigned char *maskBuffer, *buffer; - unsigned char *maskDest; - unsigned int *dest; - cairo_surface_t *maskImage, *image; - cairo_pattern_t *maskPattern, *pattern; - cairo_matrix_t maskMatrix, matrix; - unsigned char *pix; - int y; - cairo_filter_t filter; - cairo_filter_t maskFilter; - - maskImgStr = new ImageStream(maskStr, maskWidth, - maskColorMap->getNumPixelComps(), - maskColorMap->getBits()); - maskImgStr->reset(); - - maskImage = cairo_image_surface_create (CAIRO_FORMAT_A8, maskWidth, maskHeight); - if (cairo_surface_status (maskImage)) { - maskImgStr->close(); - delete maskImgStr; - return; - } - - maskBuffer = cairo_image_surface_get_data (maskImage); - row_stride = cairo_image_surface_get_stride (maskImage); - for (y = 0; y < maskHeight; y++) { - maskDest = (unsigned char *) (maskBuffer + y * row_stride); - pix = maskImgStr->getLine(); - if (likely(pix != nullptr)) { - maskColorMap->getGrayLine (pix, maskDest, maskWidth); - } - } - - maskImgStr->close(); - delete maskImgStr; - - maskFilter = getFilterForSurface (maskImage, maskInterpolate); - - cairo_surface_mark_dirty (maskImage); - maskPattern = cairo_pattern_create_for_surface (maskImage); - cairo_surface_destroy (maskImage); - if (cairo_pattern_status (maskPattern)) - return; - -#if 0 - /* ICCBased color space doesn't do any color correction - * so check its underlying color space as well */ - int is_identity_transform; - is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || - (colorMap->getColorSpace()->getMode() == csICCBased && - ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); -#endif - - /* TODO: Do we want to cache these? */ - imgStr = new ImageStream(str, width, - colorMap->getNumPixelComps(), - colorMap->getBits()); - imgStr->reset(); - - image = cairo_image_surface_create (CAIRO_FORMAT_RGB24, width, height); - if (cairo_surface_status (image)) - goto cleanup; - - buffer = cairo_image_surface_get_data (image); - row_stride = cairo_image_surface_get_stride (image); - for (y = 0; y < height; y++) { - dest = reinterpret_cast(buffer + y * row_stride); - pix = imgStr->getLine(); - colorMap->getRGBLine (pix, dest, width); - } - - filter = getFilterForSurface (image, interpolate); - - cairo_surface_mark_dirty (image); - - setMimeData(state, str, ref, colorMap, image, height); - - pattern = cairo_pattern_create_for_surface (image); - cairo_surface_destroy (image); - if (cairo_pattern_status (pattern)) - goto cleanup; - - LOG (printf ("drawSoftMaskedImage %dx%d\n", width, height)); - - cairo_pattern_set_filter (pattern, filter); - cairo_pattern_set_filter (maskPattern, maskFilter); - - if (!printing) { - cairo_pattern_set_extend (pattern, CAIRO_EXTEND_PAD); - cairo_pattern_set_extend (maskPattern, CAIRO_EXTEND_PAD); - } - - cairo_matrix_init_translate (&matrix, 0, height); - cairo_matrix_scale (&matrix, width, -height); - cairo_pattern_set_matrix (pattern, &matrix); - if (cairo_pattern_status (pattern)) { - cairo_pattern_destroy (pattern); - cairo_pattern_destroy (maskPattern); - goto cleanup; - } - - cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); - cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); - cairo_pattern_set_matrix (maskPattern, &maskMatrix); - if (cairo_pattern_status (maskPattern)) { - cairo_pattern_destroy (maskPattern); - cairo_pattern_destroy (pattern); - goto cleanup; - } - - if (fill_opacity != 1.0) - cairo_push_group (cairo); - else - cairo_save (cairo); - - cairo_set_source (cairo, pattern); - if (!printing) { - cairo_rectangle (cairo, 0., 0., 1., 1.); - cairo_clip (cairo); - } - cairo_mask (cairo, maskPattern); - - if (fill_opacity != 1.0) { - cairo_pop_group_to_source (cairo); - cairo_save (cairo); - if (!printing) { - cairo_rectangle (cairo, 0., 0., 1., 1.); - cairo_clip (cairo); - } - cairo_paint_with_alpha (cairo, fill_opacity); - } - cairo_restore (cairo); - - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_set_source (cairo_shape, pattern); - if (!printing) { - cairo_rectangle (cairo_shape, 0., 0., 1., 1.); - cairo_fill (cairo_shape); - } else { - cairo_mask (cairo_shape, pattern); - } - cairo_restore (cairo_shape); - } - - cairo_pattern_destroy (maskPattern); - cairo_pattern_destroy (pattern); - -cleanup: - imgStr->close(); - delete imgStr; -} - -bool CairoOutputDev::getStreamData (Stream *str, char **buffer, int *length) -{ - int len, i; - char *strBuffer; - - len = 0; - str->close(); - str->reset(); - while (str->getChar() != EOF) len++; - if (len == 0) - return false; - - strBuffer = (char *)gmalloc (len); - - str->close(); - str->reset(); - for (i = 0; i < len; ++i) - strBuffer[i] = str->getChar(); - - *buffer = strBuffer; - *length = len; - - return true; -} - -static bool colorMapHasIdentityDecodeMap(GfxImageColorMap *colorMap) -{ - for (int i = 0; i < colorMap->getNumPixelComps(); i++) { - if (colorMap->getDecodeLow(i) != 0.0 || colorMap->getDecodeHigh(i) != 1.0) - return false; - } - return true; -} - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 11, 2) -static cairo_status_t setMimeIdFromRef(cairo_surface_t *surface, - const char *mime_type, - const char *mime_id_prefix, - Ref ref) -{ - GooString *mime_id; - char *idBuffer; - cairo_status_t status; - - mime_id = new GooString; - - if (mime_id_prefix) - mime_id->append(mime_id_prefix); - - mime_id->appendf("{0:d}-{1:d}", ref.gen, ref.num); - - idBuffer = copyString(mime_id->c_str()); - status = cairo_surface_set_mime_data (surface, mime_type, - (const unsigned char *)idBuffer, - mime_id->getLength(), - gfree, idBuffer); - delete mime_id; - if (status) - gfree (idBuffer); - return status; -} -#endif - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) -bool CairoOutputDev::setMimeDataForJBIG2Globals(Stream *str, - cairo_surface_t *image) -{ - JBIG2Stream *jb2Str = static_cast(str); - Object* globalsStr = jb2Str->getGlobalsStream(); - char *globalsBuffer; - int globalsLength; - - // nothing to do for JBIG2 stream without Globals - if (!globalsStr->isStream()) - return true; - - if (setMimeIdFromRef(image, CAIRO_MIME_TYPE_JBIG2_GLOBAL_ID, nullptr, - jb2Str->getGlobalsStreamRef())) - return false; - - if (!getStreamData(globalsStr->getStream(), &globalsBuffer, &globalsLength)) - return false; - - if (cairo_surface_set_mime_data (image, CAIRO_MIME_TYPE_JBIG2_GLOBAL, - (const unsigned char*)globalsBuffer, - globalsLength, - gfree, (void*)globalsBuffer)) - { - gfree (globalsBuffer); - return false; - } - - return true; -} -#endif - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 10) -bool CairoOutputDev::setMimeDataForCCITTParams(Stream *str, - cairo_surface_t *image, int height) -{ - CCITTFaxStream *ccittStr = static_cast(str); - - GooString params; - params.appendf("Columns={0:d}", ccittStr->getColumns()); - params.appendf(" Rows={0:d}", height); - params.appendf(" K={0:d}", ccittStr->getEncoding()); - params.appendf(" EndOfLine={0:d}", ccittStr->getEndOfLine() ? 1 : 0); - params.appendf(" EncodedByteAlign={0:d}", ccittStr->getEncodedByteAlign() ? 1 : 0); - params.appendf(" EndOfBlock={0:d}", ccittStr->getEndOfBlock() ? 1 : 0); - params.appendf(" BlackIs1={0:d}", ccittStr->getBlackIs1() ? 1 : 0); - params.appendf(" DamagedRowsBeforeError={0:d}", ccittStr->getDamagedRowsBeforeError()); - - char *p = strdup(params.c_str()); - if (cairo_surface_set_mime_data (image, CAIRO_MIME_TYPE_CCITT_FAX_PARAMS, - (const unsigned char*)p, - params.getLength(), - gfree, (void*)p)) - { - gfree (p); - return false; - } - - return true; -} -#endif - -void CairoOutputDev::setMimeData(GfxState *state, Stream *str, Object *ref, - GfxImageColorMap *colorMap, cairo_surface_t *image, int height) -{ - char *strBuffer; - int len; - Object obj; - GfxColorSpace *colorSpace; - StreamKind strKind = str->getKind(); - const char *mime_type; - - if (!printing) - return; - - switch (strKind) { - case strDCT: - mime_type = CAIRO_MIME_TYPE_JPEG; - break; - case strJPX: - mime_type = CAIRO_MIME_TYPE_JP2; - break; -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) - case strJBIG2: - mime_type = CAIRO_MIME_TYPE_JBIG2; - break; -#endif -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 10) - case strCCITTFax: - mime_type = CAIRO_MIME_TYPE_CCITT_FAX; - break; -#endif - default: - return; - } - - obj = str->getDict()->lookup("ColorSpace"); - colorSpace = GfxColorSpace::parse(nullptr, &obj, this, state); - - // colorspace in stream dict may be different from colorspace in jpx - // data - if (strKind == strJPX && colorSpace) - return; - - // only embed mime data for gray, rgb, and cmyk colorspaces. - if (colorSpace) { - GfxColorSpaceMode mode = colorSpace->getMode(); - delete colorSpace; - switch (mode) { - case csDeviceGray: - case csCalGray: - case csDeviceRGB: - case csCalRGB: - case csDeviceCMYK: - case csICCBased: - break; - - case csLab: - case csIndexed: - case csSeparation: - case csDeviceN: - case csPattern: - return; - } - } - - if (!colorMapHasIdentityDecodeMap(colorMap)) - return; - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) - if (strKind == strJBIG2 && !setMimeDataForJBIG2Globals(str, image)) - return; -#endif - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 10) - if (strKind == strCCITTFax && !setMimeDataForCCITTParams(str, image, height)) - return; -#endif - - if (getStreamData (str->getNextStream(), &strBuffer, &len)) { - cairo_status_t status = CAIRO_STATUS_SUCCESS; - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 11, 2) - // Since 1.5.10 the cairo PS backend stores images with UNIQUE_ID in PS memory so the - // image can be re-used multiple times. As we don't know how large the images are or - // how many times they are used, there is no benefit in enabling this. Issue #106 - if (cairo_surface_get_type (cairo_get_target (cairo)) != CAIRO_SURFACE_TYPE_PS) { - if (ref && ref->isRef()) { - status = setMimeIdFromRef(image, CAIRO_MIME_TYPE_UNIQUE_ID, - "poppler-surface-", ref->getRef()); - } - } -#endif - if (!status) { - status = cairo_surface_set_mime_data (image, mime_type, - (const unsigned char *)strBuffer, len, - gfree, strBuffer); - } - - if (status) - gfree (strBuffer); - } -} - -class RescaleDrawImage : public CairoRescaleBox { -private: - ImageStream *imgStr; - GfxRGB *lookup; - int width; - GfxImageColorMap *colorMap; - int *maskColors; - int current_row; - bool imageError; - -public: - cairo_surface_t *getSourceImage(Stream *str, - int widthA, int height, - int scaledWidth, int scaledHeight, - bool printing, - GfxImageColorMap *colorMapA, - int *maskColorsA) { - cairo_surface_t *image = nullptr; - int i; - - lookup = nullptr; - colorMap = colorMapA; - maskColors = maskColorsA; - width = widthA; - current_row = -1; - imageError = false; - - /* TODO: Do we want to cache these? */ - imgStr = new ImageStream(str, width, - colorMap->getNumPixelComps(), - colorMap->getBits()); - imgStr->reset(); - -#if 0 - /* ICCBased color space doesn't do any color correction - * so check its underlying color space as well */ - int is_identity_transform; - is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || - (colorMap->getColorSpace()->getMode() == csICCBased && - ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); -#endif - - // special case for one-channel (monochrome/gray/separation) images: - // build a lookup table here - if (colorMap->getNumPixelComps() == 1) { - int n; - unsigned char pix; - - n = 1 << colorMap->getBits(); - lookup = (GfxRGB *)gmallocn(n, sizeof(GfxRGB)); - for (i = 0; i < n; ++i) { - pix = (unsigned char)i; - - colorMap->getRGB(&pix, &lookup[i]); - } - } - -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) - bool needsCustomDownscaling = false; -#else - bool needsCustomDownscaling = true; -#endif - - if (printing) { - if (width > MAX_PRINT_IMAGE_SIZE || height > MAX_PRINT_IMAGE_SIZE) { - if (width > height) { - scaledWidth = MAX_PRINT_IMAGE_SIZE; - scaledHeight = MAX_PRINT_IMAGE_SIZE * (double)height/width; - } else { - scaledHeight = MAX_PRINT_IMAGE_SIZE; - scaledWidth = MAX_PRINT_IMAGE_SIZE * (double)width/height; - } - needsCustomDownscaling = true; - - if (scaledWidth == 0) { - scaledWidth = 1; - } - if (scaledHeight == 0) { - scaledHeight = 1; - } - } else { - needsCustomDownscaling = false; - } - } - - if (!needsCustomDownscaling || scaledWidth >= width || scaledHeight >= height) { - // No downscaling. Create cairo image containing the source image data. - unsigned char *buffer; - ptrdiff_t stride; - - image = cairo_image_surface_create (maskColors ? - CAIRO_FORMAT_ARGB32 : - CAIRO_FORMAT_RGB24, - width, height); - if (cairo_surface_status (image)) - goto cleanup; - - buffer = cairo_image_surface_get_data (image); - stride = cairo_image_surface_get_stride (image); - for (int y = 0; y < height; y++) { - uint32_t *dest = reinterpret_cast(buffer + y * stride); - getRow(y, dest); - } - } else { - // // Downscaling required. Create cairo image the size of the - // rescaled image and // downscale the source image data into - // the cairo image. downScaleImage() will call getRow() to read - // source image data from the image stream. This avoids having - // to create an image the size of the source image which may - // exceed cairo's 32676x32767 image size limit (and also saves a - // lot of memory). - image = cairo_image_surface_create (maskColors ? - CAIRO_FORMAT_ARGB32 : - CAIRO_FORMAT_RGB24, - scaledWidth, scaledHeight); - if (cairo_surface_status (image)) - goto cleanup; - - downScaleImage(width, height, - scaledWidth, scaledHeight, - 0, 0, scaledWidth, scaledHeight, - image); - } - cairo_surface_mark_dirty (image); - - cleanup: - gfree(lookup); - imgStr->close(); - delete imgStr; - return image; - } - - void getRow(int row_num, uint32_t *row_data) override { - unsigned char *pix; - - if (row_num <= current_row) - return; - - while (current_row < row_num) { - pix = imgStr->getLine(); - current_row++; - } - - if (unlikely(pix == nullptr)) { - memset(row_data, 0, width*4); - if (!imageError) { - error(errInternal, -1, "Bad image stream"); - imageError = true; - } - } else if (lookup) { - unsigned char *p = pix; - GfxRGB rgb; - - for (int i = 0; i < width; i++) { - rgb = lookup[*p]; - row_data[i] = - ((int) colToByte(rgb.r) << 16) | - ((int) colToByte(rgb.g) << 8) | - ((int) colToByte(rgb.b) << 0); - p++; - } - } else { - colorMap->getRGBLine (pix, row_data, width); - } - - if (maskColors) { - for (int x = 0; x < width; x++) { - bool is_opaque = false; - for (int i = 0; i < colorMap->getNumPixelComps(); ++i) { - if (pix[i] < maskColors[2*i] || - pix[i] > maskColors[2*i+1]) { - is_opaque = true; - break; - } - } - if (is_opaque) - *row_data |= 0xff000000; - else - *row_data = 0; - row_data++; - pix += colorMap->getNumPixelComps(); - } - } - } - -}; - -void CairoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, - int widthA, int heightA, - GfxImageColorMap *colorMap, - bool interpolate, - int *maskColors, bool inlineImg) -{ - cairo_surface_t *image; - cairo_pattern_t *pattern, *maskPattern; - cairo_matrix_t matrix; - int width, height; - int scaledWidth, scaledHeight; - cairo_filter_t filter = CAIRO_FILTER_GOOD; - RescaleDrawImage rescale; - - LOG (printf ("drawImage %dx%d\n", widthA, heightA)); - - cairo_get_matrix(cairo, &matrix); - getScaledSize (&matrix, widthA, heightA, &scaledWidth, &scaledHeight); - image = rescale.getSourceImage(str, widthA, heightA, scaledWidth, scaledHeight, printing, colorMap, maskColors); - if (!image) - return; - - width = cairo_image_surface_get_width (image); - height = cairo_image_surface_get_height (image); - if (width == widthA && height == heightA) - filter = getFilterForSurface (image, interpolate); - - if (!inlineImg) { /* don't read stream twice if it is an inline image */ - // cairo 1.15.10 allows mime image data to have different size to cairo image - // mime image size will be scaled to same size as cairo image -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 10) - bool requireSameSize = false; -#else - bool requireSameSize = true; -#endif - if (!requireSameSize || (width == widthA && height == heightA)) - setMimeData(state, str, ref, colorMap, image, heightA); - } - - pattern = cairo_pattern_create_for_surface (image); - cairo_surface_destroy (image); - if (cairo_pattern_status (pattern)) - return; - - cairo_pattern_set_filter (pattern, filter); - - if (!printing) - cairo_pattern_set_extend (pattern, CAIRO_EXTEND_PAD); - - cairo_matrix_init_translate (&matrix, 0, height); - cairo_matrix_scale (&matrix, width, -height); - cairo_pattern_set_matrix (pattern, &matrix); - if (cairo_pattern_status (pattern)) { - cairo_pattern_destroy (pattern); - return; - } - - if (!mask && fill_opacity != 1.0) { - maskPattern = cairo_pattern_create_rgba (1., 1., 1., fill_opacity); - } else if (mask) { - maskPattern = cairo_pattern_reference (mask); - } else { - maskPattern = nullptr; - } - - cairo_save (cairo); - cairo_set_source (cairo, pattern); - if (!printing) - cairo_rectangle (cairo, 0., 0., 1., 1.); - if (maskPattern) { - if (!printing) - cairo_clip (cairo); - if (mask) - cairo_set_matrix (cairo, &mask_matrix); - cairo_mask (cairo, maskPattern); - } else { - if (printing) - cairo_paint (cairo); - else - cairo_fill (cairo); - } - cairo_restore (cairo); - - cairo_pattern_destroy (maskPattern); - - if (cairo_shape) { - cairo_save (cairo_shape); - cairo_set_source (cairo_shape, pattern); - if (printing) { - cairo_paint (cairo_shape); - } else { - cairo_rectangle (cairo_shape, 0., 0., 1., 1.); - cairo_fill (cairo_shape); - } - cairo_restore (cairo_shape); - } - - cairo_pattern_destroy (pattern); -} - - -//------------------------------------------------------------------------ -// ImageOutputDev -//------------------------------------------------------------------------ - -CairoImageOutputDev::CairoImageOutputDev() -{ - images = nullptr; - numImages = 0; - size = 0; - imgDrawCbk = nullptr; - imgDrawCbkData = nullptr; -} - -CairoImageOutputDev::~CairoImageOutputDev() -{ - int i; - - for (i = 0; i < numImages; i++) - delete images[i]; - gfree (images); -} - -void CairoImageOutputDev::saveImage(CairoImage *image) -{ - if (numImages >= size) { - size += 16; - images = (CairoImage **) greallocn (images, size, sizeof (CairoImage *)); - } - images[numImages++] = image; -} - -void CairoImageOutputDev::getBBox(GfxState *state, int width, int height, - double *x1, double *y1, double *x2, double *y2) -{ - const double *ctm = state->getCTM(); - cairo_matrix_t matrix; - cairo_matrix_init(&matrix, - ctm[0], ctm[1], - -ctm[2], -ctm[3], - ctm[2] + ctm[4], ctm[3] + ctm[5]); - - int scaledWidth, scaledHeight; - getScaledSize (&matrix, width, height, &scaledWidth, &scaledHeight); - - if (matrix.xx >= 0) { - *x1 = matrix.x0; - } else { - *x1 = matrix.x0 - scaledWidth; - } - *x2 = *x1 + scaledWidth; - - if (matrix.yy >= 0) { - *y1 = matrix.y0; - } else { - *y1 = matrix.y0 - scaledHeight; - } - *y2 = *y1 + scaledHeight; -} - -void CairoImageOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool interpolate, bool inlineImg) -{ - cairo_t *cr; - cairo_surface_t *surface; - double x1, y1, x2, y2; - CairoImage *image; - - getBBox(state, width, height, &x1, &y1, &x2, &y2); - - image = new CairoImage (x1, y1, x2, y2); - saveImage (image); - - if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - setCairo (cr); - cairo_translate (cr, 0, height); - cairo_scale (cr, width, -height); - - CairoOutputDev::drawImageMask(state, ref, str, width, height, invert, interpolate, inlineImg); - image->setImage (surface); - - setCairo (nullptr); - cairo_surface_destroy (surface); - cairo_destroy (cr); - } -} - -void CairoImageOutputDev::setSoftMaskFromImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool inlineImg, double *baseMatrix) -{ - cairo_t *cr; - cairo_surface_t *surface; - double x1, y1, x2, y2; - CairoImage *image; - - getBBox(state, width, height, &x1, &y1, &x2, &y2); - - image = new CairoImage (x1, y1, x2, y2); - saveImage (image); - - if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - setCairo (cr); - cairo_translate (cr, 0, height); - cairo_scale (cr, width, -height); - - CairoOutputDev::drawImageMask(state, ref, str, width, height, invert, inlineImg, false); - if (state->getFillColorSpace()->getMode() == csPattern) { - cairo_mask (cairo, mask); - } - image->setImage (surface); - - setCairo (nullptr); - cairo_surface_destroy (surface); - cairo_destroy (cr); - } -} - -void CairoImageOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, - int width, int height, GfxImageColorMap *colorMap, - bool interpolate, int *maskColors, bool inlineImg) -{ - cairo_t *cr; - cairo_surface_t *surface; - double x1, y1, x2, y2; - CairoImage *image; - - getBBox(state, width, height, &x1, &y1, &x2, &y2); - - image = new CairoImage (x1, y1, x2, y2); - saveImage (image); - - if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - setCairo (cr); - cairo_translate (cr, 0, height); - cairo_scale (cr, width, -height); - - CairoOutputDev::drawImage(state, ref, str, width, height, colorMap, interpolate, maskColors, inlineImg); - image->setImage (surface); - - setCairo (nullptr); - cairo_surface_destroy (surface); - cairo_destroy (cr); - } -} - -void CairoImageOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - GfxImageColorMap *maskColorMap, - bool maskInterpolate) -{ - cairo_t *cr; - cairo_surface_t *surface; - double x1, y1, x2, y2; - CairoImage *image; - - getBBox(state, width, height, &x1, &y1, &x2, &y2); - - image = new CairoImage (x1, y1, x2, y2); - saveImage (image); - - if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - setCairo (cr); - cairo_translate (cr, 0, height); - cairo_scale (cr, width, -height); - - CairoOutputDev::drawSoftMaskedImage(state, ref, str, width, height, colorMap, interpolate, - maskStr, maskWidth, maskHeight, maskColorMap, maskInterpolate); - image->setImage (surface); - - setCairo (nullptr); - cairo_surface_destroy (surface); - cairo_destroy (cr); - } -} - -void CairoImageOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - bool maskInvert, bool maskInterpolate) -{ - cairo_t *cr; - cairo_surface_t *surface; - double x1, y1, x2, y2; - CairoImage *image; - - getBBox(state, width, height, &x1, &y1, &x2, &y2); - - image = new CairoImage (x1, y1, x2, y2); - saveImage (image); - - if (imgDrawCbk && imgDrawCbk (numImages - 1, imgDrawCbkData)) { - surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); - cr = cairo_create (surface); - setCairo (cr); - cairo_translate (cr, 0, height); - cairo_scale (cr, width, -height); - - CairoOutputDev::drawMaskedImage(state, ref, str, width, height, colorMap, interpolate, - maskStr, maskWidth, maskHeight, maskInvert, maskInterpolate); - image->setImage (surface); - - setCairo (nullptr); - cairo_surface_destroy (surface); - cairo_destroy (cr); - } -} diff --git a/3rdparty/poppler/git/CairoOutputDev.h b/3rdparty/poppler/git/CairoOutputDev.h deleted file mode 100644 index 0fbbf0d..0000000 --- a/3rdparty/poppler/git/CairoOutputDev.h +++ /dev/null @@ -1,525 +0,0 @@ -//======================================================================== -// -// CairoOutputDev.h -// -// Copyright 2003 Glyph & Cog, LLC -// Copyright 2004 Red Hat, INC -// -//======================================================================== - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2005-2008 Jeff Muizelaar -// Copyright (C) 2005, 2006 Kristian Høgsberg -// Copyright (C) 2005 Nickolay V. Shmyrev -// Copyright (C) 2006-2011, 2013 Carlos Garcia Campos -// Copyright (C) 2008, 2009, 2011-2017 Adrian Johnson -// Copyright (C) 2008 Michael Vrable -// Copyright (C) 2010-2013 Thomas Freitag -// Copyright (C) 2015 Suzuki Toshiya -// Copyright (C) 2016 Jason Crain -// Copyright (C) 2018, 2019 Albert Astals Cid -// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, . Work sponsored by the LiMux project of the city of Munich -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - -#ifndef CAIROOUTPUTDEV_H -#define CAIROOUTPUTDEV_H - -#include -#include "OutputDev.h" -#include "TextOutputDev.h" -#include "GfxState.h" - -class PDFDoc; -class GfxState; -class GfxPath; -class Gfx8BitFont; -struct GfxRGB; -class CairoFontEngine; -class CairoFont; - -//------------------------------------------------------------------------ - -//------------------------------------------------------------------------ -// CairoImage -//------------------------------------------------------------------------ -class CairoImage { -public: - // Constructor. - CairoImage (double x1, double y1, double x2, double y2); - - // Destructor. - ~CairoImage (); - - CairoImage(const CairoImage &) = delete; - CairoImage& operator=(const CairoImage &) = delete; - - // Set the image cairo surface - void setImage (cairo_surface_t *image); - - // Get the image cairo surface - cairo_surface_t *getImage () const { return image; } - - // Get the image rectangle - void getRect (double *xa1, double *ya1, double *xa2, double *ya2) - { *xa1 = x1; *ya1 = y1; *xa2 = x2; *ya2 = y2; } - -private: - cairo_surface_t *image; // image cairo surface - double x1, y1; // upper left corner - double x2, y2; // lower right corner -}; - - -//------------------------------------------------------------------------ -// CairoOutputDev -//------------------------------------------------------------------------ - -class CairoOutputDev: public OutputDev { -public: - - // Constructor. - CairoOutputDev(); - - // Destructor. - virtual ~CairoOutputDev(); - - //----- get info about output device - - // Does this device use upside-down coordinates? - // (Upside-down means (0,0) is the top left corner of the page.) - bool upsideDown() override { return true; } - - // Does this device use drawChar() or drawString()? - bool useDrawChar() override { return true; } - - // Does this device use tilingPatternFill()? If this returns false, - // tiling pattern fills will be reduced to a series of other drawing - // operations. - bool useTilingPatternFill() override { return true; } - - // Does this device use functionShadedFill(), axialShadedFill(), and - // radialShadedFill()? If this returns false, these shaded fills - // will be reduced to a series of other drawing operations. -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) - bool useShadedFills(int type) override { return type <= 7; } -#else - bool useShadedFills(int type) override { return type > 1 && type < 4; } -#endif - - // Does this device use FillColorStop()? - bool useFillColorStop() override { return true; } - - // Does this device use beginType3Char/endType3Char? Otherwise, - // text in Type 3 fonts will be drawn with drawChar/drawString. - bool interpretType3Chars() override { return false; } - - // Does this device need to clip pages to the crop box even when the - // box is the crop box? - bool needClipToCropBox() override { return true; } - - //----- initialization and control - - // Start a page. - void startPage(int pageNum, GfxState *state, XRef *xref) override; - - // End a page. - void endPage() override; - - //----- save/restore graphics state - void saveState(GfxState *state) override; - void restoreState(GfxState *state) override; - - //----- update graphics state - void updateAll(GfxState *state) override; - void setDefaultCTM(const double *ctm) override; - void updateCTM(GfxState *state, double m11, double m12, - double m21, double m22, double m31, double m32) override; - void updateLineDash(GfxState *state) override; - void updateFlatness(GfxState *state) override; - void updateLineJoin(GfxState *state) override; - void updateLineCap(GfxState *state) override; - void updateMiterLimit(GfxState *state) override; - void updateLineWidth(GfxState *state) override; - void updateFillColor(GfxState *state) override; - void updateStrokeColor(GfxState *state) override; - void updateFillOpacity(GfxState *state) override; - void updateStrokeOpacity(GfxState *state) override; - void updateFillColorStop(GfxState *state, double offset) override; - void updateBlendMode(GfxState *state) override; - - //----- update text state - void updateFont(GfxState *state) override; - - //----- path painting - void stroke(GfxState *state) override; - void fill(GfxState *state) override; - void eoFill(GfxState *state) override; - void clipToStrokePath(GfxState *state) override; - bool tilingPatternFill(GfxState *state, Gfx *gfx, Catalog *cat, Object *str, - const double *pmat, int paintType, int tilingType, Dict *resDict, - const double *mat, const double *bbox, - int x0, int y0, int x1, int y1, - double xStep, double yStep) override; -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) - bool functionShadedFill(GfxState *state, GfxFunctionShading *shading) override; -#endif - bool axialShadedFill(GfxState *state, GfxAxialShading *shading, double tMin, double tMax) override; - bool axialShadedSupportExtend(GfxState *state, GfxAxialShading *shading) override; - bool radialShadedFill(GfxState *state, GfxRadialShading *shading, double sMin, double sMax) override; - bool radialShadedSupportExtend(GfxState *state, GfxRadialShading *shading) override; -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 12, 0) - bool gouraudTriangleShadedFill(GfxState *state, GfxGouraudTriangleShading *shading) override; - bool patchMeshShadedFill(GfxState *state, GfxPatchMeshShading *shading) override; -#endif - - //----- path clipping - void clip(GfxState *state) override; - void eoClip(GfxState *state) override; - - //----- text drawing - void beginString(GfxState *state, const GooString *s) override; - void endString(GfxState *state) override; - void drawChar(GfxState *state, double x, double y, - double dx, double dy, - double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen) override; - void beginActualText(GfxState *state, const GooString *text) override; - void endActualText(GfxState *state) override; - - bool beginType3Char(GfxState *state, double x, double y, - double dx, double dy, - CharCode code, Unicode *u, int uLen) override; - void endType3Char(GfxState *state) override; - void beginTextObject(GfxState *state) override; - void endTextObject(GfxState *state) override; - - //----- image drawing - void drawImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, bool interpolate, - bool inlineImg) override; - void setSoftMaskFromImageMask(GfxState *state, - Object *ref, Stream *str, - int width, int height, bool invert, - bool inlineImg, double *baseMatrix) override; - void unsetSoftMaskFromImageMask(GfxState *state, double *baseMatrix) override; - void drawImageMaskPrescaled(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, bool interpolate, - bool inlineImg); - void drawImageMaskRegular(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, bool interpolate, - bool inlineImg); - - void drawImage(GfxState *state, Object *ref, Stream *str, - int width, int height, GfxImageColorMap *colorMap, - bool interpolate, int *maskColors, bool inlineImg) override; - void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - GfxImageColorMap *maskColorMap, - bool maskInterpolate) override; - - void drawMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - bool maskInvert, bool maskInterpolate) override; - - //----- transparency groups and soft masks - void beginTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/, - GfxColorSpace * /*blendingColorSpace*/, - bool /*isolated*/, bool /*knockout*/, - bool /*forSoftMask*/) override; - void endTransparencyGroup(GfxState * /*state*/) override; - void popTransparencyGroup(); - void paintTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/) override; - void setSoftMask(GfxState * /*state*/, const double * /*bbox*/, bool /*alpha*/, - Function * /*transferFunc*/, GfxColor * /*backdropColor*/) override; - void clearSoftMask(GfxState * /*state*/) override; - - //----- Type 3 font operators - void type3D0(GfxState *state, double wx, double wy) override; - void type3D1(GfxState *state, double wx, double wy, - double llx, double lly, double urx, double ury) override; - - //----- special access - - // Called to indicate that a new PDF document has been loaded. - void startDoc(PDFDoc *docA, CairoFontEngine *fontEngine = nullptr); - - bool isReverseVideo() { return false; } - - void setCairo (cairo_t *cr); - void setTextPage (TextPage *text); - void setPrinting (bool printingA) { printing = printingA; needFontUpdate = true; } - void setAntialias(cairo_antialias_t antialias); - - void setInType3Char(bool inType3CharA) { inType3Char = inType3CharA; } - void getType3GlyphWidth (double *wx, double *wy) { *wx = t3_glyph_wx; *wy = t3_glyph_wy; } - bool hasType3GlyphBBox () { return t3_glyph_has_bbox; } - double *getType3GlyphBBox () { return t3_glyph_bbox; } - -protected: - void doPath(cairo_t *cairo, GfxState *state, GfxPath *path); - cairo_surface_t *downscaleSurface(cairo_surface_t *orig_surface); - void getScaledSize(const cairo_matrix_t *matrix, - int orig_width, int orig_height, - int *scaledWidth, int *scaledHeight); - cairo_filter_t getFilterForSurface(cairo_surface_t *image, - bool interpolate); - bool getStreamData (Stream *str, char **buffer, int *length); - void setMimeData(GfxState *state, Stream *str, Object *ref, - GfxImageColorMap *colorMap, cairo_surface_t *image, int height); - void fillToStrokePathClip(GfxState *state); - void alignStrokeCoords(GfxSubpath *subpath, int i, double *x, double *y); -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 14, 0) - bool setMimeDataForJBIG2Globals (Stream *str, cairo_surface_t *image); -#endif -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 15, 10) - bool setMimeDataForCCITTParams(Stream *str, cairo_surface_t *image, int height); -#endif - static void setContextAntialias(cairo_t *cr, cairo_antialias_t antialias); - - GfxRGB fill_color, stroke_color; - cairo_pattern_t *fill_pattern, *stroke_pattern; - double fill_opacity; - double stroke_opacity; - bool stroke_adjust; - bool adjusted_stroke_width; - bool align_stroke_coords; - CairoFont *currentFont; - XRef *xref; - - struct StrokePathClip { - GfxPath *path; - cairo_matrix_t ctm; - double line_width; - double *dashes; - int dash_count; - double dash_offset; - cairo_line_cap_t cap; - cairo_line_join_t join; - double miter; - int ref_count; - } *strokePathClip; - - PDFDoc *doc; // the current document - - static FT_Library ft_lib; - static bool ft_lib_initialized; - - CairoFontEngine *fontEngine; - bool fontEngine_owner; - - cairo_t *cairo; - cairo_matrix_t orig_matrix; - bool needFontUpdate; // set when the font needs to be updated - bool printing; - bool use_show_text_glyphs; - bool text_matrix_valid; - cairo_glyph_t *glyphs; - int glyphCount; - cairo_text_cluster_t *clusters; - int clusterCount; - char *utf8; - int utf8Count; - int utf8Max; - cairo_path_t *textClipPath; - bool inUncoloredPattern; // inside a uncolored pattern (PaintType = 2) - bool inType3Char; // inside a Type 3 CharProc - double t3_glyph_wx, t3_glyph_wy; - bool t3_glyph_has_bbox; - double t3_glyph_bbox[4]; - cairo_antialias_t antialias; - bool prescaleImages; - - TextPage *textPage; // text for the current page - ActualText *actualText; - - cairo_pattern_t *group; - cairo_pattern_t *shape; - cairo_pattern_t *mask; - cairo_matrix_t mask_matrix; - cairo_t *cairo_shape; - int knockoutCount; - struct ColorSpaceStack { - bool knockout; - GfxColorSpace *cs; - cairo_matrix_t group_matrix; - struct ColorSpaceStack *next; - } * groupColorSpaceStack; - - struct MaskStack { - cairo_pattern_t *mask; - cairo_matrix_t mask_matrix; - struct MaskStack *next; - } *maskStack; - -}; - -//------------------------------------------------------------------------ -// CairoImageOutputDev -//------------------------------------------------------------------------ - -//XXX: this should ideally not inherit from CairoOutputDev but use it instead perhaps -class CairoImageOutputDev: public CairoOutputDev { -public: - - // Constructor. - CairoImageOutputDev(); - - // Destructor. - virtual ~CairoImageOutputDev(); - - //----- get info about output device - - // Does this device use upside-down coordinates? - // (Upside-down means (0,0) is the top left corner of the page.) - bool upsideDown() override { return true; } - - // Does this device use drawChar() or drawString()? - bool useDrawChar() override { return false; } - - // Does this device use tilingPatternFill()? If this returns false, - // tiling pattern fills will be reduced to a series of other drawing - // operations. - bool useTilingPatternFill() override { return true; } - - // Does this device use functionShadedFill(), axialShadedFill(), and - // radialShadedFill()? If this returns false, these shaded fills - // will be reduced to a series of other drawing operations. -#if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 11, 2) - bool useShadedFills(int type) override { return type <= 7; } -#else - bool useShadedFills(int type) override { return type < 4; } -#endif - - // Does this device use FillColorStop()? - bool useFillColorStop() override { return false; } - - // Does this device use beginType3Char/endType3Char? Otherwise, - // text in Type 3 fonts will be drawn with drawChar/drawString. - bool interpretType3Chars() override { return false; } - - // Does this device need non-text content? - bool needNonText() override { return true; } - - //----- save/restore graphics state - void saveState(GfxState *state) override { } - void restoreState(GfxState *state) override { } - - //----- update graphics state - void updateAll(GfxState *state) override { } - void setDefaultCTM(const double *ctm) override { } - void updateCTM(GfxState *state, double m11, double m12, - double m21, double m22, double m31, double m32) override { } - void updateLineDash(GfxState *state) override { } - void updateFlatness(GfxState *state) override { } - void updateLineJoin(GfxState *state) override { } - void updateLineCap(GfxState *state) override { } - void updateMiterLimit(GfxState *state) override { } - void updateLineWidth(GfxState *state) override { } - void updateFillColor(GfxState *state) override { } - void updateStrokeColor(GfxState *state) override { } - void updateFillOpacity(GfxState *state) override { } - void updateStrokeOpacity(GfxState *state) override { } - void updateBlendMode(GfxState *state) override { } - - //----- update text state - void updateFont(GfxState *state) override { } - - //----- path painting - void stroke(GfxState *state) override { } - void fill(GfxState *state) override { } - void eoFill(GfxState *state) override { } - void clipToStrokePath(GfxState *state) override { } - bool tilingPatternFill(GfxState *state, Gfx *gfx, Catalog *cat, Object *str, - const double *pmat, int paintType, int tilingType, Dict *resDict, - const double *mat, const double *bbox, - int x0, int y0, int x1, int y1, - double xStep, double yStep) override { return true; } - bool axialShadedFill(GfxState *state, - GfxAxialShading *shading, - double tMin, double tMax) override { return true; } - bool radialShadedFill(GfxState *state, - GfxRadialShading *shading, - double sMin, double sMax) override { return true; } - - //----- path clipping - void clip(GfxState *state) override { } - void eoClip(GfxState *state) override { } - - //----- image drawing - void drawImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool interpolate, bool inlineImg) override; - void drawImage(GfxState *state, Object *ref, Stream *str, - int width, int height, GfxImageColorMap *colorMap, - bool interpolate, int *maskColors, bool inlineImg) override; - void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - GfxImageColorMap *maskColorMap, - bool maskInterpolate) override; - void drawMaskedImage(GfxState *state, Object *ref, Stream *str, - int width, int height, - GfxImageColorMap *colorMap, - bool interpolate, - Stream *maskStr, - int maskWidth, int maskHeight, - bool maskInvert, bool maskInterpolate) override; - void setSoftMaskFromImageMask(GfxState *state, Object *ref, Stream *str, - int width, int height, bool invert, - bool inlineImg, double *baseMatrix) override; - void unsetSoftMaskFromImageMask(GfxState *state, double *baseMatrix) override {} - - - //----- transparency groups and soft masks - void beginTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/, - GfxColorSpace * /*blendingColorSpace*/, - bool /*isolated*/, bool /*knockout*/, - bool /*forSoftMask*/) override {} - void endTransparencyGroup(GfxState * /*state*/) override {} - void paintTransparencyGroup(GfxState * /*state*/, const double * /*bbox*/) override {} - void setSoftMask(GfxState * /*state*/, const double * /*bbox*/, bool /*alpha*/, - Function * /*transferFunc*/, GfxColor * /*backdropColor*/) override {} - void clearSoftMask(GfxState * /*state*/) override {} - - //----- Image list - // By default images are not rendred - void setImageDrawDecideCbk(bool (*cbk)(int img_id, void *data), - void *data) { imgDrawCbk = cbk; imgDrawCbkData = data; } - // Iterate through list of images. - int getNumImages() const { return numImages; } - CairoImage *getImage(int i) const { return images[i]; } - -private: - void saveImage(CairoImage *image); - void getBBox(GfxState *state, int width, int height, - double *x1, double *y1, double *x2, double *y2); - - CairoImage **images; - int numImages; - int size; - bool (*imgDrawCbk)(int img_id, void *data); - void *imgDrawCbkData; -}; - -#endif diff --git a/3rdparty/poppler/git/CairoRescaleBox.cc b/3rdparty/poppler/git/CairoRescaleBox.cc deleted file mode 100644 index 2c0e1ed..0000000 --- a/3rdparty/poppler/git/CairoRescaleBox.cc +++ /dev/null @@ -1,379 +0,0 @@ -/* -*- Mode: c; c-basic-offset: 4; tab-width: 8; indent-tabs-mode: t; -*- */ -/* - * Copyright © 2009 Mozilla Corporation - * - * Permission to use, copy, modify, distribute, and sell this software and its - * documentation for any purpose is hereby granted without fee, provided that - * the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of Mozilla Corporation not be used in - * advertising or publicity pertaining to distribution of the software without - * specific, written prior permission. Mozilla Corporation makes no - * representations about the suitability of this software for any purpose. It - * is provided "as is" without express or implied warranty. - * - * MOZILLA CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT - * SHALL MOZILLA CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT OR - * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, - * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER - * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE - * OF THIS SOFTWARE. - * - * Author: Jeff Muizelaar, Mozilla Corp. - */ - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2012 Hib Eris -// Copyright (C) 2012, 2017 Adrian Johnson -// Copyright (C) 2018 Adam Reichold -// Copyright (C) 2019 Albert Astals Cid -// Copyright (C) 2019 Marek Kasik -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - - -/* This implements a box filter that supports non-integer box sizes */ - -#include - -#include -#include -#include -#include -#include -#include -#include "goo/gmem.h" -#include "CairoRescaleBox.h" - - -/* we work in fixed point where 1. == 1 << 24 */ -#define FIXED_SHIFT 24 - - -static void downsample_row_box_filter ( - int start, int width, - uint32_t *src, uint32_t *src_limit, uint32_t *dest, - int coverage[], int pixel_coverage) -{ - /* we need an array of the pixel contribution of each destination pixel on the boundaries. - * we invert the value to get the value on the other size of the box */ - /* - - value = a * contribution * 1/box_size - value += a * 1/box_size - value += a * 1/box_size - value += a * 1/box_size - value += a * (1 - contribution) * 1/box_size - a * (1/box_size - contribution * 1/box_size) - - box size is constant - - - value = a * contribution_a * 1/box_size + b * contribution_b * 1/box_size - contribution_b = (1 - contribution_a) - = (1 - contribution_a_next) - */ - - /* box size = ceil(src_width/dest_width) */ - int x = 0; - - /* skip to start */ - /* XXX: it might be possible to do this directly instead of iteratively, however - * the iterative solution is simple */ - while (x < start && src < src_limit) - { - int box = 1 << FIXED_SHIFT; - int start_coverage = coverage[x]; - box -= start_coverage; - src++; - while (box >= pixel_coverage && src < src_limit) - { - src++; - box -= pixel_coverage; - } - x++; - } - - while (x < start + width && src < src_limit) - { - uint32_t a = 0; - uint32_t r = 0; - uint32_t g = 0; - uint32_t b = 0; - int box = 1 << FIXED_SHIFT; - int start_coverage = coverage[x]; - - a = ((*src >> 24) & 0xff) * start_coverage; - r = ((*src >> 16) & 0xff) * start_coverage; - g = ((*src >> 8) & 0xff) * start_coverage; - b = ((*src >> 0) & 0xff) * start_coverage; - src++; - x++; - box -= start_coverage; - - while (box >= pixel_coverage && src < src_limit) - { - a += ((*src >> 24) & 0xff) * pixel_coverage; - r += ((*src >> 16) & 0xff) * pixel_coverage; - g += ((*src >> 8) & 0xff) * pixel_coverage; - b += ((*src >> 0) & 0xff) * pixel_coverage; - src++; - - box -= pixel_coverage; - } - - /* multiply by whatever is leftover - * this ensures that we don't bias down. - * i.e. start_coverage + n*pixel_coverage + box == 1 << 24 */ - if (box > 0 && src < src_limit) - { - a += ((*src >> 24) & 0xff) * box; - r += ((*src >> 16) & 0xff) * box; - g += ((*src >> 8) & 0xff) * box; - b += ((*src >> 0) & 0xff) * box; - } - - a >>= FIXED_SHIFT; - r >>= FIXED_SHIFT; - g >>= FIXED_SHIFT; - b >>= FIXED_SHIFT; - - *dest = (a << 24) | (r << 16) | (g << 8) | b; - dest++; - } -} - -static void downsample_columns_box_filter ( - int n, - int start_coverage, - int pixel_coverage, - uint32_t *src, uint32_t *dest) -{ - int stride = n; - while (n--) { - uint32_t a = 0; - uint32_t r = 0; - uint32_t g = 0; - uint32_t b = 0; - uint32_t *column_src = src; - int box = 1 << FIXED_SHIFT; - - a = ((*column_src >> 24) & 0xff) * start_coverage; - r = ((*column_src >> 16) & 0xff) * start_coverage; - g = ((*column_src >> 8) & 0xff) * start_coverage; - b = ((*column_src >> 0) & 0xff) * start_coverage; - column_src += stride; - box -= start_coverage; - - while (box >= pixel_coverage) - { - a += ((*column_src >> 24) & 0xff) * pixel_coverage; - r += ((*column_src >> 16) & 0xff) * pixel_coverage; - g += ((*column_src >> 8) & 0xff) * pixel_coverage; - b += ((*column_src >> 0) & 0xff) * pixel_coverage; - column_src += stride; - box -= pixel_coverage; - } - - if (box > 0) { - a += ((*column_src >> 24) & 0xff) * box; - r += ((*column_src >> 16) & 0xff) * box; - g += ((*column_src >> 8) & 0xff) * box; - b += ((*column_src >> 0) & 0xff) * box; - } - - a >>= FIXED_SHIFT; - r >>= FIXED_SHIFT; - g >>= FIXED_SHIFT; - b >>= FIXED_SHIFT; - - *dest = (a << 24) | (r << 16) | (g << 8) | b; - dest++; - src++; - } -} - -static int compute_coverage (int coverage[], int src_length, int dest_length) -{ - int i; - /* num = src_length/dest_length - total = sum(pixel) / num - - pixel * 1/num == pixel * dest_length / src_length - */ - /* the average contribution of each source pixel */ - int ratio = ((1 << 24)*(long long int)dest_length)/src_length; - /* because ((1 << 24)*(long long int)dest_length) won't always be divisible by src_length - * we'll need someplace to put the other bits. - * - * We want to ensure a + n*ratio < 1<<24 - * - * 1<<24 - * */ - - double scale = (double)src_length/dest_length; - - /* for each destination pixel compute the coverage of the left most pixel included in the box */ - /* I have a proof of this, which this margin is too narrow to contain */ - for (i=0; i= i*scale - - floor((i+1)*scale) - ceil(i*scale) <= scale - - further since: floor((i+1)*scale) - ceil(i*scale) is an integer - - therefore: - floor((i+1)*scale) - ceil(i*scale) <= floor(scale) - */ - - if (left_fract == 0.) - count--; - - /* compute how much the right-most pixel contributes */ - overage = ratio*(right_fract); - - /* the remainder is the amount that the left-most pixel - * contributes */ - coverage[i] = (1<<24) - (count * ratio + overage); - } - - return ratio; -} - - -bool CairoRescaleBox::downScaleImage(unsigned orig_width, unsigned orig_height, - signed scaled_width, signed scaled_height, - unsigned short int start_column, unsigned short int start_row, - unsigned short int width, unsigned short int height, - cairo_surface_t *dest_surface) { - int pixel_coverage_x, pixel_coverage_y; - int dest_y; - int src_y = 0; - uint32_t *scanline; - int *x_coverage = nullptr; - int *y_coverage = nullptr; - uint32_t *temp_buf = nullptr; - bool retval = false; - unsigned int *dest; - int dst_stride; - - dest = reinterpret_cast(cairo_image_surface_get_data (dest_surface)); - dst_stride = cairo_image_surface_get_stride (dest_surface); - - scanline = (uint32_t*)gmallocn (orig_width, sizeof(int)); - - x_coverage = (int *)gmallocn (orig_width, sizeof(int)); - y_coverage = (int *)gmallocn (orig_height, sizeof(int)); - - /* we need to allocate enough room for ceil(src_height/dest_height)+1 - Example: - src_height = 140 - dest_height = 50 - src_height/dest_height = 2.8 - - |-------------| 2.8 pixels - |----|----|----|----| 4 pixels - need to sample 3 pixels - - |-------------| 2.8 pixels - |----|----|----|----| 4 pixels - need to sample 4 pixels - */ - - temp_buf = (uint32_t *)gmallocn3 ((orig_height + scaled_height-1)/scaled_height+1, scaled_width, sizeof(uint32_t)); - - if (!x_coverage || !y_coverage || !scanline || !temp_buf) - goto cleanup; - - pixel_coverage_x = compute_coverage (x_coverage, orig_width, scaled_width); - pixel_coverage_y = compute_coverage (y_coverage, orig_height, scaled_height); - - assert (width + start_column <= scaled_width); - - - - /* skip the rows at the beginning */ - for (dest_y = 0; dest_y < start_row; dest_y++) - { - int box = 1 << FIXED_SHIFT; - int start_coverage_y = y_coverage[dest_y]; - box -= start_coverage_y; - src_y++; - while (box >= pixel_coverage_y) - { - box -= pixel_coverage_y; - src_y++; - } - } - - for (; dest_y < start_row + height; dest_y++) - { - int columns = 0; - int box = 1 << FIXED_SHIFT; - int start_coverage_y = y_coverage[dest_y]; - - getRow(src_y, scanline); - downsample_row_box_filter (start_column, width, scanline, scanline + orig_width, temp_buf + width * columns, x_coverage, pixel_coverage_x); - columns++; - src_y++; - box -= start_coverage_y; - - while (box >= pixel_coverage_y) - { - getRow(src_y, scanline); - downsample_row_box_filter (start_column, width, scanline, scanline + orig_width, temp_buf + width * columns, x_coverage, pixel_coverage_x); - columns++; - src_y++; - box -= pixel_coverage_y; - } - - /* downsample any leftovers */ - if (box > 0) - { - getRow(src_y, scanline); - downsample_row_box_filter (start_column, width, scanline, scanline + orig_width, temp_buf + width * columns, x_coverage, pixel_coverage_x); - columns++; - } - - /* now scale the rows we just downsampled in the y direction */ - downsample_columns_box_filter (width, start_coverage_y, pixel_coverage_y, temp_buf, dest); - dest += dst_stride / 4; - -// assert(width*columns <= ((orig_height + scaled_height-1)/scaled_height+1) * width); - } -// assert (src_y<=orig_height); - - retval = true; - -cleanup: - free (x_coverage); - free (y_coverage); - free (temp_buf); - free (scanline); - - return retval; -} diff --git a/3rdparty/poppler/git/CairoRescaleBox.h b/3rdparty/poppler/git/CairoRescaleBox.h deleted file mode 100644 index b00ad6a..0000000 --- a/3rdparty/poppler/git/CairoRescaleBox.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2009 Mozilla Corporation - * - * Permission to use, copy, modify, distribute, and sell this software and its - * documentation for any purpose is hereby granted without fee, provided that - * the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of Mozilla Corporation not be used in - * advertising or publicity pertaining to distribution of the software without - * specific, written prior permission. Mozilla Corporation makes no - * representations about the suitability of this software for any purpose. It - * is provided "as is" without express or implied warranty. - * - * MOZILLA CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT - * SHALL MOZILLA CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT OR - * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, - * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER - * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE - * OF THIS SOFTWARE. - * - * Author: Jeff Muizelaar, Mozilla Corp. - */ - -//======================================================================== -// -// Modified under the Poppler project - http://poppler.freedesktop.org -// -// All changes made under the Poppler project to this file are licensed -// under GPL version 2 or later -// -// Copyright (C) 2012 Adrian Johnson -// Copyright (C) 2018 Albert Astals Cid -// -// To see a description of the changes please see the Changelog file that -// came with your tarball or type make ChangeLog if you are building from git -// -//======================================================================== - -#ifndef CAIRO_RESCALE_BOX_H -#define CAIRO_RESCALE_BOX_H - -#include - -class CairoRescaleBox { -public: - - CairoRescaleBox() {}; - virtual ~CairoRescaleBox() {}; - - CairoRescaleBox(const CairoRescaleBox &) = delete; - CairoRescaleBox& operator=(const CairoRescaleBox &) = delete; - - virtual bool downScaleImage(unsigned orig_width, unsigned orig_height, - signed scaled_width, signed scaled_height, - unsigned short int start_column, unsigned short int start_row, - unsigned short int width, unsigned short int height, - cairo_surface_t *dest_surface); - - virtual void getRow(int row_num, uint32_t *row_data) = 0; - -}; - -#endif /* CAIRO_RESCALE_BOX_H */ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 72508e2..51159c6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,7 @@ A few channels are available to reach the developers, please find the most prope ### The Issue Tracker -The [Issue Tracker](https://github.com/coolwanglu/pdf2htmlEX/issues) +The [Issue Tracker](https://github.com/pdf2htmlEX/pdf2htmlEX/issues) is the best way for [bug reports](#bug-reports), [features requests](#feature-requests) @@ -54,7 +54,7 @@ However do not report issues or submit patches there, since it's terrible to kee pdf2htmlEX is mostly written and maintained by 王璐 (Lu Wang). His email and twitter account can be found in -[README.md](https://github.com/coolwanglu/pdf2htmlEX/blob/master/README.md). +[README.md](https://github.com/pdf2htmlEX/pdf2htmlEX/blob/master/README.md). Please post only messages that do not fit into the above channels, otherwise note that he no longer replies with _Please post your question to the mailing list_ or _Please file an issue at GitHub_, consider your message already replied. @@ -73,7 +73,7 @@ follow the following steps to get it resolved as fast as possible: First of all, did you realize that your question might have been already answered in one of the following places? -- [pdf2htmlEX Wiki](https://github.com/coolwanglu/pdf2htmlEX/wiki) +- [pdf2htmlEX Wiki](https://github.com/pdf2htmlEX/pdf2htmlEX/wiki) - The manpage (run `man pdf2htmlEX`) - Old posts in the [mailing list](#the-mailing-list) or the [issue tracker](#the-issue-tracker) - [Google](http://www.google.com/) @@ -93,7 +93,7 @@ Bugs should always be reported to [the Issue Tracker](#the-issue-tracker). Before you report any bug: - Use the latest git version of pdf2htmlEX, since the issue may have been already fixed. - Search for previous issues (open or closed), to make sure that the issue has not been reported before. -- If pdf2htmlEX crashed, take a look at [this article](https://github.com/coolwanglu/pdf2htmlEX/wiki/Troubleshooting-Crashes). +- If pdf2htmlEX crashed, take a look at [this article](https://github.com/pdf2htmlEX/pdf2htmlEX/wiki/Troubleshooting-Crashes). A good bug report shouldn't leave others needing to chase you up for more information. The developers may be very familiar with the code base of pdf2htmlEX, @@ -110,7 +110,7 @@ If you are not sure, please try to answer the following questions: - What steps will reproduce the issue? — please try to remove unnecessary steps - What's the result and what did you expect? — e.g. you can post screenshots - What error messages did you see? -- What's the affected PDF file and which pages are causing the issue? Create a pull request on [this repo](https://github.com/coolwanglu/pdf2htmlEX-testcase). +- What's the affected PDF file and which pages are causing the issue? Create a pull request on [this repo](https://github.com/pdf2htmlEX/pdf2htmlEX-testcase). Especially for issues regarding building pdf2htmlEX: - Which compiler are you using? diff --git a/INSTALL b/INSTALL index 64e4613..574e0a6 100644 --- a/INSTALL +++ b/INSTALL @@ -1,3 +1,3 @@ For instructions of building the source code, visit: -https://github.com/coolwanglu/pdf2htmlEX/wiki/Building +https://github.com/pdf2htmlEX/pdf2htmlEX/wiki/Building diff --git a/LICENSE b/LICENSE index 0665c92..1a196de 100644 --- a/LICENSE +++ b/LICENSE @@ -1,23 +1,25 @@ -pdf2htmlEX (https://github.com/coolwanglu/pdf2htmlEX) +pdf2htmlEX (https://github.com/pdf2htmlEX/pdf2htmlEX) Copyright (c) 2012-2014 Lu Wang and other contributors -pdf2htmlEX, as a whole package, is licensed under GPLv3 (or any later version). +pdf2htmlEX, as a whole package, is licensed under GPLv3 (or any later +version). -Files in share/ and logo/ are released under relaxed licenses, -read the respective `LICENSE` file in the folders for details. +Files in pdf2htmlEX/share/ pdf2htmlEX/logo/ and pdf2htmlEX/brewFormual are +released under relaxed licenses, read the respective `LICENSE` file in +these folders for details. ----- GPLv3 -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. +This program is free software: you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the Free +Software Foundation, either version 3 of the License, or (at your option) +any later version. -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +more details. -You should have received a copy of the GNU General Public License -along with this program. If not, see . +You should have received a copy of the GNU General Public License along +with this program. If not, see . diff --git a/README.md b/README.md index e86e656..c4bd168 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![Build Status](https://travis-ci.org/pdf2htmlEX/pdf2htmlEX.svg?branch=master)](https://travis-ci.org/pdf2htmlEX/pdf2htmlEX) -# Differences from upstream pdf2htmlEX: +# Differences from upstream pdf2htmlEX: This is my branch of pdf2htmlEX which aims to allow an open collaboration to help keep the project active. A number of changes and improvements have been incorperated from other forks: diff --git a/build_for_ppa.py b/archive/build_for_ppa.py similarity index 100% rename from build_for_ppa.py rename to archive/build_for_ppa.py diff --git a/archive/createDebianPackage b/archive/createDebianPackage new file mode 100755 index 0000000..7f5054c --- /dev/null +++ b/archive/createDebianPackage @@ -0,0 +1,178 @@ +#!/usr/bin/env python + +""" +Dirty script for building package for PPA +by WangLu +2011.01.13 + +modified for pdf2htmlEX +2012.08.28 + +modified for general git repo +2013.05.30 +""" + +# CONSIDER PORTING to either BASH or PERL (as used by dpkg-buldpackage) +# CONSIDER BINARY ONLY PACKAGE based on appDir or docerDir +# +# See: https://blog.serverdensity.com/how-to-create-a-debian-deb-package/ +# See: http://www.sj-vs.net/creating-a-simple-debian-deb-package-based-on-a-directory-structure/ +# See: https://unix.stackexchange.com/questions/30303/how-to-create-a-deb-file-manually +# See: https://askubuntu.com/questions/1130558/how-to-build-deb-package-for-ubuntu-18-04 +# See: https://blog.knoldus.com/create-a-debian-package-using-dpkg-deb-tool/ +# See: http://www.tldp.org/HOWTO/html_single/Debian-Binary-Package-Building-HOWTO/ +# See: https://coderwall.com/p/urkybq/how-to-create-debian-package-from-source +# +# NOTES: +# 1. Should use something to force update of changelog +# 2. How best to compute dpkg version +# 3. Distribute only binary package (no source package -- link to main github repo) +# 4. Use ppa: https://launchpad.net/~pdf2htmlex/+archive/ubuntu/pdf2htmlex +# 5. Rename poppler-data destination to poppler-pdf2htmlEX +# 6. Ensure source code location of poppler-data has been updated + +import os +import sys +import re +import time + +package='pdf2htmlex' +ppa_name='ppa:pdf2htmlex/pdf2htmlex' +supported_distributions=('disco',) +dist_pattern=re.compile('|'.join(['\\) '+i for i in supported_distributions])) +archive_cmd='cd pdf2htmlEX/build && (rm CMakeCache.txt || true) && cmake .. && make dist' +archive_suffix='.tar.bz2' + +#if os.path.exists('imageBuild/debianDir'): +# sys.stdout.write('Build area already exists, delete to continue?(y/n)') +# sys.stdout.flush() +# ans = raw_input().lower() +# while ans not in ['y', 'n']: +# sys.stdout.write('I don\'t understand, enter \'y\' or \'n\':') +# ans = raw_input().lower() +# +# if ans == 'n': +# print 'Skipped.' +# sys.exit(0) +# +if os.system('rm -rf imageBuild/debianDir') != 0: + print 'Failed to clean up old build directory' + sys.exit(-1) + +print 'Generating version...' +try: + version = re.findall( + r'set\(PDF2HTMLEX_VERSION\s*"([^"]*)"\)', + open('pdf2htmlEX/CMakeLists.txt').read() + )[0] +except: + print 'Cannot get package name and version number' + sys.exit(-1) + +try: + rev = open('.git/refs/heads/master').read()[:5] +except: + print 'Cannot get revision number' + sys.exit(-1) + +projectdir=os.getcwd() +today_timestr = time.strftime('%Y%m%d') +deb_version = version+'-1~git'+today_timestr+'r'+rev +full_deb_version = deb_version+'-0ubuntu1' + +print 'Version: %s' % (version,) +print 'Full Version: %s' % (full_deb_version,) + +#check if we need to update debian/changelog +with open('debian/changelog') as f: + if re.findall(r'\(([^)]+)\)', f.readline())[0] == full_deb_version: + print + print 'No need to update debian/changelog, skipping' + else: + print + print 'Writing debian/changelog' + if os.system('dch -v "%s"' % (full_deb_version,)) != 0: + print 'Failed when updating debian/changelog' + sys.exit(-1) + +# changelog may have been updated, reopen it +with open('debian/changelog') as f: + #check dist mark of changelog + changelog = f.read() + m = dist_pattern.search(changelog) + if m is None or m.pos >= changelog.find('\n'): + print 'Cannot locate the dist name in the first line of changelog' + sys.exit(-1) + +print +print 'Preparing build ...' +# handling files +if os.system(archive_cmd) != 0: + print 'Failed in creating tarball' + sys.exit(-1) + +orig_tar_filename = package+'-'+version+archive_suffix +os.mkdir('imageBuild/debianDir') +if os.system('test -e pdf2htmlEX/build/%s && cp pdf2htmlEX/build/%s imageBuild/debianDir/' % (orig_tar_filename, orig_tar_filename)) != 0: + print 'Cannot copy tarball file to build area' + sys.exit(-1) + +deb_orig_tar_filename = package+'_'+deb_version+'.orig'+archive_suffix +try: + os.chdir('imageBuild/debianDir') +except: + print 'Cannot find imageBuild/debianDir' + sys.exit(-1) + +# remove old dir +os.system('rm -rf %s' % (package+'-'+version,)) + +if os.system('mv %s %s && tar -xvf %s' % (orig_tar_filename, deb_orig_tar_filename, deb_orig_tar_filename)) != 0: + print 'Cannot extract tarball' + sys.exit(-1) + +try: + os.chdir(package+'-'+version) +except: + print 'Cannot enter project dir' + sys.exit(-1) + +os.system('cp -r %s/debian .' % (projectdir,)) + +for cur_dist in supported_distributions: + print + print 'Building for ' + cur_dist + ' ...' + # substitute distribution name + with open('debian/changelog', 'w') as f: + f.write(dist_pattern.sub('~%s1) %s' % (cur_dist, cur_dist), changelog, 1)) + +# No PPA Orginization set up, only building dpkg +# # building for ppa +# if os.system('debuild -S -sa') != 0: +# print 'Failed in debuild' +# sys.exit(-1) +# +# print +# sys.stdout.write('Everything seems to be good so far, upload?(y/n)') +# sys.stdout.flush() +# ans = raw_input().lower() +# while ans not in ['y', 'n']: +# sys.stdout.write('I don\'t understand, enter \'y\' or \'n\':') +# ans = raw_input().lower() +# +# if ans == 'n': +# print 'Skipped.' +# sys.exit(0) +# +# print 'Uploading' +# if os.system('dput %s ../%s' % (ppa_name, package+'_'+full_deb_version+'~'+cur_dist+'1_source.changes')) != 0: +# print 'Failed in uploading by dput' +# sys.exit(-1) + + # building for dpkg + if os.system('dpkg-buildpackage -b --no-sign') != 0: + print 'Failed in dpkg-buildpackage' + sys.exit(-1) + +print 'Build area not cleaned.' +print 'All done. Cool!' diff --git a/archive/debian/changelog b/archive/debian/changelog new file mode 100644 index 0000000..b77562a --- /dev/null +++ b/archive/debian/changelog @@ -0,0 +1,317 @@ +pdf2htmlex (0.18.7-1~git20200531r3fcd0-0ubuntu1) UNRELEASED; urgency=medium + + * test packaging + + -- Stephen Gaito Sun, 31 May 2020 13:38:59 +0000 + +pdf2htmlex (0.18.7-1~git20190927rb69b8-0ubuntu1) disco; urgency=low + + * Package for poppler-0.81.0 + + -- Stephen Gaito Fri, 27 Sep 2019 12:55:39 +0000 + +pdf2htmlex (0.18.6-1~git20190927r583b1-0ubuntu1) disco; urgency=low + + * Package for poppler-0.80.0 + + -- Stephen Gaito Fri, 27 Sep 2019 11:58:57 +0000 + +pdf2htmlex (0.18.5-1~git20190927rdb4cc-0ubuntu1) disco; urgency=low + + * Package for poppler-0.79.0 + + -- Stephen Gaito Fri, 27 Sep 2019 09:12:53 +0000 + +pdf2htmlex (0.18.4-1~git20190927r34bac-0ubuntu1) disco; urgency=low + + * Package for poppler-0.78.0 + + -- Stephen Gaito Fri, 27 Sep 2019 07:46:26 +0000 + +pdf2htmlex (0.18.3-1~git20190926r7ed19-0ubuntu1) disco; urgency=low + + * Package for poppler-0.77.0 + + -- Stephen Gaito Thu, 26 Sep 2019 17:56:51 +0000 + +pdf2htmlex (0.18.2-1~git20190926ra37f7-0ubuntu1) disco; urgency=low + + * Package for poppler-0.76.0 + + -- Stephen Gaito Thu, 26 Sep 2019 15:29:27 +0000 + +pdf2htmlex (0.18.1-1~git20190926r11e2a-0ubuntu1) disco; urgency=low + + * Package for poppler-0.75.0 + + -- Stephen Gaito Thu, 26 Sep 2019 10:59:59 +0000 + +pdf2htmlex (0.18.0-1~git20190924r37921-0ubuntu1) disco; urgency=medium + + * Package for Ubuntu 19.04 (poppler-0.74.0) + + -- Stephen Gaito Tue, 24 Sep 2019 14:56:03 +0000 + +pdf2htmlex (0.17.0-1~git20190924r37921-0ubuntu1) cosmic; urgency=low + + * Package for 18.10 (poppler-0.68.0) + + -- Stephen Gaito Tue, 24 Sep 2019 10:32:08 +0000 + +pdf2htmlex (0.16.0-1~git20190920r21a9f-0ubuntu1) bionic; urgency=low + + * Package for 18.04 + + -- Trent Petersen Thu, 19 Sep 2019 10:33:35 -0500 + +pdf2htmlex (0.11-1~git201311150048r23755-0ubuntu1) saucy; urgency=low + + * Fix packaging + + -- WANG Lu Fri, 15 Nov 2013 00:48:06 +0800 + +pdf2htmlex (0.11-1~git201311042119refddc-0ubuntu1) saucy; urgency=low + + * Packaging for 13.10 + + -- WANG Lu Mon, 04 Nov 2013 21:19:41 +0800 + +pdf2htmlex (0.11-1~git201310172203re1b11-0ubuntu1) raring; urgency=low + + * Fix typo in dependencies + + -- WANG Lu Thu, 17 Oct 2013 22:03:42 +0800 + +pdf2htmlex (0.10-1~git201310171220rc344e-0ubuntu1) raring; urgency=low + + * Fix build + + -- WANG Lu Thu, 17 Oct 2013 12:20:59 +0800 + +pdf2htmlex (0.10-1~git201310171209rdc970-0ubuntu1) raring; urgency=low + + * v0.10 released, see Changelog + + -- WANG Lu Thu, 17 Oct 2013 12:09:01 +0800 + +pdf2htmlex (0.9-1~git201309161133rd60eb-0ubuntu1) raring; urgency=low + + * fix cmake test for packaging + + -- WANG Lu Mon, 16 Sep 2013 11:33:11 +0800 + +pdf2htmlex (0.9-1~git201309161021rf2993-0ubuntu1) raring; urgency=low + + * v0.9 released, see Changelog + + -- WANG Lu Mon, 16 Sep 2013 10:21:05 +0800 + +pdf2htmlex (0.9-1~git201305291247rf655a-0ubuntu1) raring; urgency=low + + * Regular upload + + -- WANG Lu Wed, 29 May 2013 12:47:16 +0800 + +pdf2htmlex (0.8-1~git201305051429r92eab-0ubuntu1) raring; urgency=low + + * v0.8 released, see Changelog + + -- WANG Lu Sun, 05 May 2013 14:29:07 +0800 + +pdf2htmlex (0.8-1~git201304281550rd5f9c-0ubuntu1) raring; urgency=low + + * Test packaging for multiple distributions + * Fix crashing with --split-pages + + -- WANG Lu Sun, 28 Apr 2013 15:39:34 +0800 + +pdf2htmlex (0.8-1~git201304151420r1da9b-0ubuntu1) quantal; urgency=low + + * HTML optimization + * New options: --optimize-text, --fallabck + * See more in Changelog + + -- WANG Lu Mon, 15 Apr 2013 14:20:22 +0800 + +pdf2htmlex (0.8-1~git201303011406r3bc73-0ubuntu1) quantal; urgency=low + + * Experimental printing support + * New version + + -- WANG Lu Fri, 01 Mar 2013 14:06:42 +0800 + +pdf2htmlex (0.7-1~git201302282259r3bc73-0ubuntu1) quantal; urgency=low + + * suggests ttfautohint + + -- WANG Lu Thu, 28 Feb 2013 22:59:45 +0800 + +pdf2htmlex (0.7-1~git201302271054r3bc73-0ubuntu1) precise; urgency=low + + * Packaging for 12.04 + + -- WANG Lu Wed, 27 Feb 2013 10:54:12 +0800 + +pdf2htmlex (0.7-1~git201302271053r3bc73-0ubuntu1) quantal; urgency=low + + * Fix packpage dependency + + -- WANG Lu Wed, 27 Feb 2013 10:52:17 +0800 + +pdf2htmlex (0.7-1~git201302270111r3bc73-0ubuntu1) quantal; urgency=low + + * Regular upload + + -- WANG Lu Wed, 27 Feb 2013 01:11:56 +0800 + +pdf2htmlex (0.7-1~git201302182049r3bc73-0ubuntu1) quantal; urgency=low + + * New parameter: process-outline + + -- WANG Lu Mon, 18 Feb 2013 20:49:57 +0800 + +pdf2htmlex (0.7-1~git201301292229r2595c-0ubuntu1) quantal; urgency=low + + * Fixed a CSS issue + + -- WANG Lu Tue, 29 Jan 2013 22:29:21 +0800 + +pdf2htmlex (0.7-1~git201301282229r2595c-0ubuntu1) quantal; urgency=low + + * Process PDF Outline + + -- WANG Lu Mon, 28 Jan 2013 22:29:35 +0800 + +pdf2htmlex (0.7-1~git201301261427r2595c-0ubuntu1) quantal; urgency=low + + * New version, see Changelog for changelog + + -- WANG Lu Sat, 26 Jan 2013 14:27:18 +0800 + +pdf2htmlex (0.6-1~git201212182148rd76af-0ubuntu1) quantal; urgency=low + + * fix dependency of poppler for quantal + + -- WANG Lu Tue, 18 Dec 2012 21:48:35 +0800 + +pdf2htmlex (0.6-1~git201212111844rd76af-0ubuntu1) quantal; urgency=low + + * Package for quantal + + -- WANG Lu Tue, 11 Dec 2012 18:44:44 +0800 + +pdf2htmlex (0.6-1~git201210070052rcb9a8-0ubuntu1) precise; urgency=low + + * New version + + -- WANG Lu Sun, 07 Oct 2012 00:52:42 +0800 + +pdf2htmlex (0.5-1~git201210051800rbaa37-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Fri, 05 Oct 2012 18:00:48 +0800 + +pdf2htmlex (0.5-1~git201209270317r6fa14-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Thu, 27 Sep 2012 03:17:02 +0800 + +pdf2htmlex (0.5-1~git201209261622r170a0-0ubuntu1) precise; urgency=low + + * new version + + -- WANG Lu Wed, 26 Sep 2012 16:22:50 +0800 + +pdf2htmlex (0.4-1~git201209241628r30aee-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Mon, 24 Sep 2012 16:28:18 +0800 + +pdf2htmlex (0.4-1~git201209170124r8b4ec-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Mon, 17 Sep 2012 01:24:29 +0800 + +pdf2htmlex (0.4-1~git201209162328r8b4ec-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Sun, 16 Sep 2012 23:28:03 +0800 + +pdf2htmlex (0.3-1~git201209152353rf02e1-0ubuntu1) precise; urgency=low + + * Regularly re-packing. + + -- WANG Lu Sat, 15 Sep 2012 23:53:43 +0800 + +pdf2htmlex (0.3-1~git201209071504ra0de6-0ubuntu1) precise; urgency=low + + * fix build + * 0.3 comes with more bug fixed + + -- WANG Lu Fri, 07 Sep 2012 15:04:09 +0800 + +pdf2htmlex (0.2-3~git201209052329rbc256-0ubuntu1) precise; urgency=low + + * Change dependency of fontforge + + -- WANG Lu Wed, 05 Sep 2012 23:29:49 +0800 + +pdf2htmlex (0.2-3~git201209030158r926cf-0ubuntu1) precise; urgency=low + + * Fix dependency of libpoppler27 + + -- WANG Lu Mon, 03 Sep 2012 01:58:42 +0800 + +pdf2htmlex (0.2-3~git201209010002rfe7b3-0ubuntu1) precise; urgency=low + + * update license + + -- WANG Lu Sat, 01 Sep 2012 00:02:23 +0800 + +pdf2htmlex (0.2-3~git201208312351rd12b8-0ubuntu1) precise; urgency=low + + * 0.2dev, many bugs fixed + + -- WANG Lu Fri, 31 Aug 2012 23:51:57 +0800 + +pdf2htmlex (0.1-3~git201208281638r1addb-0ubuntu1) precise; urgency=low + + * Add debian files + + -- WANG Lu Tue, 28 Aug 2012 16:38:19 +0800 + +pdf2htmlex (0.1-3~git201208281523r80dc3-0ubuntu1) precise; urgency=low + + * Add dependency libpng + + -- WANG Lu Tue, 28 Aug 2012 15:22:22 +0800 + +pdf2htmlex (0.1-3~git201208281431r383b1-0ubuntu1) precise; urgency=low + + * Updated CMakeList.txt + + -- WANG Lu Tue, 28 Aug 2012 14:29:43 +0800 + +pdf2htmlex (0.1-3~git201208281420rc53d7-0ubuntu1) precise; urgency=low + + * Added config.h.in + + -- WANG Lu Tue, 28 Aug 2012 14:06:22 +0800 + +pdf2htmlex (0.1-3~git201208281356r5731e-0ubuntu1) precise; urgency=low + + * Fix version for package + + -- WANG Lu Tue, 28 Aug 2012 13:46:09 +0800 + +pdf2htmlex (0.1-1~git20120828rf083f-0ubuntu1) precise; urgency=low + + * Initial release. + + -- WANG Lu Tue, 28 Aug 2012 01:26:33 +0800 + diff --git a/archive/debian/compat b/archive/debian/compat new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/archive/debian/compat @@ -0,0 +1 @@ +10 diff --git a/archive/debian/control b/archive/debian/control new file mode 100644 index 0000000..7c0a227 --- /dev/null +++ b/archive/debian/control @@ -0,0 +1,14 @@ +Source: pdf2htmlex +Section: universe/web +Priority: extra +Maintainer: Trent Petersen +Build-Depends: cmake (>= 2.6.0), pkg-config, debhelper (>= 10), libpng-dev, libjpeg-dev, openjdk-8-jre-headless +Standards-Version: 3.9.3 +Homepage: http://github.com/pdf2htmlEX/pdf2htmlEX + +Package: pdf2htmlex +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Suggests: ttfautohint +Description: Converts PDF to HTML without losing format + pdf2htmlEX converts PDF to HTML while retaining text, format & style as much as possible diff --git a/archive/debian/copyright b/archive/debian/copyright new file mode 100644 index 0000000..836b598 --- /dev/null +++ b/archive/debian/copyright @@ -0,0 +1,23 @@ +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: pdf2htmlEX +Upstream-Contact: WANG Lu . +Source: http://github.com/pdf2htmlEX/pdf2htmlEX + +Files: * +Copyright: 2012 WANG Lu +License: GPL-3+ + +License: GPL-3 + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + . + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + . + You should have received a copy of the GNU General Public License + along with this program. If not, see . + diff --git a/archive/debian/dirs b/archive/debian/dirs new file mode 100644 index 0000000..e772481 --- /dev/null +++ b/archive/debian/dirs @@ -0,0 +1 @@ +usr/bin diff --git a/test/browser_tests/test_fail/THIS_FOLDER_SHOULD_BE_EMPTY b/archive/debian/pdf2htmlex.NEWS similarity index 100% rename from test/browser_tests/test_fail/THIS_FOLDER_SHOULD_BE_EMPTY rename to archive/debian/pdf2htmlex.NEWS diff --git a/archive/debian/pdf2htmlex.README b/archive/debian/pdf2htmlex.README new file mode 100644 index 0000000..b43bf86 --- /dev/null +++ b/archive/debian/pdf2htmlex.README @@ -0,0 +1 @@ +README.md diff --git a/archive/debian/pdf2htmlex.TODO b/archive/debian/pdf2htmlex.TODO new file mode 100644 index 0000000..e69de29 diff --git a/archive/debian/rules b/archive/debian/rules new file mode 100755 index 0000000..26ba418 --- /dev/null +++ b/archive/debian/rules @@ -0,0 +1,14 @@ +#!/usr/bin/make -f +%: + dh $@ + +override_dh_auto_test: + dh_auto_test || true + +# The following override is required when creating a Debian package +# associated with a version of poppler which has NO debian package (ie when +# poppler has been compiled and installed from source). +# +override_dh_shlibdeps: + dh_shlibdeps --dpkg-shlibdeps-params=--ignore-missing-info + diff --git a/archive/debian/source/format b/archive/debian/source/format new file mode 100644 index 0000000..c3d9f24 --- /dev/null +++ b/archive/debian/source/format @@ -0,0 +1,2 @@ +3.0 (quilt) + diff --git a/buildScripts/Readme.md b/buildScripts/Readme.md new file mode 100644 index 0000000..33fae62 --- /dev/null +++ b/buildScripts/Readme.md @@ -0,0 +1,334 @@ +# Building pdf2htmlEX + +Because of its intimate use of *specific* versions of both Poppler and +FontForge, cleanly building `pdf2htmlEX` is rather more complex than +normal. + +The (shell) scripts in this directory help automate this mutli-stage +process. + +For all but the most experienced programmers, we *strongly* encourage you +to use these scripts to build `pdf2htmlEX`. + +--- + +**Table of contents** + +- [TL;DR ...](#tldr-) + - [Downloading precompiled versions](#downloading-precompiled-versions-downloads) + - [Building yourself](#building-yourself) +- [The problem](#the-problem) +- [Our solution](#our-solution) +- [The gory details ...](#the-gory-details-) + - [Top-level scripts](#top-level-scripts) + - [Individual steps](#individual-steps) + - [Helper files and scripts](#helper-files-and-scripts) +- [Yet more details?](#yet-more-details) + +--- + +## TL;DR ... + +### Downloading precompiled versions + +For most users, you probably really want to simply download one of the +[precompiled versions of +`pdf2htmlEX`](https://github.com/pdf2htmlEX/pdf2htmlEX/releases): + +- [Debian archive](https://en.wikipedia.org/wiki/Dpkg) : Download, + [apt](https://en.wikipedia.org/wiki/APT_(software)) install locally, + and run... + + This will work on any [Debian](https://www.debian.org/) based and most + recent Windows 10 machines. + + Experienced users of Linux, may be able to repackage the `*.deb` we + provide for use with their favourite package management tool. + +- [AppImage](https://appimage.org/) : Download, make executable, and + run... + + This will work on most Linuxes, and most recent Windows 10. + + (It will not currently work on MacOS or Alpine based machines). + +- [Docker](https://www.docker.com/) Image from the [`pdf2htmlEX` Docker + hub](https://hub.docker.com/orgs/pdf2htmlex/repositories). + + This will work on any machine with Docker installed. + + (Note: that *advanced* use of `pdf2htmlEX` requires careful attention to + the configuration of various tools, such as fontconfig, iconv and your + locally available fonts use by the poppler and fontforge libraries. The + docker images created by the pdf2htmlEX team might not be as well + configured for *your needs* as a docker created and configured by you) + +### Building yourself + +To build `pdf2htmlEX` on a Debian/Apt related machine, inside the root +directory of a fresh clone of the +[pdf2htmlEX/pdf2htmlEX](https://github.com/pdf2htmlEX/pdf2htmlEX) +repository, type: + +``` + ./buildScripts/buildInstallLocallyApt +``` + +This will automatically install all required development tools and +libraries, and then proceed to download and statically compile the +required versions of both Poppler and FontForge before compiling and +installing `pdf2htmlEX` into /usr/local/bin. + +**NOTE:** at the moment this will **only** work on machines with a +[Debian](https://www.debian.org/) based distribution. such as +[Ubuntu](https://ubuntu.com/), [Linux Mint](https://linuxmint.com/), etc. + +**NOTE:** there is currently an *experimental* build script, +`./buildScripts/buildInstallLocallyAlpine`, for builds in Alpine +environments. + +## The problem + +To provide its full functionality, the `pdf2htmlEX` sources make direct +use of source code and unexposed methods from both the Poppler and +FontForge projects. Unfortunately the source code in the Poppler and +FontForge projects that the `pdf2htmlEX` uses changes regularly. + +This means that the `pdf2htmlEX` souce code *must* be updated regularly to +match *specific releases* of both Poppler and FontForge. + +Unfortunately, the installed versions of both Poppler and FontForge in +most Linux distributions, lag the official releases of both of these +projects. Even worse few distributions install the same versions. + +This means that it is nearly impossible for the `pdf2htmlEX` code to +'predict' which version of Poppler or FontForge will be installed on a +given user's machine. + +## Our solution + +While we *could* keep multiple versions of the `pdf2htmlEX` source code, +each version matched to a particular distribution's installed versions of +Poppler and FontForge, this would be a logistic and testing 'nightmare'. + +Instead, when building `pdf2htmlEX`, we download specific versions of both +the Poppler and FontForge sources (usually the most recent), and then +compile *static* versions of the Poppler and FontForge libraries which are +then *statically* linked into the `pdf2htmlEX` binary. + +This means that the `pdf2htmlEX` binary is completely independent of any +locally installed versions of either Poppler or FontForge. + +However, to get the matched versions of Poppler and FontForge and then +compile them statically, *our* build process becomes much more complex +than a "simple", `configure, make, make install` cycle. + +Hence this directory has a large number of shell scripts each of which +automate one simple step in the overall our build process. + +## The gory details ... + +The shell scripts in this directory automate the download, build, install, +test and upload steps required to provide a complete build/test/release +cycle of `pdf2htmlEX`. + +Each script can be used individually to re-run a particular step if needed. + +### Top-level scripts + +Typically, most users, will run one of the following "top-level" scripts: + +1. **`buildInstallLocallyApt`** (**`buildInstallLocallyAlpine`**) + + This will automate: + + 1. the installation of all required development tools + and libraries, + + 2. download and statically compile the required versions of both + Poppler and FontForge, + + 3. compile and install `pdf2htmlEX`. + + The `*Apt` script will build on any machine which uses the + `apt`/`apt-get` command. + + The `*Alpine` script will build on any machine which uses the + `apk` command (Alpine). + +2. **`createImagesApt`** (**`createImagesAlpine`**) + + Following a successful `buildInstallLocallyApt`, the `createImagesApt` + shell script will create the following images: + + 1. AppImage + + 2. Docker image + + 3. Debian archive + + Following a successful `buildInstallLocallyAlpine`, the + `createImagesAlpine` shell script will create the following images: + + 1. Alpine tar file + + 2. Docker image + +3. **`runTests`** + + Following a successful `buildInstallLocallyApt` (or + `buildInstallLocallyAlpine` ), the `runTests` shell script will run the + various 'local' tests reporting errors as they occur. + + When run in [Travis-ci](https://travis-ci.org/), failing browser tests + will *not* fail the overall Travis build, but will instead upload the + test results to the GitHub Release page for later review. + +4. **`uploadImages`** + + Following successful `buildInstallLocally`, `createImages` and + `runTests`, this will automate the upload of the various artefacts to + the `pdf2htmlEX` releases page, and docker hub repository. + + **Note** that this step requires the user to enter passwords for each + of the respective services. *Most* users will not need (or be able) to + run this step. + +5. **`travisLinuxDoItAll`** + + This script is used by the `.travis.yml` configuration to build, test + and upload a complete `pdf2htmlEX` release cycle. It is essentially a + compendium of all of the build scripts in the correct order. + +### Individual steps + +- **`buildFontforge`**: Compiles a *static* version of `libfontforge` for + use by `pdf2htmlEX`. + + Statically linking `libfontforge` into `phd2htmlEX` ensures that any + versions of FontForge already installed by the user, are not broken by + the user's installation of `pdf2htmlEX`. + +- **`buildPdf2htmlEX`**: Compiles and links `pdf2htmlEX`. + +- **`buildPoppler`**: Compiles a *static* version of `libpoppler` and + `libpopper-glib` for use by `pdf2htmlEX`. + + Statically linking `libpoppler` and `libpoppler-glib` into `phd2htmlEX` + ensures that any versions of Poppler already installed by the user, are + not broken by the user's installation of `pdf2htmlEX`. + +- **`createAlpineTarFile`**: Using an already compiled version of `pdf2htmlEX`, + installs it and `popper-data` into a tar file suitable for use in any + Alpine environment. + +- **`createAppImage`**: Using an already compiled version of `pdf2htmlEX`, + installs it and `popper-data` into an AppImage. + +- **`createDebianPackage`**: Using an already compiled version of + `pdf2htmlEX`, installs it and `poppler-data` into a Debian archive + (`*.deb`). + +- **`createDockerAlpineImageFromTarFile`**: Installs the Alpine tar file + archive of `pdf2htmlEX` created by `createAlpineTarFile` into an Alpine + Docker image. + +- **`createDockerUbuntuImageFromDeb`**: Installs the Debian archive of + `pdf2htmlEX` created by `createDebianPackage` into a Docker image. + +- **`getBuildToolsAlpine`**: Locally `apk` installs all development + *tools* required to build `pdf2htmlEX`. + +- **`getBuildToolsApt`**: Locally `apt` installs all development *tools* + required to build `pdf2htmlEX`. + +- **`getDevLibrariesAlpine`**: Locally `apk` installs all development + *libraries* required to build `pdf2htmlEX`. + +- **`getDevLibrariesApt`**: Locally `apt` installs all development + *libraries* required to build `pdf2htmlEX`. + + This script provides a definitive list of all libraries required to run + `pdf2htmlEX`. + + This script provides a definitive list of all libraries required to run + `pdf2htmlEX`. + +- **`getFontforge`**: Downloads and unpacks the version of FontForge specified in the + `FONTFORGE_VERSION` environment variable into the + `pdf2htmlEX/fontoforge` directory. + + The `FONTFORGE_VERSION` variable is specified in the `versionEnvs` + script. + +- **`getPoppler`**: Downloads and unpacks the version of Poppler specified in the + `POPPLER_VERSION` environment variable into the `pdf2htmlEX/poppler` + directory. + + The `POPPLER_VERSION` variable is specified in the `versionEnvs` script. + + The `getPoppler` script also downloads and unpacks the most recent + version of `poppler-data`. Since `poppler-data` does not change very + often, the correct version of `poppler-data` is specified in the + `getPoppler` script itself. + +- **`installPdf2htmlEX`**: Installs an already compiled version of + `pdf2htmlEX` and `poppler-data` into the location specified by the + `PDF2HTMLEX_PREFIX` environment variable. + + The `PDF2HTMLEX_PREFIX` variable is specified in the `versionEnvs` + script. + +- **`runTests`**: Runs the tests located in the + `pdf2htmlEX/pdf2htmlEX/test` directory. See the + `pdf2htmlEX/pdf2htmlEx/test` directory's Readme file for details. + +- **`uploadDockerImage`**: Upload the `pdf2htmlEX` Docker image to + Docker hub repository associated to the docker hub users specified in + the `DOCKER_USERNAME` environement variable. + + Unless the `DOCKER_USERNAME` and `DOCKER_PASSWORD` environment variables + are pre-defined, this script will prompt the user for the respective + values. + +- **`uploadGitHubRelease`**: Upload the `pdf2htmlEX` artefacts (AppImage, + Debian archive, test results, etc) to the *continuous* section of the + release page associated with the `TRAVIS_REPO_SLUG` (user/project) + environment variable. + + Unless the `GITHUB_USERNAME`, `GITHUB_TOKEN`, and `TRAVIS_REPO_SLUG` + (user/project) environment variables are pre-defined, this script will + prompt the user for the respective values. + +### Helper files and scripts + +- **`versionEnvs`**: Specifies all of the evnironment variables required + for a standard build of `pdf2htmlEX`. Changes in this script effect + *all* of the other build scripts. + +- **`reSourceVersionEnvs`**: This shell script is automatically generated + by the build scripts as they are run. It records the values of all + important environment variables required by the buildScripts. It is + typcically `source`d by each script before it preforms any actions. + +- **`reportEnvs`**: Echos all important enviroment variables to the + console. This script is used by the top-level scripts to ensure the + current environment variables are listed before each build. + +- **`uploadGitHubReleaseDSL`**: A collection of shell functions used by the + `uploadGitHubRelease` script to automate the upload of release artefacts. + +- **`uploadGitHubReleaseMessage`**: The contents of this *text* file is + used by the `uploadGitHubRelease` script as the contents of the release + message, as visible to the user, for the 'continuous' release section. + +- **`listFilesByChangeTime`**: A simple shell script which lists the files + in the buildScripts directory by most recently changed files first. + +- **`Readme.md`**: This read me file. + +## Yet more details? + +The various shell script files are meant to be fairly readable. They +contain additional comments about what each step is meant to be doing. + diff --git a/buildScripts/buildFontforge b/buildScripts/buildFontforge new file mode 100755 index 0000000..e58d495 --- /dev/null +++ b/buildScripts/buildFontforge @@ -0,0 +1,92 @@ +#!/bin/sh + +# This shell script build FontForge + +# source buildScripts/reSourceVersionEnvs +. buildScripts/reSourceVersionEnvs + +echo "" +echo "-------------------------------------------------------------------" +echo "BUILDING FontForge (using CMake)" +echo "-------------------------------------------------------------------" +echo "" + +set -ev + +cd fontforge + +mkdir build + +cd build + +cmake \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=$PDF2HTMLEX_PREFIX \ + -DBUILD_SHARED_LIBS:BOOL=OFF \ + -DENABLE_GUI:BOOL=OFF \ + -DENABLE_X11:BOOL=OFF \ + -DENABLE_NATIVE_SCRIPTING:BOOL=ON \ + -DENABLE_PYTHON_SCRIPTING:BOOL=OFF \ + -DENABLE_PYTHON_EXTENSION:AUTO=OFF \ + -DENABLE_LIBSPIRO:BOOL=OFF \ + -DENABLE_LIBUNINAMESLIST:BOOL=OFF \ + -DENABLE_LIBGIF:AUTO=OFF \ + -DENABLE_LIBJPEG:AUTO=ON \ + -DENABLE_LIBPNG:AUTO=ON \ + -DENABLE_LIBREADLINE:AUTO=OFF \ + -DENABLE_LIBTIFF:AUTO=OFF \ + -DENABLE_WOFF2:AUTO=OFF \ + -DENABLE_DOCS:AUTO=OFF \ + -DENABLE_CODE_COVERAGE:BOOL=OFF \ + -DENABLE_DEBUG_RAW_POINTS:BOOL=OFF \ + -DENABLE_FONTFORGE_EXTRAS:BOOL=OFF \ + -DENABLE_MAINTAINER_TOOLS:BOOL=OFF \ + -DENABLE_TILE_PATH:BOOL=OFF \ + -DENABLE_WRITE_PFM:BOOL=OFF \ + -DENABLE_SANITIZER:ENUM="none" \ + -DENABLE_FREETYPE_DEBUGGER:PATH="" \ + -DSPHINX_USE_VENV:BOOL=OFF \ + -DREAL_TYPE:ENUM="double" \ + -DTHEME:ENUM="tango" \ + .. + +# Apply any patches required for fontforge raw sources before we make +# +#for APATCHFILE in $(ls ../patches/fontforge-$FONTFORGE_VERSION-*) +#do +# echo "patching fontforge using [$APATCHFILE]" +# patch -p 1 < $APATCHFILE +#done + +make $MAKE_PARALLEL + +########################################################## +# FontForge CMakeLists.txt build options (2020/05/31): + +# BUILD_SHARED_LIBS:BOOL=OFF "Build libfontforge as a shared library") +# ENABLE_GUI:BOOL=OFF "Build FontForge with GUI support") +# ENABLE_X11:BOOL=OFF "Build the GUI using the X backend INSTEAD of the GDK backend" "ENABLE_GUI") +# ENABLE_NATIVE_SCRIPTING:BOOL=ON "Enables FontForge's native scripting support") +# ENABLE_PYTHON_SCRIPTING:BOOL=OFF "Enables FontForge's Python scripting support") +# ENABLE_PYTHON_EXTENSION:AUTO=OFF "Builds the Python models for use with system python") +# ENABLE_LIBSPIRO:BOOL=ON "Enables libspiro support") +# ENABLE_LIBUNINAMESLIST:BOOL=ON "Enables libuninameslist support") +# ENABLE_LIBGIF:AUTO=OFF "Enables GIF support") +# ENABLE_LIBJPEG:AUTO=ON "Enables JPEG support") +# ENABLE_LIBPNG:AUTO=ON "Enables PNG support") +# ENABLE_LIBREADLINE:AUTO=OFF "Enables Readline support") +# ENABLE_LIBTIFF:AUTO=OFF "Enables TIFF support") +# ENABLE_WOFF2:AUTO=OFF "Enables WOFF2 support") +# ENABLE_DOCS:AUTO=OFF "Enables building and installing documentation. Sphinx is required to build it.") +# ENABLE_CODE_COVERAGE:BOOL=OFF "Build with code coverage support") +# ENABLE_DEBUG_RAW_POINTS:BOOL=OFF "Add a raw mode to the points window of the debugger") +# ENABLE_FONTFORGE_EXTRAS:BOOL=OFF "Builds programs from the contrib directory") +# ENABLE_MAINTAINER_TOOLS:BOOL=OFF "Build programs normally only used by FontForge maintainers and developers") +# ENABLE_TILE_PATH:BOOL=OFF "Enable a 'tile path' command (a variant of 'expand stroke')") +# ENABLE_WRITE_PFM:BOOL=OFF "Add the ability to save a PFM file without creating the associated font file") +# ENABLE_SANITIZER:ENUM="none" "Enables a sanitizer. Requires support from the compiler." +# ENABLE_FREETYPE_DEBUGGER:PATH="" "Use FreeTypes internal debugger within FontForge." +# SPHINX_USE_VENV:BOOL=OFF "If building documentation and Sphinx is not installed, try to install and use it from a python3 venv." +# REAL_TYPE:ENUM="double" "Sets the floating point type used." "double" "float") +# THEME:ENUM="tango" "Sets the GUI theme." "tango" "2012") + diff --git a/buildScripts/buildInstallLocallyAlpine b/buildScripts/buildInstallLocallyAlpine new file mode 100755 index 0000000..5a535bc --- /dev/null +++ b/buildScripts/buildInstallLocallyAlpine @@ -0,0 +1,49 @@ +#!/bin/sh + +# This shell script builds the complete pdf2htmlEX application LOCALLY +# (It does not create the AppImage or Docker images) + +# Adjust the following two environment variables to suit your needs +# +export UNATTENDED="--assume-yes" +export MAKE_PARALLEL="-j $(nproc)" + +# choose one of the following... +# +# export PDF2HTMLEX_BRANCH="<>" +export PDF2HTMLEX_BRANCH="$(git rev-parse --abbrev-ref HEAD)" + +# The following environment variable determines where the poppler, +# poppler-data, fontforge and pdf2htmlEX packages are installed. +# CHANGE IT TO SUIT YOUR NEEDS: +# +export PDF2HTMLEX_PREFIX=/usr/local + +# Ensure all Apt packages are installed with no user interaction +# +export DEBIAN_FRONTEND=noninteractive + +set -ev + +################ +# do the build + +./buildScripts/versionEnvs + +./buildScripts/reportEnvs + +./buildScripts/getBuildToolsAlpine + +./buildScripts/getDevLibrariesAlpine + +./buildScripts/getPoppler + +./buildScripts/buildPoppler + +./buildScripts/getFontforge + +./buildScripts/buildFontforge + +./buildScripts/buildPdf2htmlEX + +./buildScripts/installPdf2htmlEX diff --git a/buildScripts/buildInstallLocallyApt b/buildScripts/buildInstallLocallyApt new file mode 100755 index 0000000..a26afc4 --- /dev/null +++ b/buildScripts/buildInstallLocallyApt @@ -0,0 +1,49 @@ +#!/bin/sh + +# This shell script builds the complete pdf2htmlEX application LOCALLY +# (It does not create the AppImage or Docker images) + +# Adjust the following two environment variables to suit your needs +# +export UNATTENDED="--assume-yes" +export MAKE_PARALLEL="-j $(nproc)" + +# choose one of the following... +# +# export PDF2HTMLEX_BRANCH="<>" +export PDF2HTMLEX_BRANCH="$(git rev-parse --abbrev-ref HEAD)" + +# The following environment variable determines where the poppler, +# poppler-data, fontforge and pdf2htmlEX packages are installed. +# CHANGE IT TO SUIT YOUR NEEDS: +# +export PDF2HTMLEX_PREFIX=/usr/local + +# Ensure all Apt packages are installed with no user interaction +# +export DEBIAN_FRONTEND=noninteractive + +set -ev + +################ +# do the build + +./buildScripts/versionEnvs + +./buildScripts/reportEnvs + +./buildScripts/getBuildToolsApt + +./buildScripts/getDevLibrariesApt + +./buildScripts/getPoppler + +./buildScripts/buildPoppler + +./buildScripts/getFontforge + +./buildScripts/buildFontforge + +./buildScripts/buildPdf2htmlEX + +./buildScripts/installPdf2htmlEX diff --git a/buildScripts/buildPdf2htmlEX b/buildScripts/buildPdf2htmlEX new file mode 100755 index 0000000..daa62a3 --- /dev/null +++ b/buildScripts/buildPdf2htmlEX @@ -0,0 +1,19 @@ +#!/bin/sh + +# This shell script builds pdf2htmlEX + +echo "" +echo "-------------------------------------------------------------------" +echo "BUILDING pdf2htmlEX (using gcc)" +echo "-------------------------------------------------------------------" + +echo "" + +set -ev + +cd pdf2htmlEX +rm -rf build +mkdir build +cd build +cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$PDF2HTMLEX_PREFIX .. +make $MAKE_PARALLEL diff --git a/buildScripts/buildPoppler b/buildScripts/buildPoppler new file mode 100755 index 0000000..4583ccb --- /dev/null +++ b/buildScripts/buildPoppler @@ -0,0 +1,103 @@ +#!/bin/sh + +# This shell script builds the latest poppler + +echo "" +echo "-------------------------------------------------------------------" +echo "BUILDING Poppler (using CMake)" +echo "-------------------------------------------------------------------" +echo "" + +set -ev + +cd poppler +mkdir build +cd build +cmake \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=$PDF2HTMLEX_PREFIX \ + -DENABLE_UNSTABLE_API_ABI_HEADERS=OFF \ + -DBUILD_GTK_TESTS=OFF \ + -DBUILD_QT5_TESTS=OFF \ + -DBUILD_CPP_TESTS=OFF \ + -DENABLE_SPLASH=ON \ + -DENABLE_UTILS=OFF \ + -DENABLE_CPP=OFF \ + -DENABLE_GLIB=ON \ + -DENABLE_GOBJECT_INTROSPECTION=OFF \ + -DENABLE_GTK_DOC=OFF \ + -DENABLE_QT5=OFF \ + -DENABLE_LIBOPENJPEG="none" \ + -DENABLE_CMS="none" \ + -DENABLE_DCTDECODER="libjpeg" \ + -DENABLE_LIBCURL=OFF \ + -DENABLE_ZLIB=ON \ + -DENABLE_ZLIB_UNCOMPRESS=OFF \ + -DUSE_FLOAT=OFF \ + -DBUILD_SHARED_LIBS=OFF \ + -DRUN_GPERF_IF_PRESENT=OFF \ + -DEXTRA_WARN=OFF \ + -DWITH_JPEG=ON \ + -DWITH_PNG=ON \ + -DWITH_TIFF=OFF \ + -DWITH_NSS=OFF \ + -DWITH_Cairo=ON \ + .. + +make $MAKE_PARALLEL + + +############################################################### +# Poppler CMakeLists.text build options (2020/05/31): + +# ENABLE_UNSTABLE_API_ABI_HEADERS=OFF "Install API/ABI unstable xpdf headers." +# BUILD_GTK_TESTS=OFF "Whether to compile the GTK+ test programs." +# BUILD_QT5_TESTS=OFF "Whether to compile the Qt5 test programs." +# BUILD_CPP_TESTS=OFF "Whether to compile the CPP test programs." +# ENABLE_SPLASH=ON "Build the Splash graphics backend." +# ENABLE_UTILS=OFF "Compile poppler command line utils." +# ENABLE_CPP=ON "Compile poppler cpp wrapper." +# ENABLE_GLIB=ON "Compile poppler glib wrapper." +# ENABLE_GOBJECT_INTROSPECTION=ON "Whether to generate GObject introspection." +# ENABLE_GTK_DOC=OFF "Whether to generate glib API documentation." +# ENABLE_QT5=OFF "Compile poppler qt5 wrapper." +# +# ENABLE_LIBOPENJPEG="none" +# +# "Use libopenjpeg for JPX streams. Possible values: openjpeg2, +# unmaintained, none. 'unmaintained' gives you the internal unmaintained +# decoder. Use at your own risk. 'none' compiles no JPX decoder at all. +# Default: openjpeg2" +# +# ENABLE_CMS="lcms2" +# +# "Use color management system. Possible values: lcms2, none. 'none' +# disables color management system." +# +# ENABLE_DCTDECODER="libjpeg" +# +# "Use libjpeg for DCT streams. Possible values: libjpeg, unmaintained, +# none. will use libjpeg if available or fail if not. 'unmaintained' gives +# you the internal unmaintained decoder. Use at your own risk. 'none' +# compiles no DCT decoder at all. Default: libjpeg" +# +# ENABLE_LIBCURL=OFF "Build libcurl based HTTP support." +# ENABLE_ZLIB=ON "Build with zlib." +# ENABLE_ZLIB_UNCOMPRESS=OFF "Use zlib to uncompress flate streams (not totally safe)." +# USE_FLOAT=OFF "Use single precision arithmetic in the Splash backend" +# BUILD_SHARED_LIBS=OFF "Build poppler as a shared library" +# RUN_GPERF_IF_PRESENT=OFF "Run gperf if it is found" +# EXTRA_WARN=OFF "Enable extra compile warnings" + +# The following packages are optional and only used if found: +# JPEG is required by pdf2htmlEX +# PNG is required by pdf2htmlEX +# TIFF is not used by pdf2htmlEX +# NSS3 is not used by pdf2htmlEX? +# CAIRO is required by pdf2htmlEX +# GLIB is requrired by pdf2htmlEX +# GObjectIntrospection is not needed by pdf2htmlEX? +# Iconv is only used if ENABLE_CPP +# +# They can be explicitly DISABLED using ENABLE_XXXX:BOOL=OFF where XXXX is +# the package name diff --git a/buildScripts/createAlpineTarFile b/buildScripts/createAlpineTarFile new file mode 100755 index 0000000..8022180 --- /dev/null +++ b/buildScripts/createAlpineTarFile @@ -0,0 +1,80 @@ +#!/bin/sh + +# This shell script creates a docker image from an existing pdf2htmlEX +# +# This is the part which can run *inside* a docker container. + +echo "" +echo "-------------------------------------------------------------------" +echo "CREATING pdf2htmlEX Docker Image (run inside a docker container)" +echo " (based on Alpine linux $BUILD_DIST)" +echo "-------------------------------------------------------------------" +echo "" + +# Collect everything that will be needed... + +# source buildScripts/reSourceVersionEnvs +. buildScripts/reSourceVersionEnvs + +export ALPINE_NAME="pdf2htmlEX-$PDF2HTMLEX_NAME" + +echo "export ALPINE_NAME=\"$ALPINE_NAME\"" >> buildScripts/reSourceVersionEnvs + +set -ev + +mkdir -p imageBuild/alpineTarDir + +cd pdf2htmlEX/build + +sudo rm -rf install_manifest.txt + +make install DESTDIR=../../imageBuild/alpineTarDir + +cd ../../poppler-data + +make install \ + prefix=$PDF2HTMLEX_PREFIX \ + datadir=$PDF2HTMLEX_PREFIX/share/pdf2htmlEX \ + DESTDIR=../imageBuild/alpineTarDir + +cd ../imageBuild + +tar czvf $ALPINE_NAME.tar.gz alpineTarDir + +cat < $ALPINE_NAME.install +#!/bin/sh + +# This (alpine) shell script installs a locally existing tar.gz file of +# the pdf2htmlEX binaries compiled on Alpine $DIST. +# +# You MUST have root/sudo privileges to run this file. +# + +# We start by installing all of the (known) required runtime dependencies +# +apk update +# +apk add --no-cache \ + tar \ + libstdc++ \ + libgcc \ + gnu-libiconv \ + gettext \ + glib \ + freetype \ + fontconfig \ + cairo \ + libpng \ + libjpeg-turbo \ + libxml2 + +# Now we install the (Alpine $DIST) compiled pdf2htmlEX binaries and +# configuration files. +# +cd / +# +tar xvf $ALPINE_NAME.tar.gz --strip-comonents=1 + +ALPINE_INSTALL + +chmod a+x $ALPINE_NAME.tar.gz diff --git a/buildScripts/createAppImage b/buildScripts/createAppImage new file mode 100755 index 0000000..1a72152 --- /dev/null +++ b/buildScripts/createAppImage @@ -0,0 +1,81 @@ +#!/bin/sh + +# This shell script creates an AppImage for pdf2htmlEX + +# source ./buildScripts/reSourceVersionEnvs +. ./buildScripts/reSourceVersionEnvs + +echo "" +echo "-------------------------------------------------------------------" +echo "CREATING pdf2htmlEX AppImage" +echo "-------------------------------------------------------------------" +echo "" + +set -ev + +# For appimage output plugin +# +#export VERSION="$PDF2HTMLEX_BRANCH-$BUILD_TIME" +export APPIMAGE_NAME="pdf2htmlEX-$PDF2HTMLEX_NAME.AppImage" + +echo "export APPIMAGE_NAME=\"$APPIMAGE_NAME\"" >> buildScripts/reSourceVersionEnvs + +mkdir -p imageBuild/appDir/usr/lib/ + +cd pdf2htmlEX/build + +sudo rm -rf install_manifest.txt + +make install DESTDIR=../../imageBuild/appDir + +cd ../../poppler-data + +make install \ + prefix=$PDF2HTMLEX_PREFIX \ + datadir=$PDF2HTMLEX_PREFIX/share/pdf2htmlEX \ + DESTDIR=../imageBuild/appDir + +cd ../imageBuild + +# Make sure directories can be traversed by nobody +# +#find appDir -type d -exec chmod 755 {} \; +# +# Make sure files can be read by nobody +# +#find appDir -type f -exec chmod 644 {} \; + +# force libfontconfig into AppImage (linuxdeploy blacklists libfontconfig) +# (turned off since libfontconfig needs to be matched to the underlying +# OS's collection of fonts and /etc/fonts configuration files) +# +#cp /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 appDir/usr/lib/ + +LINUX_DEPLOY_APP_IMAGE=linuxdeploy-$MACHINE_ARCH.AppImage + +wget https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/$LINUX_DEPLOY_APP_IMAGE + +chmod a+x $LINUX_DEPLOY_APP_IMAGE + +if [ -f /.dockerenv ] ; then + # WE ARE INSIDE A DOCKER CONTAINER... + # + # We explicilty extract the appimage to a squashfs to allow it to be used + # inside Docker containers + # + ./$LINUX_DEPLOY_APP_IMAGE --appimage-extract + # + LINUX_DEPLOY_APP_IMAGE=squashfs-root/AppRun +fi + +export VERBOSE=1 +export OUTPUT=$APPIMAGE_NAME + +./$LINUX_DEPLOY_APP_IMAGE \ + -e appDir/$PDF2HTMLEX_PREFIX/bin/pdf2htmlEX \ + --create-desktop-file \ + -i ../pdf2htmlEX/logo/pdf2htmlEX.svg \ + --appdir=appDir \ + --output appimage + + diff --git a/buildScripts/createDebianPackage b/buildScripts/createDebianPackage new file mode 100755 index 0000000..3c47d5f --- /dev/null +++ b/buildScripts/createDebianPackage @@ -0,0 +1,112 @@ +#!/bin/sh + +# This shell script creates a (binary) Debian Package Archive for pdf2htmlEX + +# source ./buildScripts/reSourceVersionEnvs +. ./buildScripts/reSourceVersionEnvs + +echo "" +echo "-------------------------------------------------------------------" +echo "CREATING pdf2htmlEX (binary) Debian package" +echo "-------------------------------------------------------------------" +echo "" + +set -ev + +export DPKG_NAME="pdf2htmlEX-$PDF2HTMLEX_NAME.deb" + +echo "export DPKG_NAME=\"$DPKG_NAME\"" >> buildScripts/reSourceVersionEnvs + +# Adapted from: https://blog.serverdensity.com/how-to-create-a-debian-deb-package/ +# and: http://www.sj-vs.net/creating-a-simple-debian-deb-package-based-on-a-directory-structure/ + +DEBDIR=imageBuild/debianDir +DOCDIR=$DEBDIR/usr/local/share/doc/pdf2htmlEX + +sudo rm -rf $DEBDIR +mkdir -p $DOCDIR + +# Install pdf2htmlEX +# +cd pdf2htmlEX/build +# +make install DESTDIR=../../$DEBDIR + +# Install a copy of poppler-data for pdf2htmlEX's exclusive use +# +cd ../../poppler-data +# +make install \ + prefix=$PDF2HTMLEX_PREFIX \ + datadir=$PDF2HTMLEX_PREFIX/share/pdf2htmlEX \ + DESTDIR=../$DEBDIR + +cd .. + +# Create a 'useful' changelog +# +git log --format="%cd %h %d %n %s%n" --date=short > $DOCDIR/gitLog + +# Ensure the license and readme details are embedded in the debian archive +# +cp LICENSE $DOCDIR +cp LICENSE_GPLv3 $DOCDIR +cp README.md $DOCDIR + +######################################## +# setup the DEBIAN package files + +controlFile=$DEBDIR/DEBIAN/control +conffilesFile=$DEBDIR/DEBIAN/conffiles +md5sumsFile=$DEBDIR/DEBIAN/md5sums + +mkdir -p $DEBDIR/DEBIAN + +# Create the md5sums file +# +find $DEBDIR -type f | xargs md5sum > $md5sumsFile + +# Accumulate the control file information +# +versionValue=$PDF2HTMLEX_VERSION.$PDF2HTMLEX_BRANCH.$BUILD_DIST.$BUILD_DATE +architectureValue=$(dpkg-architecture -q DEB_BUILD_ARCH_CPU) +maintainerValue="$(git config --get user.name) <$(git config --get user.email)>" + +# Now create the control file +# +echo "Package: pdf2htmlEX" > $controlFile +echo "Version: 0:0.$versionValue-0" >> $controlFile +echo "Distribution: $BUILD_DIST" >> $controlFile +echo "Architecture: $architectureValue" >> $controlFile +echo "Section: universe/web" >> $controlFile +echo "Priority: optional" >> $controlFile +echo "Essential: no" >> $controlFile +echo "Depends: libglib2.0-0, libfreetype6, libfontconfig1, libcairo2, libpng16-16, libjpeg-turbo8, libxml2" >> $controlFile +echo "Maintainer: $maintainerValue" >> $controlFile +echo "Homepage: http://github.com/pdf2htmlEX/pdf2htmlEX" >> $controlFile +echo "Description: Converts PDF to HTML without losing format" >> $controlFile +echo " pdf2htmlEX converts PDF to HTML while retaining text, format & style as much as possible" >> $controlFile + +# Create the (empty) conffiles +# +touch $conffilesFile + +# Finally create the debian archive +# +cd imageBuild +# +# Make sure directories can be traversed by nobody +# +#find debianDir -type d -exec chmod 755 {} \; +# +# Make sure files can be read by nobody +# +#find debianDir -type f -exec chmod 644 {} \; +# +# Make sure root:root owns all files +# +sudo chown -R root:root debianDir +# +# Build the package +# +dpkg --build debianDir $DPKG_NAME diff --git a/buildScripts/createDockerAlpineImageFromTarFile b/buildScripts/createDockerAlpineImageFromTarFile new file mode 100755 index 0000000..5f1edf4 --- /dev/null +++ b/buildScripts/createDockerAlpineImageFromTarFile @@ -0,0 +1,66 @@ +#!/bin/sh + +# This shell script creates a docker image from an existing pdf2htmlEX +# +# This is the part which must be run *outside* of any docker container. + +echo "" +echo "-------------------------------------------------------------------" +echo "CREATING pdf2htmlEX Docker Image (run outside any docker container)" +echo " (based on Alpine linux $BUILD_DIST)" +echo "-------------------------------------------------------------------" +echo "" + +# Collect everything that will be needed... + +# source buildScripts/reSourceVersionEnvs +. buildScripts/reSourceVersionEnvs + +set -ev + +mkdir -p imageBuild/dockerDir + +cd imageBuild/dockerDir + +cp ../$ALPINE_NAME.* . + +if [ -z "$DOCKER_FROM" ]; then + echo "" + read -p "Enter the docker image for the 'from' base: " DOCKER_FROM + echo "" + if [ -z "$DOCKER_FROM" ]; then + echo "DOCKER_FROM not set... so we can not build the docker image" + exit 1 + fi +fi + +if [ -z "$DOCKER_USERNAME" ]; then + echo "" + read -p "Enter a docker username: " DOCKER_USERNAME + echo "" + if [ -z "$DOCKER_USERNAME" ]; then + echo "DOCKER_USERNAME not set... so we can not build the docker image" + exit 1 + fi +fi + +export DOCKER_NAME="$DOCKER_USERNAME/pdf2htmlex:$PDF2HTMLEX_NAME" + +echo "export DOCKER_FROM=\"$DOCKER_FROM\"" >> ../../buildScripts/reSourceVersionEnvs +echo "export DOCKER_USERNAME=\"$DOCKER_USERNAME\"" >> ../../buildScripts/reSourceVersionEnvs +echo "export DOCKER_NAME=\"$DOCKER_NAME\"" >> ../../buildScripts/reSourceVersionEnvs + +cat > Dockerfile <> ../../buildScripts/reSourceVersionEnvs +echo "export DOCKER_USERNAME=\"$DOCKER_USERNAME\"" >> ../../buildScripts/reSourceVersionEnvs +echo "export DOCKER_NAME=\"$DOCKER_NAME\"" >> ../../buildScripts/reSourceVersionEnvs + +cat > Dockerfile <> buildScripts/reSourceVersionEnvs + +set -ev + +# This shell script runs the pdf2htmlEX tests + +cd pdf2htmlEX/test + +# The following is only needed for the local browser tests +# +./installAutomaticTestSoftwareApt + +./runLocalTestsShell + +./runLocalBrowserTests + +cd ../.. + +mkdir -p imageBuild + +zip -r imageBuild/$TEST_RESULTS_NAME /tmp/pdf2htmlEX/html /tmp/pdf2htmlEX/png diff --git a/buildScripts/travisLinuxDoItAll b/buildScripts/travisLinuxDoItAll new file mode 100755 index 0000000..4d3e697 --- /dev/null +++ b/buildScripts/travisLinuxDoItAll @@ -0,0 +1,39 @@ +#!/bin/sh + +# This shell script builds everyting on an TravisCI Linux (Ubunutu) worker + +set -ev + +export UNATTENDED="--assume-yes" + +export MAKE_PARALLEL="-j $(nproc)" + +export PDF2HTMLEX_BRANCH=$TRAVIS_BRANCH + +export PDF2HTMLEX_PREFIX=/usr/local + +export PDF2HTMLEX_PATH=/usr/local/bin/pdf2htmlEX + +# Ensure all Apt packages are installed with no user interaction +# +export DEBIAN_FRONTEND=noninteractive + +################ +# do the build + +./buildScripts/versionEnvs +./buildScripts/reportEnvs +./buildScripts/getBuildToolsApt +./buildScripts/getDevLibrariesApt +./buildScripts/getPoppler +./buildScripts/buildPoppler +./buildScripts/getFontforge +./buildScripts/buildFontforge +./buildScripts/buildPdf2htmlEX +./buildScripts/installPdf2htmlEX +./buildScripts/runTests +./buildScripts/createAppImage +./buildScripts/createDebianPackage +./buildScripts/createDockerUbuntuImageFromDeb +#./buildScripts/uploadGitHubRelease +#./buildScripts/uploadDockerImage diff --git a/buildScripts/uploadDockerImage b/buildScripts/uploadDockerImage new file mode 100755 index 0000000..48cb0ec --- /dev/null +++ b/buildScripts/uploadDockerImage @@ -0,0 +1,49 @@ +#!/bin/sh + +# This shell script uploads the pdf2htmlEX docker image to docker hub +# +# We EXPECT the following environment variables to be set: +# DOCKER_USERNAME +# +# You can OPTIONALLY set the following environment variables: +# DOCKER_PASSWORD (if not set you will be asked for your password) +# + +# source ./buildScripts/reSourceVersionEnvs +. ./buildScripts/reSourceVersionEnvs + +echo "" +echo "-------------------------------------------------------------------" +echo "UPLOADING pdf2htmlEX Docker Image to Docker Hub" +echo "-------------------------------------------------------------------" +echo "" + +################################## +# push docker image +# +if [ -x "$(which docker)" ]; then + + if [ -z "$DOCKER_USERNAME" ]; then + echo "" + read -p "Enter the Docker usernane): " DOCKER_USERNAME + echo "" + if [ -z "$DOCKER_USERNAME" ]; then + echo "DOCKER_USERNAME not set... so we do not know where to push image." + exit 1 + fi + fi + + if [ -z "$DOCKER_PASSWORD" ]; then + echo "" + echo "Please type your the Docker hub password" + docker login -u "$DOCKER_USERNAME" + else + echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin + fi + + docker push $DOCKER_USERNAME/pdf2htmlex + +else + echo "Docker is not installed... skipping upload of docker image." +fi + diff --git a/buildScripts/uploadGitHubRelease b/buildScripts/uploadGitHubRelease new file mode 100755 index 0000000..ffde585 --- /dev/null +++ b/buildScripts/uploadGitHubRelease @@ -0,0 +1,92 @@ +#!/bin/sh + +# This shell script uploads the pdf2htmlEX release artefacts +# +# We EXPECT the following environment variables to be set: +# GITHUB_TOKEN +# DOCKER_USERNAME +# +# You can OPTIONALLY set the following environment variables: +# DOCKER_PASSWORD (if not set you will be asked for your password) +# + +# source ./buildScripts/reSourceVersionEnvs +. ./buildScripts/reSourceVersionEnvs +cp ./buildScripts/reSourceVersionEnvs imageBuild/buildInfo.sh +. ./buildScripts/uploadGitHubReleaseDSL +# source ./buildScripts/uploadGitHubReleaseDSL + +echo "" +echo "-------------------------------------------------------------------" +echo "UPLOADING pdf2htmlEX AppImage and Docker Images" +echo "-------------------------------------------------------------------" +echo "" + + +################################## +# upload github release artefacts +# + +# begin by gathering the required environment variables +# + +if [ -z "$GITHUB_USERNAME" ]; then + echo "" + read -p "Enter the GitHub upload username: " GITHUB_USERNAME + echo "" + if [ -z "$GITHUB_USERNAME" ]; then + echo "GITHUB_USERNAME not set... so we can not upload release artefacts." + exit 1 + fi +fi + +if [ -z "$GITHUB_TOKEN" ]; then + echo "" + read -p "Enter the GitHub upload token/password: " GITHUB_TOKEN + echo "" + if [ -z "$GITHUB_TOKEN" ]; then + echo "GITHUB_TOKEN not set... so we can not upload release artefacts." + exit 1 + fi +fi + +if [ -z "$TRAVIS_REPO_SLUG" ]; then + echo "" + read -p "Enter the GitHub repository (user/proj): " TRAVIS_REPO_SLUG + echo "" + if [ -z "$TRAVIS_REPO_SLUG" ]; then + echo "TRAVIS_REPO_SLUG (Github repository) not set... so we can not upload release artefacts." + exit 1 + fi +fi + +cd imageBuild + +ls -la + +echo "machine api.github.com" > $HOME/.netrc +echo " login $GITHUB_USERNAME" >> $HOME/.netrc +echo " password $GITHUB_TOKEN" >> $HOME/.netrc +echo "machine uploads.github.com" >> $HOME/.netrc +echo " login $GITHUB_USERNAME" >> $HOME/.netrc +echo " password $GITHUB_TOKEN" >> $HOME/.netrc + +echo $APPIMAGE_NAME > appImageName.txt +echo $DOCKER_NAME > dockerImageName.txt +echo $DPKG_NAME > debianArchiveName.txt +echo $TEST_RESULTS_NAME > testResultsName.txt + +deleteReleaseByTag "$TRAVIS_REPO_SLUG" "continuous-$BUILD_DIST" + +createNewRelease "$TRAVIS_REPO_SLUG" "continuous-$BUILD_DIST" "Latest $BUILD_DIST release" \ + ../buildScripts/uploadGitHubReleaseMessage + +uploadAnAsset $upload_url "appImageName.txt" "text/plain" +uploadAnAsset $upload_url "testResultsName.txt" "text/plain" +uploadAnAsset $upload_url "buildInfo.sh" "text/plain" +uploadAnAsset $upload_url "dockerImageName.txt" "text/plain" +uploadAnAsset $upload_url "debianArchiveName.txt" "text/plain" +uploadAnAsset $upload_url $APPIMAGE_NAME "application/zip" +uploadAnAsset $upload_url $TEST_RESULTS_NAME "application/zip" +uploadAnAsset $upload_url $DPKG_NAME "application/x-debian-package" + diff --git a/buildScripts/uploadGitHubReleaseDSL b/buildScripts/uploadGitHubReleaseDSL new file mode 100755 index 0000000..eb226d6 --- /dev/null +++ b/buildScripts/uploadGitHubReleaseDSL @@ -0,0 +1,208 @@ +#!/usr/bin/env sh + +# This shell script is a collection of functions to interact with the GitHub +# release and git/tag APIs. It essentially provides a shell script based DSL +# for uploading GitHub release artefacts. + +# NOTE-1: These functions make use of your ".netrc" file to authenticate +# with GitHub. In order to use these functions, make sure you have **both** +# "api.github.com" and "upload.github.com" in this file. For example: +# +# machine api.github.com +# login foca +# password +# machine uploads.github.com +# login foca +# password +# +# You can generate the required access token at +# https://github.com/settings/tokens +# Make sure this access token has access to the "repo" scope. +# +# NOTE-2: These functions require the "jq" library to parse the JSON +# returned by the GitHub APIs. + +############################# +function deleteReleaseByTag { + + [ -n "$1" ] || (echo "deleteReleaseByTag: missing repository"; exit 1); + [ -n "$2" ] || (echo "deleteReleaseByTag: missing releaseTag"; exit 1); + + REPO=$1 + releaseTag=$2 + + echo "" + echo "deleting the release tagged $releaseTag" + echo " from the repository $REPO" + echo "" + + echo "looking for an existing '$releaseTag' release in the repo $REPO" + + response=$( + curl --fail \ + --netrc \ + --silent \ + --location \ + --request "GET" \ + "https://api.github.com/repos/${REPO}/releases" + ) + + releaseID=$(echo $response | \ + jq --arg releaseTag $releaseTag \ + '.[] | select(.tag_name == $releaseTag) | .id') + + echo "" + echo "releaseID(s): $releaseID" + echo "" + + if [ -n "$releaseID" ] ; then + + for aReleaseID in $releaseID + do + echo "deleting an existing '$releaseTag'($aReleaseID) release in the repo $REPO" + response=$( + curl --fail \ + --netrc \ + --silent \ + --location \ + --request "DELETE" \ + "https://api.github.com/repos/${REPO}/releases/$aReleaseID" + ) + done + echo "" + fi + + echo "looking for an existing '$releaseTag' git/tag in the repo $REPO" + + response=$( + curl --fail \ + --netrc \ + --silent \ + --location \ + --request "GET" \ + "https://api.github.com/repos/${REPO}/git/matching-refs/tags/$releaseTag" + ) + + tagURL=$(echo $response | jq '.[].url') + tagURL="${tagURL%\"}" + tagURL="${tagURL#\"}" + + if [ -n "$tagURL" ]; then + echo "deleting an existing '$releaseTag' git/tag in the repo $REPO" + response=$( + curl --fail \ + --netrc \ + --silent \ + --location \ + --request "DELETE" \ + $tagURL + ) + fi +} + +########################### +function createNewRelease { +# returns: upload_url (envVar) + + [ -n "$1" ] || (echo "createNewRelease: missing repository"; exit 1); + [ -n "$2" ] || (echo "createNewRelease: missing releaseTag"; exit 1); + [ -n "$3" ] || (echo "createNewRelease: missing release name"; exit 1); + [ -n "$4" ] || (echo "createNewRelease: missing release description filename"; exit 1); + + REPO=$1 + TAG=$2 + NAME=$3 + BODY=$(cat $4) + + echo "" + echo "Creating a new release in the repository $REPO" + echo " with tag $TAG" + echo " and name $NAME" + echo " using the message in the file $4" + echo "--------------------------------------------------------------" + echo $BODY + echo "--------------------------------------------------------------" + + payload=$( + jq --null-input \ + --arg tag "$TAG" \ + --arg name "$NAME" \ + --arg body "$BODY" \ + '{ tag_name: $tag, name: $name, body: $body, draft: false, prerelease: true }' + ) + + response=$( + curl --fail \ + --netrc \ + --silent \ + --location \ + --data "$payload" \ + "https://api.github.com/repos/${REPO}/releases" + ) + + upload_url="$(echo "$response" | \ + jq -r .upload_url | sed -e "s/{?name,label}//")" + + echo "" + echo "upload_url:" + echo $upload_url +} + +######################## +function uploadAnAsset { + + [ -n "$1" ] || (echo "uploadAnAsset: missing upload url"; exit 1); + [ -n "$2" ] || (echo "uploadAnAsset: missing file name"; exit 1); + [ -n "$3" ] || (echo "uploadAnAsset: missing file type"; exit 1); + + upload_url=$1 + file=$2 + fileType=$3 + + echo "" + echo "uploading the asset $file" + echo " of type $fileType" + + curl --netrc \ + --silent \ + --header "Content-Type:$fileType" \ + --data-binary "@$file" \ + "$upload_url?name=$(basename "$file")" + echo "" +} + +# The above has been heavily modified into a collection of shell functions +# by Stephen Gaito working on the pdf2htmlEX project. +# +# It has been based upon the code in: +# https://gist.github.com/foca/38d82e93e32610f5241709f8d5720156 +# on 2019-11-28 +# +# The relevant GitHub API can be found at: +# https://developer.github.com/v3/git/refs/ +# https://developer.github.com/v3/repos/releases/ +# +# The original code has been used under the following (MIT-like) license: + +# Copyright (c) 2016 Nicolas Sanguinetti +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation +# files (the "Software"), to deal in the Software without +# restriction, including without limitation the rights to use, +# copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following +# conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. diff --git a/buildScripts/uploadGitHubReleaseMessage b/buildScripts/uploadGitHubReleaseMessage new file mode 100644 index 0000000..0070e94 --- /dev/null +++ b/buildScripts/uploadGitHubReleaseMessage @@ -0,0 +1,35 @@ +This is the most recent release of the pdf2htmlEX project. + +We release three types of binary objects: + +1. The file *.AppImage on this release page is an AppImage + + You can download the AppImage, make it executable and then 'just run + it'. + + See: https://appimage.org/ for details + +2. The file *.deb is a Debian Archive + + You can download the Debian Archive and install it locally using: + + sudo apt install <> + + While the Debian archive is built on a specific Ubuntu release, it can + usually be used on any more recent Ubuntu releases. + +3. You can alternatively get pdf2htmlEX Docker images from Docker Hub in + either of the repositories: + + pdf2htmlEX/pdf2htmlEX (offical release) + + or + + stephengaito/pdf2htmlEX (development releases) + +We also release a zip archive of the browser test results in the +*-testResults.zip file. + +Finally, the various *.txt and *buildInfo.sh files have well known +(unchanging) names which can be used by automatic scripts to identifiy the +current full names of the corresponding binary artifacts. diff --git a/buildScripts/uploadImages b/buildScripts/uploadImages new file mode 100755 index 0000000..28760a0 --- /dev/null +++ b/buildScripts/uploadImages @@ -0,0 +1,17 @@ +#!/bin/sh + +# This shell script uploads already existing pdf2htmlEX AppImage and Docker +# Images + +################ +# do the uploads + +set -ev + +./buildScripts/reportEnvs || { echo 'reportEnvs FAILED' ; exit 1 ; } + +./buildScripts/uploadGitHubRelease || { echo 'uploadGitHubRelease FAILED' ; exit 1 ; } + +./buildScripts/uploadDockerImage || { echo 'uploadDockerImage FAILED' ; exit 1 ; } + + diff --git a/buildScripts/versionEnvs b/buildScripts/versionEnvs new file mode 100755 index 0000000..00ac4b6 --- /dev/null +++ b/buildScripts/versionEnvs @@ -0,0 +1,78 @@ +#!/bin/sh + +# This shell script exports environment variables for the latest software +# versions + +# see: https://poppler.freedesktop.org/releases.html +# current working: 0.83.0 + +export PDF2HTMLEX_VERSION=0.18.8.alpha + +export POPPLER_VERSION=poppler-0.89.0 +#export POPPLER_VERSION=poppler-0.88.0 +#export POPPLER_VERSION=poppler-0.87.0 +#export POPPLER_VERSION=poppler-0.86.1 +#export POPPLER_VERSION=poppler-0.86.0 +#export POPPLER_VERSION=poppler-0.85.0 +#export POPPLER_VERSION=poppler-0.84.0 +#export POPPLER_VERSION=poppler-0.83.0 +#export POPPLER_VERSION=poppler-0.82.0 +#export POPPLER_VERSION=poppler-0.81.0 + +# see: https://github.com/fontforge/fontforge/releases +# current working: 20190801 + +export FONTFORGE_VERSION=20200314 +#export FONTFORGE_VERSION=20190801 +#export FONTFORGE_VERSION=20190413 +#export FONTFORGE_VERSION=20190413 +#export FONTFORGE_VERSION=20190317 +#export FONTFORGE_VERSION=20170731 + +if [ -z "$PDF2HTMLEX_BRANCH" ]; then + export PDF2HTMLEX_BRANCH="$(git rev-parse --abbrev-ref HEAD)" + if [ -z "$PDF2HTMLEX_BRANCH" ]; then + echo "" + read -p "Enter the pdf2htmlEX branch or version: " PDF2HTMLEX_BRANCH + echo "" + if [ -z "$PDF2HTMLEX_BRANCH" ]; then + echo "PDF2HTMLEX_BRANCH not set... so we can not build anything." + exit 1 + fi + fi +fi + +if test -r /etc/lsb-release ; then + cat /etc/lsb-release + # source /etc/lsb-release + . /etc/lsb-release + export BUILD_DIST=$DISTRIB_CODENAME + export BUILD_OS=$DISTRIB_ID +elif test -r /etc/alpine-release ; then + cat /etc/alpine-release + export BUILD_OS=alpine + export BUILD_DIST=$(cat /etc/alpine-release) +else + echo "FAILURE: could not determine release" + exit -1 +fi + +export BUILD_DATE="$(date +%Y%m%d)" + +export BUILD_TIME="$(date +%Y_%m_%d-%H_%M_%S)" + +export MACHINE_ARCH="$(uname -m)" + +export PDF2HTMLEX_NAME=$PDF2HTMLEX_VERSION-$PDF2HTMLEX_BRANCH-$BUILD_DATE-$BUILD_OS-$BUILD_DIST-$MACHINE_ARCH + +echo "export PDF2HTMLEX_NAME=\"$PDF2HTMLEX_NAME\"" > buildScripts/reSourceVersionEnvs +echo "export PDF2HTMLEX_VERSION=\"$PDF2HTMLEX_VERSION\"" >> buildScripts/reSourceVersionEnvs +echo "export POPPLER_VERSION=\"$POPPLER_VERSION\"" >> buildScripts/reSourceVersionEnvs +echo "export FONTFORGE_VERSION=\"$FONTFORGE_VERSION\"" >> buildScripts/reSourceVersionEnvs +echo "export PDF2HTMLEX_BRANCH=\"$PDF2HTMLEX_BRANCH\"" >> buildScripts/reSourceVersionEnvs +echo "export MACHINE_ARCH=\"$MACHINE_ARCH\"" >> buildScripts/reSourceVersionEnvs +echo "export BUILD_OS=\"$BUILD_OS\"" >> buildScripts/reSourceVersionEnvs +echo "export BUILD_DIST=\"$BUILD_DIST\"" >> buildScripts/reSourceVersionEnvs +echo "export BUILD_DATE=\"$BUILD_DATE\"" >> buildScripts/reSourceVersionEnvs +echo "export BUILD_TIME=\"$BUILD_TIME\"" >> buildScripts/reSourceVersionEnvs +echo "export PDF2HTMLEX_PREFIX=\"$PDF2HTMLEX_PREFIX\"" >> buildScripts/reSourceVersionEnvs diff --git a/dobuild b/dobuild deleted file mode 100755 index 97e5ac1..0000000 --- a/dobuild +++ /dev/null @@ -1,4 +0,0 @@ -mkdir build -cd build -cmake .. -make diff --git a/dobuildClang b/dobuildClang deleted file mode 100755 index 4a9914a..0000000 --- a/dobuildClang +++ /dev/null @@ -1,4 +0,0 @@ -mkdir build -cd build -CC=clang CXX=clang++ cmake .. -make diff --git a/doclean b/doclean deleted file mode 100755 index 97f8946..0000000 --- a/doclean +++ /dev/null @@ -1 +0,0 @@ -rm -rf build pdf2htmlEX.1 share/*.css share/*.js share/*.min.* src/pdf2htmlEX-config.h src/util/css_const.h diff --git a/doinstall b/doinstall deleted file mode 100755 index de19338..0000000 --- a/doinstall +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -if [[ $# -eq 0 ]] ; then - - echo "This installation assumes you have 'sudo' privileges" - echo "Type ctrl-c now if DO NOT want to continue" - read -p "Type anything else to continue: " - -fi - -cd build -sudo make install diff --git a/patches/fontforge-20170731-fixGDraw.patch b/patches/fontforge-20170731-fixGDraw.patch new file mode 100644 index 0000000..8d162d2 --- /dev/null +++ b/patches/fontforge-20170731-fixGDraw.patch @@ -0,0 +1,32 @@ +diff --git a/gdraw/drawboxborder.c b/gdraw/drawboxborder.c +index 629968608..0b00e9dd5 100644 +--- a/gdraw/drawboxborder.c ++++ b/gdraw/drawboxborder.c +@@ -24,6 +24,7 @@ + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ ++#include + #include + #include + #include +diff --git a/gdraw/gpsdraw.c b/gdraw/gpsdraw.c +index 5e58b6208..099e41bbd 100644 +--- a/gdraw/gpsdraw.c ++++ b/gdraw/gpsdraw.c +@@ -24,6 +24,7 @@ + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ ++#include "fontforge-config.h" + #include + #include + #include +@@ -31,7 +32,6 @@ + #if !defined(__MINGW32__) + #include + #endif +-#include "fontforge-config.h" + #include + + #include "gpsdrawP.h" diff --git a/patches/fontforge-20170731-fixGitVersion.patch b/patches/fontforge-20170731-fixGitVersion.patch new file mode 100644 index 0000000..887c05d --- /dev/null +++ b/patches/fontforge-20170731-fixGitVersion.patch @@ -0,0 +1,13 @@ +fontforge-config.h +--- a/inc/fontforge-config.h 2019-11-23 06:38:36.632042953 +0000 ++++ b/inc/fontforge-config.h 2019-11-23 06:38:47.424229496 +0000 +@@ -67,7 +67,7 @@ + /* #undef FONTFORGE_DEBUG */ + + /* "git hash that source are built from" */ +-#define FONTFORGE_GIT_VERSION "" ++#define FONTFORGE_GIT_VERSION "20170731" + + /* ExeLibFontForge Major Version */ + #define FONTFORGE_LIBFFE_VERSION_MAJOR 2 + diff --git a/3rdparty/PDF.js/LICENSE b/pdf2htmlEX/3rdparty/PDF.js/LICENSE similarity index 100% rename from 3rdparty/PDF.js/LICENSE rename to pdf2htmlEX/3rdparty/PDF.js/LICENSE diff --git a/3rdparty/PDF.js/build.sh b/pdf2htmlEX/3rdparty/PDF.js/build.sh similarity index 100% rename from 3rdparty/PDF.js/build.sh rename to pdf2htmlEX/3rdparty/PDF.js/build.sh diff --git a/3rdparty/PDF.js/compatibility.js b/pdf2htmlEX/3rdparty/PDF.js/compatibility.js similarity index 100% rename from 3rdparty/PDF.js/compatibility.js rename to pdf2htmlEX/3rdparty/PDF.js/compatibility.js diff --git a/3rdparty/PDF.js/compatibility.min.js b/pdf2htmlEX/3rdparty/PDF.js/compatibility.min.js similarity index 100% rename from 3rdparty/PDF.js/compatibility.min.js rename to pdf2htmlEX/3rdparty/PDF.js/compatibility.min.js diff --git a/3rdparty/closure-compiler/COPYING b/pdf2htmlEX/3rdparty/closure-compiler/COPYING similarity index 100% rename from 3rdparty/closure-compiler/COPYING rename to pdf2htmlEX/3rdparty/closure-compiler/COPYING diff --git a/3rdparty/closure-compiler/README b/pdf2htmlEX/3rdparty/closure-compiler/README similarity index 100% rename from 3rdparty/closure-compiler/README rename to pdf2htmlEX/3rdparty/closure-compiler/README diff --git a/3rdparty/closure-compiler/compiler.jar b/pdf2htmlEX/3rdparty/closure-compiler/compiler.jar similarity index 100% rename from 3rdparty/closure-compiler/compiler.jar rename to pdf2htmlEX/3rdparty/closure-compiler/compiler.jar diff --git a/3rdparty/yuicompressor/LICENSE.TXT b/pdf2htmlEX/3rdparty/yuicompressor/LICENSE.TXT similarity index 100% rename from 3rdparty/yuicompressor/LICENSE.TXT rename to pdf2htmlEX/3rdparty/yuicompressor/LICENSE.TXT diff --git a/3rdparty/yuicompressor/yuicompressor-2.4.8.jar b/pdf2htmlEX/3rdparty/yuicompressor/yuicompressor-2.4.8.jar similarity index 100% rename from 3rdparty/yuicompressor/yuicompressor-2.4.8.jar rename to pdf2htmlEX/3rdparty/yuicompressor/yuicompressor-2.4.8.jar diff --git a/CMakeLists.txt b/pdf2htmlEX/CMakeLists.txt similarity index 77% rename from CMakeLists.txt rename to pdf2htmlEX/CMakeLists.txt index 3852c22..218c54d 100644 --- a/CMakeLists.txt +++ b/pdf2htmlEX/CMakeLists.txt @@ -20,30 +20,38 @@ add_custom_target(dist find_package(PkgConfig) -pkg_check_modules(POPPLER REQUIRED poppler>=0.25.0) -include_directories(${POPPLER_INCLUDE_DIRS}) -link_directories(${POPPLER_LIBRARY_DIRS}) -set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${POPPLER_LIBRARIES}) +# SINCE we have a very intimate relationship with a particular version of +# poppler... we explicitly describe the poppler include and library +# paths. +# +include_directories( + ../poppler/build/poppler + ../poppler/build + ../poppler/poppler + ../poppler +) +# +# The following order is critical as the glib functions use functions +# located in the main poppler library +# +set(POPPLER_LIBRARIES ${POPPLER_LIBRARIES} + ${CMAKE_SOURCE_DIR}/../poppler/build/glib/libpoppler-glib.a + ${CMAKE_SOURCE_DIR}/../poppler/build/libpoppler.a +) + if(ENABLE_SVG) pkg_check_modules(CAIRO REQUIRED cairo>=1.10.0) - message("Trying to locate cairo-svg...") + message("-- Trying to locate cairo-svg...") find_path(CAIRO_SVG_INCLUDE_PATH cairo-svg.h PATHS ${CAIRO_INCLUDE_DIRS} NO_DEFAULT_PATH) if(CAIRO_SVG_INCLUDE_PATH) + message("-- found cairo-svg...") include_directories(${CAIRO_INCLUDE_DIRS}) - link_directories(${CAIRO_LIBRARY_DIRS}) - set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${CAIRO_LIBRARIES}) + if(NOT DEFINED ENV{USING_BREW}) + link_directories(${CAIRO_LIBRARY_DIRS}) + set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${CAIRO_LIBRARIES}) + endif() set(ENABLE_SVG 1) - set(CAIROOUTPUTDEV_PATH 3rdparty/poppler/git) - include_directories(${CAIROOUTPUTDEV_PATH}) - set(PDF2HTMLEX_SRC ${PDF2HTMLEX_SRC} - ${CAIROOUTPUTDEV_PATH}/CairoFontEngine.h - ${CAIROOUTPUTDEV_PATH}/CairoFontEngine.cc - ${CAIROOUTPUTDEV_PATH}/CairoRescaleBox.h - ${CAIROOUTPUTDEV_PATH}/CairoRescaleBox.cc - ${CAIROOUTPUTDEV_PATH}/CairoOutputDev.h - ${CAIROOUTPUTDEV_PATH}/CairoOutputDev.cc - ) else() message(FATAL_ERROR "Error: no SVG support found in Cairo") endif() @@ -51,14 +59,50 @@ if(ENABLE_SVG) find_package(Freetype REQUIRED) include_directories(${FREETYPE_INCLUDE_DIRS}) link_directories(${FREETYPE_LIBRARY_DIRS}) - set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${FREETYPE_LIBRARIES}) +# set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${FREETYPE_LIBRARIES}) endif() -# fontforge starts using pkg-config 'correctly' since 2.0.0 -pkg_check_modules(FONTFORGE REQUIRED libfontforge>=2.0.0) +# SINCE we have a very intimate relationship with a particular version of +# fontforge... we explicitly describe the fontforge include and library +# paths. +# +include_directories( + ../fontforge/fontforge + ../fontforge + ../fontforge/build/inc + ../fontforge/inc +) +# include_directories(${FONTFORGE_INCLUDE_DIRS}) link_directories(${FONTFORGE_LIBRARY_DIRS}) -set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} ${FONTFORGE_LIBRARIES}) +set(FONTFORGE_LIBRARIES ${FONTFORGE_LIBRARIES} + ${CMAKE_SOURCE_DIR}/../fontforge/build/lib/libfontforge.a +) + +# If we are using Alpine Linux then we need to add -lintl +# +if (EXISTS /usr/lib/libintl.so ) + set(LIB_INTL_LIBRARIES -lintl ) +else () + set(LIB_INTL_LIBRARIES "" ) +endif() + +set(PDF2HTMLEX_LIBS ${PDF2HTMLEX_LIBS} + ${POPPLER_LIBRARIES} + ${FONTFORGE_LIBRARIES} + ${LIB_INTL_LIBRARIES} + ${CAIRO_LIBRARIES} + -ljpeg + -lpng + -lfontconfig + -lfreetype + -lxml2 + -lglib-2.0 + -lgio-2.0 + -pthread + -lz + -lm +) # debug build flags (overwrite default cmake debug flags) set(CMAKE_C_FLAGS_DEBUG "-ggdb -pg") @@ -80,9 +124,11 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Woverloaded-virtual") # CYGWIN or GCC 4.5.x bug if(CYGWIN) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++0x") +# was: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++0x") +# the following change is untested: +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++14") else() -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -pthread") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -pthread") endif() # check the C++11 features we need @@ -149,6 +195,8 @@ set(PDF2HTMLEX_SRC ${PDF2HTMLEX_SRC} src/util/unicode.cc src/util/mingw.h src/util/mingw.cc + src/util/SignalHandler.h + src/util/SignalHandler.cc src/ArgParser.h src/ArgParser.cc src/Base64Stream.h @@ -223,6 +271,7 @@ set(PDF2HTMLEX_TMPDIR /tmp/pdf2htmlEX/tmp) set(PDF2HTMLEX_DATDIR /tmp/pdf2htmlEX/dat) set(PDF2HTMLEX_PNGDIR /tmp/pdf2htmlEX/png) set(PDF2HTMLEX_OUTDIR /tmp/pdf2htmlEX/out) +set(PDF2HTMLEX_HTMDIR /tmp/pdf2htmlEX/html) file(MAKE_DIRECTORY ${PDF2HTMLEX_TMPDIR}) file(MAKE_DIRECTORY ${PDF2HTMLEX_DATDIR}) file(MAKE_DIRECTORY ${PDF2HTMLEX_PNGDIR}) diff --git a/CMakeLists.txt.patch b/pdf2htmlEX/CMakeLists.txt.patch similarity index 100% rename from CMakeLists.txt.patch rename to pdf2htmlEX/CMakeLists.txt.patch diff --git a/logo/LICENSE b/pdf2htmlEX/logo/LICENSE similarity index 100% rename from logo/LICENSE rename to pdf2htmlEX/logo/LICENSE diff --git a/logo/LICENSE_CC-BY-3.0 b/pdf2htmlEX/logo/LICENSE_CC-BY-3.0 similarity index 100% rename from logo/LICENSE_CC-BY-3.0 rename to pdf2htmlEX/logo/LICENSE_CC-BY-3.0 diff --git a/logo/design.svg b/pdf2htmlEX/logo/design.svg similarity index 100% rename from logo/design.svg rename to pdf2htmlEX/logo/design.svg diff --git a/logo/notes.txt b/pdf2htmlEX/logo/notes.txt similarity index 100% rename from logo/notes.txt rename to pdf2htmlEX/logo/notes.txt diff --git a/logo/pdf2htmlEX-256x256.png b/pdf2htmlEX/logo/pdf2htmlEX-256x256.png similarity index 100% rename from logo/pdf2htmlEX-256x256.png rename to pdf2htmlEX/logo/pdf2htmlEX-256x256.png diff --git a/logo/pdf2htmlEX-64x64.png b/pdf2htmlEX/logo/pdf2htmlEX-64x64.png similarity index 100% rename from logo/pdf2htmlEX-64x64.png rename to pdf2htmlEX/logo/pdf2htmlEX-64x64.png diff --git a/logo/pdf2htmlEX.svg b/pdf2htmlEX/logo/pdf2htmlEX.svg similarity index 100% rename from logo/pdf2htmlEX.svg rename to pdf2htmlEX/logo/pdf2htmlEX.svg diff --git a/logo/update_png.sh b/pdf2htmlEX/logo/update_png.sh similarity index 100% rename from logo/update_png.sh rename to pdf2htmlEX/logo/update_png.sh diff --git a/pdf2htmlEX.1.in b/pdf2htmlEX/pdf2htmlEX.1.in similarity index 99% rename from pdf2htmlEX.1.in rename to pdf2htmlEX/pdf2htmlEX.1.in index d3cd881..570997c 100644 --- a/pdf2htmlEX.1.in +++ b/pdf2htmlEX/pdf2htmlEX.1.in @@ -359,7 +359,7 @@ pdf2htmlEX is written by Lu Wang .SH SEE ALSO .TP Home page -https://github.com/coolwanglu/pdf2htmlEX +https://github.com/pdf2htmlEX/pdf2htmlEX .TP pdf2htmlEX Wiki -https://github.com/coolwanglu/pdf2htmlEX/wiki +https://github.com/pdf2htmlEX/pdf2htmlEX/wiki diff --git a/share/LICENSE b/pdf2htmlEX/share/LICENSE similarity index 100% rename from share/LICENSE rename to pdf2htmlEX/share/LICENSE diff --git a/share/base.css.in b/pdf2htmlEX/share/base.css.in similarity index 98% rename from share/base.css.in rename to pdf2htmlEX/share/base.css.in index 515134d..7b2feac 100644 --- a/share/base.css.in +++ b/pdf2htmlEX/share/base.css.in @@ -2,7 +2,7 @@ /*! * Base CSS for pdf2htmlEX * Copyright 2012,2013 Lu Wang - * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE + * https://github.com/pdf2htmlEX/pdf2htmlEX/blob/master/share/LICENSE */ /* Part 1: Web Page Layout: Free to modify, except for a few of them which are required by pdf2htmlEX.js, see the comments */ #sidebar { /* Sidebar */ diff --git a/share/build_css.sh b/pdf2htmlEX/share/build_css.sh similarity index 100% rename from share/build_css.sh rename to pdf2htmlEX/share/build_css.sh diff --git a/share/build_js.sh b/pdf2htmlEX/share/build_js.sh similarity index 100% rename from share/build_js.sh rename to pdf2htmlEX/share/build_js.sh diff --git a/share/fancy.css.in b/pdf2htmlEX/share/fancy.css.in similarity index 98% rename from share/fancy.css.in rename to pdf2htmlEX/share/fancy.css.in index bdba3f6..138b6f2 100644 --- a/share/fancy.css.in +++ b/pdf2htmlEX/share/fancy.css.in @@ -2,7 +2,7 @@ /*! * Fancy styles for pdf2htmlEX * Copyright 2012,2013 Lu Wang - * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE + * https://github.com/pdf2htmlEX/pdf2htmlEX/blob/master/share/LICENSE */ @keyframes fadein { from { opacity:0;} to { opacity:1;} } @-webkit-keyframes fadein { from { opacity:0;} to { opacity:1;} } diff --git a/share/manifest b/pdf2htmlEX/share/manifest similarity index 97% rename from share/manifest rename to pdf2htmlEX/share/manifest index b03560f..0380867 100644 --- a/share/manifest +++ b/pdf2htmlEX/share/manifest @@ -17,7 +17,7 @@ # Declaration - Do not modify """ - + diff --git a/share/pdf2htmlEX-64x64.png b/pdf2htmlEX/share/pdf2htmlEX-64x64.png similarity index 100% rename from share/pdf2htmlEX-64x64.png rename to pdf2htmlEX/share/pdf2htmlEX-64x64.png diff --git a/share/pdf2htmlEX.js.in b/pdf2htmlEX/share/pdf2htmlEX.js.in similarity index 99% rename from share/pdf2htmlEX.js.in rename to pdf2htmlEX/share/pdf2htmlEX.js.in index a678759..9423ce9 100644 --- a/share/pdf2htmlEX.js.in +++ b/pdf2htmlEX/share/pdf2htmlEX.js.in @@ -2,7 +2,7 @@ /** * @license pdf2htmlEX.js: Core UI functions for pdf2htmlEX * Copyright 2012,2013 Lu Wang and other contributors - * https://github.com/coolwanglu/pdf2htmlEX/blob/master/share/LICENSE + * https://github.com/pdf2htmlEX/pdf2htmlEX/blob/master/share/LICENSE */ /* diff --git a/src/ArgParser.cc b/pdf2htmlEX/src/ArgParser.cc similarity index 100% rename from src/ArgParser.cc rename to pdf2htmlEX/src/ArgParser.cc diff --git a/src/ArgParser.h b/pdf2htmlEX/src/ArgParser.h similarity index 100% rename from src/ArgParser.h rename to pdf2htmlEX/src/ArgParser.h diff --git a/src/BackgroundRenderer/BackgroundRenderer.cc b/pdf2htmlEX/src/BackgroundRenderer/BackgroundRenderer.cc similarity index 100% rename from src/BackgroundRenderer/BackgroundRenderer.cc rename to pdf2htmlEX/src/BackgroundRenderer/BackgroundRenderer.cc diff --git a/src/BackgroundRenderer/BackgroundRenderer.h b/pdf2htmlEX/src/BackgroundRenderer/BackgroundRenderer.h similarity index 100% rename from src/BackgroundRenderer/BackgroundRenderer.h rename to pdf2htmlEX/src/BackgroundRenderer/BackgroundRenderer.h diff --git a/src/BackgroundRenderer/CairoBackgroundRenderer.cc b/pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.cc similarity index 99% rename from src/BackgroundRenderer/CairoBackgroundRenderer.cc rename to pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.cc index a7eaed8..ae5c809 100644 --- a/src/BackgroundRenderer/CairoBackgroundRenderer.cc +++ b/pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.cc @@ -46,7 +46,7 @@ CairoBackgroundRenderer::~CairoBackgroundRenderer() void CairoBackgroundRenderer::drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen) + CharCode code, int nBytes, const Unicode *u, int uLen) { // draw characters as image when // - in fallback mode diff --git a/src/BackgroundRenderer/CairoBackgroundRenderer.h b/pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.h similarity index 97% rename from src/BackgroundRenderer/CairoBackgroundRenderer.h rename to pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.h index d5c8637..f8bbc07 100644 --- a/src/BackgroundRenderer/CairoBackgroundRenderer.h +++ b/pdf2htmlEX/src/BackgroundRenderer/CairoBackgroundRenderer.h @@ -42,7 +42,7 @@ public: virtual void drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen); + CharCode code, int nBytes, const Unicode *u, int uLen); //for proof void beginTextObject(GfxState *state); diff --git a/src/BackgroundRenderer/SplashBackgroundRenderer.cc b/pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.cc similarity index 96% rename from src/BackgroundRenderer/SplashBackgroundRenderer.cc rename to pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.cc index be14222..1f6c184 100644 --- a/src/BackgroundRenderer/SplashBackgroundRenderer.cc +++ b/pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.cc @@ -59,13 +59,12 @@ SplashBackgroundRenderer::SplashBackgroundRenderer(const string & imgFormat, HTM void SplashBackgroundRenderer::startPage(int pageNum, GfxState *state, XRef *xrefA) { SplashOutputDev::startPage(pageNum, state, xrefA); - clearModRegion(); } void SplashBackgroundRenderer::drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen) + CharCode code, int nBytes, const Unicode *u, int uLen) { if (param.proof || html_renderer->is_char_covered(drawn_char_count)) { SplashOutputDev::drawChar(state,x,y,dx,dy,originX,originY,code,nBytes,u,uLen); @@ -127,8 +126,16 @@ void SplashBackgroundRenderer::embed_image(int pageno) { // xmin->xmax is top->bottom int xmin, xmax, ymin, ymax; - getModRegion(&xmin, &ymin, &xmax, &ymax); - +// poppler-0.84.0 hack to recover from the removal of *ModRegion tracking +// + auto * bitmap = getBitmap(); + xmin = 0; + xmax = bitmap->getWidth(); + ymin = 0; + ymax = bitmap->getHeight(); +// +// end of hack + // dump the background image only when it is not empty if((xmin <= xmax) && (ymin <= ymax)) { diff --git a/src/BackgroundRenderer/SplashBackgroundRenderer.h b/pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.h similarity index 96% rename from src/BackgroundRenderer/SplashBackgroundRenderer.h rename to pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.h index 55baeb3..b8e07c0 100644 --- a/src/BackgroundRenderer/SplashBackgroundRenderer.h +++ b/pdf2htmlEX/src/BackgroundRenderer/SplashBackgroundRenderer.h @@ -44,7 +44,7 @@ public: virtual void drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen); + CharCode code, int nBytes, const Unicode *u, int uLen); //for proof void beginTextObject(GfxState *state); diff --git a/src/Base64Stream.cc b/pdf2htmlEX/src/Base64Stream.cc similarity index 100% rename from src/Base64Stream.cc rename to pdf2htmlEX/src/Base64Stream.cc diff --git a/src/Base64Stream.h b/pdf2htmlEX/src/Base64Stream.h similarity index 100% rename from src/Base64Stream.h rename to pdf2htmlEX/src/Base64Stream.h diff --git a/src/Color.cc b/pdf2htmlEX/src/Color.cc similarity index 100% rename from src/Color.cc rename to pdf2htmlEX/src/Color.cc diff --git a/src/Color.h b/pdf2htmlEX/src/Color.h similarity index 100% rename from src/Color.h rename to pdf2htmlEX/src/Color.h diff --git a/src/CoveredTextDetector.cc b/pdf2htmlEX/src/CoveredTextDetector.cc similarity index 100% rename from src/CoveredTextDetector.cc rename to pdf2htmlEX/src/CoveredTextDetector.cc diff --git a/src/CoveredTextDetector.h b/pdf2htmlEX/src/CoveredTextDetector.h similarity index 100% rename from src/CoveredTextDetector.h rename to pdf2htmlEX/src/CoveredTextDetector.h diff --git a/src/DrawingTracer.cc b/pdf2htmlEX/src/DrawingTracer.cc similarity index 98% rename from src/DrawingTracer.cc rename to pdf2htmlEX/src/DrawingTracer.cc index 7086565..5d23d42 100644 --- a/src/DrawingTracer.cc +++ b/pdf2htmlEX/src/DrawingTracer.cc @@ -136,10 +136,10 @@ void DrawingTracer::restore() #endif } -void DrawingTracer::do_path(GfxState * state, GfxPath * path) +void DrawingTracer::do_path(GfxState * state, const GfxPath * path) { //copy from CairoOutputDev::doPath - GfxSubpath *subpath; + const GfxSubpath *subpath; int i, j; double x, y; cairo_new_path(cairo); @@ -220,9 +220,9 @@ void DrawingTracer::stroke(GfxState * state) break; } - GfxPath * path = state->getPath(); + const GfxPath * path = state->getPath(); for (int i = 0; i < path->getNumSubpaths(); ++i) { - GfxSubpath * subpath = path->getSubpath(i); + const GfxSubpath * subpath = path->getSubpath(i); if (subpath->getNumPoints() <= 0) continue; double x = subpath->getX(0); diff --git a/src/DrawingTracer.h b/pdf2htmlEX/src/DrawingTracer.h similarity index 97% rename from src/DrawingTracer.h rename to pdf2htmlEX/src/DrawingTracer.h index 3a0bc88..0d186d0 100644 --- a/src/DrawingTracer.h +++ b/pdf2htmlEX/src/DrawingTracer.h @@ -65,7 +65,7 @@ public: private: void finish(); // Following methods operate in user space (just before CTM is applied) - void do_path(GfxState * state, GfxPath * path); + void do_path(GfxState * state, const GfxPath * path); void draw_non_char_bbox(GfxState * state, double * bbox, int what); void draw_char_bbox(GfxState * state, double * bbox, int inTransparencyGroup); // If cairo is available, parameter state is ignored diff --git a/src/HTMLRenderer/HTMLRenderer.h b/pdf2htmlEX/src/HTMLRenderer/HTMLRenderer.h similarity index 98% rename from src/HTMLRenderer/HTMLRenderer.h rename to pdf2htmlEX/src/HTMLRenderer/HTMLRenderer.h index a1195e8..6f2c24c 100644 --- a/src/HTMLRenderer/HTMLRenderer.h +++ b/pdf2htmlEX/src/HTMLRenderer/HTMLRenderer.h @@ -75,7 +75,7 @@ namespace pdf2htmlEX { struct HTMLRenderer : OutputDev { - HTMLRenderer(Param & param); + HTMLRenderer(const char* progPath, Param & param); virtual ~HTMLRenderer(); void process(PDFDoc * doc); @@ -156,7 +156,9 @@ struct HTMLRenderer : OutputDev virtual void drawString(GfxState * state, const GooString * s); - virtual void drawImage(GfxState * state, Object * ref, Stream * str, int width, int height, GfxImageColorMap * colorMap, bool interpolate, int *maskColors, bool inlineImg); + virtual void drawImage(GfxState * state, Object * ref, Stream * str, + int width, int height, GfxImageColorMap * colorMap, + bool interpolate, const int *maskColors, bool inlineImg); virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, diff --git a/src/HTMLRenderer/draw.cc b/pdf2htmlEX/src/HTMLRenderer/draw.cc similarity index 100% rename from src/HTMLRenderer/draw.cc rename to pdf2htmlEX/src/HTMLRenderer/draw.cc diff --git a/src/HTMLRenderer/font.cc b/pdf2htmlEX/src/HTMLRenderer/font.cc similarity index 99% rename from src/HTMLRenderer/font.cc rename to pdf2htmlEX/src/HTMLRenderer/font.cc index 3392a9e..466f691 100644 --- a/src/HTMLRenderer/font.cc +++ b/pdf2htmlEX/src/HTMLRenderer/font.cc @@ -636,7 +636,8 @@ void HTMLRenderer::embed_font(const string & filepath, GfxFont * font, FontInfo if(mapped_code > max_key) max_key = mapped_code; - Unicode u, *pu=&u; + Unicode u; + Unicode const *pu=&u; if(info.use_tounicode) { int n = ctu ? diff --git a/src/HTMLRenderer/form.cc b/pdf2htmlEX/src/HTMLRenderer/form.cc similarity index 100% rename from src/HTMLRenderer/form.cc rename to pdf2htmlEX/src/HTMLRenderer/form.cc diff --git a/src/HTMLRenderer/general.cc b/pdf2htmlEX/src/HTMLRenderer/general.cc similarity index 99% rename from src/HTMLRenderer/general.cc rename to pdf2htmlEX/src/HTMLRenderer/general.cc index 459e091..7d43d13 100644 --- a/src/HTMLRenderer/general.cc +++ b/pdf2htmlEX/src/HTMLRenderer/general.cc @@ -41,7 +41,7 @@ using std::abs; using std::cerr; using std::endl; -HTMLRenderer::HTMLRenderer(Param & param) +HTMLRenderer::HTMLRenderer(const char* progPath, Param & param) :OutputDev() ,param(param) ,html_text_page(param, all_manager) @@ -56,7 +56,7 @@ HTMLRenderer::HTMLRenderer(Param & param) globalParams->setErrQuiet(true); } - ffw_init(param.debug); + ffw_init(progPath, param.debug); cur_mapping.resize(0x10000); cur_mapping2.resize(0x100); diff --git a/src/HTMLRenderer/image.cc b/pdf2htmlEX/src/HTMLRenderer/image.cc similarity index 92% rename from src/HTMLRenderer/image.cc rename to pdf2htmlEX/src/HTMLRenderer/image.cc index ef51ffc..b4d84cc 100644 --- a/src/HTMLRenderer/image.cc +++ b/pdf2htmlEX/src/HTMLRenderer/image.cc @@ -12,7 +12,9 @@ namespace pdf2htmlEX { -void HTMLRenderer::drawImage(GfxState * state, Object * ref, Stream * str, int width, int height, GfxImageColorMap * colorMap, bool interpolate, int *maskColors, bool inlineImg) +void HTMLRenderer::drawImage(GfxState * state, Object * ref, Stream * str, + int width, int height, GfxImageColorMap * colorMap, + bool interpolate, const int *maskColors, bool inlineImg) { tracer.draw_image(state); diff --git a/src/HTMLRenderer/link.cc b/pdf2htmlEX/src/HTMLRenderer/link.cc similarity index 90% rename from src/HTMLRenderer/link.cc rename to pdf2htmlEX/src/HTMLRenderer/link.cc index 842b6de..7cfb1bc 100644 --- a/src/HTMLRenderer/link.cc +++ b/pdf2htmlEX/src/HTMLRenderer/link.cc @@ -34,7 +34,11 @@ using std::endl; * The string will be put into a HTML attribute, surrounded by single quotes * So pay attention to the characters used here */ -static string get_linkdest_detail_str(LinkDest * dest, Catalog * catalog, int & pageno) +static string get_linkdest_detail_str( + LinkDest * dest, // borrow the caller's std::unique_ptr + Catalog * catalog, + int & pageno +) { pageno = 0; if(dest->isPageRef()) @@ -126,7 +130,10 @@ static string get_linkdest_detail_str(LinkDest * dest, Catalog * catalog, int & return sout.str(); } -string HTMLRenderer::get_linkaction_str(const LinkAction * action, string & detail) +string HTMLRenderer::get_linkaction_str( + const LinkAction * action, + string & detail +) { string dest_str; detail = ""; @@ -137,21 +144,26 @@ string HTMLRenderer::get_linkaction_str(const LinkAction * action, string & deta { case actionGoTo: { - auto * real_action = dynamic_cast(action); - LinkDest * dest = nullptr; + auto * real_action = + dynamic_cast(action); + std::unique_ptr dest = nullptr; if(auto _ = real_action->getDest()) - dest = _->copy(); + dest = std::unique_ptr( _->copy() ); else if (auto _ = real_action->getNamedDest()) dest = cur_catalog->findDest(_); if(dest) { int pageno = 0; - detail = get_linkdest_detail_str(dest, cur_catalog, pageno); + detail = get_linkdest_detail_str( + dest.get(), cur_catalog, pageno + ); if(pageno > 0) { - dest_str = (char*)str_fmt("#%s%x", CSS::PAGE_FRAME_CN, pageno); + dest_str = (char*)str_fmt( + "#%s%x", CSS::PAGE_FRAME_CN, pageno + ); } - delete dest; + dest.reset(); } } break; @@ -164,7 +176,7 @@ string HTMLRenderer::get_linkaction_str(const LinkAction * action, string & deta { auto * real_action = dynamic_cast(action); assert(real_action != nullptr); - dest_str = real_action->getURI()->toStr(); + dest_str = real_action->getURI(); } break; case actionLaunch: diff --git a/src/HTMLRenderer/outline.cc b/pdf2htmlEX/src/HTMLRenderer/outline.cc similarity index 100% rename from src/HTMLRenderer/outline.cc rename to pdf2htmlEX/src/HTMLRenderer/outline.cc diff --git a/src/HTMLRenderer/state.cc b/pdf2htmlEX/src/HTMLRenderer/state.cc similarity index 100% rename from src/HTMLRenderer/state.cc rename to pdf2htmlEX/src/HTMLRenderer/state.cc diff --git a/src/HTMLRenderer/text.cc b/pdf2htmlEX/src/HTMLRenderer/text.cc similarity index 99% rename from src/HTMLRenderer/text.cc rename to pdf2htmlEX/src/HTMLRenderer/text.cc index 06df7aa..506f947 100644 --- a/src/HTMLRenderer/text.cc +++ b/pdf2htmlEX/src/HTMLRenderer/text.cc @@ -74,7 +74,7 @@ void HTMLRenderer::drawString(GfxState * state, const GooString * s) int uLen; CharCode code; - Unicode *u = nullptr; + Unicode const *u = nullptr; HR_DEBUG(printf("HTMLRenderer::drawString:len=%d\n", len)); diff --git a/src/HTMLState.h b/pdf2htmlEX/src/HTMLState.h similarity index 100% rename from src/HTMLState.h rename to pdf2htmlEX/src/HTMLState.h diff --git a/src/HTMLTextLine.cc b/pdf2htmlEX/src/HTMLTextLine.cc similarity index 100% rename from src/HTMLTextLine.cc rename to pdf2htmlEX/src/HTMLTextLine.cc diff --git a/src/HTMLTextLine.h b/pdf2htmlEX/src/HTMLTextLine.h similarity index 100% rename from src/HTMLTextLine.h rename to pdf2htmlEX/src/HTMLTextLine.h diff --git a/src/HTMLTextPage.cc b/pdf2htmlEX/src/HTMLTextPage.cc similarity index 100% rename from src/HTMLTextPage.cc rename to pdf2htmlEX/src/HTMLTextPage.cc diff --git a/src/HTMLTextPage.h b/pdf2htmlEX/src/HTMLTextPage.h similarity index 100% rename from src/HTMLTextPage.h rename to pdf2htmlEX/src/HTMLTextPage.h diff --git a/src/Param.h b/pdf2htmlEX/src/Param.h similarity index 100% rename from src/Param.h rename to pdf2htmlEX/src/Param.h diff --git a/src/Preprocessor.cc b/pdf2htmlEX/src/Preprocessor.cc similarity index 97% rename from src/Preprocessor.cc rename to pdf2htmlEX/src/Preprocessor.cc index 42318b2..643bbc7 100644 --- a/src/Preprocessor.cc +++ b/pdf2htmlEX/src/Preprocessor.cc @@ -65,7 +65,7 @@ void Preprocessor::process(PDFDoc * doc) void Preprocessor::drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen) + CharCode code, int nBytes, const Unicode *u, int uLen) { GfxFont * font = state->getFont(); if(!font) return; diff --git a/src/Preprocessor.h b/pdf2htmlEX/src/Preprocessor.h similarity index 96% rename from src/Preprocessor.h rename to pdf2htmlEX/src/Preprocessor.h index d121b59..756993d 100644 --- a/src/Preprocessor.h +++ b/pdf2htmlEX/src/Preprocessor.h @@ -39,7 +39,7 @@ public: virtual void drawChar(GfxState *state, double x, double y, double dx, double dy, double originX, double originY, - CharCode code, int nBytes, Unicode *u, int uLen); + CharCode code, int nBytes, const Unicode *u, int uLen); // Start a page. // UGLY: These 2 versions are for different versions of poppler diff --git a/src/StateManager.h b/pdf2htmlEX/src/StateManager.h similarity index 100% rename from src/StateManager.h rename to pdf2htmlEX/src/StateManager.h diff --git a/src/StringFormatter.cc b/pdf2htmlEX/src/StringFormatter.cc similarity index 100% rename from src/StringFormatter.cc rename to pdf2htmlEX/src/StringFormatter.cc diff --git a/src/StringFormatter.h b/pdf2htmlEX/src/StringFormatter.h similarity index 100% rename from src/StringFormatter.h rename to pdf2htmlEX/src/StringFormatter.h diff --git a/src/TmpFiles.cc b/pdf2htmlEX/src/TmpFiles.cc similarity index 100% rename from src/TmpFiles.cc rename to pdf2htmlEX/src/TmpFiles.cc diff --git a/src/TmpFiles.h b/pdf2htmlEX/src/TmpFiles.h similarity index 100% rename from src/TmpFiles.h rename to pdf2htmlEX/src/TmpFiles.h diff --git a/src/css_class_names.cmakelists.txt b/pdf2htmlEX/src/css_class_names.cmakelists.txt similarity index 100% rename from src/css_class_names.cmakelists.txt rename to pdf2htmlEX/src/css_class_names.cmakelists.txt diff --git a/src/pdf2htmlEX-config.h.in b/pdf2htmlEX/src/pdf2htmlEX-config.h.in similarity index 100% rename from src/pdf2htmlEX-config.h.in rename to pdf2htmlEX/src/pdf2htmlEX-config.h.in diff --git a/src/pdf2htmlEX.cc b/pdf2htmlEX/src/pdf2htmlEX.cc similarity index 92% rename from src/pdf2htmlEX.cc rename to pdf2htmlEX/src/pdf2htmlEX.cc index bdc56aa..7197e51 100644 --- a/src/pdf2htmlEX.cc +++ b/pdf2htmlEX/src/pdf2htmlEX.cc @@ -25,6 +25,8 @@ #include "pdf2htmlEX-config.h" +#include "util/SignalHandler.h" + #if ENABLE_SVG #include #endif @@ -55,15 +57,18 @@ void show_usage_and_exit(const char * dummy = nullptr) void show_version_and_exit(const char * dummy = nullptr) { + const FFWVersionInfo* ffwVersionInfo = ffw_get_version_info(); + cerr << "pdf2htmlEX version " << PDF2HTMLEX_VERSION << endl; cerr << "Copyright 2012-2015 Lu Wang and other contributors" << endl; cerr << "Libraries: " << endl; cerr << " poppler " << POPPLER_VERSION << endl; - cerr << " libfontforge " << ffw_get_version() << endl; + cerr << " libfontforge (date) " << ffwVersionInfo->versionDate << endl; #if ENABLE_SVG cerr << " cairo " << cairo_version_string() << endl; #endif cerr << "Default data-dir: " << param.data_dir << endl; + cerr << "Poppler data-dir: " << param.poppler_data_dir << endl; cerr << "Supported image format:"; #ifdef ENABLE_LIBPNG cerr << " png"; @@ -368,6 +373,13 @@ int main(int argc, char **argv) param.data_dir = PDF2HTMLEX_DATA_PATH; #endif + if (getenv("APPDIR")) { + // we are running inside an AppImage so we need to adjust the data_dir + // however the user can supply some other absolute path later + // + param.data_dir = string(getenv("APPDIR")) + param.data_dir; + } + param.poppler_data_dir = param.data_dir + "/poppler"; parse_options(argc, argv); check_param(); @@ -387,9 +399,18 @@ int main(int argc, char **argv) exit(EXIT_FAILURE); } + // setup the signal handler + setupSignalHandler(argc, (const char**)argv, + param.data_dir.c_str(), + param.poppler_data_dir.c_str(), + param.tmp_dir.c_str()); + bool finished = false; - // read config file - globalParams = new GlobalParams(!param.poppler_data_dir.empty() ? param.poppler_data_dir.c_str() : NULL); + // read poppler config file + globalParams = std::make_unique( + !param.poppler_data_dir.empty() ? param.poppler_data_dir.c_str() : NULL + ); + // open PDF file PDFDoc * doc = nullptr; try @@ -416,11 +437,14 @@ int main(int argc, char **argv) cerr << "Document has copy-protection bit set." << endl; } - param.first_page = min(max(param.first_page, 1), doc->getNumPages()); - param.last_page = min(max(param.last_page, param.first_page), doc->getNumPages()); + param.first_page = + min(max(param.first_page, 1), doc->getNumPages()); + param.last_page = + min(max(param.last_page, param.first_page), + doc->getNumPages()); - unique_ptr(new HTMLRenderer(param))->process(doc); + unique_ptr(new HTMLRenderer(argv[0], param))->process(doc); finished = true; } @@ -435,7 +459,7 @@ int main(int argc, char **argv) // clean up delete doc; - delete globalParams; + globalParams.reset(); // check for memory leaks // Poppler Object class (Object.h) no longer has memCheck diff --git a/pdf2htmlEX/src/util/SignalHandler.cc b/pdf2htmlEX/src/util/SignalHandler.cc new file mode 100644 index 0000000..f98edc5 --- /dev/null +++ b/pdf2htmlEX/src/util/SignalHandler.cc @@ -0,0 +1,219 @@ +/* + * SignalHandler.cc + * + * Created on: 2019-Nov-14 + * Author: Stephen Gaito + */ + +/********** + +This collection of basic ANSI-C functions implement a crude SIG-SEGV +handler for when things go horribly wrong ;-( + +We implement them in as simple a maner as possible so that it will be as +portable as possible and less likely to fall into a reentrant deadlock. + +At the moment the most critical SIG-SEGVs are happening inside the +FontForge library. So we start by focusing upon adding more helpful +messages when FontForge can't save a file for us. + +**********/ + + +#include +#include +#include +#include +#include + +#include "pdf2htmlEX-config.h" +#include "util/ffw.h" +#include +#include + +const char* oopsMessage = + "\n" + "\n" + "Oops! Something went horribly wrong.... sorry!\n" + "\n"; + +const char* ffwMessage_1 = + "I was in the middle of asking FontForge to "; + +const char* ffwMessage_2 = + " a font.\n" + "\n" + "I suspect that the problem is that FontForge is having trouble\n" + "working with one of the fonts embedded in your pdf file.\n" + "\n" + "The best way to verify this is to install FontForge and to try\n" + "loading and then (re)generating each font in the\n" + "\n" + " "; + +const char* ffwMessage_3 = + "\n" + "\n" + "directory. See:\n" + "\n" + " https://github.com/pdf2htmlEX/pdf2htmlEX/wiki/Troubleshooting-Crashes\n" + "\n" + "for details.\n" + "\n" + "If one of these fonts crashes FontForge, then it is certainly not a\n" + "pdf2htmlEX problem.... sorry.\n" + "\n" + "IF it *is* a FontForge problem then you have the following options:\n" + "\n" + " 1) You can send a copy of the font you found which crashed FontForge to\n" + " the FontForge developers and see if they can find the problem.\n" + " (Be warned FontForge is a complex application, so it might be\n" + " very hard for the developers to isolate your problem.... )\n" + "\n" + " 2) You can try re-creating your PDF with a different font.\n" + "\n" + " 3) Or you can do both of these things...\n" + "\n" + "IF you were not able to crash FontForge using the fonts in the above\n" + "directory... then and only then please raise an issue with the pdf2htmlEX\n" + "team... make sure you provide them with your pdf, as well as the following\n" + "details:\n"; + +const char* noFfwMessage = + "Please raise an issue with the pdf2hmtlEX team so they can fix this...\n" + "\n" + "Please make sure you provide them with your pdf as well as the following\n" + "details:\n"; + +const char* detailsHeader = + "\n" + "--------------------------------------------------------------------------\n" + "\n"; + +const char* detailsBody = "no details recorded\n"; + +const char* pdf2htmlEXTmpDir = NULL; +const char* ffwAction = NULL; + +struct sigaction act; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-result" +void signalHandler(int sigInt) { + write(STDERR_FILENO, oopsMessage, strlen(oopsMessage) ); + + if (ffwAction) { + write(STDERR_FILENO, ffwMessage_1, strlen(ffwMessage_1) ); + write(STDERR_FILENO, ffwAction, strlen(ffwAction) ); + write(STDERR_FILENO, ffwMessage_2, strlen(ffwMessage_2) ); + write(STDERR_FILENO, pdf2htmlEXTmpDir, strlen(pdf2htmlEXTmpDir) ); + write(STDERR_FILENO, ffwMessage_3, strlen(ffwMessage_3) ); + } else { + write(STDERR_FILENO, noFfwMessage, strlen(noFfwMessage) ); + } + + write(STDERR_FILENO, detailsHeader, strlen(detailsHeader) ); + write(STDERR_FILENO, detailsBody, strlen(detailsBody) ); + exit(-1); + +} +#pragma GCC diagnostic pop + +#ifdef __cplusplus +extern "C" { +#endif + +void ffwSetAction(const char* anAction) { ffwAction = anAction; } +void ffwClearAction(const char* anAction) { ffwAction = NULL; } + +#ifdef __cplusplus +} +#endif + +void setupSignalHandler( + int argc, const char* argv[], + const char* data_dir, + const char* poppler_data_dir, + const char* tmp_dir) { + // THIS MUST BE CALLED AFTER ARGUMENT PARSING + + // Start by setting up the messages + // + // Construct the command line information + std::string detailInfo; + detailInfo = "Command line:\n"; + for (int i = 0 ; i < argc ; i++ ){ + detailInfo = detailInfo + " " + std::to_string(i) + ": [" + argv[i] + "]\n" ; + } + detailInfo = detailInfo + "\n"; + + // Construct the version information + const pdf2htmlEX::FFWVersionInfo* ffwVersionInfo = + pdf2htmlEX::ffw_get_version_info(); + + detailInfo = detailInfo + "Version information:\n"; + detailInfo = detailInfo + " pdf2htmlEX version " + pdf2htmlEX::PDF2HTMLEX_VERSION + "\n"; + detailInfo = detailInfo + " Copyright 2012-2015 Lu Wang and other contributors\n"; + detailInfo = detailInfo + "\n"; + detailInfo = detailInfo + "Libraries:\n" ; + detailInfo = detailInfo + " poppler " + POPPLER_VERSION + "\n"; + detailInfo = detailInfo + " libfontforge (date) " + ffwVersionInfo->versionDate + "\n"; +#if ENABLE_SVG + detailInfo = detailInfo + " cairo " + cairo_version_string() + "\n"; +#endif + detailInfo = detailInfo + "\n"; + detailInfo = detailInfo + "Default data-dir: " + data_dir + "\n"; + detailInfo = detailInfo + "Default poppler-data-dir: " + poppler_data_dir + "\n"; + detailInfo = detailInfo + "Default tmp-dir: " + tmp_dir + "\n"; + detailInfo = detailInfo + "\n"; + detailInfo = detailInfo + "Supported image formats:"; +#ifdef ENABLE_LIBPNG + detailInfo = detailInfo + " png"; +#endif +#ifdef ENABLE_LIBJPEG + detailInfo = detailInfo + " jpg"; +#endif +#if ENABLE_SVG + detailInfo = detailInfo + " svg"; +#endif + detailInfo = detailInfo + "\n\n"; + + detailsBody = strdup(detailInfo.c_str()); + + pdf2htmlEXTmpDir = strdup(tmp_dir); + + // Now setup the signal handler + // + memset(&act, 0, sizeof(act)); + act.sa_handler = signalHandler; + // + sigaction(SIGILL, &act, NULL); // Illegal Instruction + sigaction(SIGFPE, &act, NULL); // Floating-point exception + sigaction(SIGSEGV, &act, NULL); // Invalid memory reference + sigaction(SIGBUS, &act, NULL); // Bus error (bad memory access) + sigaction(SIGSYS, &act, NULL); // Bad system call (SVr4) + + // All done +} + + +/*** +int main(int argc, const char* argv[]) { + + setupSignalHandler(argc, argv, "aTmpDir"); + + ffwSetAction("save"); + + for (int i = 0; i < 5; i++) { + printf("sleeping.... \n"); + sleep(1); + } + + int *foo = NULL; + + *foo = 1; + + printf("We should not reach here!\n"); + +} +***/ diff --git a/pdf2htmlEX/src/util/SignalHandler.h b/pdf2htmlEX/src/util/SignalHandler.h new file mode 100644 index 0000000..d39b844 --- /dev/null +++ b/pdf2htmlEX/src/util/SignalHandler.h @@ -0,0 +1,21 @@ +#ifndef SIGNAL_HANDLER_H +#define SIGNAL_HANDLER_H + +#ifdef __cplusplus +extern "C" { +#endif + +void ffwSetAction(const char* anAction); +void ffwClearAction(void); + +#ifdef __cplusplus +} +#endif + +void setupSignalHandler( + int argc, const char* argv[], + const char* data_dir, + const char* poppler_data_dir, + const char* tmp_dir); + +#endif diff --git a/src/util/const.cc b/pdf2htmlEX/src/util/const.cc similarity index 100% rename from src/util/const.cc rename to pdf2htmlEX/src/util/const.cc diff --git a/src/util/const.h b/pdf2htmlEX/src/util/const.h similarity index 100% rename from src/util/const.h rename to pdf2htmlEX/src/util/const.h diff --git a/src/util/css_const.h.in b/pdf2htmlEX/src/util/css_const.h.in similarity index 100% rename from src/util/css_const.h.in rename to pdf2htmlEX/src/util/css_const.h.in diff --git a/src/util/encoding.cc b/pdf2htmlEX/src/util/encoding.cc similarity index 100% rename from src/util/encoding.cc rename to pdf2htmlEX/src/util/encoding.cc diff --git a/src/util/encoding.h b/pdf2htmlEX/src/util/encoding.h similarity index 100% rename from src/util/encoding.h rename to pdf2htmlEX/src/util/encoding.h diff --git a/src/util/ffw.c b/pdf2htmlEX/src/util/ffw.c similarity index 73% rename from src/util/ffw.c rename to pdf2htmlEX/src/util/ffw.c index c296f38..ff2473f 100644 --- a/src/util/ffw.c +++ b/pdf2htmlEX/src/util/ffw.c @@ -16,19 +16,22 @@ #include #include -#include "ffw.h" -#include "fontforge-2.0.20170731/autowidth.h" -#include "fontforge-2.0.20170731/bitmapchar.h" -#include "fontforge-2.0.20170731/cvimages.h" -#include "fontforge-2.0.20170731/encoding.h" -#include "fontforge-2.0.20170731/fvfonts.h" -#include "fontforge-2.0.20170731/namelist.h" -#include "fontforge-2.0.20170731/savefont.h" -#include "fontforge-2.0.20170731/splineorder2.h" -#include "fontforge-2.0.20170731/splineutil.h" -#include "fontforge-2.0.20170731/splineutil2.h" -#include "fontforge-2.0.20170731/start.h" -#include "fontforge-2.0.20170731/tottf.h" +#include "SignalHandler.h" + +#include "ffw.h" // needed for: +#include "gfile.h" // FindProgDir +#include "fontforge/autowidth.h" // FVRemoveKerns +#include "fontforge/bitmapchar.h" // SFReplaceEncodingBDFProps +#include "fontforge/cvimages.h" // FVImportImages +#include "fontforge/encoding.h" // (helpful as we have a name conflict) +#include "fontforge/fvfonts.h" // SFFindSlot +#include "fontforge/namelist.h" // UniFromName +#include "fontforge/savefont.h" // GenerateScript +#include "fontforge/splineorder2.h" // SFConvertToOrder2 +#include "fontforge/splineutil.h" // AltUniFree +#include "fontforge/splineutil2.h" // SplineFontNew +#include "fontforge/start.h" // InitSimpleStuff +#include "fontforge/tottf.h" // SFDefaultOS2Info static real EPS=1e-6; @@ -64,8 +67,11 @@ static void dumb_logwarning(const char * format, ...) { } static void dumb_post_error(const char * title, const char * error, ...) { } -void ffw_init(int debug) +void ffw_init(const char* progPath, int debug) { + ffwSetAction("initialize"); + char *localProgPath = strdup(progPath); + FindProgDir(localProgPath); InitSimpleStuff(); if ( default_encoding==NULL ) default_encoding=FindOrMakeEncoding("ISO8859-1"); @@ -88,10 +94,12 @@ void ffw_init(int debug) v.u.ival = 1; SetPrefs("DetectDiagonalStems", &v, NULL); } + ffwClearAction(); } void ffw_finalize(void) { + ffwSetAction("finalize"); while(enc_head) { Encoding * next = enc_head->next; @@ -107,33 +115,48 @@ void ffw_finalize(void) free(enc_head); enc_head = next; } + ffwClearAction(); } -long ffw_get_version(void) +// see: https://stackoverflow.com/a/2653351 +#define xstr(a) str(a) +#define str(a) #a + +static FFWVersionInfo ffwVersionInfo; + +const FFWVersionInfo* ffw_get_version_info(void) { - return FONTFORGE_VERSIONDATE_RAW; + ffwVersionInfo.versionDate = FONTFORGE_VERSION; + + return &ffwVersionInfo; } void ffw_new_font() { + ffwSetAction("create"); assert((cur_fv == NULL) && "Previous font is not destroyed"); cur_fv = FVAppend(_FontViewCreate(SplineFontNew())); + ffwClearAction(); } void ffw_load_font(const char * filename) { + ffwSetAction("load"); assert((cur_fv == NULL) && "Previous font is not destroyed"); char * _filename = strcopy(filename); - SplineFont * font = LoadSplineFont(_filename, 1); + SplineFont * font = LoadSplineFont(_filename, of_fstypepermitted); free(_filename); if(!font) err("Cannot load font %s\n", filename); - if(!font->fv) + + if(!font->fv) { + assert(fv_interface && "fv_interface not initialized!"); FVAppend(_FontViewCreate(font)); + } assert(font->fv); @@ -147,22 +170,24 @@ void ffw_load_font(const char * filename) cur_fv->cidmaster->ascent = cur_fv->sf->ascent; cur_fv->cidmaster->descent = cur_fv->sf->descent; } + ffwClearAction(); } -/* - * Fight again dirty stuffs - */ +// +// Fight again dirty stuffs +// void ffw_prepare_font(void) { + ffwSetAction("prepare"); memset(cur_fv->selected, 1, cur_fv->map->enccount); // remove kern FVRemoveKerns(cur_fv); FVRemoveVKerns(cur_fv); - /* - * Remove Alternate Unicodes - * We never use them because we will do a force encoding - */ + // + // Remove Alternate Unicodes + // We never use them because we will do a force encoding + // int i; SplineFont * sf = cur_fv->sf; for(i = 0; i < sf->glyphcnt; ++i) @@ -179,16 +204,18 @@ void ffw_prepare_font(void) } } - /* - * Wipe out font name - * browsers may rejects fonts with malformed font names - */ + // + // Wipe out font name + // browsers may rejects fonts with malformed font names + // free(sf->fontname); sf->fontname = strcopy(""); + ffwClearAction(); } void ffw_save(const char * filename) { + ffwSetAction("save"); char * _filename = strcopy(filename); char * _ = strcopy(""); @@ -200,11 +227,15 @@ void ffw_save(const char * filename) if(!r) err("Cannot save font to %s\n", filename); + ffwClearAction(); } + void ffw_close(void) { + ffwSetAction("close"); FontViewClose(cur_fv); cur_fv = NULL; + ffwClearAction(); } static void ffw_do_reencode(Encoding * encoding, int force) @@ -234,25 +265,32 @@ static void ffw_do_reencode(Encoding * encoding, int force) void ffw_reencode_glyph_order(void) { + ffwSetAction("re-encode the glyph order in"); ffw_do_reencode(original_enc, 0); + ffwClearAction(); } void ffw_reencode_unicode_full(void) { + ffwSetAction("re-encode to unicode"); ffw_do_reencode(unicodefull_enc, 0); + ffwClearAction(); } void ffw_reencode(const char * encname, int force) { + ffwSetAction("re-encode"); Encoding * enc = FindOrMakeEncoding(encname); if(!enc) err("Unknown encoding %s\n", encname); ffw_do_reencode(enc, force); + ffwClearAction(); } void ffw_reencode_raw(int32 * mapping, int mapping_len, int force) { + ffwSetAction("re-encode (raw1)"); Encoding * enc = calloc(1, sizeof(Encoding)); enc->only_1byte = enc->has_1byte = true; @@ -273,10 +311,12 @@ void ffw_reencode_raw(int32 * mapping, int mapping_len, int force) enc_head = enc; ffw_do_reencode(enc, force); + ffwClearAction(); } void ffw_reencode_raw2(const char ** mapping, int mapping_len, int force) { + ffwSetAction("re-encode (raw2)"); Encoding * enc = calloc(1, sizeof(Encoding)); enc->enc_name = strcopy(""); enc->char_cnt = mapping_len; @@ -300,6 +340,7 @@ void ffw_reencode_raw2(const char ** mapping, int mapping_len, int force) enc_head = enc; ffw_do_reencode(enc, force); + ffwClearAction(); } void ffw_cidflatten(void) @@ -309,15 +350,18 @@ void ffw_cidflatten(void) fprintf(stderr, "Cannot flatten a non-CID font\n"); return; } - SFFlatten(cur_fv->sf->cidmaster); + ffwSetAction("flatten the cid in"); + SFFlatten(&(cur_fv->sf->cidmaster)); + ffwClearAction(); } -/* - * There is no check if a glyph with the same unicode exists! - * TODO: let FontForge fill in the standard glyph name <- or maybe this might cause collision? - */ +// +// There is no check if a glyph with the same unicode exists! +// TODO: let FontForge fill in the standard glyph name <- or maybe this might cause collision? +// void ffw_add_empty_char(int32_t unicode, int width) { + ffwSetAction("add an empty character to"); SplineChar * sc = SFMakeChar(cur_fv->sf, cur_fv->map, cur_fv->map->enccount); char buffer[400]; SCSetMetaData(sc, @@ -325,22 +369,29 @@ void ffw_add_empty_char(int32_t unicode, int width) cur_fv->sf->uni_interp, cur_fv->sf->for_new_glyphs)), unicode, sc->comment); SCSynchronizeWidth(sc, width, sc->width, cur_fv); + ffwClearAction(); } int ffw_get_em_size(void) { - return cur_fv->sf->ascent + cur_fv->sf->descent; + ffwSetAction("get the em size of"); + int emSize = cur_fv->sf->ascent + cur_fv->sf->descent; + ffwClearAction(); + return emSize; } void ffw_fix_metric() { + ffwSetAction("fix the metric of"); double ascent, descent; ffw_get_metric(&ascent, &descent); ffw_set_metric(ascent, descent); + ffwClearAction(); } void ffw_get_metric(double * ascent, double * descent) { + ffwSetAction("get the metric of"); SplineFont * sf = cur_fv->sf; DBounds bb; @@ -357,10 +408,12 @@ void ffw_get_metric(double * ascent, double * descent) { *ascent = *descent = 0; } + ffwClearAction(); } void ffw_set_metric(double ascent, double descent) { + ffwSetAction("set the metric of"); SplineFont * sf = cur_fv->sf; struct pfminfo * info = &sf->pfminfo; @@ -375,17 +428,17 @@ void ffw_set_metric(double ascent, double descent) if(a < 0) a = 0; if(d > 0) d = 0; - /* - sf->ascent = min(a, em); - sf->descent = em - bb.maxy; - */ + // + //sf->ascent = min(a, em); + //sf->descent = em - bb.maxy; + // - /* - * The embedded fonts are likely to have inconsistent values for the 3 sets of ascent/descent - * PDF viewers don't care, since they don't even use these values - * But have to unify them, for different browsers on different platforms - * Things may become easier when there are CSS rules for baseline-based positioning. - */ + // + // The embedded fonts are likely to have inconsistent values for the 3 sets of ascent/descent + // PDF viewers don't care, since they don't even use these values + // But have to unify them, for different browsers on different platforms + // Things may become easier when there are CSS rules for baseline-based positioning. + // info->os2_winascent = a; info->os2_typoascent = a; info->hhead_ascent = a; @@ -402,14 +455,16 @@ void ffw_set_metric(double ascent, double descent) info->os2_typolinegap = 0; info->linegap = 0; + ffwClearAction(); } -/* - * TODO:bitmap, reference have not been considered in this function - */ +// +// TODO:bitmap, reference have not been considered in this function +// void ffw_set_widths(int * width_list, int mapping_len, int stretch_narrow, int squeeze_wide) { + ffwSetAction("set the widths of"); SplineFont * sf = cur_fv->sf; if(sf->onlybitmaps @@ -424,9 +479,9 @@ void ffw_set_widths(int * width_list, int mapping_len, int imax = min(mapping_len, map->enccount); for(i = 0; i < imax; ++i) { - /* - * Don't mess with it if the glyphs is not used. - */ + // + // Don't mess with it if the glyphs is not used. + // if(width_list[i] == -1) { continue; @@ -453,19 +508,32 @@ void ffw_set_widths(int * width_list, int mapping_len, SCSynchronizeWidth(sc, width_list[i], sc->width, cur_fv); } + ffwClearAction(); } void ffw_import_svg_glyph(int code, const char * filename, double ox, double oy, double width) { + ffwSetAction("import the glyphs from"); int enc = SFFindSlot(cur_fv->sf, cur_fv->map, code, ""); - if(enc == -1) + if(enc == -1) { + ffwClearAction(); return; + } SplineChar * sc = SFMakeChar(cur_fv->sf, cur_fv->map, enc); memset(cur_fv->selected, 0, cur_fv->map->enccount); cur_fv->selected[enc] = 1; - int ok = FVImportImages(cur_fv, (char*)filename, fv_svg, 0, -1); + ImportParams ip; + InitImportParams(&ip); + int ok = FVImportImages( + cur_fv, + (char*)filename, + fv_svg, + 0 /*toback*/, + true /*preclear*/, + &ip + ); if(!ok) err("Import SVG glyph failed"); @@ -483,10 +551,12 @@ void ffw_import_svg_glyph(int code, const char * filename, double ox, double oy, SCSynchronizeWidth(sc, floor(width * (a+d) + 0.5), sc->width, cur_fv); } + ffwClearAction(); } void ffw_auto_hint(void) { + ffwSetAction("automatically hint"); // convert to quadratic if(!(cur_fv->sf->layers[ly_fore].order2)) { @@ -496,11 +566,14 @@ void ffw_auto_hint(void) memset(cur_fv->selected, 1, cur_fv->map->enccount); FVAutoHint(cur_fv); FVAutoInstr(cur_fv); + ffwClearAction(); } void ffw_override_fstype(void) { + ffwSetAction("override the fstype of"); *(int16 *)(&cur_fv->sf->pfminfo.fstype) = 0; cur_fv->sf->pfminfo.pfmset = true; cur_fv->sf->changed = true; + ffwClearAction(); } diff --git a/src/util/ffw.h b/pdf2htmlEX/src/util/ffw.h similarity index 90% rename from src/util/ffw.h rename to pdf2htmlEX/src/util/ffw.h index 106310a..50a7f50 100644 --- a/src/util/ffw.h +++ b/pdf2htmlEX/src/util/ffw.h @@ -21,9 +21,14 @@ extern "C" { //////////////////////// // global -void ffw_init(int debug); +void ffw_init(const char* progPath, int debug); void ffw_finalize(void); -long ffw_get_version(void); + +typedef struct ffw_version_info { + const char* versionDate; +} FFWVersionInfo ; + +const FFWVersionInfo* ffw_get_version_info(void); //////////////////////// // load & save diff --git a/src/util/math.cc b/pdf2htmlEX/src/util/math.cc similarity index 100% rename from src/util/math.cc rename to pdf2htmlEX/src/util/math.cc diff --git a/src/util/math.h b/pdf2htmlEX/src/util/math.h similarity index 100% rename from src/util/math.h rename to pdf2htmlEX/src/util/math.h diff --git a/src/util/mingw.cc b/pdf2htmlEX/src/util/mingw.cc similarity index 100% rename from src/util/mingw.cc rename to pdf2htmlEX/src/util/mingw.cc diff --git a/src/util/mingw.h b/pdf2htmlEX/src/util/mingw.h similarity index 100% rename from src/util/mingw.h rename to pdf2htmlEX/src/util/mingw.h diff --git a/src/util/misc.cc b/pdf2htmlEX/src/util/misc.cc similarity index 100% rename from src/util/misc.cc rename to pdf2htmlEX/src/util/misc.cc diff --git a/src/util/misc.h b/pdf2htmlEX/src/util/misc.h similarity index 100% rename from src/util/misc.h rename to pdf2htmlEX/src/util/misc.h diff --git a/src/util/namespace.h b/pdf2htmlEX/src/util/namespace.h similarity index 100% rename from src/util/namespace.h rename to pdf2htmlEX/src/util/namespace.h diff --git a/src/util/path.cc b/pdf2htmlEX/src/util/path.cc similarity index 100% rename from src/util/path.cc rename to pdf2htmlEX/src/util/path.cc diff --git a/src/util/path.h b/pdf2htmlEX/src/util/path.h similarity index 100% rename from src/util/path.h rename to pdf2htmlEX/src/util/path.h diff --git a/src/util/unicode.cc b/pdf2htmlEX/src/util/unicode.cc similarity index 95% rename from src/util/unicode.cc rename to pdf2htmlEX/src/util/unicode.cc index 31ec4f8..2ebc88e 100644 --- a/src/util/unicode.cc +++ b/pdf2htmlEX/src/util/unicode.cc @@ -55,7 +55,7 @@ Unicode unicode_from_font (CharCode code, GfxFont * font) return map_to_private(code); } -Unicode check_unicode(Unicode * u, int len, CharCode code, GfxFont * font) +Unicode check_unicode(Unicode const * u, int len, CharCode code, GfxFont * font) { if(len == 0) return map_to_private(code); diff --git a/src/util/unicode.h b/pdf2htmlEX/src/util/unicode.h similarity index 98% rename from src/util/unicode.h rename to pdf2htmlEX/src/util/unicode.h index c789dea..d4a5d48 100644 --- a/src/util/unicode.h +++ b/pdf2htmlEX/src/util/unicode.h @@ -83,7 +83,7 @@ Unicode unicode_from_font (CharCode code, GfxFont * font); * if we got multi-unicode values, it might be expanded ligature, try to restore it * if we cannot figure it out at the end, use a private mapping */ -Unicode check_unicode(Unicode * u, int len, CharCode code, GfxFont * font); +Unicode check_unicode(Unicode const * u, int len, CharCode code, GfxFont * font); } // namespace pdf2htmlEX diff --git a/test/.gitattributes b/pdf2htmlEX/test/.gitattributes similarity index 100% rename from test/.gitattributes rename to pdf2htmlEX/test/.gitattributes diff --git a/pdf2htmlEX/test/README.md b/pdf2htmlEX/test/README.md new file mode 100644 index 0000000..24a0209 --- /dev/null +++ b/pdf2htmlEX/test/README.md @@ -0,0 +1,124 @@ +# pdf2htmlEX tests + +This directory contains a collection of python3 unittests of the output of +pdf2htmlEX. + +The graphical output of pdf2htmlEX can be tested both locally and remotely +using [Selenium](https://www.selenium.dev/) and the [Pillow Python Imaging +Library](https://python-pillow.org/). + +The browser tests use Selenium to take a screenshot of a FireFox browser's +rendering of the pdf2htmlEX output for a given pdf file and compares that +image to an image of the previously saved reference html. + +## Tests which are currently failing: + +- **browser_tests/text_visibility** At the moment clipping has been broken +and needs to be fixed. Rerun `runLocalBrowserTests` and use the +`compareTestImages` for the `test_visibility` test to see the problem. + +## Running tests + +There are three shell scripts which automate the running of a given +collection of tests: + +1. **runLocalTests** runs a simple collection of tests which do not +require Selenium or a browser. + +``` + ./runLocalTests +``` + +2. **runLocalBrowserTests** runs a more complex collection of tests which +*require* Selenium, a FireFox browser, as well as a 'virtual frame buffer' +(Xvfb) to be installed. + +``` + ./runLocalBrowserTests +``` + +3. **runRemoteBrowserTests** runs the same complex collection of tests as +run by `runLocalBrowserTests` but this time using 'Sauce Connect'. (At the +moment this is not fully implemented or (re)tested) + +``` + ./runRemoteBrowserTests +``` + +In order to run these tests, you *must* have the correct testing software +installed locally. To do this you can run the command: + +``` + ./installAutomaticTestSoftware +``` + +## Understanding browser test failures + +If any of the automatic browser tests *fail* then you might want to +manually view the PNG images for a given test using the command: + +``` + ./compareTestImages <> +``` + +This command opens the three PNG images associated with a given failed +test so that you can manually compare the new output (`*.out.png`), the +reference output (`*.ref.png`) and an image of the 'difference' between +the two images (`*.diff.png`). To pass, the 'difference' image must be +*completely* black. + +Usually it will be obvious that the newer version of pdf2htmlEX has only +slightly moved various image elements. Any such tests can be made to pass +by updating the reference html using the tool: + +``` + ./regenerateTestHtml <> +``` + +This command will regenerate the reference html for the specifed test. + +All of these manual comparison tools require additional software which can +be installed using the command: + +``` + ./installManualTestSoftware +``` + +--- + +## OLD README contents: + +### Dependencies + +- python2 and packages + - Python Imaging Library + - Selenium + - unittest +- Firefox + - firefoxdriver + +### Usage +- Run all tests: + - python test_output.py + - python test_local_browser.py +- Environment variables: + - `export P2H_TEST_GEN=1` to generate new reference files (when done, `unset P2H_TEST_GEN`) + - `export P2H_TEST_REMOTE=1` to test different browsers using Sauce Labs + - Install `sauceclient` for Python + - Set correct values for `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` + - Setup a HTTP server at `/` on port 8000 + - Enable Sauce Connect + - See `.travis.yml` as an example + - python test_remote_browser.py + +### Add new test cases + +- Make sure you have the proper copyrights. +- Using meaningful file names, a description of the file, or issueXXX.pdf. +- Make each test case minimal: + - One page only, unless the test case is about multiple pages. + - Grayscale only, unless the test case is about colors. + - Remove unnecessary elements. +- [Optional] Include the source files that the PDF file is generated from. +- Add the new PDF file to the correct folder in `test/`, and add a new function in the corresponding Python file +- Run `P2H_TEST_GEN=1 test/test.py test_issueXXX` to generate the reference, assuming that the new function is called `test_issueXXX` diff --git a/test/browser_tests.py b/pdf2htmlEX/test/browser_tests.py similarity index 59% rename from test/browser_tests.py rename to pdf2htmlEX/test/browser_tests.py index c1880a9..e09c54a 100644 --- a/test/browser_tests.py +++ b/pdf2htmlEX/test/browser_tests.py @@ -5,6 +5,7 @@ import subprocess import shutil import unittest +#from selenium.common.exceptions import WebDriverException from PIL import Image, ImageChops from test import Common @@ -30,19 +31,29 @@ class BrowserTests(Common): def run_test_case(self, filename, args=[], page_must_load=True): basefilename, extension = os.path.splitext(filename) - self.assertEquals(extension.lower(), '.pdf', 'Input file is not PDF') + self.assertEqual(extension.lower(), '.pdf', 'Input file is not PDF') htmlfilename = basefilename + '.html' ref_htmlfolder = os.path.join(self.TEST_DATA_DIR, basefilename) ref_htmlfilename = os.path.join(ref_htmlfolder, htmlfilename) out_htmlfilename = os.path.join(self.OUTDIR, htmlfilename) - - pdf2htmlEX_args = self.DEFAULT_PDF2HTMLEX_ARGS + args + [ + pre_htmlfilename = os.path.join(self.PREDIR, htmlfilename) + + try: + # see if we have pre-compiled the html file... + # if so simply copy it into place + # + shutil.copy(pre_htmlfilename, out_htmlfilename) + except: + # we have not pre-compiled the html file + # so create it using pdf2htmlEX + # + pdf2htmlEX_args = self.DEFAULT_PDF2HTMLEX_ARGS + args + [ os.path.join(self.TEST_DATA_DIR, filename), htmlfilename ] - result = self.run_pdf2htmlEX(pdf2htmlEX_args) - - self.assertIn(htmlfilename, result['output_files'], 'HTML file is not generated') + result = self.run_pdf2htmlEX(pdf2htmlEX_args) + # + self.assertIn(htmlfilename, result['output_files'], 'HTML file is not generated') if self.GENERATING_MODE: # copy generated html files @@ -50,23 +61,46 @@ class BrowserTests(Common): shutil.copytree(self.OUTDIR, ref_htmlfolder) return + # keep a record of the HTML files (and any differences) + # for later reporting of test results + # + try: + os.makedirs(self.HTMDIR, 0o755, True) + outHtmlFile = os.path.join(self.HTMDIR, basefilename+'.out.html') + refHtmlFile = os.path.join(self.HTMDIR, basefilename+'.ref.html') + difHtmlFile = os.path.join(self.HTMDIR, basefilename+'.diff.html') + shutil.copy(out_htmlfilename, outHtmlFile) + shutil.copy(ref_htmlfilename, refHtmlFile) + os.system("diff "+outHtmlFile+" "+refHtmlFile+" > "+difHtmlFile+" 2>&1") + except: + pass + pngfilename_out = os.path.join(self.PNGDIR, basefilename + '.out.png') self.generate_image(out_htmlfilename, pngfilename_out) - out_img = Image.open(pngfilename_out) + out_img = Image.open(pngfilename_out).convert('RGB') pngfilename_ref = os.path.join(self.PNGDIR, basefilename + '.ref.png') self.generate_image(ref_htmlfilename, pngfilename_ref, page_must_load=page_must_load) - ref_img = Image.open(pngfilename_ref) + ref_img = Image.open(pngfilename_ref).convert('RGB') diff_img = ImageChops.difference(ref_img, out_img); + # ALWAYS save the diff image so we can manually check the diff + # see: (http://stackoverflow.com/questions/15721484): + diff_file_name = os.path.join(self.PNGDIR, basefilename + '.diff.png') + diff_img.convert('RGB').save(diff_file_name) + diff_bbox = diff_img.getbbox() - if diff_bbox is not None: + print("\nTesting at: [", basefilename, "]") + + if diff_bbox is None: + print(" SUCCESS: ", basefilename) + elif basefilename == "test_fail" : + print(" SUCCESS: ", basefilename) + else: + print(" FAILURE: ", basefilename, " diff bounding box: ", diff_bbox, " should be None") diff_size = (diff_bbox[2] - diff_bbox[0]) * (diff_bbox[3] - diff_bbox[1]) img_size = ref_img.size[0] * ref_img.size[1] - # save the diff image (http://stackoverflow.com/questions/15721484): - diff_file_name = os.path.join(self.PNGDIR, basefilename + '.diff.png') - diff_img.convert('RGB').save(diff_file_name) self.fail(('PNG files %s and %s differ by at most %d pixels, '+ '(%f%% of %d pixels in total), difference: %s') % (pngfilename_out, pngfilename_ref, @@ -86,6 +120,7 @@ class BrowserTests(Common): def test_geneve_1564(self): self.run_test_case('geneve_1564.pdf') + @unittest.skip("Skipping text_visibility test due to clipping issues") def test_text_visibility(self): self.run_test_case('text_visibility.pdf', ['--correct-text-visibility', 1]) diff --git a/test/browser_tests/basic_text.pdf b/pdf2htmlEX/test/browser_tests/basic_text.pdf similarity index 100% rename from test/browser_tests/basic_text.pdf rename to pdf2htmlEX/test/browser_tests/basic_text.pdf diff --git a/test/browser_tests/basic_text.tex b/pdf2htmlEX/test/browser_tests/basic_text.tex similarity index 100% rename from test/browser_tests/basic_text.tex rename to pdf2htmlEX/test/browser_tests/basic_text.tex diff --git a/test/browser_tests/basic_text/basic_text.html b/pdf2htmlEX/test/browser_tests/basic_text/basic_text.html similarity index 100% rename from test/browser_tests/basic_text/basic_text.html rename to pdf2htmlEX/test/browser_tests/basic_text/basic_text.html diff --git a/test/browser_tests/fontfile3_opentype.pdf b/pdf2htmlEX/test/browser_tests/fontfile3_opentype.pdf similarity index 100% rename from test/browser_tests/fontfile3_opentype.pdf rename to pdf2htmlEX/test/browser_tests/fontfile3_opentype.pdf diff --git a/pdf2htmlEX/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html b/pdf2htmlEX/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html new file mode 100644 index 0000000..65e7097 --- /dev/null +++ b/pdf2htmlEX/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html @@ -0,0 +1,160 @@ + + + + + + + + + + + + + +
+
PDFClown
Generated by PDF Clown on Sat Mar 05 20:06:01 CET 2011
For more info, visit http://www.pdfclown.org
Welcome
This is a sample document
that merely demonstrates
some basic graphics
features supported by
PDF Clown.
Enjoy!
PS: As promised, since version 0.0.3 PDF Clown has supported embedded latin
OpenFont/TrueType and non-embedded Type 1 fonts along with paragraph construction facilities
through the BlockComposer class.
Since version 0.0.4 the content stream stack has been completed, providing fully object-oriented
access to the graphics objects that describe the contents on a page. It's a great step towards
a whole bunch of possibilities, such as text extraction/replacement, that next releases will
progressively exploit.
Since version 0.0.6 it has supported Unicode for OpenFont/TrueType fonts.
This page was crafted with the nice
LazyDog font
(by Paul Neave, www.neave.com)
Source: http://www.wikipedia.org/
+
+ + diff --git a/test/browser_tests/geneve_1564.pdf b/pdf2htmlEX/test/browser_tests/geneve_1564.pdf similarity index 100% rename from test/browser_tests/geneve_1564.pdf rename to pdf2htmlEX/test/browser_tests/geneve_1564.pdf diff --git a/pdf2htmlEX/test/browser_tests/geneve_1564/geneve_1564.html b/pdf2htmlEX/test/browser_tests/geneve_1564/geneve_1564.html new file mode 100644 index 0000000..33a644c --- /dev/null +++ b/pdf2htmlEX/test/browser_tests/geneve_1564/geneve_1564.html @@ -0,0 +1,738 @@ + + + + + + + + + + + + + +
+
1
Le premier lire de Moyſe,
Di Geneſe.
.
Ce premier lire comprend l’origine caſes de totes choſes, principalement la creation de l’homme, q’il a eſté d
commencement, ſa chete releement : comment d’n tos ont eſté procreés, por lers enormes pechés Die
les a conſmés, par le delge, reſeré hi, dont la ſemence a rempli tote la terre. Pis il deſcrit les ies, fais, reli-
gion, lignees des ſaints Patriarches, qi ont eſc deant la Loy : Les benediions, promees, alliances d Sei-
gner faies aecicex : Comment de le la terre de Chanaan ſont deſcends en Epte. Acns ont appelé ce lire, le
lire des Iſtes. Totefois ceci a obten entre nos predeceers nos, q’il eſt appelé Geneſe, qi eſt n mot Grec,
gnifiant generation origine : d’atant q’en iceli eſt deſcrite l’origine procreation de totes choſes : nom-
mément des Peres anciens, qi ont eſté tant deant q’apres le delge, e eſgard à deſcen-
d d’icex ſelon la chair.
.
I
Creation d ciel de la terre, II, 10. de tot ce qi y eſt
comprins. 3.14. De la lmiere a, 26 de l’homme, 18
qel tot eſt abietti. 2.2. 18 Die benit totes ſes œ-
res, 31 q’il a accomplies en x iors.
1
Ie
a
crea
b
a com
mence -
ment
c
le
ciel & la
terre.
2 Or la
terre eſ-
toit ſans
forme, &
vide, & les tenebres eſtoyent ſr les
abyſmes : & l’Eſprit de Die
d
eſtoit
eſpand par des les eax.
3 Adonc Die dît,
2
’il y ait lmie-
re.
e
Et la lmiere ft.
4 Et Die vid q
la lmiere eſtoit bon-
ne : & ſepara la lmiere des tenebres.
5 Et Die appela la lmiere ior,& les
tenebres ni. Lors ft fai le
f
ſoir &
le matin d premier ior.
6 Pis Die dît,
3
’il y ait ne
g
eſ-
tende entre les eax, & qelle ſepare
les
h
eax daec les eax.
7 Die donc fit leſtende, & diiſa
I
Ce premier cha-
pitre eſt fort diffi-
cile : & por cette
caſe, il eſtoit de-
fend entre les He
briex de le lire &
interpreter deant
laage de trente
ans.
a
Fit de rien, &
ſans acne ma-
tiere.
1
Iob 38.4, Pſea.
33.6, 89.12.,
135.5, Eccleſtiaſti.
13.1, A. 14-15,
17.14
b
Tot premiere-
ment, & aãt q’il
y et acne crea-
tre, Iean 1.10.
2
Hebr. 11.3.
c
Le ciel & la
terre, les eax, les
abyſmes, ſe pren-
nent ici por vne
meſme choſe : aſç.
por ne matiere
cõfſe & ſans for-
me, q
Die forma
& agença apres
par ſa Parole.
d
O, ſe mo-
voit. Ceſt, ſoſte-
noit et conſeroit
en ſon eſtre cette
matiere confſe.
Car il eſt impo-
ble, q
acne cho-
ſe apres aoir eſté
faies,pie ſb-
ſter n ſel mo-
ment,  Die ne la
ſoſtient & cõſer-
ve par ſa vert,
Pſea. 130.
e
Cette lmiere
neſtoit point en-
core a ſoleil, car
il naoit pas eſté
creé, mais eſtoit en
la main de Die,
ayãt ſon ordre ſc-
cef aec les tene-
bres, por faire le
ior & la ni &
ce iſqes a qa-
trieme ior, qe
Die fit le ſoleil
por eſtre miniſtre
& diſpenſater de
cette lmiere, aec
la lne & eſtoilles.
3
Pſea. 33.6,
136.5.
Ierem. 10.11
51.15.
f
Ici eſt la caſe
les eax, qi eſtoyent ſos leſtende,
daec celles, qi eſtoyent ſr leſten-
de. Et ft ain fai.
8 EtDie appela leſtende, Ciel. Lors
ft fai le ſoir & le matin d ſecond
ior.
9 Pis Die dît,
4 i
e les eax, qi
ſont ſos le ciel, ſoyent aemblees en
n lie, & qe le ſec apparoie. Et ft
ain fai.
10 EtDie appeꝉale ſec,Terre,& laem
blee des eax, mers. Et Die vid qe
celà eſtoit bon.
11 Et Die dît, e la terre prodiſe
verdre, herbe prodiſant ſemence, &
arbre friier, faiſant fri ſelon ſon
eſpece, leqel ait ſa ſemẽce en ſoy-meſ-
me ſr la terre. Et ft ain fai.
12 La terre dõc prodit verdre, her-
be prodiſant ſemẽce ſelon ſon eſpece,
& arbre ſans fri, leqel aoit ſa
ſemence en ſoymeſme ſelon ſon eſpe-
ce. Et Die vid qe celà eſtoit bon.
13 Lors ft fai le ſoir & le matin d
troieme ior.
14 Apres Die dît,
5 k
’il y ait lmi
naires en leſtende d ciel, por ſepa-
rer la ni d ior : & ſoyẽt en
l
gnes,
a en
porqoy les He-
briex cõmencent
le ior natrel le
ſoir apres le ſoleil
cochant.
g
Ce mot d’Eſtẽ
de, comprẽd tot
ce qi ſe voit par
des nos, tãt en
la region celeſte,
qelementaire.
4
Pſea. 33.7.
h
Il eſt ici parlé
de dex manieres
deax : asçaoir,
celles q ſont ſos
leſtende, comme
la mer, les flees,
& atres qi ſont
ſr la terre & cel-
les, qi ſont ſr
leſtende, comme
ſont les nees plei-
nes dea ça hat
en lair par des
nos. Die a mis
entre ces dex for
ces deax ne grã
de eſtende, qon
appelle le ciel : de
nos appelons
les oiſeax d ciel.
i
Ceci appartiẽt a
ſecõd ior, aqel
Die ſepara, & fit
apparoir la terre d
milie des eax.
k
Il inſtite n
noel ordre en
natre, qand il
fat & ordonne le
ſoleil diſtribter
de cette lmiere
q’il aoit creée
aant li, & aant
la lne & les eſ-
toilles.
5
Pſea. 136.7
l
Ceſt por -
gnifier dierſes di-
ſpotions qe les
corps ĩferiers ſe-
lon lordre de na-
tre ont des corps
celeſtes, cõme ca
ſes ſecõdes ordon
nees de Die à ce-
là. En qoy to-
teſfois fat fir c-
rioté & ſperſti-
tion q
les hõmes
ont cõtroee ſr
celà.
+
+ + diff --git a/test/browser_tests/invalid_unicode_issue477.pdf b/pdf2htmlEX/test/browser_tests/invalid_unicode_issue477.pdf similarity index 100% rename from test/browser_tests/invalid_unicode_issue477.pdf rename to pdf2htmlEX/test/browser_tests/invalid_unicode_issue477.pdf diff --git a/test/browser_tests/invalid_unicode_issue477/invalid_unicode_issue477.html b/pdf2htmlEX/test/browser_tests/invalid_unicode_issue477/invalid_unicode_issue477.html similarity index 100% rename from test/browser_tests/invalid_unicode_issue477/invalid_unicode_issue477.html rename to pdf2htmlEX/test/browser_tests/invalid_unicode_issue477/invalid_unicode_issue477.html diff --git a/test/browser_tests/svg_background_with_page_rotation_issue402.pdf b/pdf2htmlEX/test/browser_tests/svg_background_with_page_rotation_issue402.pdf similarity index 100% rename from test/browser_tests/svg_background_with_page_rotation_issue402.pdf rename to pdf2htmlEX/test/browser_tests/svg_background_with_page_rotation_issue402.pdf diff --git a/pdf2htmlEX/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html b/pdf2htmlEX/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html new file mode 100644 index 0000000..5de3676 --- /dev/null +++ b/pdf2htmlEX/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html @@ -0,0 +1,642 @@ + + + + + + + + + + + + + +
+
Airports & AAL -
A
irport Authorization List
Airway Manual
Airport Authorization List
R = Regular F = Fueling A = Alternate AO = Off-Line Alternate (T) = ETOPS Alternate
[
SA
Q]
= S
p
ecial Air
p
ort
Q
ualification
[
T
Q]
= Theater
Q
ualification ~ or blank = Emer
g
enc
y
Air
p
ort
ICAO Location
IATA
Longest Rwy
24 Hrs
Precision App
A319
A320
A330-200
A330-300
B717
B737-700
B737-800
B737-900
B747
B757
B757-200ER
B757-300ER
B767-300
B767-300ER
B767-300ET
B767-400
B777-200ER
B777-200LR
MD88
MD90
ENCN KRISTIANSAND, NO KRS 6.6 N Y (T) (T)
ENGMOSLO, NO OSL11.8YY~~AOAO~~~~~AOAOAO(T)AO~AOAOAO~~
ENSB SVALBARD, NO [SAQ] LYR 8.1 Y Y (T) (T) (T)
ENVATRONDHEIM, NO TRD 9.0YY~~(T)(T)~~~~~~AO~(T)AO~(T)AOAO~~
ENZV STAVANGER, NO SVG 8.3 Y Y (T) (T) (T) (T) (T)
EPWA
WARSAW PL
WAW
12 1
Y
Y
AO
AO
AO
AO
EPWA
WARSAW
,
PL
WAW
12
.
1
Y
Y
~~
AO
AO
~~~~~~~~~
AO
~
AO
~~~~
ESGGGOTEBORG, SE GOT10.8YN~~~~~~~~~~AO~~AO~AO~~~~
ESMSMALMO, SE MMX9.1YY~~AOAO~~~~~~AO~~AO~AO~~~~
ESOW VAESTERAAS, STOCKHOLM, SE VST 8.4 N N ~~~~~~~~~~AO~~AO~AO~~~~
ESSA ARLANDA, STOCKHOLM, SE [TQ] ARN 10.8 Y Y ~ ~ F F ~~~~~~R~~R~~~~~~
ESSD BORLANGE, SE BLE 7.5 N Y
ETAR RAMSTEIN, DE RMS 10.4 Y Y
EVRA RIGA, LV RIX 10.4 Y Y
FABLBLOEMFONTEIN, ZA BFN 8.3NN~~~~~~~~~~~~~AO~AOAOAO~~
FACT CAPE TOWN, ZA CPT 10.5 Y Y ~~~~~~~~~~~~~AO~AOAOAO~~
FALEDURBAN, ZA DUR12.1YY~~~~~~~~ ~~~~AO~AOAOAO~~
FAOR JOHANNESBURG, ZA [TQ] JNB 14.4 Y Y ~~~~~~~~~~~~~A~ARR~~
FBSKGABORONE, BW GBE13.1NY~~~~~~~~~~~~~AO~AOAOAO~~
FCBB BRAZZAVILLE, CG BZV 10.8 Y Y
FCPP POINTE NOIRE, CG PNR 8.5 Y Y
FGSL MALABO, GQ SSG 9.6 Y Y
FHAW ASCENSION, SH ASI 10.0 Y N (T) (T) (T) (T) (T) (T)
FKKD DOUALA, CM DLA 9.3 Y Y
FKYS YAOUNDE, CM NSI 11.1 Y N
FNLU LUANDA, AO LAD 12.1 Y N (T) (T) (T) (T) (T) (T) (T)
March 28, 2014 OPS-6TA.AD&AAL.2.11
Copyright © Delta Air Lines, Inc. See title page for details.
+
+ + diff --git a/test/browser_tests/test_fail.pdf b/pdf2htmlEX/test/browser_tests/test_fail.pdf similarity index 100% rename from test/browser_tests/test_fail.pdf rename to pdf2htmlEX/test/browser_tests/test_fail.pdf diff --git a/test/browser_tests/test_fail.tex b/pdf2htmlEX/test/browser_tests/test_fail.tex similarity index 100% rename from test/browser_tests/test_fail.tex rename to pdf2htmlEX/test/browser_tests/test_fail.tex diff --git a/pdf2htmlEX/test/browser_tests/test_fail/THIS_FOLDER_SHOULD_BE_EMPTY b/pdf2htmlEX/test/browser_tests/test_fail/THIS_FOLDER_SHOULD_BE_EMPTY new file mode 100644 index 0000000..e69de29 diff --git a/test/browser_tests/text_visibility.pdf b/pdf2htmlEX/test/browser_tests/text_visibility.pdf similarity index 100% rename from test/browser_tests/text_visibility.pdf rename to pdf2htmlEX/test/browser_tests/text_visibility.pdf diff --git a/test/browser_tests/text_visibility/text_visibility.html b/pdf2htmlEX/test/browser_tests/text_visibility/text_visibility.html similarity index 100% rename from test/browser_tests/text_visibility/text_visibility.html rename to pdf2htmlEX/test/browser_tests/text_visibility/text_visibility.html diff --git a/test/browser_tests/with_form.pdf b/pdf2htmlEX/test/browser_tests/with_form.pdf similarity index 100% rename from test/browser_tests/with_form.pdf rename to pdf2htmlEX/test/browser_tests/with_form.pdf diff --git a/pdf2htmlEX/test/browser_tests/with_form/with_form.html b/pdf2htmlEX/test/browser_tests/with_form/with_form.html new file mode 100644 index 0000000..7f8fc64 --- /dev/null +++ b/pdf2htmlEX/test/browser_tests/with_form/with_form.html @@ -0,0 +1,216 @@ + + + + + + + + + + + + + +
+
Éditions « À Reproduire » Internet : www.envolee.com
Question de textes 4
7
Nom
Mona veut un chien
4 Que veut dire la mère de Mona quand elle dit : « C’est beaucoup de travail, avoir un chien » ?
a) Mona doit faire plus de recherche avant d’être prête à avoir un chien.
b) Les chiens travaillent fort afi n d’être de bons animaux de compagnie pour les gens.
c) Les chiens ont besoin de nourriture et d’exercice. Il faut aussi ramasser leurs dégâts.
d) Mona devra se reposer plus si elle a un chien.
5 Comment Mona a-t-elle acquis autant de connaissances sur les chiens ?
a) En écoutant son enseignante à l’école.
b) En visitant un site Web.
c) En écrivant à la Société protectrice des animaux.
d) En regardant une vidéo sur les chiens.
6 Pourquoi Mona veut-elle un Jack Russell ?
7 Que devra faire Mona même si elle est fatiguée ou qu’il pleut ?
8 Décris physiquement le chien que Mona veut choisir.
9 Quand fait-elle ses recherches sur le Web ?
10 Que contient le site Web préféré de Mona ? Nomme deux éléments.
REPÉRAGE
+
+
+
+
+ + + + + + +
+
+
+
+ +
+
+ + diff --git a/pdf2htmlEX/test/compareTestImages b/pdf2htmlEX/test/compareTestImages new file mode 100755 index 0000000..c1af68a --- /dev/null +++ b/pdf2htmlEX/test/compareTestImages @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +# This python script displays the three images for a given test +# +# ref image: is the currently "corrrect" image archived with pdf2htmlEX +# out image: is the result of pdf2htmlEXing a given test pdf +# diff image: is the difference of the ref and out ('RGB') images +# +# In all cases, the diff image MUST be completely BLACK for a test to +# pass. +# +# Type Ctrl-Q inside the image to quit each image display. +# + +import os +import sys + +if len(sys.argv) != 2 : + print("usage: compareTestImages <>") + sys.exit(-1) + +baseFileName = os.path.splitext(sys.argv[1])[0] +testPNGDir = "/tmp/pdf2htmlEX/png" + +outPNGFile = os.path.join(testPNGDir, baseFileName+".out.png") +refPNGFile = os.path.join(testPNGDir, baseFileName+".ref.png") +diffPNGFile = os.path.join(testPNGDir, baseFileName+".diff.png") + +os.system("display "+outPNGFile+"&") +os.system("display "+refPNGFile+"&") +os.system("display "+diffPNGFile+"&") diff --git a/test/fancy.min.css b/pdf2htmlEX/test/fancy.min.css similarity index 100% rename from test/fancy.min.css rename to pdf2htmlEX/test/fancy.min.css diff --git a/pdf2htmlEX/test/installAutomaticTestSoftwareApt b/pdf2htmlEX/test/installAutomaticTestSoftwareApt new file mode 100755 index 0000000..fd41a7f --- /dev/null +++ b/pdf2htmlEX/test/installAutomaticTestSoftwareApt @@ -0,0 +1,39 @@ +#!/bin/sh + +set -ev + +# This shell script installs all local software required to run the +# pdf2htmlEX tests + +export DEBIAN_FRONTEND=noninteractive + +# Start by making sure all required apt packages exist +# +sudo apt -y install \ + wget \ + diffutils \ + zip \ + python3 \ + python3-pip \ + xvfb \ + firefox + +# Now get the geckodriver for firefox (as required by selenium) +# +oldPWD=$(pwd) +cd /tmp +# +wget https://github.com/mozilla/geckodriver/releases/download/v0.26.0/geckodriver-v0.26.0-linux64.tar.gz +# +tar xvf geckodriver-v0.26.0-linux64.tar.gz +# +sudo mv geckodriver /usr/local/bin +# +cd $oldPWD + +# Now make sure all python packages exist (install into the local user's +# PyPI archive) +# +pip3 install \ + selenium \ + Pillow diff --git a/pdf2htmlEX/test/installManualTestSoftware b/pdf2htmlEX/test/installManualTestSoftware new file mode 100755 index 0000000..5dc3e8a --- /dev/null +++ b/pdf2htmlEX/test/installManualTestSoftware @@ -0,0 +1,13 @@ +#!/bin/sh + +# This shell script installs all local software required to run the +# pdf2htmlEX tests + +export DEBIAN_FRONTEND=noninteractive + +# Start by making sure all required apt packages exist +# +sudo apt -y install \ + graphicsmagick-imagemagick-compat \ + okular + diff --git a/test/old/convert_to_woff.fontforge b/pdf2htmlEX/test/old/convert_to_woff.fontforge similarity index 100% rename from test/old/convert_to_woff.fontforge rename to pdf2htmlEX/test/old/convert_to_woff.fontforge diff --git a/test/old/test.py b/pdf2htmlEX/test/old/test.py similarity index 100% rename from test/old/test.py rename to pdf2htmlEX/test/old/test.py diff --git a/pdf2htmlEX/test/produceHtmlForBrowserTests b/pdf2htmlEX/test/produceHtmlForBrowserTests new file mode 100755 index 0000000..448a35f --- /dev/null +++ b/pdf2htmlEX/test/produceHtmlForBrowserTests @@ -0,0 +1,111 @@ +#!/bin/sh + +# This shell script walks through the browser_tests directory running +# pdf2htmlEX on each *.pdf file. + +# This is how we run pdf2htmlEX on a particular file, and arguments. +# +runPdf2htmlEX() { + pdfFileName=$1 + htmlFileName=$(echo $pdfFileName | cut -d'.' -f1).html + arguments=$2 + # + echo "" + echo "---" + echo " pdfFileName: [$pdfFileName]" + echo "htmlFileName: [$htmlFileName]" + echo " arguments: [$arguments]" + # + # now run pdf2htmlEX to produce the output files + # + echo $PDF2HTMLEX_PATH \ + --data-dir=$PDF2HTMLEX_DATDIR \ + --dest-dir $PDF2HTMLEX_TMPDIR \ + --fit-width=800 --last-page=1 \ + $arguments \ + browser_tests/$pdfFileName \ + $htmlFileName + # + $PDF2HTMLEX_PATH \ + --data-dir=$PDF2HTMLEX_DATDIR \ + --dest-dir $PDF2HTMLEX_TMPDIR \ + --fit-width=800 --last-page=1 \ + $arguments \ + browser_tests/$pdfFileName \ + $htmlFileName +} + +# This is how we copy a file omitting lines between '#TEST_IGNORE_BEGIN' +# and '#TEST_IGNORE_END' (we pipe the file in via stdin and save it via +# stdout) +# +copy_TEST_IGNORE_file() { + skipLine=echo + while IFS= read -r line ; do + if echo $line | grep -q "^#TEST_IGNORE_BEGIN" ; then + skipLine=true + elif echo $line | grep -q "^#TEST_IGNORE_END" ; then + skipLine=echo + else + $skipLine "$line" + fi + done +} + +if test -z "$PDF2HTMLEX_PATH" ; then + echo "PANIC: we do not know where to find the pdf2htmlEX executable" + exit 1 +fi + +if test -z "$PDF2HTMLEX_DATDIR" ; then + export PDF2HTMLEX_DATDIR=/tmp/pdf2htmlEX/dat +fi + +if test -z "$PDF2HTMLEX_TMPDIR" ; then + export PDF2HTMLEX_TMPDIR=/tmp/pdf2htmlEX/tmp +fi + +if test -z "$PDF2HTMLEX_PREDIR" ; then + export PDF2HTMLEX_PREDIR=/tmp/pdf2htmlEX/pre +fi + +if test -z "$PDF2HTMLEX_TEST_DIR" ; then + export PDF2HTMLEX_TEST_DIR=. +fi + +# clear out the TMPDIR +# +rm -rf $PDF2HTMLEX_TMPDIR +mkdir -p $PDF2HTMLEX_TMPDIR +# + +# setup the correct data files +# +cat $PDF2HTMLEX_TEST_DIR/../share/manifest | \ + copy_TEST_IGNORE_file > $PDF2HTMLEX_DATDIR/manifest + +cp $PDF2HTMLEX_TEST_DIR/../share/base.min.css $PDF2HTMLEX_DATDIR +cp $PDF2HTMLEX_TEST_DIR/../test/fancy.min.css $PDF2HTMLEX_DATDIR + +runPdf2htmlEX 'test_fail.pdf' + +runPdf2htmlEX 'basic_text.pdf' + +runPdf2htmlEX 'geneve_1564.pdf' + +runPdf2htmlEX 'text_visibility.pdf' '--correct-text-visibility=1' + +runPdf2htmlEX 'with_form.pdf' '--process-form=1' + +runPdf2htmlEX 'invalid_unicode_issue477.pdf' + +runPdf2htmlEX 'svg_background_with_page_rotation_issue402.pdf' '--bg-format=svg' + +runPdf2htmlEX 'fontfile3_opentype.pdf' + +# clear out the PREDIR +# +rm -rf $PDF2HTMLEX_PREDIR +mkdir -p $PDF2HTMLEX_PREDIR +# +cp $PDF2HTMLEX_TMPDIR/* $PDF2HTMLEX_PREDIR diff --git a/pdf2htmlEX/test/regenerateTest b/pdf2htmlEX/test/regenerateTest new file mode 100755 index 0000000..402944b --- /dev/null +++ b/pdf2htmlEX/test/regenerateTest @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +# This python script regenerates the html files associated with a given browser test. +# +# This script MUST ONLY be run after the full (local) browser test. +# + +import os +import sys +import shutil + +if len(sys.argv) != 2 : + print("usage: compareTestImages <>") + sys.exit(-1) + +print("") +baseFileName = os.path.splitext(sys.argv[1])[0] +testDir = "/tmp/pdf2htmlEX/out" +ref_htmlDir = os.path.join("browser_tests", baseFileName) +test_htmlFile = os.path.join(testDir, baseFileName+'.html') + +if baseFileName == "test_fail" : + print("The test_fail test can not be regenerated") + print("") + sys.exit(-1) + +if not os.path.isfile(test_htmlFile) : + print("The test file [", test_htmlFile, "] has not been found") + print("Do you need to re-run the browser tests?") + print("") + sys.exit(-1) + +print("Are you sure you want to copy: ") +print(" ", test_htmlFile) +print("to: ") +print(" ", ref_htmlDir) +try: + input("\nType Ctrl-C now to abort: ") +except: + print("\n") + sys.exit(0) + +shutil.rmtree(ref_htmlDir, True) +os.makedirs(ref_htmlDir, 0o755, True) +shutil.copy(test_htmlFile, ref_htmlDir) + +print("") + diff --git a/pdf2htmlEX/test/runLocalBrowserTests b/pdf2htmlEX/test/runLocalBrowserTests new file mode 100755 index 0000000..f27cae2 --- /dev/null +++ b/pdf2htmlEX/test/runLocalBrowserTests @@ -0,0 +1,55 @@ +#!/bin/sh + +# This shell script runs the local browser tests + +# We start by running a virtual frame buffer as display 99.0 +# +/sbin/start-stop-daemon \ + --start \ + --pidfile /tmp/custom_xvfb_99.pid \ + --make-pidfile \ + --background \ + --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1920x16 +# +echo "" +echo "check that Xvfb is running:" +echo "-----------------------------------------------------------" +ps -ef | grep -v grep | grep Xvfb +echo "-----------------------------------------------------------" +echo "" + +# Now we tell the test drivers about this display +# (Note: you MUST not specify the host!) +# +export DISPLAY=:99.0 +# +echo "xwindows (xvfb) display: $DISPLAY" + +# Now we actually run the python3 based tests +# +echo "" +echo "running local browser tests:" +echo "-----------------------------------------------------------" +python3 test_local_browser.py +export returnCode=$? +echo "-----------------------------------------------------------" +echo "" + +# Now we shutdown the virtual frame buffer +# +/sbin/start-stop-daemon \ + --stop \ + --pidfile /tmp/custom_xvfb_99.pid \ + --retry 5 +# +echo "check that Xvfb is no longer running:" +echo "-----------------------------------------------------------" +ps -ef | grep -v grep | grep Xvfb +echo "-----------------------------------------------------------" +echo "" + +if [ -z "$TRAVIS_DIST"] ; then + exit $returnCode +fi + +exit 0 diff --git a/pdf2htmlEX/test/runLocalTestsPython b/pdf2htmlEX/test/runLocalTestsPython new file mode 100755 index 0000000..8f0fa85 --- /dev/null +++ b/pdf2htmlEX/test/runLocalTestsPython @@ -0,0 +1,7 @@ +#!/bin/sh + +set -ev + +# This shell script runs the (simple non-browser) tests + +python3 test_output.py diff --git a/pdf2htmlEX/test/runLocalTestsShell b/pdf2htmlEX/test/runLocalTestsShell new file mode 100755 index 0000000..692245a --- /dev/null +++ b/pdf2htmlEX/test/runLocalTestsShell @@ -0,0 +1,7 @@ +#!/bin/sh + +set -ev + +# This shell script runs the (simple non-browser) tests + +./testOutput diff --git a/test/test.py.in b/pdf2htmlEX/test/test.py.in similarity index 77% rename from test/test.py.in rename to pdf2htmlEX/test/test.py.in index e21e211..163626f 100755 --- a/test/test.py.in +++ b/pdf2htmlEX/test/test.py.in @@ -12,9 +12,11 @@ class Common(object): Variables and methods for common use in different tests. """ PDF2HTMLEX_PATH = "@PDF2HTMLEX_PATH@" # defined in CMakeLists.txt - if not os.path.isfile(PDF2HTMLEX_PATH) or not os.access(PDF2HTMLEX_PATH, os.X_OK): - print >> sys.stderr, "Cannot locate pdf2htmlEX executable, expected at ", PDF2HTMLEX_PATH, - ". Make sure source was built before running this test." + PDF2HTMLEX_EXE = PDF2HTMLEX_PATH.split() + PDF2HTMLEX_EXE = PDF2HTMLEX_EXE[0] + if not os.path.isfile(PDF2HTMLEX_EXE) or not os.access(PDF2HTMLEX_EXE, os.X_OK): + print( sys.stderr, "Cannot locate pdf2htmlEX executable, expected at ", PDF2HTMLEX_EXE, + ". Make sure source was built before running this test." ) exit(1) SRC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -28,6 +30,8 @@ class Common(object): PNGDIR = "@PDF2HTMLEX_PNGDIR@" DATDIR = "@PDF2HTMLEX_DATDIR@" OUTDIR = "@PDF2HTMLEX_OUTDIR@" + PREDIR = "@PDF2HTMLEX_PREDIR@" + HTMDIR = "@PDF2HTMLEX_HTMDIR@" def setUp(self): # filter manifest @@ -61,15 +65,18 @@ class Common(object): shutil.rmtree(self.TMPDIR, ignore_errors=False, onerror=None) os.mkdir(self.TMPDIR) - args = [Common.PDF2HTMLEX_PATH, - '--data-dir', self.DATDIR, + # To allow the user to specify additional command line arguments + # in the path, we split the PATH on whitespace and then append our + # arguments. + # + args = Common.PDF2HTMLEX_PATH.split() + [ '--data-dir', self.DATDIR, '--dest-dir', self.TMPDIR - ] + args - + ] + args + with open(os.devnull, 'w') as fnull: return_code = subprocess.call(list(map(str, args)), stderr=fnull) - self.assertEquals(return_code, 0, 'cannot execute pdf2htmlEX') + self.assertEqual(return_code, 0, 'cannot execute pdf2htmlEX') files = os.listdir(self.TMPDIR) for file in files: diff --git a/pdf2htmlEX/test/testOutput b/pdf2htmlEX/test/testOutput new file mode 100755 index 0000000..3a44f25 --- /dev/null +++ b/pdf2htmlEX/test/testOutput @@ -0,0 +1,206 @@ +#!/bin/sh + +# This shell script checks that pdf2htmlEX does not crash, and produces +# correct files. Do not check the content of the files. + +# We use a shell script to implement the python3 test_output.py so that we +# do not need to install any extra packages to test this functionality. + +# This is how we run pdf2htmlEX on a particular file, and arguments. +# +runPdf2htmlEX() { + # collect the arguments + # + export LAST_TEST_NAME="$*" + # + pdfFileName=$1 + # + shift + arguments=$* + + # clear out the TMPDIR + # + rm -rf $PDF2HTMLEX_TMPDIR + mkdir -p $PDF2HTMLEX_TMPDIR + # + # now run pdf2htmlEX to produce the output files + # + echo "test: [$LAST_TEST_NAME]" + echo "---" + $PDF2HTMLEX_PATH \ + --data-dir $PDF2HTMLEX_DATDIR \ + --dest-dir $PDF2HTMLEX_TMPDIR \ + $PDF2HTMLEX_TEST_DIR/test_output/$pdfFileName \ + $arguments +} + +# This is how we test for expected output files +# +hasExpectedFiles() { + filesFound="true" + for anExpectedFile in $1 ; do + if ! test -r $PDF2HTMLEX_TMPDIR/$anExpectedFile ; then + echo "NOT FOUND [$PDF2HTMLEX_TMPDIR/$anExpectedFile]" + filesFound="false" + fi + done + if test $filesFound = "true" ; then + echo "SUCCESS: $LAST_TEST_NAME" >> testOutputResults + else + echo "FAILURE: $LAST_TEST_NAME" >> testOutputResults + fi + echo "---" + echo "" +} + +# This is how we copy a file omitting lines between '#TEST_IGNORE_BEGIN' +# and '#TEST_IGNORE_END' (we pipe the file in via stdin and save it via +# stdout) +# +copy_TEST_IGNORE_file() { + skipLine=echo + while IFS= read -r line ; do + if echo $line | grep -q "^#TEST_IGNORE_BEGIN" ; then + skipLine=true + elif echo $line | grep -q "^#TEST_IGNORE_END" ; then + skipLine=echo + else + $skipLine "$line" + fi + done +} + +if test -z "$PDF2HTMLEX_PATH" ; then + echo "PANIC: we do not know where to find the pdf2htmlEX executable" + exit 1 +fi + +if test -z "$PDF2HTMLEX_DATDIR" ; then + export PDF2HTMLEX_DATDIR=/tmp/pdf2htmlex/dat +fi + +mkdir -p $PDF2HTMLEX_DATDIR + +if test -z "$PDF2HTMLEX_TMPDIR" ; then + export PDF2HTMLEX_TMPDIR=/tmp/pdf2htmlex/tmp +fi + +mkdir -p $PDF2HTMLEX_TMPDIR + +if test -z "$PDF2HTMLEX_TEST_DIR" ; then + export PDF2HTMLEX_TEST_DIR=. +fi + +mkdir -p $PDF2HTMLEX_TEST_DIR + +# Make sure any previous testOutputResults are cleared +# +rm -f testOutputResults + +# setup the correct data files +# +cat $PDF2HTMLEX_TEST_DIR/../share/manifest | \ + copy_TEST_IGNORE_file > $PDF2HTMLEX_DATDIR/manifest + +cp $PDF2HTMLEX_TEST_DIR/../share/base.min.css $PDF2HTMLEX_DATDIR +cp $PDF2HTMLEX_TEST_DIR/../test/fancy.min.css $PDF2HTMLEX_DATDIR + +# Do the tests +# +echo "" +echo "-------------------------------------------------------" +echo "running testOutput tests (simple non-browser tests)" +echo "-------------------------------------------------------" +echo "" + +export LAST_TEST_NAME="unknown" +# +runPdf2htmlEX '1-page.pdf' --version + +runPdf2htmlEX '1-page.pdf' +hasExpectedFiles '1-page.html' + +runPdf2htmlEX '2-pages.pdf' +hasExpectedFiles '2-pages.html' + +runPdf2htmlEX '1-page.pdf' 'foo.html' +hasExpectedFiles 'foo.html' + +runPdf2htmlEX '2-pages.pdf' 'foo.html' +hasExpectedFiles 'foo.html' + +runPdf2htmlEX '1-page.pdf' '--split-pages=1' +hasExpectedFiles '1-page.html 1-page1.page' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1' +hasExpectedFiles '3-pages.html 3-pages1.page 3-pages2.page 3-pages3.page' + +runPdf2htmlEX '1-page.pdf' '--split-pages=1 --page-filename=foo.xyz' +hasExpectedFiles '1-page.html foo1.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=foo.xyz' +hasExpectedFiles '3-pages.html foo1.xyz foo2.xyz foo3.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=fo%do.xyz' +hasExpectedFiles '3-pages.html fo1o.xyz fo2o.xyz fo3o.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=fo%03do.xyz' +hasExpectedFiles '3-pages.html fo001o.xyz fo002o.xyz fo003o.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%do%do.xyz' +hasExpectedFiles '3-pages.html f1o%do.xyz f2o%do.xyz f3o%do.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%soo.xyz' +hasExpectedFiles '3-pages.html f%soo1.xyz f%soo2.xyz f%soo3.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%poo.xyz' +hasExpectedFiles '3-pages.html f%poo1.xyz f%poo2.xyz f%poo3.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%noo.xyz' +hasExpectedFiles '3-pages.html f%noo1.xyz f%noo2.xyz f%noo3.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%%oo.xyz' +hasExpectedFiles '3-pages.html f%%oo1.xyz f%%oo2.xyz f%%oo3.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%%o%do.xyz' +hasExpectedFiles '3-pages.html f%%o1o.xyz f%%o2o.xyz f%%o3o.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=fo%do%%.xyz' +hasExpectedFiles '3-pages.html fo1o%%.xyz fo2o%%.xyz fo3o%%.xyz' + +runPdf2htmlEX '3-pages.pdf' '--split-pages=1 --page-filename=f%02%doo.xyz' +hasExpectedFiles '3-pages.html f%021oo.xyz f%022oo.xyz f%023oo.xyz' + +runPdf2htmlEX '1-page.pdf' '--split-pages=1 --page-filename=foo' +hasExpectedFiles '1-page.html foo1' + +runPdf2htmlEX '2-pages.pdf' 'foo%d.html' +hasExpectedFiles 'foo%d.html' + +runPdf2htmlEX '2-pages.pdf' 'foo%p.html' +hasExpectedFiles 'foo%p.html' + +runPdf2htmlEX '2-pages.pdf' 'foo%n.html' +hasExpectedFiles 'foo%n.html' + +runPdf2htmlEX '2-pages.pdf' 'foo%%.html' +hasExpectedFiles 'foo%%.html' + +runPdf2htmlEX 'issue501' '--split-pages=1 --embed-css=0' +hasExpectedFiles '' + +# Let the user know what the testOutputResults were +# +echo "" +echo "-------------------------------------------------------" +echo "testOutput results:" +echo "-------------------------------------------------------" +cat testOutputResults +echo "-------------------------------------------------------" +echo "" + +# fail the script IF we find the work 'FAILURE' in the testOutputResults +# +if grep FAILURE testOutputResults ; then + exit 1 +fi diff --git a/pdf2htmlEX/test/test_local_browser.py b/pdf2htmlEX/test/test_local_browser.py new file mode 100755 index 0000000..62a3657 --- /dev/null +++ b/pdf2htmlEX/test/test_local_browser.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +# Run browsers tests with a local Firefox + +import unittest + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions +from selenium.common.exceptions import WebDriverException +from browser_tests import BrowserTests + +class test_local_browser(BrowserTests, unittest.TestCase): + @classmethod + def setUpClass(cls): + super(test_local_browser, cls).setUpClass() + if not cls.GENERATING_MODE: + cls.browser = webdriver.Firefox() + cls.browser.set_window_size(810, 1210) + #cls.browser.maximize_window() # (does not seem to maximize to size of the frame buffer) + size = cls.browser.get_window_size() + print(" browser size width: ", size['width']) + print(" browser size height: ", size['height']) + assert ((size['width'] >= cls.BROWSER_WIDTH) and (size['height'] >= cls.BROWSER_HEIGHT)), 'Screen is not large enough' + cls.browser.set_window_size(cls.BROWSER_WIDTH, cls.BROWSER_HEIGHT) + + @classmethod + def tearDownClass(cls): + if not cls.GENERATING_MODE: + cls.browser.quit() + super(test_local_browser, cls).tearDownClass() + + def generate_image(self, html_file, png_file, page_must_load=True): + try: + self.browser.get('file://' + html_file) + WebDriverWait(self.browser, 5) \ + .until(expected_conditions.presence_of_element_located((By.ID, 'page-container'))) + except WebDriverException as e: + if page_must_load: + raise e + finally: + self.browser.save_screenshot(png_file) + +if __name__ == '__main__': + # turn warnings OFF to prevent 'ResourceWarning: unclosed =256. So an encoding might be */ -/* valid for the domain [0x20..0x7f] [0xa1a1..0xfefe] */ -/* In other words, we're interested in the ordering displayed in the */ -/* fontview. Nothing else */ -/* The max value need not be exact (though it should be at least as big)*/ -/* if you create a new font with the given encoding, then the font will */ -/* have max slots in it by default */ -/* A return value of -1 (from an EncFunc) indicates no mapping */ -/* AddEncoding returns 1 if the encoding was added, 2 if it replaced */ -/* an existing encoding, 0 if you attempt to replace a builtin */ -/* encoding */ -typedef int (*EncFunc)(int); -extern int AddEncoding(char *name, EncFunc enc_to_uni, EncFunc uni_to_enc, int max); - -extern int CID2NameUni(struct cidmap *map, int cid, char *buffer, int len); -extern int CID2Uni(struct cidmap *map, int cid); -extern int CIDFromName(char *name, SplineFont *cidmaster); -extern int CountOfEncoding(Encoding *encoding_name); -extern int MaxCID(struct cidmap *map); -extern int NameUni2CID(struct cidmap *map, int uni, const char *name); -extern int SFFlattenByCMap(SplineFont *sf, char *cmapname); -extern int SFForceEncoding(SplineFont *sf, EncMap *old, Encoding *new_enc); -extern int SFReencode(SplineFont *sf, const char *encname, int force); -extern SplineFont *CIDFlatten(SplineFont *cidmaster, SplineChar **glyphs, int charcnt); -extern SplineFont *MakeCIDMaster(SplineFont *sf, EncMap *oldmap, int bycmap, char *cmapfilename, struct cidmap *cidmap); -extern struct altuni *CIDSetAltUnis(struct cidmap *map, int cid); -extern struct cidmap *FindCidMap(char *registry, char *ordering, int supplement, SplineFont *sf); -extern struct cidmap *LoadMapFromFile(char *file, char *registry, char *ordering, int supplement); -extern void BDFOrigFixup(BDFFont *bdf, int orig_cnt, SplineFont *sf); -extern void CIDMasterAsDes(SplineFont *sf); -extern void DumpPfaEditEncodings(void); -extern void FVAddEncodingSlot(FontViewBase *fv, int gid); -extern void LoadPfaEditEncodings(void); -extern void MMMatchGlyphs(MMSet *mm); -extern void SFAddEncodingSlot(SplineFont *sf, int gid); -extern void SFAddGlyphAndEncode(SplineFont *sf, SplineChar *sc, EncMap *basemap, int baseenc); -extern void SFEncodeToMap(SplineFont *sf, struct cidmap *map); -extern void SFExpandGlyphCount(SplineFont *sf, int newcnt); -extern void SFMatchGlyphs(SplineFont *sf, SplineFont *target, int addempties); -extern void SFRemoveGlyph(SplineFont *sf, SplineChar *sc); - -#endif /* FONTFORGE_ENCODING_H */ diff --git a/src/util/fontforge-2.0.20170731/fvfonts.h b/src/util/fontforge-2.0.20170731/fvfonts.h deleted file mode 100644 index 304c7a0..0000000 --- a/src/util/fontforge-2.0.20170731/fvfonts.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef FONTFORGE_FVFONTS_H -#define FONTFORGE_FVFONTS_H - -#include "baseviews.h" -#include "splinefont.h" - -extern AnchorClass *MCConvertAnchorClass(struct sfmergecontext *mc, AnchorClass *ac); -extern BDFChar *BDFCharCopy(BDFChar *bc); -extern int SFCIDFindCID(SplineFont *sf, int unienc, const char *name); -extern int SFCIDFindExistingChar(SplineFont *sf, int unienc, const char *name); -extern int SFFindExistingSlot(SplineFont *sf, int unienc, const char *name); -extern int SFFindGID(SplineFont *sf, int unienc, const char *name); -extern int SFFindSlot(SplineFont *sf, EncMap *map, int unienc, const char *name); -extern int SFHasChar(SplineFont *sf, int unienc, const char *name); -extern int SFHasCID(SplineFont *sf, int cid); -extern PST *PSTCopy(PST *base, SplineChar *sc, struct sfmergecontext *mc); -extern RefChar *RefCharsCopy(RefChar *ref); -extern SplineChar *SFGetChar(SplineFont *sf, int unienc, const char *name); -extern SplineChar *SFGetOrMakeCharFromUnicodeBasic(SplineFont *sf, int ch); -extern SplineChar *SFHashName(SplineFont *sf, const char *name); -extern SplineChar *SplineCharCopy(SplineChar *sc, SplineFont *into, struct sfmergecontext *mc); -extern SplineChar *SplineCharInterpolate(SplineChar *base, SplineChar *other, real amount, SplineFont *newfont); -extern SplineFont *InterpolateFont(SplineFont *base, SplineFont *other, real amount, Encoding *enc); -extern SplineSet *SplineSetsInterpolate(SplineSet *base, SplineSet *other, real amount, SplineChar *sc); -extern struct altuni *AltUniCopy(struct altuni *altuni, SplineFont *noconflicts); -extern struct lookup_subtable *MCConvertSubtable(struct sfmergecontext *mc, struct lookup_subtable *sub); -extern void BitmapsCopy(SplineFont *to, SplineFont *from, int to_index, int from_index); -extern void GlyphHashFree(SplineFont *sf); -extern void __GlyphHashFree(struct glyphnamehash *hash); -extern void MergeFont(FontViewBase *fv, SplineFont *other, int preserveCrossFontKerning); -extern void SFFinishMergeContext(struct sfmergecontext *mc); -extern void SFHashGlyph(SplineFont *sf, SplineChar *sc); - -#endif /* FONTFORGE_FVFONTS_H */ diff --git a/src/util/fontforge-2.0.20170731/namelist.h b/src/util/fontforge-2.0.20170731/namelist.h deleted file mode 100644 index 3f87c76..0000000 --- a/src/util/fontforge-2.0.20170731/namelist.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef FONTFORGE_NAMELIST_H -#define FONTFORGE_NAMELIST_H - -#include "splinefont.h" - -extern char **AllGlyphNames(int uni, NameList *for_this_font, SplineChar *sc); -extern char **AllNamelistNames(void); -extern char **SFTemporaryRenameGlyphsToNamelist(SplineFont *sf, NameList *new); -extern const char *RenameGlyphToNamelist(char *buffer, SplineChar *sc, NameList *old, NameList *new, char **sofar); -extern const char *StdGlyphName(char *buffer, int uni, enum uni_interp interp, NameList *for_this_font); -extern int UniFromName(const char *name, enum uni_interp interp, Encoding *encname); -extern NameList *DefaultNameListForNewFonts(void); -extern NameList *LoadNamelist(char *filename); -extern NameList *NameListByName(const char *name); -extern void LoadNamelistDir(char *dir); -extern void SFRenameGlyphsToNamelist(SplineFont *sf, NameList *new); -extern void SFTemporaryRestoreGlyphNames(SplineFont *sf, char **former); - -#endif /* FONTFORGE_NAMELIST_H */ diff --git a/src/util/fontforge-2.0.20170731/savefont.h b/src/util/fontforge-2.0.20170731/savefont.h deleted file mode 100644 index 1bde2a1..0000000 --- a/src/util/fontforge-2.0.20170731/savefont.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright (C) 2007-2012 by George Williams */ -/* - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - - * The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef FONTFORGE_SAVEFONT_H -#define FONTFORGE_SAVEFONT_H - -#include - -#include "splinefont.h" - -extern const char (*savefont_extensions[]), (*bitmapextensions[]); -extern int old_sfnt_flags; - -void PrepareUnlinkRmOvrlp(SplineFont *sf,const char *filename,int layer); -void RestoreUnlinkRmOvrlp(SplineFont *sf,const char *filename,int layer); -int _DoSave(SplineFont *sf,char *newname,int32 *sizes,int res, - EncMap *map, char *subfontdefinition,int layer); -int CheckIfTransparent(SplineFont *sf); - -extern int GenerateScript(SplineFont *sf, char *filename, const char *bitmaptype, int fmflags, int res, char *subfontdirectory, struct sflist *sfs, EncMap *map, NameList *rename_to, int layer); - -#ifdef FONTFORGE_CONFIG_WRITE_PFM -extern int WritePfmFile(char *filename, SplineFont *sf, EncMap *map, int layer); -#endif - -#endif /* FONTFORGE_SAVEFONT_H */ diff --git a/src/util/fontforge-2.0.20170731/splineorder2.h b/src/util/fontforge-2.0.20170731/splineorder2.h deleted file mode 100644 index b94430c..0000000 --- a/src/util/fontforge-2.0.20170731/splineorder2.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef FONTFORGE_SPLINEORDER2_H -#define FONTFORGE_SPLINEORDER2_H - -#include "splinefont.h" - -extern SplinePoint *SplineTtfApprox(Spline *ps); -extern SplineSet *SplineSetsConvertOrder(SplineSet *ss, int to_order2); -extern SplineSet *SplineSetsPSApprox(SplineSet *ss); -extern SplineSet *SplineSetsTTFApprox(SplineSet *ss); -extern SplineSet *SSPSApprox(SplineSet *ss); -extern SplineSet *SSttfApprox(SplineSet *ss); -extern Spline *SplineMake2(SplinePoint *from, SplinePoint *to); -extern void SCConvertLayerToOrder2(SplineChar *sc, int layer); -extern void SCConvertLayerToOrder3(SplineChar *sc, int layer); -extern void SCConvertOrder(SplineChar *sc, int to_order2); -extern void SCConvertToOrder2(SplineChar *sc); -extern void SCConvertToOrder3(SplineChar *sc); -extern void SFConvertGridToOrder2(SplineFont *_sf); -extern void SFConvertGridToOrder3(SplineFont *_sf); -extern void SFConvertLayerToOrder2(SplineFont *_sf, int layer); -extern void SFConvertLayerToOrder3(SplineFont *_sf, int layer); -extern void SFConvertToOrder2(SplineFont *_sf); -extern void SFConvertToOrder3(SplineFont *_sf); -extern void SplinePointNextCPChanged2(SplinePoint *sp); -extern void SplinePointPrevCPChanged2(SplinePoint *sp); -extern void SplineRefigure2(Spline *spline); -extern void SplineRefigureFixup(Spline *spline); - -#endif /* FONTFORGE_SPLINEORDER2_H */ diff --git a/src/util/fontforge-2.0.20170731/splineutil.h b/src/util/fontforge-2.0.20170731/splineutil.h deleted file mode 100644 index c0e329b..0000000 --- a/src/util/fontforge-2.0.20170731/splineutil.h +++ /dev/null @@ -1,217 +0,0 @@ -#ifndef FONTFORGE_SPLINEUTIL_H -#define FONTFORGE_SPLINEUTIL_H - -#include "psfont.h" -#include "splinefont.h" -#include "ttfinstrs.h" -#include "views.h" - -extern AnchorClass *SFFindOrAddAnchorClass(SplineFont *sf, char *name, struct lookup_subtable *sub); -extern AnchorPoint *AnchorPointsCopy(AnchorPoint *alist); -extern AnchorPoint *APAnchorClassMerge(AnchorPoint *anchors, AnchorClass *into, AnchorClass *from); -extern bigreal DistanceBetweenPoints(BasePoint *p1, BasePoint *p2); -extern bigreal SplineCurvature(Spline *s, bigreal t); -extern bigreal SplineMinDistanceToPoint(Spline *s, BasePoint *p); - -extern size_t count_caps(const char * input); -extern char *upper_case(const char * input); -extern char *same_case(const char * input); -extern char *delimit_null(const char * input, char delimiter); - -extern char *strconcat3(const char *str1, const char *str2, const char *str3); -extern char **StringExplode(const char *input, char delimiter); -extern char *XUIDFromFD(int xuid[20]); -extern DeviceTable *DeviceTableCopy(DeviceTable *orig); -extern double CheckExtremaForSingleBitErrors(const Spline1D *sp, double t, double othert); -extern DStemInfo *DStemInfoCopy(DStemInfo *h); -extern EncMap *EncMap1to1(int enccount); -extern EncMap *EncMapCopy(EncMap *map); -extern EncMap *EncMapNew(int enccount, int backmax, Encoding *enc); - -/* Uses an iterative approximation */ -extern extended IterateSplineSolve(const Spline1D *sp, extended tmin, extended tmax, extended sought_y); -/* Uses an iterative approximation and then tries to fix things up */ -extern extended IterateSplineSolveFixup(const Spline1D *sp, extended tmin, extended tmax, extended sought_y); - -extern FPST *FPSTCopy(FPST *fpst); -extern HintMask *HintMaskFromTransformedRef(RefChar *ref, BasePoint *trans, SplineChar *basesc,HintMask *hm); -extern ImageList *ImageListCopy(ImageList *cimg); -extern ImageList *ImageListTransform(ImageList *img, real transform[6], int everything); -extern int CountKerningClasses(SplineFont *sf); -extern int _CubicSolve(const Spline1D *sp, bigreal sought, extended ts[3]); -extern int GroupNameType(const char *input); -extern int IntersectLines(BasePoint *inter, BasePoint *line1_1, BasePoint *line1_2, BasePoint *line2_1, BasePoint *line2_2); -extern int IntersectLinesClip(BasePoint *inter, BasePoint *line1_1, BasePoint *line1_2, BasePoint *line2_1, BasePoint *line2_2); -extern int IntersectLinesSlopes(BasePoint *inter, BasePoint *line1, BasePoint *slope1, BasePoint *line2, BasePoint *slope2); -extern int LineTangentToSplineThroughPt(Spline *s, BasePoint *pt, extended ts[4], extended tmin, extended tmax); -extern int NearSpline(FindSel *fs, Spline *spline); -extern int SCRoundToCluster(SplineChar *sc, int layer, int sel, bigreal within, bigreal max); -extern int SFKerningGroupExistsSpecific(const struct splinefont *sf, const char *groupname, int isv, int isr); -extern int SpExistsInSS(SplinePoint *sp, SplineSet *ss); -extern int Spline2DFindExtrema(const Spline *sp, extended extrema[4]); -extern int Spline2DFindPointsOfInflection(const Spline *sp, extended poi[2]); -extern int SplineAtInflection(Spline1D *sp, bigreal t); -extern int SplineAtMinMax(Spline1D *sp, bigreal t); -extern int SplineExistsInSS(Spline *s, SplineSet *ss); -extern int SplinePointIsACorner(SplinePoint *sp); -extern int SplineSetIntersect(SplineSet *spl, Spline **_spline, Spline **_spline2); -extern int SplineSetsRemoveAnnoyingExtrema(SplineSet *ss, bigreal err); - -/* Two lines intersect in at most 1 point */ -/* Two quadratics intersect in at most 4 points */ -/* Two cubics intersect in at most 9 points */ /* Plus an extra space for a trailing -1 */ -extern int SplinesIntersect(const Spline *s1, const Spline *s2, BasePoint pts[9], extended t1s[10], extended t2s[10]); - -extern int SplineT2SpiroIndex(Spline *spline, bigreal t, SplineSet *spl); -extern int SSBoundsWithin(SplineSet *ss, bigreal z1, bigreal z2, bigreal *wmin, bigreal *wmax, int major); -extern int SSExistsInLayer(SplineSet *ss, SplineSet *lots); -extern int SSHasClip(SplineSet *ss); -extern int SSHasDrawn(SplineSet *ss); -extern int SSPointWithin(SplineSet *spl, BasePoint *pt); -extern int StringInStrings(char const* const* space, int length, const char *target); -extern KernClass *KernClassCopy(KernClass *kc); -extern LinearApprox *SplineApproximate(Spline *spline, real scale); -extern MinimumDistance *MinimumDistanceCopy(MinimumDistance *md); -extern real SplineNearPoint(Spline *spline, BasePoint *bp, real fudge); -extern RefChar *RefCharCreate(void); -extern SplineChar *SFSplineCharCreate(SplineFont *sf); -extern SplineFont *SplineFontFromPSFont(FontDict *fd); -extern SplinePointList *SPLCopyTransformedHintMasks(RefChar *r, SplineChar *basesc, BasePoint *trans,int layer); -extern SplinePointList *SPLCopyTranslatedHintMasks(SplinePointList *base, SplineChar *basesc, SplineChar *subsc, BasePoint *trans); -extern SplinePointList *SplinePointListCopy1(const SplinePointList *spl); -extern SplinePointList *SplinePointListCopySelected(SplinePointList *base); -extern SplinePointList *SplinePointListCopySpiroSelected(SplinePointList *base); -extern SplinePointList *SplinePointListRemoveSelected(SplineChar *sc, SplinePointList *base); -extern SplinePointList *SplinePointListShift(SplinePointList *base, real xoff, enum transformPointType allpoints); -extern SplinePointList *SplinePointListSpiroTransform(SplinePointList *base, real transform[6], int allpoints); -extern SplinePointList *SplinePointListTransformExtended(SplinePointList *base, real transform[6], enum transformPointType tpt, enum transformPointMask tpmask); - -extern SplinePoint *SplineBisect(Spline *spline, extended t); -extern SplinePoint *SplinePointCreate(real x, real y); -extern SplineSet *LayerAllSplines(Layer *layer); -extern SplineSet *LayerUnAllSplines(Layer *layer); -extern Spline *SplineMake3(SplinePoint *from, SplinePoint *to); -extern Spline *SplineSplit(Spline *spline, extended ts[3]); -extern struct baselangextent *BaseLangCopy(struct baselangextent *extent); -extern struct ff_glyphclasses *SFGetGroup(const struct splinefont *sf, int index, const char *name); -extern struct glyphvariants *GlyphVariantsCopy(struct glyphvariants *gv); -extern struct gradient *GradientCopy(struct gradient *old, real transform[6]); -extern struct jstf_lang *JstfLangsCopy(struct jstf_lang *jl); -extern struct mathkern *MathKernCopy(struct mathkern *mk); -extern struct pattern *PatternCopy(struct pattern *old, real transform[6]); -extern ValDevTab *ValDevTabCopy(ValDevTab *orig); -extern void AltUniFree(struct altuni *altuni); -extern void AnchorClassesFree(AnchorClass *an); -extern void AnchorPointsFree(AnchorPoint *ap); -extern void ApTransform(AnchorPoint *ap, real transform[6]); -extern void ASMFree(ASM *sm); -extern void BaseFree(struct Base *base); -extern void BaseLangFree(struct baselangextent *extent); -extern void BaseScriptFree(struct basescript *bs); -extern void BpTransform(BasePoint *to, BasePoint *from, real transform[6]); -extern void BrushCopy(struct brush *into, struct brush *from, real transform[6]); -extern void CIDLayerFindBounds(SplineFont *cidmaster, int layer, DBounds *bounds); -extern void DeviceTableFree(DeviceTable *dt); -extern void DeviceTableSet(DeviceTable *adjust, int size, int correction); -extern void DStemInfoFree(DStemInfo *h); -extern void DStemInfosFree(DStemInfo *h); -extern void EncMapFree(EncMap *map); -extern void ExplodedStringFree(char **input); -extern void FeatureScriptLangListFree(FeatureScriptLangList *fl); -extern void FPSTClassesFree(FPST *fpst); -extern void FPSTFree(FPST *fpst); -extern void FPSTRuleContentsFree(struct fpst_rule *r, enum fpossub_format format); -extern void FPSTRulesFree(struct fpst_rule *r, enum fpossub_format format, int rcnt); -extern void GlyphGroupFree(struct ff_glyphclasses* group); -extern void GlyphGroupKernFree(struct ff_rawoffsets* groupkern); -extern void GlyphGroupKernsFree(struct ff_rawoffsets* root); -extern void GlyphGroupsFree(struct ff_glyphclasses* root); -extern void GlyphVariantsFree(struct glyphvariants *gv); -extern void GradientFree(struct gradient *grad); -extern void GrowBufferAdd(GrowBuf *gb, int ch); -extern void GrowBufferAddStr(GrowBuf *gb, char *str); -extern void ImageListsFree(ImageList *imgs); -extern void JstfLangFree(struct jstf_lang *jl); -extern void JustifyFree(Justify *just); -extern void KernClassClearSpecialContents(KernClass *kc); -extern void KernClassFreeContents(KernClass *kc); -extern void KernClassListClearSpecialContents(KernClass *kc); -extern void KernClassListFree(KernClass *kc); -extern void KernPairsFree(KernPair *kp); -extern void LayerDefault(Layer *layer); -extern void LayerFreeContents(SplineChar *sc, int layer); -extern void LinearApproxFree(LinearApprox *la); -extern void LineListFree(LineList *ll); -extern void MacFeatListFree(MacFeat *mf); -extern void MacNameListFree(struct macname *mn); -extern void MacSettingListFree(struct macsetting *ms); -extern void MarkClassFree(int cnt, char **classes, char **names); -extern void MarkSetFree(int cnt, char **classes, char **names); -extern void MathKernFree(struct mathkern *mk); -extern void MathKernVContentsFree(struct mathkernvertex *mk); -extern void MinimumDistancesFree(MinimumDistance *md); -extern void MMSetClearSpecial(MMSet *mm); -extern void MMSetFreeContents(MMSet *mm); -extern void OtfFeatNameListFree(struct otffeatname *fn); -extern void OtfNameListFree(struct otfname *on); -extern void OTLookupFree(OTLookup *lookup); -extern void OTLookupListFree(OTLookup *lookup); -extern void PatternFree(struct pattern *pat); -extern void PenCopy(struct pen *into, struct pen *from, real transform[6]); -extern void RefCharFindBounds(RefChar *rf); -extern void RefCharFree(RefChar *ref); -extern void RefCharsFree(RefChar *ref); -extern void SCCategorizePoints(SplineChar *sc); -extern void SCMakeDependent(SplineChar *dependent, SplineChar *base); -extern void SCRefToSplines(SplineChar *sc, RefChar *rf, int layer); -extern void SCReinstanciateRefChar(SplineChar *sc, RefChar *rf, int layer); -extern void SCRemoveDependent(SplineChar *dependent, RefChar *rf, int layer); -extern void SCRemoveDependents(SplineChar *dependent); -extern void SCRemoveLayerDependents(SplineChar *dependent, int layer); -extern void SFInstanciateRefs(SplineFont *sf); -extern void SFReinstanciateRefs(SplineFont *sf); -extern void SFRemoveAnchorClass(SplineFont *sf, AnchorClass *an); -extern void SFRemoveSavedTable(SplineFont *sf, uint32 tag); -extern void SPLCategorizePointsKeepCorners(SplinePointList *spl); -extern void SplineCharFindBounds(SplineChar *sc, DBounds *bounds); -extern void SplineCharFreeContents(SplineChar *sc); -extern void SplineCharLayerFindBounds(SplineChar *sc, int layer, DBounds *bounds); -extern void SplineCharLayerQuickBounds(SplineChar *sc, int layer, DBounds *bounds); -extern void SplineCharListsFree(struct splinecharlist *dlist); -extern void SplineCharQuickBounds(SplineChar *sc, DBounds *b); -extern void SplineCharQuickConservativeBounds(SplineChar *sc, DBounds *b); -extern void SplineFindExtrema(const Spline1D *sp, extended *_t1, extended *_t2); -extern void SplineFontClearSpecial(SplineFont *sf); -extern void SplineFontFindBounds(SplineFont *sf, DBounds *bounds); -extern void SplineFontFree(SplineFont *sf); -extern void SplineFontLayerFindBounds(SplineFont *sf, int layer, DBounds *bounds); -extern void SplineFontQuickConservativeBounds(SplineFont *sf, DBounds *b); -extern void SplineFree(Spline *spline); -extern void SplinePointCategorize(SplinePoint *sp); -extern void SplinePointFree(SplinePoint *sp); -extern void SplinePointListFree(SplinePointList *spl); -extern void SplinePointListMDFree(SplineChar *sc, SplinePointList *spl); -extern void SplinePointListSelect(SplinePointList *spl, int sel); -extern void SplinePointListsFree(SplinePointList *spl); -extern void SplinePointListsMDFree(SplineChar *sc, SplinePointList *spl); -extern void SplinePointMDFree(SplineChar *sc, SplinePoint *sp); -extern void SplinePointsFree(SplinePointList *spl); -extern void SplineRemoveExtremaTooClose(Spline1D *sp, extended *_t1, extended *_t2); -extern void SplineSetBeziersClear(SplinePointList *spl); -extern void SplineSetFindBounds(const SplinePointList *spl, DBounds *bounds); -extern void SplineSetQuickBounds(SplineSet *ss, DBounds *b); -extern void SplineSetQuickConservativeBounds(SplineSet *ss, DBounds *b); -extern void SplineSetSpirosClear(SplineSet *spl); -extern void TTFLangNamesFree(struct ttflangname *l); -extern void TtfTablesFree(struct ttf_table *tab); -extern void ValDevFree(ValDevTab *adjust); - -#ifdef FF_UTHASH_GLIF_NAMES -struct glif_name_index; -extern int KerningClassSeekByAbsoluteIndex(const struct splinefont *sf, int seek_index, struct kernclass **okc, int *oisv, int *oisr, int *ooffset); -extern int HashKerningClassNames(SplineFont *sf, struct glif_name_index * class_name_hash); -extern int HashKerningClassNamesCaps(SplineFont *sf, struct glif_name_index * class_name_hash); -extern int HashKerningClassNamesFlex(SplineFont *sf, struct glif_name_index * class_name_hash, int capitalize); -#endif /* FF_UTHASH_GLIF_NAMES */ - -#endif /* FONTFORGE_SPLINEUTIL_H */ diff --git a/src/util/fontforge-2.0.20170731/splineutil2.h b/src/util/fontforge-2.0.20170731/splineutil2.h deleted file mode 100644 index b5ed7fa..0000000 --- a/src/util/fontforge-2.0.20170731/splineutil2.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef FONTFORGE_SPLINEUTIL2_H -#define FONTFORGE_SPLINEUTIL2_H - -#include "splinefont.h" - -enum ae_type { ae_all, ae_between_selected, ae_only_good, ae_only_good_rm_later }; - -extern bigreal PathLength(SplineSet *ss); -extern bigreal SplineLengthRange(Spline *spline, real from_t, real to_t); -extern char *GetNextUntitledName(void); -extern int PointListIsSelected(SplinePointList *spl); -extern int PointsDiagonalable(SplineFont *sf, BasePoint **bp, BasePoint *unit); -extern int RealApprox(real a, real b); -extern int RealNearish(real a, real b); -extern int RealRatio(real a, real b, real fudge); -extern int RealWithin(real a, real b, real fudge); -extern int SPInterpolate(const SplinePoint *sp); -extern int SpIsExtremum(SplinePoint *sp); -extern int Spline1DCantExtremeX(const Spline *s); -extern int Spline1DCantExtremeY(const Spline *s); -extern int SplineInSplineSet(Spline *spline, SplineSet *spl); -extern int SplineIsLinearMake(Spline *spline); -extern int SplinePointListIsClockwise(const SplineSet *spl); -extern int SPLNearlyLines(SplineChar *sc, SplineSet *ss, bigreal err); -extern int Within16RoundingErrors(bigreal v1, bigreal v2); -extern int Within4RoundingErrors(bigreal v1, bigreal v2); -extern int Within64RoundingErrors(bigreal v1, bigreal v2); -extern Spline *ApproximateSplineFromPointsSlopes(SplinePoint *from, SplinePoint *to, TPoint *mid, int cnt, int order2); -extern SplineFont *SplineFontBlank(int charcnt); -extern SplineFont *SplineFontEmpty(void); -extern SplineFont *SplineFontNew(void); -extern Spline *PathFindDistance(SplineSet *path, bigreal d, bigreal *_t); -extern SplineSet *SplineCharRemoveTiny(SplineChar *sc, SplineSet *head); -extern SplineSet *SplineCharSimplify(SplineChar *sc, SplineSet *head, struct simplifyinfo *smpl); -extern SplineSet *SplineSetBindToPath(SplineSet *ss, int doscale, int glyph_as_unit, int align, real offset, SplineSet *path); -extern SplineSet *SplineSetJoin(SplineSet *start, int doall, real fudge, int *changed); -extern SplineSet *SplineSetReverse(SplineSet *spl); -extern SplineSet *SplineSetsAntiCorrect(SplineSet *base); -extern SplineSet *SplineSetsCorrect(SplineSet *base, int *changed); -extern SplineSet *SplineSetsDetectDir(SplineSet **_base, int *_lastscan); -extern SplineSet *SplineSetsExtractOpen(SplineSet **tbase); -extern SplineSet *SSRemoveZeroLengthSplines(SplineSet *base); -extern Spline *SplineAddExtrema(Spline *s, int always, real lenbound, real offsetbound, DBounds *b); -extern void BP_HVForce(BasePoint *vector); -extern void CanonicalContours(SplineChar *sc, int layer); -extern void SFIncrementXUID(SplineFont *sf); -extern void SFRandomChangeXUID(SplineFont *sf); -extern void SPAdjustControl(SplinePoint *sp, BasePoint *cp, BasePoint *to, int order2); -extern void SPAverageCps(SplinePoint *sp); -extern void SPHVCurveForce(SplinePoint *sp); -extern void SPLAverageCps(SplinePointList *spl); -extern void SplineCharAddExtrema(SplineChar *sc, SplineSet *head, enum ae_type between_selected, int emsize); -extern void SplineCharDefaultNextCP(SplinePoint *base); -extern void SplineCharDefaultPrevCP(SplinePoint *base); -extern void SplineCharMerge(SplineChar *sc, SplineSet **head, int type); -extern void SplineCharTangentNextCP(SplinePoint *sp); -extern void SplineCharTangentPrevCP(SplinePoint *sp); -extern void SplinePointListSet(SplinePointList *tobase, SplinePointList *frombase); -extern void SplinePointListSimplify(SplineChar *sc, SplinePointList *spl, struct simplifyinfo *smpl); -extern void SplineSetAddExtrema(SplineChar *sc, SplineSet *ss, enum ae_type between_selected, int emsize); -extern void SplineSetJoinCpFixup(SplinePoint *sp); -extern void SplineSetsInsertOpen(SplineSet **tbase, SplineSet *open); -extern void SplineSetsUntick(SplineSet *spl); -extern void SplinesRemoveBetween(SplineChar *sc, SplinePoint *from, SplinePoint *to, int type); -extern void SPLNearlyHvCps(SplineChar *sc, SplineSet *ss, bigreal err); -extern void SPLNearlyHvLines(SplineChar *sc, SplineSet *ss, bigreal err); -extern void SPLsStartToLeftmost(SplineChar *sc, int layer); -extern void SPLStartToLeftmost(SplineChar *sc, SplinePointList *spl, int *changed); -extern void SPSmoothJoint(SplinePoint *sp); - -/** - * This is like SPAdjustControl but you have not wanting to move the - * BCP at all, but you would like the current location of the passed - * BCP to reshape the spline through the splinepoint. For example, if - * you drag the spline between two points then you might like to touch - * the inside BCP between the two splinepoints to reshape the whole - * curve through a curve point. - */ -extern void SPTouchControl(SplinePoint *sp, BasePoint *which, int order2); - -extern void SPWeightedAverageCps(SplinePoint *sp); -extern void SSOverlapClusterCpAngles(SplineSet *base, bigreal within); -extern void SSRemoveStupidControlPoints(SplineSet *base); - -#endif /* FONTFORGE_SPLINEUTIL2_H */ diff --git a/src/util/fontforge-2.0.20170731/start.h b/src/util/fontforge-2.0.20170731/start.h deleted file mode 100644 index 037731b..0000000 --- a/src/util/fontforge-2.0.20170731/start.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef FONTFORGE_START_H -#define FONTFORGE_START_H - -extern void doinitFontForgeMain(void); -extern void doversion(const char *source_version_str); -extern void InitSimpleStuff(void); - -#endif /* FONTFORGE_START_H */ diff --git a/src/util/fontforge-2.0.20170731/tottf.h b/src/util/fontforge-2.0.20170731/tottf.h deleted file mode 100644 index 28895f7..0000000 --- a/src/util/fontforge-2.0.20170731/tottf.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef FONTFORGE_TOTTF_H -#define FONTFORGE_TOTTF_H - -#include "splinefont.h" -#include "ttf.h" - -extern char *utf8_verify_copy(const char *str); -extern int32 filechecksum(FILE *file); - -extern int AlreadyMSSymbolArea(SplineFont *sf, EncMap *map); -extern int RefDepth(RefChar *ref, int layer); -extern int SFFigureDefWidth(SplineFont *sf, int *_nomwid); -extern int SFHasInstructions(SplineFont *sf); -extern int SSAddPoints(SplineSet *ss, int ptcnt, BasePoint *bp, char *flags); -extern int ttfcopyfile(FILE *ttf, FILE *other, int pos, const char *tab_name); -extern int WriteTTC(const char *filename, struct sflist *sfs, enum fontformat format, enum bitmapformat bf, int flags, int layer, enum ttc_flags ttcflags); -extern int WriteTTFFont(char *fontname, SplineFont *sf, enum fontformat format, int32 *bsizes, enum bitmapformat bf, int flags, EncMap *enc, int layer); -extern int _WriteTTFFont(FILE *ttf, SplineFont *sf, enum fontformat format, int32 *bsizes, enum bitmapformat bf, int flags, EncMap *enc, int layer); -extern int _WriteType42SFNTS(FILE *type42, SplineFont *sf, enum fontformat format, int flags, EncMap *enc, int layer); -extern void cvt_unix_to_1904(long long time, int32 result[2]); -extern void DefaultTTFEnglishNames(struct ttflangname *dummy, SplineFont *sf); -extern void OS2FigureCodePages(SplineFont *sf, uint32 CodePage[2]); -extern void OS2FigureUnicodeRanges(SplineFont *sf, uint32 Ranges[4]); -extern void SFDefaultOS2Info(struct pfminfo *pfminfo, SplineFont *sf, char *fontname); -extern void SFDefaultOS2Simple(struct pfminfo *pfminfo, SplineFont *sf); -extern void SFDefaultOS2SubSuper(struct pfminfo *pfminfo, int emsize, double italic_angle); -extern void SFDummyUpCIDs(struct glyphinfo *gi, SplineFont *sf); - -extern void putfixed(FILE *file, real dval); -extern void putlong(FILE *file, int val); -extern void putshort(FILE *file, int sval); - -#endif /* FONTFORGE_TOTTF_H */ diff --git a/src/util/fontforge-2.0.20170731/views.h b/src/util/fontforge-2.0.20170731/views.h deleted file mode 100644 index 3988e92..0000000 --- a/src/util/fontforge-2.0.20170731/views.h +++ /dev/null @@ -1,1496 +0,0 @@ -/* Copyright (C) 2000-2012 by George Williams */ -/* - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - - * The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -#ifndef _VIEWS_H -#define _VIEWS_H - -#include - -#include "ttfinstrs.h" - -#include "ffglib.h" -#include "baseviews.h" - -#include -#include "dlist.h" -#include "search.h" - - -struct gfi_data; -struct contextchaindlg; -struct statemachinedlg; - - -extern struct cvshows { - int showfore, showback, showgrids, showhhints, showvhints, showdhints; - int showpoints, showfilled; - int showrulers; - int showrounds; /* 0=>no, 1=>auto, 2=>always */ - int showmdx, showmdy; /* minimum distances x,y */ - int showhmetrics, showvmetrics; /* show advance width, baseline, etc. */ - int markextrema; - int markpoi; /* Points of inflection */ - int showblues, showfamilyblues; - int showanchor; - int showcpinfo; - int showtabs; /* with the names of former glyphs */ - int showsidebearings; - int showrefnames; - int snapoutlines; - int showalmosthvlines; - int showalmosthvcurves; - int hvoffset; - int checkselfintersects; /* Not really something shown, but convenient to keep it here */ - int showdebugchanges; /* Changes the way changing rasters are displayed in tt debug mode */ - int alwaysshowcontrolpoints; //< Always show the BCP even when their splinepoint is not selected -} CVShows; - -extern struct bvshows { - int showfore, showoutline, showgrid; - int lastpixelsize; -} BVShows; - -enum debug_wins { dw_registers=0x1, dw_stack=0x2, dw_storage=0x4, dw_points=0x8, - dw_cvt=0x10, dw_raster=0x20, dw_gloss=0x40 }; - -struct instrinfo { - int isel_pos; - int16 lheight,lpos; - char *scroll, *offset; - GWindow v; - GGadget *vsb; - int16 sbw; - int16 vheight, vwidth; - int16 lstopped; - int16 as, fh; - struct instrdata *instrdata; - GFont *gfont; - unsigned int showaddr: 1; - unsigned int showhex: 1; - unsigned int mousedown: 1; - void *userdata; - void (*selection_callback)(struct instrinfo *,int ip); - int (*bpcheck)(struct instrinfo *,int ip); - int (*handle_char)(struct instrinfo *,GEvent *e); -}; - -struct reflist { - RefChar *ref; - struct reflist *parent; -}; - -typedef struct debugview { - struct debugger_context *dc; /* Local to freetype.c */ - GWindow dv, v; - /* Windows for twilight points, cvt, registers, stack, storage, stack gloss */ - GWindow regs, stack, storage, points, cvt, raster, gloss; /* order matters */ - GWindow points_v; - GGadget *cvtsb; - GGadget *pts_vsb; - GGadget *glosssb; - GGadget *storagesb; - GGadget *regsb; - GGadget *stacksb; - struct instrdata id; - struct instrinfo ii; - int dwidth, toph; - struct charview *cv; - double scalex, scaley; - int pts_head, cvt_offtop, gloss_offtop, storage_offtop, stack_offtop, reg_offtop; - int points_offtop; - - int codeSize; - uint8 initialbytes[4]; - struct reflist *active_refs; - int last_npoints; - int layer; -} DebugView; - - -/* The number of tabs allowed in the outline glyph view of former glyphs */ -#define FORMER_MAX 10 - -enum dv_coderange { cr_none=0, cr_fpgm, cr_prep, cr_glyph }; /* cleverly chosen to match ttobjs.h */ - -struct freehand { - struct tracedata *head, *last; /* for the freehand tool */ - SplinePointList *current_trace; - int ignore_wobble; /* Ignore wiggles smaller than this */ - int skip_cnt; -}; - -enum expandedge { ee_none, ee_nw, ee_up, ee_ne, ee_right, ee_se, ee_down, - ee_sw, ee_left, ee_max }; - -enum { charviewtab_charselectedsz = 1024 }; -typedef struct charviewtab -{ - char charselected[ charviewtab_charselectedsz + 1 ]; - char tablabeltxt[ charviewtab_charselectedsz + 1 ]; -} CharViewTab; - -enum { charview_cvtabssz = 100 }; - - - /* approximately BACK_LAYER_MAX / 32 */ -#define BACK_LAYERS_VIEW_MAX 8 - -typedef struct charview { - CharViewBase b; - uint32 showback[BACK_LAYERS_VIEW_MAX]; - unsigned int showfore:1; - unsigned int showgrids:1; - unsigned int showhhints:1; - unsigned int showvhints:1; - unsigned int showdhints:1; - unsigned int showpoints:1; - unsigned int alwaysshowcontrolpoints:1; - unsigned int showfilled:1; - unsigned int showrulers:1; - unsigned int showrounds:2; /* 0=>no, 1=>auto, 2=>always */ - unsigned int showmdx:1; - unsigned int showmdy:1; - unsigned int showhmetrics:1; - unsigned int showvmetrics:1; - unsigned int showblues:1; /* 16 */ - unsigned int showfamilyblues:1; - unsigned int showanchor:1; - unsigned int showpointnumbers:2; - unsigned int markextrema:1; - unsigned int markpoi:1; - unsigned int needsrasterize:1; /* Rasterization (of fill or fontview) needed on mouse up */ - unsigned int recentchange:1; /* a change happened in the grids or background. don't need to rasterize */ - unsigned int info_within: 1; /* cursor is within main window */ - unsigned int back_img_out_of_date: 1; /* Force redraw of back image pixmap */ - unsigned int cntrldown:1; - unsigned int joinvalid:1; - unsigned int widthsel:1; - unsigned int vwidthsel:1; - unsigned int lbearingsel:1; - unsigned int icsel:1; - unsigned int tah_sel:1; - unsigned int inactive:1; /* When in a search view (32) */ - unsigned int show_ft_results: 1; - unsigned int show_ft_results_live_update : 1; - unsigned int coderange: 2; /* For the debugger */ - unsigned int autonomous_ruler_w: 1; - unsigned int showcpinfo: 1; - unsigned int showtabs: 1; - unsigned int showsidebearings: 1; - unsigned int showing_spiro_pt_menu: 1; - unsigned int ruler_pressed: 1; - unsigned int ruler_pressedv: 1; - unsigned int showrefnames: 1; - unsigned int snapoutlines: 1; - unsigned int showalmosthvlines: 1; - unsigned int showalmosthvcurves: 1; - unsigned int checkselfintersects: 1; - unsigned int showdebugchanges: 1; - unsigned int inPreviewMode: 1; - unsigned int inDraggingComparisonOutline: 1; - unsigned int activeModifierControl: 1; //< Is control being held right now? - unsigned int activeModifierAlt: 1; //< Is alt being held right now? - unsigned int changedActiveGlyph: 1; //< Set in CVSwitchActiveSC() cleared in cvmouseup() - - int hvoffset; /* for showalmosthvlines */ - int layers_off_top; - real scale; - GWindow gw, v; - GGadget *vsb, *hsb, *mb, *tabs; - GFont *small, *normal; - GWindow icon; - GWindow ruler_w; - GWindow ruler_linger_w; - unichar_t ruler_linger_lines[40][80]; - int ruler_linger_num_lines; - int num_ruler_intersections; - int allocated_ruler_intersections; - BasePoint *ruler_intersections; - int start_intersection_snapped; - int end_intersection_snapped; - GFont *rfont; - GTimer *pressed; - GWindow backimgs; - GIC *gic; - GIC *gwgic; - int width, height; - float xoff, yoff; /* must be floating point, for precise zoom by scroll */ - int mbh; //< menu bar height - int charselectorh; //< char selection input box height - int infoh; //< info bar height - int rulerh; //< ruler height - int16 sas, sfh, sdh, nas, nfh; - BasePoint info; - SplinePoint *info_sp; - Spline *info_spline; - real info_t; - GPoint e; /* mouse location */ - GPoint olde; - BasePoint last_c; - BDFChar *filled; - GImage gi; /* used for fill bitmap only */ - int enc; - EncMap *map_of_enc; /* Only use for comparison against fontview's map to see if our enc be valid */ - /* Will not be updated when fontview is reencoded */ - PressedOn p; - SplinePoint *lastselpt; - spiro_cp *lastselcp; - /*GWindow tools, layers;*/ - int8 b1_tool, cb1_tool, b2_tool, cb2_tool; /* Button 3 does a popup */ - int8 b1_tool_old; /* Used by mingw port */ - int8 s1_tool, s2_tool, er_tool; /* Bindings for wacom stylus and eraser */ - int8 showing_tool, pressed_tool, pressed_display, had_control, active_tool; - int8 spacebar_hold; /* spacebar is held down */ - SplinePointList *active_spl; - SplinePoint *active_sp; - spiro_cp *active_cp; - IPoint handscroll_base; - uint16 rfh, ras; - BasePoint lastknife; - struct freehand freehand; - enum expandedge expandedge; - BasePoint expandorigin; - real expandwidth, expandheight; - SplinePointList *active_shape; - SplinePoint joinpos; - spiro_cp joincp; - SplineChar *template1, *template2; -#if HANYANG - struct jamodisplay *jamodisplay; -#endif - real oldwidth, oldvwidth; - real oldlbearing; - int16 oldic, oldtah; -#if _ModKeysAutoRepeat - GTimer *autorpt; - int keysym, oldstate; - int oldkeyx, oldkeyy; - GWindow oldkeyw; -#endif - PST *lcarets; - int16 nearcaret; - /* freetype results display */ - int16 ft_dpi, ft_ppemy, ft_ppemx, ft_depth; - real ft_pointsizey, ft_pointsizex; - struct freetype_raster *raster, *oldraster; - DebugView *dv; - uint32 mmvisible; - char *former_names[FORMER_MAX]; - int former_cnt; - AnchorPoint *apmine, *apmatch; - SplineChar *apsc; - int guide_pos; - struct qg_data *qg; - int16 note_x, note_y; - struct dlistnode* pointInfoDialogs; - GGadget* charselector; //< let the user type in more than one char to view at once. - GGadget* charselectorNext; //< move to next word in charselector - GGadget* charselectorPrev; //< move to prev word in charselector - int charselectoridx; - SplineChar* additionalCharsToShow [51]; //< additionalCharsToShowLimit + 1 in size - int additionalCharsToShowActiveIndex; - - CharViewTab cvtabs[ charview_cvtabssz+1 ]; - int oldtabnum; - -} CharView; - -typedef struct bitmapview { - BDFChar *bc; - BDFFont *bdf; - struct fontview *fv; - EncMap *map_of_enc; - int enc; - GWindow gw, v; - GGadget *vsb, *hsb, *mb; - GGadget *recalc; - GFont *small; - int xoff, yoff; - int width, height; - int infoh, mbh; - int scale; - real scscale; - struct bitmapview *next; - unsigned int showfore:1; - unsigned int showoutline:1; - unsigned int showgrid:1; - unsigned int cntrldown:1; - unsigned int recentchange:1; - unsigned int clearing:1; - unsigned int shades_hidden:1; - unsigned int shades_down:1; - /*GWindow tools, layers;*/ - int8 b1_tool, cb1_tool, b2_tool, cb2_tool; /* Button 3 does a popup */ - int8 s1_tool, s2_tool, er_tool; /* Bindings for wacom stylus and eraser */ - int8 showing_tool, pressed_tool, pressed_display, had_control, active_tool; - int pressed_x, pressed_y; - int info_x, info_y; - int event_x, event_y; - int16 sas, sfh; -#if _ModKeysAutoRepeat - GTimer *autorpt; - int keysym, oldstate; -#endif - int color; /* for greyscale fonts (between 0,255) */ - int color_under_cursor; -} BitmapView; - -struct aplist { AnchorPoint *ap; int connected_to, selected; struct aplist *next; }; - -enum mv_grids { mv_hidegrid, mv_showgrid, mv_partialgrid, mv_hidemovinggrid }; -enum mv_type { mv_kernonly, mv_widthonly, mv_kernwidth }; - -struct metricchar { - int16 dx, dwidth; /* position and width of the displayed char */ - int16 dy, dheight; /* displayed info for vertical metrics */ - int xoff, yoff; - int16 mx, mwidth; /* position and width of the text underneath */ - int16 kernafter; - unsigned int selected: 1; - GGadget *width, *lbearing, *rbearing, *kern, *name; - GGadget* updownkparray[10]; /* Cherry picked elements from width...kern allowing up/down key navigation */ -}; - -typedef struct metricsview { - struct fontview *fv; - SplineFont *sf; - int pixelsize; /* If the user has manually requested a pixelsize */ - /* then rasterize at that size no matter how large */ - /* the font is zoomed. For non-user requesed sizes */ - /* this is the pixelsize * zoom-factor */ - BDFFont *bdf; /* We can also see metric info on a bitmap font */ - BDFFont *show; /* Or the rasterized version of the outline font */ - GWindow gw, v; - GFont *font; - GGadget *hsb, *vsb, *mb, *text, *textPrev, *textNext, *script, *features, *subtable_list; - GGadget *namelab, *widthlab, *lbearinglab, *rbearinglab, *kernlab; - int16 xstart; - int16 width, height, dwidth; - int16 vwidth, vheight; - int16 mbh,sbh; - int16 topend; /* y value of the end of the region containing the text field */ - int16 displayend; /* y value of the end of the region showing filled characters */ - int16 fh, as; - int16 cmax, clen; - SplineChar **chars; /* Character input stream */ - struct opentype_str *glyphs;/* after going through the various gsub/gpos transformations */ - struct metricchar *perchar; /* One for each glyph above */ - SplineChar **sstr; /* Character input stream */ - int16 mwidth, mbase; - int16 glyphcnt, max; - int16 pressed_x, pressed_y; - int16 activeoff; - int xoff, coff, yoff; - struct metricsview *next; - unsigned int right_to_left: 1; - unsigned int pressed: 1; - unsigned int pressedwidth: 1; - unsigned int pressedkern: 1; - unsigned int showgrid: 2; - unsigned int antialias: 1; - unsigned int vertical: 1; - unsigned int type: 2; /* enum mv_type */ - unsigned int usehinting: 1; /* should the hints be used during the render */ - unsigned int pixelsize_set_by_window; - int xp, yp, ap_owner; - BasePoint ap_start; - int cursor; - int scale_index; - struct lookup_subtable *cur_subtable; - GTextInfo *scriptlangs; - int word_index; - int layer; - int fake_unicode_base; - GIC *gwgic; - int ptsize, dpi; - int ybaseline; - int oldscript, oldlang; -} MetricsView; - -enum fv_metrics { fvm_baseline=1, fvm_origin=2, fvm_advanceat=4, fvm_advanceto=8 }; -typedef struct fontview { - FontViewBase b; - BDFFont *show, *filled; - GWindow gw, v; - GFont **fontset; - GGadget *vsb, *mb; - GTimer *pressed; - GTimer *resize; - GEvent resize_event; - GIC *gic; - GIC *gwgic; - int width, height; /* of v */ - int16 infoh,mbh; - int16 lab_height, lab_as; - int16 colcnt, rowcnt; /* of display window */ - int32 rowoff, rowltot; /* Can be really big in full unicode */ - int16 cbw,cbh; /* width/height of a character box */ - int pressed_pos, end_pos; - unsigned int antialias:1; - unsigned int bbsized:1; /* displayed bitmap should be scaled by bounding box rather than emsize */ - unsigned int wasonlybitmaps:1; - /*unsigned int refstate: 3;*/ /* 0x1 => paste orig of all non exist refs, 0x2=>don't, 0x3 => don't warn about non-exist refs with no source font */ - unsigned int touched: 1; - unsigned int showhmetrics: 4; - unsigned int showvmetrics: 4; - unsigned int drag_and_drop: 1; - unsigned int has_dd_no_cursor: 1; - unsigned int any_dd_events_sent: 1; - unsigned int resize_expected: 1; - /* Some window managers do not honour my resize requests (if window is*/ - /* maximized for example), but we depend on the resize request to */ - /* fix up the window. We do get a configure notify, but the window */ - /* stays the same size, so kludge things */ - unsigned int glyphlabel: 2; - unsigned int notactive:1; /* When embedded in a dlg */ - int16 magnify; - int16 user_requested_magnify; - struct searchview *sv; - SplineChar *sc_near_top; - int sel_index; - struct lookup_subtable *cur_subtable; - struct qg_data *qg; - GPid pid_webfontserver; -} FontView; - -typedef struct findsel { - GEvent *e; - real fudge; /* One pixel fudge factor */ - real xl,xh, yl, yh; /* One pixel fudge factor */ - real c_xl,c_xh, c_yl, c_yh; /* fudge rectangle for control points, larger than above if alt is depressed */ - unsigned int select_controls: 1; /* notice control points */ - unsigned int seek_controls: 1; /* notice control points before base points */ - unsigned int all_controls: 1; /* notice control points even if the base points aren't selected (in truetype point numbering mode where all cps are visible) */ - unsigned int alwaysshowcontrolpoints:1; /* if the BCP are forced on, then we want the selection code paths - * to also know that so the user can drag the BCP of a non selected splinepoint */ - real scale; - PressedOn *p; -} FindSel; - -typedef struct searchview { - struct cvcontainer base; - FontView dummy_fv; - SplineFont dummy_sf; - LayerInfo layerinfo[2]; - SplineChar *chars[2]; - EncMap dummy_map; - int32 map[2], backmap[2]; - uint8 sel[2]; - CharView cv_srch, cv_rpl; - CharView *lastcv; -/* ****** */ - GWindow gw; - GGadget *mb; - GFont *plain, *bold; - int mbh; - int fh, as; - int rpl_x, cv_y; - int cv_width, cv_height; - short button_height, button_width; -/* ****** */ - SearchData sd; - unsigned int showsfindnext: 1; - unsigned int findenabled: 1; - unsigned int rplallenabled: 1; - unsigned int rplenabled: 1; - unsigned int isvisible: 1; -} SearchView; - -typedef struct mathkernview { - struct cvcontainer base; - FontView dummy_fv; - SplineFont dummy_sf; - LayerInfo layerinfo[2]; - SplineChar sc_topright, sc_topleft, sc_bottomright, sc_bottomleft; - SplineChar *chars[4]; - EncMap dummy_map; - int32 map[4], backmap[4]; - uint8 sel[4]; - CharView cv_topright, cv_topleft, cv_bottomright, cv_bottomleft; - CharView *lastcv; -/* ****** */ - GWindow gw; - GWindow cvparent_w; - GGadget *mb; - GFont *plain, *bold; - int mbh; - int fh, as; - int mid_space, cv_y; - int cv_width, cv_height; - short button_height, button_width; -/* ****** */ - SplineChar *cursc; - int def_layer; - struct mathkern *orig_mathkern; - uint8 saved_mathkern; /* Can't just check if orig is non-NULL, because NULL is a perfectly valid initial state */ - uint8 last_aspect; - uint8 done; -} MathKernDlg; - -# ifdef FONTFORGE_CONFIG_TILEPATH - -typedef struct tilepathdlg { - struct cvcontainer base; - FontView dummy_fv; - SplineFont dummy_sf; - LayerInfo layerinfo[2]; - SplineChar sc_first, sc_medial, sc_final, sc_isolated; - SplineChar *chars[4]; - EncMap dummy_map; - int32 map[4], backmap[4]; - uint8 sel[4]; - CharView cv_first, cv_medial, cv_final, cv_isolated; - CharView *lastcv; -/* ****** */ - GWindow gw; - GGadget *mb; - GFont *plain, *bold; - int mbh; - int fh, as; - int mid_space, cv_y; - int cv_width, cv_height; -/* ****** */ - struct tiledata *td; - SplineFont *base_sf; - uint8 done, oked; -} TilePathDlg; -extern void TPDCharViewInits(TilePathDlg *tpd, int cid); -extern void PTDCharViewInits(TilePathDlg *tpd, int cid); -#endif /* Tile Path */ - -typedef struct gradientdlg { - struct cvcontainer base; - FontView dummy_fv; - SplineFont dummy_sf; - LayerInfo layerinfo[2]; - SplineChar sc_grad; - SplineChar *chars[1]; - EncMap dummy_map; - int32 map[1], backmap[1]; - uint8 sel[1]; - CharView cv_grad; -/* ****** */ - GWindow gw; - GGadget *mb; - GFont *plain, *bold; - int mbh; - int fh, as; - int mid_space, cv_y; - int cv_width, cv_height; -/* ****** */ - uint8 done, oked; - struct gradient *active; -} GradientDlg; -extern void GDDCharViewInits(GradientDlg *gdd,int cid); - -typedef struct strokedlg { - struct cvcontainer base; - FontView dummy_fv; - SplineFont dummy_sf; - LayerInfo layerinfo[2]; - SplineChar sc_stroke; - SplineChar *chars[1]; - EncMap dummy_map; - int32 map[1], backmap[1]; - uint8 sel[1]; - CharView cv_stroke; - int cv_width, cv_height; - GGadget *mb; - int mbh; - SplineSet *old_poly; -/* ****** */ - int done; - GWindow gw; - CharView *cv; - FontView *fv; - SplineFont *sf; - void (*strokeit)(void *,StrokeInfo *,int); - StrokeInfo *si; - GRect r1, r2; - int up[2]; - int dontexpand; -} StrokeDlg; -extern void StrokeCharViewInits(StrokeDlg *sd,int cid); - -struct lksubinfo { - struct lookup_subtable *subtable; - unsigned int deleted: 1; - unsigned int new: 1; - unsigned int selected: 1; - unsigned int moved: 1; -}; - -struct lkinfo { - OTLookup *lookup; - unsigned int open: 1; - unsigned int deleted: 1; - unsigned int new: 1; - unsigned int selected: 1; - unsigned int moved: 1; - int16 subtable_cnt, subtable_max; - struct lksubinfo *subtables; -}; - -struct lkdata { - int cnt, max; - int off_top, off_left; - struct lkinfo *all; -}; - -struct anchor_shows { - CharView *cv; - SplineChar *sc; - int restart; -}; - -struct gfi_data { /* FontInfo */ - SplineFont *sf; - int def_layer; - GWindow gw; - int tn_active; - int private_aspect, ttfv_aspect, tn_aspect, tx_aspect, unicode_aspect; - int old_sel, old_aspect, old_lang, old_strid; - int ttf_set, names_set, tex_set; - int langlocalecode; /* MS code for the current locale */ - unsigned int family_untitled: 1; - unsigned int human_untitled: 1; - unsigned int done: 1; - unsigned int mpdone: 1; - unsigned int lk_drag_and_drop: 1; - unsigned int lk_dropablecursor: 1; - struct anchor_shows anchor_shows[2]; - struct texdata texdata; - GFont *font; - int as, fh; - struct lkdata tables[2]; - int lkwidth, lkheight; - int first_sel_lookup, first_sel_subtable; - int last_panose_family; -}; - -struct kf_dlg /* : fvcontainer */ { - struct fvcontainer base; - struct lookup_subtable *sub; - GWindow gw, dw; - GFont *plain, *bold; - int fh, as; - GGadget *mb, *guts, *topbox; - int mbh, label2_y, infoh; - - SplineFont *sf; - int def_layer; - struct kf_results *results; - int done; - - FontView *active; - FontView *first_fv; - FontView *second_fv; -}; - -enum genfam { gf_none, gf_macfamily, gf_ttc }; - -extern void FVMarkHintsOutOfDate(SplineChar *sc); -extern void FVRefreshChar(FontView *fv,int gid); -extern void _FVMenuOpen(FontView *fv); -extern int _FVMenuSave(FontView *fv); -extern int _FVMenuSaveAs(FontView *fv); -extern int _FVMenuGenerate(FontView *fv,int family); -extern void _FVCloseWindows(FontView *fv); -extern char *GetPostScriptFontName(char *defdir,int mult); -extern void MergeKernInfo(SplineFont *sf,EncMap *map); -extern int SFGenerateFont(SplineFont *sf,int layer, int family,EncMap *map); - -extern void NonLinearDlg(FontView *fv,struct charview *cv); -extern void FVChangeChar(FontView *fv,int encoding); -extern void FVMergeFonts(FontView *fv); -extern void FVInterpolateFonts(FontView *fv); - -extern void FVDeselectAll(FontView *fv); - -extern void FVAutoWidth2(FontView *fv); -/*extern void FVAutoKern(FontView *fv);*/ -/*extern void FVAutoWidth(FontView *fv);*/ - -extern void SC_MarkInstrDlgAsChanged(SplineChar *sc); - -extern void PythonUI_Init(void); -extern void PythonUI_namedpipe_Init(void); - -extern void SCStroke(SplineChar *sc); - -extern void PfaEditSetFallback(void); -extern void RecentFilesRemember(char *filename); -extern void LastFonts_Save(void); - -struct debugger_context; -extern void DebuggerTerminate(struct debugger_context *dc); -extern void DebuggerReset(struct debugger_context *dc,real pointsizey, real pointsizex,int dpi,int dbg_fpgm, int is_bitmap); -extern struct debugger_context *DebuggerCreate(SplineChar *sc,int layer,real pointsizey,real pointsizex,int dpi,int dbg_fpgm, int is_bitmap); -enum debug_gotype { dgt_continue, dgt_step, dgt_next, dgt_stepout }; -extern void DebuggerGo(struct debugger_context *dc,enum debug_gotype,DebugView *dv); -extern struct TT_ExecContextRec_ *DebuggerGetEContext(struct debugger_context *dc); -extern void DebuggerToggleBp(struct debugger_context *dc,int range,int ip); -extern int DebuggerBpCheck(struct debugger_context *dc,int range,int ip); -extern void DebuggerSetWatches(struct debugger_context *dc,int n, uint8 *w); -extern uint8 *DebuggerGetWatches(struct debugger_context *dc, int *n); -extern void DebuggerSetWatchStores(struct debugger_context *dc,int n, uint8 *w); -extern uint8 *DebuggerGetWatchStores(struct debugger_context *dc, int *n); -extern int DebuggerIsStorageSet(struct debugger_context *dc, int index); -extern void DebuggerSetWatchCvts(struct debugger_context *dc,int n, uint8 *w); -extern uint8 *DebuggerGetWatchCvts(struct debugger_context *dc, int *n); -extern int DebuggingFpgm(struct debugger_context *dc); - - -extern void PrintFFDlg(FontView *fv,SplineChar *sc,MetricsView *mv); -extern void PrintWindowClose(void); -extern void InsertTextDlg(CharView *cv); - -extern char *Kern2Text(SplineChar *other,KernPair *kp,int isv); -extern char *PST2Text(PST *pst,SplineFont *sf); - - - -void EmboldenDlg(FontView *fv, CharView *cv); -void CondenseExtendDlg(FontView *fv, CharView *cv); -void ObliqueDlg(FontView *fv, CharView *cv); -void GlyphChangeDlg(FontView *fv, CharView *cv, enum glyphchange_type gc); -void ItalicDlg(FontView *fv, CharView *cv); -void ChangeXHeightDlg(FontView *fv,CharView *cv); - -extern int FVParseSelectByPST(FontView *fv,struct lookup_subtable *sub, - int search_type); -extern void DropChars2Text(GWindow gw, GGadget *glyphs,GEvent *event); - - -extern void FVReplaceOutlineWithReference( FontView *fv, double fudge ); -extern void SVDestroy(struct searchview *sv); - - - -extern int SLICount(SplineFont *sf); -extern unichar_t *ClassName(const char *name,uint32 feature_tag, - uint16 flags, int script_lang_index, int merge_with, int act_type, - int macfeature,SplineFont *sf); -extern unichar_t *DecomposeClassName(const unichar_t *clsnm, unichar_t **name, - uint32 *feature_tag, int *macfeature, - uint16 *flags, uint16 *script_lang_index,int *merge_with,int *act_type, - SplineFont *sf); -extern PST *AddSubs(PST *last,uint32 tag,char *name,uint16 flags, - uint16 sli,SplineChar *sc); - - -extern void FVSetUIToMatch(FontView *destfv,FontView *srcfv); -extern void FVScrollToChar(FontView *fv,int i); -extern void FVRegenChar(FontView *fv,SplineChar *sc); -extern FontView *FontNew(void); -extern void _MenuWarnings(GWindow gw,struct gmenuitem *mi,GEvent *e); -extern void MenuPrefs(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuXRes(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuSaveAll(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuExit(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuHelp(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuIndex(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuAbout(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuLicense(GWindow base,struct gmenuitem *mi,GEvent *e); -extern void MenuNew(GWindow gw,struct gmenuitem *mi,GEvent *e); -extern void WindowMenuBuild(GWindow base,struct gmenuitem *mi,GEvent *); -extern void MenuRecentBuild(GWindow base,struct gmenuitem *mi,GEvent *); -extern void MenuScriptsBuild(GWindow base,struct gmenuitem *mi,GEvent *); -extern void mb2FreeGetText(GMenuItem2 *mb); -extern void mb2DoGetText(GMenuItem2 *mb); -extern void mbFreeGetText(GMenuItem *mb); -extern void mbDoGetText(GMenuItem *mb); -extern int RecentFilesAny(void); -extern void _aplistbuild(struct gmenuitem *mi,SplineFont *sf, - void (*func)(GWindow,struct gmenuitem *,GEvent *)); -extern int32 *ParseBitmapSizes(GGadget *g,char *msg,int *err); -extern GTextInfo *AddMacFeatures(GTextInfo *opentype,enum possub_type type,SplineFont *sf); -extern unichar_t *AskNameTag(char *title,unichar_t *def,uint32 def_tag,uint16 flags, - int script_lang_index, enum possub_type type, SplineFont *sf, SplineChar *default_script, - int merge_with,int act_type); -extern unichar_t *ShowScripts(unichar_t *usedef); -extern GTextInfo *SFLangList(SplineFont *sf,int addfinal,SplineChar *default_script); -extern GTextInfo **SFLangArray(SplineFont *sf,int addfinal); -extern int ScriptLangList(SplineFont *sf,GGadget *list,int sli); -extern void GListDelSelected(GGadget *list); -extern void GListMoveSelected(GGadget *list,int offset); -extern GTextInfo *GListChangeLine(GGadget *list,int pos, const unichar_t *line); -extern GTextInfo *GListAppendLine(GGadget *list,const unichar_t *line,int select); -extern GTextInfo *GListChangeLine8(GGadget *list,int pos, const char *line); -extern GTextInfo *GListAppendLine8(GGadget *list,const char *line,int select); -extern void CharInfoInit(void); -extern void SCLigCaretCheck(SplineChar *sc,int clean); -extern char *DevTab_Dlg(GGadget *g, int r, int c); -extern int DeviceTableOK(char *dvstr, int *_low, int *_high); -extern void VRDevTabParse(struct vr *vr,struct matrix_data *md); -extern DeviceTable *DeviceTableParse(DeviceTable *dv,char *dvstr); -extern void DevTabToString(char **str,DeviceTable *adjust); -extern void ValDevTabToStrings(struct matrix_data *mds,int first_offset,ValDevTab *adjust); -extern void KpMDParse(SplineChar *sc,struct lookup_subtable *sub, - struct matrix_data *possub,int rows,int cols,int i); -extern void GFI_LookupEnableButtons(struct gfi_data *gfi, int isgpos); -extern void GFI_LookupScrollbars(struct gfi_data *gfi, int isgpos, int refresh); -extern void FontInfo(SplineFont *sf,int layer,int aspect,int sync); -extern void FontInfoDestroy(SplineFont *sf); -extern void FontMenuFontInfo(void *fv); -extern struct enc *MakeEncoding(SplineFont *sf, EncMap *map); -extern void LoadEncodingFile(void); -extern void RemoveEncoding(void); -extern void SFPrivateInfo(SplineFont *sf); -extern void FVDelay(FontView *fv,void (*func)(FontView *)); -extern void GFI_FinishContextNew(struct gfi_data *d,FPST *fpst, int success); -extern void SCPreparePopup(GWindow gw,SplineChar *sc, struct remap *remap, int enc, int actualuni); -enum outlinesfm_flags { - sfm_stroke=0x1, - sfm_fill=0x2, - sfm_nothing=0x4, - sfm_stroke_trans = (0x1|0x8), - sfm_clip_preserve = 0x16 -}; -extern void CVDrawSplineSetSpecialized( CharView *cv, GWindow pixmap, SplinePointList *set, - Color fg, int dopoints, DRect *clip, - enum outlinesfm_flags strokeFillMode, - Color AlphaChannelOverride ); -extern void CVDrawSplineSet(CharView *cv, GWindow pixmap, SplinePointList *set, - Color fg, int dopoints, DRect *clip ); -extern void CVDrawSplineSetOutlineOnly(CharView *cv, GWindow pixmap, SplinePointList *set, - Color fg, int dopoints, DRect *clip, enum outlinesfm_flags strokeFillMode ); -extern GWindow CVMakeTools(CharView *cv); -extern GWindow CVMakeLayers(CharView *cv); -extern GWindow BVMakeTools(BitmapView *bv); -extern GWindow BVMakeLayers(BitmapView *bv); -extern void CVSetLayer(CharView *cv,int layer); -extern int CVPaletteMnemonicCheck(GEvent *event); -extern int TrueCharState(GEvent *event); -extern void CVToolsPopup(CharView *cv, GEvent *event); -extern void BVToolsPopup(BitmapView *bv, GEvent *event); -extern real CVRoundRectRadius(void); -extern int CVRectElipseCenter(void); -extern void CVRectEllipsePosDlg(CharView *cv); -extern real CVStarRatio(void); -extern int CVPolyStarPoints(void); -extern StrokeInfo *CVFreeHandInfo(void); -extern void BVToolsSetCursor(BitmapView *bv, int state,char *device); -extern void CVToolsSetCursor(CharView *cv, int state,char *device); -extern int CVPaletteIsVisible(CharView *cv,int which); -extern void CVPaletteSetVisible(CharView *cv,int which,int visible); -extern void CVPalettesRaise(CharView *cv); -extern void CVLayersSet(CharView *cv); -extern void _CVPaletteActivate(CharView *cv,int force); -extern void CVPaletteActivate(CharView *cv); -extern void CV_LayerPaletteCheck(SplineFont *sf); -extern void CVPalettesHideIfMine(CharView *cv); -extern int BVPaletteIsVisible(BitmapView *bv,int which); -extern void BVPaletteSetVisible(BitmapView *bv,int which,int visible); -extern void BVPaletteActivate(BitmapView *bv); -extern void BVPalettesHideIfMine(BitmapView *bv); -extern void BVPaletteColorChange(BitmapView *bv); -extern void BVPaletteColorUnderChange(BitmapView *bv,int color); -extern void BVPaletteChangedChar(BitmapView *bv); -extern void CVPaletteDeactivate(void); -extern void PalettesChangeDocking(void); -extern int CVPalettesWidth(void); -extern int BVPalettesWidth(void); -extern int CVInSpiro( CharView *cv ); - -extern void CVDoTransform(CharView *cv, enum cvtools cvt ); - -// apply transform to specified layer -extern void CVTransFuncLayer(CharView *cv,Layer *ly,real transform[6], enum fvtrans_flags flags); -// apply transform to the current layer only -extern void CVTransFunc(CharView *cv,real transform[6],enum fvtrans_flags); -// apply transform to all layers -extern void CVTransFuncAllLayers(CharView *cv,real transform[6], enum fvtrans_flags flags); -enum transdlg_flags { tdf_enableback=0x1, tdf_enablekerns=0x2, - tdf_defaultkerns=0x4, tdf_addapply=0x8 }; -extern void TransformDlgCreate(void *data,void (*transfunc)(void *,real *,int,BVTFunc *,enum fvtrans_flags), - int (*getorigin)(void *,BasePoint *,int), enum transdlg_flags flags, - enum cvtools cvt); -extern void BitmapDlg(FontView *fv,SplineChar *sc, int isavail); -extern int SimplifyDlg(SplineFont *sf,struct simplifyinfo *smpl); -extern void CVReviewHints(CharView *cv); -extern void CVCreateHint(CharView *cv,int ishstem,int preserveundoes); -extern void SCRemoveSelectedMinimumDistances(SplineChar *sc,int inx); -extern int CVExport(CharView *cv); -extern int BVExport(BitmapView *bv); - -extern void DrawAnchorPoint(GWindow pixmap,int x, int y,int selected); -extern void DefaultY(GRect *pos); -extern void CVDrawRubberRect(GWindow pixmap, CharView *cv); -extern void CVInfoDraw(CharView *cv, GWindow pixmap ); -extern void CVChar(CharView *cv, GEvent *event ); -extern void PI_ShowHints(SplineChar *sc, GGadget *list, int set); -extern GTextInfo *SCHintList(SplineChar *sc,HintMask *); -extern void CVResize(CharView *cv ); -extern CharView *CharViewCreate(SplineChar *sc,FontView *fv,int enc); -extern void CharViewFinishNonStatic(); - -/** - * Extended version of CharViewCreate() which allows a window to be created but - * not displayed. - */ -extern CharView *CharViewCreateExtended(SplineChar *sc, FontView *fv,int enc, int show ); -extern void CharViewFree(CharView *cv); -extern int CVValid(SplineFont *sf, SplineChar *sc, CharView *cv); -extern void CVSetCharChanged(CharView *cv,int changed); -extern int CVAnySel(CharView *cv, int *anyp, int *anyr, int *anyi, int *anya); -extern int CVAnySelPoints(CharView *cv); - -/** - * Get all the selected points in the current cv. - * Caller must g_list_free() the returned value. - */ -extern GList_Glib* CVGetSelectedPoints(CharView *cv); -extern void CVSelectPointAt(CharView *cv); -extern int CVClearSel(CharView *cv); -extern int CVSetSel(CharView *cv,int mask); -extern void CVInvertSel(CharView *cv); -extern int CVAllSelected(CharView *cv); -extern SplinePointList *CVAnySelPointList(CharView *cv); -extern int CVAnySelPoint(CharView *cv, SplinePoint **selsp, spiro_cp **selcp); -extern int CVOneThingSel(CharView *cv, SplinePoint **sp, SplinePointList **spl, - RefChar **ref, ImageList **img, AnchorPoint **ap, spiro_cp **cp); -extern int CVOneContourSel(CharView *cv, SplinePointList **_spl, - RefChar **ref, ImageList **img); -extern void CVInfoDrawText(CharView *cv, GWindow pixmap ); -extern void CVImport(CharView *cv); -extern void BVImport(BitmapView *bv); -extern void FVImport(FontView *bv); -extern void CVFindCenter(CharView *cv, BasePoint *bp, int nosel); -extern void CVStroke(CharView *cv); -extern void FVStroke(FontView *fv); -extern void FreeHandStrokeDlg(StrokeInfo *si); -extern void OutlineDlg(FontView *fv, CharView *cv,MetricsView *mv,int isinline); -extern void ShadowDlg(FontView *fv, CharView *cv,MetricsView *mv,int wireframe); -extern void CVTile(CharView *cv); -extern void FVTile(FontView *fv); -extern void CVPatternTile(CharView *cv); -extern void FVPatternTile(FontView *fv); -extern void SCCharInfo(SplineChar *sc,int deflayer,EncMap *map,int enc); -extern void CharInfoDestroy(struct charinfo *ci); -extern SplineChar *SuffixCheck(SplineChar *sc,char *suffix); -extern void SCSubtableDefaultSubsCheck(SplineChar *sc, struct lookup_subtable *sub, struct matrix_data *possub, int col_cnt, int r,int layer); -extern GImage *PST_GetImage(GGadget *pstk,SplineFont *sf,int def_layer, - struct lookup_subtable *sub,int popup_r, SplineChar *sc ); -extern GImage *NameList_GetImage(SplineFont *sf,SplineChar *sc,int def_layer, - char *namelist, int isliga ); -extern GImage *GV_GetConstructedImage(SplineChar *sc,int def_layer, struct glyphvariants *gv, - int is_horiz); -extern GImage *SC_GetLinedImage(SplineChar *sc, int def_layer, int pos, int is_italic_cor); -extern struct glyphvariants *GV_ParseConstruction(struct glyphvariants *gv, - struct matrix_data *stuff, int rows, int cols); -extern void GV_ToMD(GGadget *g, struct glyphvariants *gv); -extern void CVGetInfo(CharView *cv); -extern void CVPGetInfo(CharView *cv); -extern int SCUsedBySubs(SplineChar *sc); -extern void SCSubBy(SplineChar *sc); -extern void SCRefBy(SplineChar *sc); -extern void ApGetInfo(CharView *cv, AnchorPoint *ap); -extern void CVMakeClipPath(CharView *cv); -extern void CVAddAnchor(CharView *cv); -extern AnchorClass *AnchorClassUnused(SplineChar *sc,int *waslig); -extern void FVSetWidth(FontView *fv,enum widthtype wtype); -extern void CVSetWidth(CharView *cv,enum widthtype wtype); -extern void GenericVSetWidth(FontView *fv,SplineChar* sc,enum widthtype wtype); -extern void CVChangeSC(CharView *cv, SplineChar *sc ); -extern Undoes *CVPreserveTState(CharView *cv); -/** - * If isTState > 0 then CVPreserveTState(cv) - * otherwise CVPreserveState(cv) - */ -extern Undoes *CVPreserveMaybeState(CharView *cv, int isTState ); -extern void CVRestoreTOriginalState(CharView *cv); -extern void CVUndoCleanup(CharView *cv); - -extern void AdjustControls(SplinePoint *sp); -extern void CVAdjustPoint(CharView *cv, SplinePoint *sp); -extern void CVMergeSplineSets(CharView *cv, SplinePoint *active, SplineSet *activess, - SplinePoint *merge, SplineSet *mergess); -extern void CVAdjustControl(CharView *cv,BasePoint *cp, BasePoint *to); -extern int CVMoveSelection(CharView *cv, real dx, real dy, uint32 input_state); -extern int CVTestSelectFromEvent(CharView *cv,GEvent *event); -extern void CVMouseMovePen(CharView *cv, PressedOn *p, GEvent *event); -extern void CVMouseUpPoint(CharView *cv,GEvent *event); -extern int CVMouseMovePointer(CharView *cv, GEvent *event); -extern void CVMouseDownPointer(CharView *cv, FindSel *fs, GEvent *event); -extern void CVMouseDownRuler(CharView *cv, GEvent *event); -extern void CVMouseMoveRuler(CharView *cv, GEvent *event); -extern int CVMouseAtSpline(CharView *cv,GEvent *event); -extern void CVMouseUpRuler(CharView *cv, GEvent *event); -extern void CVMouseMoveHand(CharView *cv, GEvent *event); -extern void CVMouseDownFreeHand(CharView *cv, GEvent *event); -extern void CVMouseMoveFreeHand(CharView *cv, GEvent *event); -extern void CVMouseUpFreeHand(CharView *cv, GEvent *event); -extern void CVMouseDownShape(CharView *cv,GEvent *event); -extern void CPStartInfo(CharView *cv, GEvent *event); -extern void CPUpdateInfo(CharView *cv, GEvent *event); -extern void CPEndInfo(CharView *cv); -extern void BVChar(BitmapView *cv, GEvent *event ); -extern void CVMouseDownPoint(CharView *cv,GEvent *event); -extern void CVMouseMovePoint(CharView *cv,PressedOn *); -extern void CVMouseUpPointer(CharView *cv ); -extern void CVCheckResizeCursors(CharView *cv); -extern void CVMouseDownHand(CharView *cv); -extern void CVMouseUpHand(CharView *cv); -extern void CVMouseDownTransform(CharView *cv); -extern void CVMouseMoveTransform(CharView *cv); -extern void CVMouseUpTransform(CharView *cv); -extern void CVMouseDownKnife(CharView *cv); -extern void CVMouseMoveKnife(CharView *cv,PressedOn *); -extern void CVMouseUpKnife(CharView *cv,GEvent *event); -extern void CVMouseMoveShape(CharView *cv); -extern void CVMouseUpShape(CharView *cv); -extern void LogoExpose(GWindow pixmap,GEvent *event, GRect *r,enum drawmode dm); -extern void CVDebugPointPopup(CharView *cv); - -extern int GotoChar(SplineFont *sf,EncMap *map, int *merge_with_selection); - -extern void CVShowPoint(CharView *cv, BasePoint *me); - -extern void BitmapViewFinishNonStatic(); -extern BitmapView *BitmapViewCreate(BDFChar *bc, BDFFont *bdf, FontView *fv,int enc); -extern BitmapView *BitmapViewCreatePick(int enc, FontView *fv); -extern void BitmapViewFree(BitmapView *bv); -extern void BVMenuRotateInvoked(GWindow gw,struct gmenuitem *mi, GEvent *e); -extern void BVRotateBitmap(BitmapView *bv,enum bvtools type ); -extern int BVColor(BitmapView *bv); -extern void BCGeneralFunction(BitmapView *bv, - void (*SetPoint)(BitmapView *,int x, int y, void *data),void *data); -extern char *BVFlipNames[]; -extern void BVChangeBC(BitmapView *bv, BDFChar *bc, int fitit ); - -extern void MVSetSCs(MetricsView *mv, SplineChar **scs); -extern void MVRefreshChar(MetricsView *mv, SplineChar *sc); -extern void MVRegenChar(MetricsView *mv, SplineChar *sc); -extern void MVReKern(MetricsView *mv); -extern void MetricsViewFinishNonStatic(); -extern MetricsView *MetricsViewCreate(FontView *fv,SplineChar *sc,BDFFont *bdf); -extern void MetricsViewFree(MetricsView *mv); -extern void MVRefreshAll(MetricsView *mv); -extern void MV_FriendlyFeatures(GGadget *g, int pos); -extern GTextInfo *SLOfFont(SplineFont *sf); - -extern void DoPrefs(void); -extern void DoXRes(void); -extern void PointerDlg(CharView *cv); -extern void GListAddStr(GGadget *list,unichar_t *str, void *ud); -extern void GListReplaceStr(GGadget *list,int index, unichar_t *str, void *ud); -extern struct macname *NameGadgetsGetNames( GWindow gw ); -extern void NameGadgetsSetEnabled( GWindow gw, int enable ); -extern int GCDBuildNames(GGadgetCreateData *gcd,GTextInfo *label,int pos,struct macname *names); -extern void GCDFillMacFeat(GGadgetCreateData *mfgcd,GTextInfo *mflabels, int width, - MacFeat *all, int fromprefs, GGadgetCreateData *boxes, - GGadgetCreateData **array); -extern void Prefs_ReplaceMacFeatures(GGadget *list); - -extern unichar_t *FVOpenFont(char *title, const char *defaultfile, int mult); - - - - -extern void ShowAboutScreen(void); -extern void DelayEvent(void (*func)(void *), void *data); - -extern void FindProblems(FontView *fv,CharView *cv,SplineChar *sc); -typedef enum -{ - constrainSelection_AveragePoints = 0, - constrainSelection_SpacePoints = 1, - constrainSelection_SpaceSelectedRegions = 2 -} constrainSelection_t; -extern void CVConstrainSelection(CharView *cv, constrainSelection_t type); -extern void CVMakeParallel(CharView *cv); - -extern void ScriptDlg(FontView *fv,CharView *cv); - -# if HANYANG -extern void MenuNewComposition(GWindow gw, struct gmenuitem *, GEvent *); -extern void CVDisplayCompositions(GWindow gw, struct gmenuitem *, GEvent *); -extern void Disp_DoFinish(struct jamodisplay *d, int cancel); -extern void Disp_RefreshChar(SplineFont *sf,SplineChar *sc); -extern void Disp_DefaultTemplate(CharView *cv); -# endif - -extern SearchView *SVCreate(FontView *fv); -extern void SVCharViewInits(SearchView *sv); -extern void SV_DoClose(struct cvcontainer *cvc); -extern void SVMakeActive(SearchView *sv,CharView *cv); -extern int SVAttachFV(FontView *fv,int ask_if_difficult); -extern void SVDetachFV(FontView *fv); - -extern void MKDMakeActive(MathKernDlg *mkd,CharView *cv); -extern void MKD_DoClose(struct cvcontainer *cvc); -extern void MKDCharViewInits(MathKernDlg *mkd); -extern void MathKernDialog(SplineChar *sc,int def_layer); - -extern void ShowAtt(SplineFont *sf,int def_layer); -extern void FontCompareDlg(FontView *fv); -extern void SFShowKernPairs(SplineFont *sf,SplineChar *sc,AnchorClass *ac,int layer); -extern void SFShowLigatures(SplineFont *sf,SplineChar *sc); - -extern void SCEditInstructions(SplineChar *sc); -extern void SFEditTable(SplineFont *sf, uint32 tag); -extern void IIScrollTo(struct instrinfo *ii,int ip,int mark_stop); -extern void IIReinit(struct instrinfo *ii,int ip); -extern int ii_v_e_h(GWindow gw, GEvent *event); -extern void instr_scroll(struct instrinfo *ii,struct sbevent *sb); - -extern void CVGridFitChar(CharView *cv); -/** - * If a live preview of grid fit is somehow in effect, call CVGridFitChar() for us. - * A caller can call here after a change and any CVGridFitChar() will be updated if need be. - */ -extern void CVGridHandlePossibleFitChar(CharView *cv); -extern void CVFtPpemDlg(CharView *cv,int debug); -extern void SCDeGridFit(SplineChar *sc); -extern void SCReGridFit(SplineChar *sc,int layer); - -extern void CVDebugReInit(CharView *cv,int restart_debug,int dbg_fpgm); -extern void CVDebugFree(DebugView *dv); -extern int DVChar(DebugView *dv, GEvent *e); - -extern void KernClassD(KernClass *kc, SplineFont *sf, int layer, int isv); -extern void ShowKernClasses(SplineFont *sf,MetricsView *mv,int layer,int isv); -extern void KCLD_End(struct kernclasslistdlg *kcld); -extern void KCLD_MvDetach(struct kernclasslistdlg *kcld,MetricsView *mv); -extern void KernPairD(SplineFont *sf,SplineChar *sc1,SplineChar *sc2,int layer, int isv); -extern void KCD_DrawGlyph(GWindow pixmap,int x,int baseline,BDFChar *bdfc,int mag); -extern GTextInfo *BuildFontList(FontView *except); -extern void TFFree(GTextInfo *tf); - -extern void AnchorControl(SplineChar *sc,AnchorPoint *ap,int layer); -extern void AnchorControlClass(SplineFont *_sf,AnchorClass *ac,int layer); - -extern void FVSelectByPST(FontView *fv); - -enum hist_type { hist_hstem, hist_vstem, hist_blues }; -struct psdict; -extern void SFHistogram(SplineFont *sf,int layer, struct psdict *private,uint8 *selected, - EncMap *map, enum hist_type which); - -extern void ContextChainEdit(SplineFont *sf,FPST *fpst, - struct gfi_data *gfi,unichar_t *newname,int layer); -extern char *cu_copybetween(const unichar_t *start, const unichar_t *end); - -extern void StateMachineEdit(SplineFont *sf,ASM *sm,struct gfi_data *d); -extern void GFI_FinishSMNew(struct gfi_data *d,ASM *sm, int success,int isnew); - -extern void MMChangeBlend(MMSet *mm,FontView *fv,int tonew); -extern void MMWizard(MMSet *mm); - -extern int LayerDialog(Layer *layer,SplineFont *sf); -extern void CVLayerChange(CharView *cv); - -extern int PointOfViewDlg(struct pov_data *pov,SplineFont *sf,int flags); - -extern SplineChar *FVMakeChar(FontView *fv,int i); - -extern void CVPointOfView(CharView *cv,struct pov_data *); - -extern void DVCreateGloss(DebugView *dv); -extern void DVMarkPts(DebugView *dv,SplineSet *ss); -extern int CVXPos(DebugView *dv,int offset,int width); - -extern GMenuItem *GetEncodingMenu(void (*func)(GWindow,GMenuItem *,GEvent *), - Encoding *current); - -extern GTextInfo *TIFromName(const char *name); - -enum subtable_data_flags { - /* I have flags for each alternative because I want "unspecified" to be */ - /* an option */ - sdf_kernclass = 0x01, - sdf_kernpair = 0x02, - sdf_verticalkern = 0x04, - sdf_horizontalkern = 0x08, - sdf_dontedit = 0x10 -}; -struct subtable_data { - int flags; - SplineChar *sc; -}; - -extern GTextInfo **SFLookupListFromType(SplineFont *sf, int lookup_type ); -extern GTextInfo *SFLookupArrayFromType(SplineFont *sf, int lookup_type ); -extern GTextInfo *SFLookupArrayFromMask(SplineFont *sf, int lookup_mask ); -extern GTextInfo **SFSubtablesOfType(SplineFont *sf, int lookup_type, int kernclass, int add_none); -extern GTextInfo *SFSubtableListOfType(SplineFont *sf, int lookup_type, int kernclass, int add_none); -extern struct lookup_subtable *SFNewLookupSubtableOfType(SplineFont *sf, int lookup_type, struct subtable_data *sd, int def_layer ); -extern int EditLookup(OTLookup *otl,int isgpos,SplineFont *sf); -extern int EditSubtable(struct lookup_subtable *sub,int isgpos,SplineFont *sf, - struct subtable_data *sd,int def_layer); -extern void _LookupSubtableContents(SplineFont *sf, struct lookup_subtable *sub, - struct subtable_data *sd,int def_layer); -extern char *SCNameUniStr(SplineChar *sc); -extern unichar_t *uSCNameUniStr(SplineChar *sc); -extern char *SFNameList2NameUni(SplineFont *sf, char *str); -extern unichar_t **SFGlyphNameCompletion(SplineFont *sf,GGadget *t,int from_tab, - int new_name_after_space); -extern char *GlyphNameListDeUnicode( char *str ); -extern void AddRmLang(SplineFont *sf, struct lkdata *lk,int add_lang); -extern void FVMassGlyphRename(FontView *fv); - -extern void SFBdfProperties(SplineFont *sf, EncMap *map, BDFFont *thisone); - - - -extern GMenuItem2 helplist[]; -extern BasePoint last_ruler_offset[]; - -extern void CVCopyLayerToLayer(CharView *cv); -extern void FVCopyLayerToLayer(FontView *fv); -extern void CVCompareLayerToLayer(CharView *cv); -extern void FVCompareLayerToLayer(FontView *fv); - -extern void MathInit(void); -extern void SFMathDlg(SplineFont *sf,int def_layer); - -extern GMenuItem2 *cvpy_menu, *fvpy_menu; -extern void cvpy_tllistcheck(GWindow gw,struct gmenuitem *mi,GEvent *e); -extern void fvpy_tllistcheck(GWindow gw,struct gmenuitem *mi,GEvent *e); - -extern GMenuItem2 *cv_menu, *fv_menu; -extern void cv_tl2listcheck(GWindow gw,struct gmenuitem *mi,GEvent *e); -extern void fv_tl2listcheck(GWindow gw,struct gmenuitem *mi,GEvent *e); - -extern void SFValidationWindow(SplineFont *sf,int layer, enum fontformat format); -extern void ValidationDestroy(SplineFont *sf); - - - -extern const char *UI_TTFNameIds(int id); -extern const char *UI_MSLangString(int language); -extern void FontInfoInit(void); -extern void LookupUIInit(void); -extern enum psstrokeflags Ps_StrokeFlagsDlg(void); -extern struct cidmap *AskUserForCIDMap(void); - -extern void DefineGroups(struct fontview *fv); -extern void DisplayGroups(struct fontview *fv); - -extern struct Base *SFBaselines(SplineFont *sf,struct Base *old,int is_vertical); -extern void JustifyDlg(SplineFont *sf); -extern char *GlyphListDlg(SplineFont *sf, char *glyphstr); - -extern void DeltaSuggestionDlg(FontView *fv,CharView *cv); -extern void QGRmFontView(struct qg_data *qg,FontView *fv); -extern void QGRmCharView(struct qg_data *qg,CharView *cv); - - -extern struct hslrgb *SFFontCols(SplineFont *sf,struct hslrgb fontcols[6]); - -extern Color view_bgcol; /* Background color for views */ -extern void MVColInit(void); -extern void CVColInit( void ); - -extern void FontViewRemove(FontView *fv); -extern void FontViewFinishNonStatic(); -extern void FVChar(FontView *fv,GEvent *event); -extern void FVDrawInfo(FontView *fv,GWindow pixmap,GEvent *event); -extern void FVRedrawAllCharViews(FontView *fv); -extern void KFFontViewInits(struct kf_dlg *kf,GGadget *drawable); -extern char *GlyphSetFromSelection(SplineFont *sf,int def_layer,char *current); -extern void ME_ListCheck(GGadget *g,int r, int c, SplineFont *sf); -extern void ME_SetCheckUnique(GGadget *g,int r, int c, SplineFont *sf); -extern void ME_ClassCheckUnique(GGadget *g,int r, int c, SplineFont *sf); -extern void PI_Destroy(struct dlistnode *node); -struct gidata; -extern void PIChangePoint(struct gidata *ci); - -extern void CVRegenFill(CharView *cv); -extern void RulerDlg(CharView *cv); -extern int CVCountSelectedPoints(CharView *cv); -extern void _CVMenuInsertPt(CharView *cv); -extern void _CVMenuNamePoint(CharView *cv, SplinePoint *sp); -extern void _CVMenuNameContour(CharView *cv); - -extern void Prefs_LoadDefaultPreferences( void ); - - -extern CharView* CharViewFindActive(); -extern FontViewBase* FontViewFindActive(); -extern FontViewBase* FontViewFind( int (*testFunc)( FontViewBase*, void* ), void* udata ); - -extern int FontViewFind_byXUID( FontViewBase* fv, void* udata ); -extern int FontViewFind_byXUIDConnected( FontViewBase* fv, void* udata ); -extern int FontViewFind_byCollabPtr( FontViewBase* fv, void* udata ); -extern int FontViewFind_bySplineFont( FontViewBase* fv, void* udata ); -extern int FontViewFind_byCollabBasePort( FontViewBase* fv, void* udata ); - -extern void SPSelectNextPoint( SplinePoint *sp, int state ); -extern void SPSelectPrevPoint( SplinePoint *sp, int state ); - - -/** - * Is the next BCP for the sp selected, and is it the primary BCP for the selection - * @see SPIsNextCPSelected - */ -extern bool SPIsNextCPSelectedSingle( SplinePoint *sp, CharView *cv ); -/** - * Is the prev BCP for the sp selected, and is it the primary BCP for the selection - * @see SPIsNextCPSelected - */ -extern bool SPIsPrevCPSelectedSingle( SplinePoint *sp, CharView *cv ); -/** - * Is the next BCP for the sp selected, it can be the primary or any - * of the secondary selected BCP - * - * The last selected BCP is the 'primary' selected BCP. Code which - * only handles a single selected BCP will only honor the primary - * selected BCP - * - * There can also be one or more seconday selected BCP. These might be - * drawn with slightly less highlight graphically and are only handled - * by code which has been updated to allow mutliple selected BCP to be - * operated on at once. - */ -extern bool SPIsNextCPSelected( SplinePoint *sp, CharView *cv ); -/** - * Is the prev BCP for the sp selected, it can be the primary or any of the secondary selected BCP - * - * @see SPIsNextCPSelected - */ -extern bool SPIsPrevCPSelected( SplinePoint *sp, CharView *cv ); - -typedef struct FE_adjustBCPByDeltaDataS -{ - CharView *cv; //< used to update view - real dx; //< Add this to the BCP x - real dy; //< Add this to the BCP y - int keyboarddx; - -} FE_adjustBCPByDeltaData; - - -/** - * Visitor function type for visitSelectedControlPoints() - */ -typedef void (*visitSelectedControlPointsVisitor) ( void* key, - void* value, - SplinePoint* sp, - BasePoint *which, - bool isnext, - void* udata ); - -/** - * Visitor function to move each BCP by data->dx/data->dy - * - * - * Visitor: visitSelectedControlPointsVisitor - * UsedBy: CVFindAndVisitSelectedControlPoints - */ -extern void FE_adjustBCPByDelta( void* key, - void* value, - SplinePoint* sp, - BasePoint *which, - bool isnext, - void* udata ); - -extern void FE_adjustBCPByDeltaWhilePreservingBCPAngle( void* key, - void* value, - SplinePoint* sp, - BasePoint *which, - bool isnext, - void* udata ); - -/** - * Visitor function to unselect every BCP passed - * - * Visitor: visitSelectedControlPointsVisitor - * UsedBy: CVFindAndVisitSelectedControlPoints - * CVUnselectAllBCP - * - * @see SPIsNextCPSelected - */ -extern void FE_unselectBCP( void* key, - void* value, - SplinePoint* sp, - BasePoint *which, - bool isnext, - void* udata ); - -extern void FE_touchControlPoint( void* key, - void* value, - SplinePoint* sp, - BasePoint *which, - bool isnext, - void* udata ); - -/** - * Find all the selected BCP and apply the visitor function f to them - * passing the user data pointer udata to the 'f' visitor. - * - * This function doesn't use udata at all, it simply passes it on to - * your visitor function so it may do something with it like record - * results or take optional parameters. - * - * If preserveState is true and there are selected BCP then - * CVPreserveState() is called before the visitor function. - */ -extern void CVFindAndVisitSelectedControlPoints( CharView *cv, bool preserveState, - visitSelectedControlPointsVisitor f, void* udata ); -/** - * NOTE: doesn't do all, just all on selected spline. - */ -extern void CVVisitAllControlPoints( CharView *cv, bool preserveState, - visitSelectedControlPointsVisitor f, void* udata ); - -/** - * Unselect all the BCP which are currently selected. - */ -extern void CVUnselectAllBCP( CharView *cv ); - - -/** - * This will call your visitor function 'f' on any selected BCP. This - * is regardless of if the BCP is the next or prev BCP for it's - * splinepoint. - * - * This function doesn't use udata at all, it simply passes it on to - * your visitor function so it may do something with it like record - * results or take optional parameters. - */ -extern void visitSelectedControlPoints( GHashTable *col, visitSelectedControlPointsVisitor f, gpointer udata ); -/** - * NOTE: doesn't do all, just all on selected spline. - */ -extern void visitAllControlPoints( GHashTable *col, visitSelectedControlPointsVisitor f, gpointer udata ); - -extern void CVVisitAdjacentToSelectedControlPoints( CharView *cv, bool preserveState, - visitSelectedControlPointsVisitor f, void* udata ); - -extern void CVFreePreTransformSPL( CharView* cv ); - -extern bool CVShouldInterpolateCPsOnMotion( CharView* cv ); - -extern int CVNearRBearingLine( CharView* cv, real x, real fudge ); -extern int CVNearLBearingLine( CharView* cv, real x, real fudge ); - -extern void CVMenuConstrain(GWindow gw, struct gmenuitem *mi, GEvent *UNUSED(e)); - - - -#endif /* _VIEWS_H */ diff --git a/test/README.md b/test/README.md deleted file mode 100644 index 9370d8f..0000000 --- a/test/README.md +++ /dev/null @@ -1,34 +0,0 @@ -### Dependencies - -- python2 and packages - - Python Imaging Library - - Selenium - - unittest -- Firefox - - firefoxdriver - -### Usage -- Run all tests: - - python test_output.py - - python test_local_browser.py -- Environment variables: - - `export P2H_TEST_GEN=1` to generate new reference files (when done, `unset P2H_TEST_GEN`) - - `export P2H_TEST_REMOTE=1` to test different browsers using Sauce Labs - - Install `sauceclient` for Python - - Set correct values for `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` - - Setup a HTTP server at `/` on port 8000 - - Enable Sauce Connect - - See `.travis.yml` as an example - - python test_remote_browser.py - -### Add new test cases - -- Make sure you have the proper copyrights. -- Using meaningful file names, a description of the file, or issueXXX.pdf. -- Make each test case minimal: - - One page only, unless the test case is about multiple pages. - - Grayscale only, unless the test case is about colors. - - Remove unnecessary elements. -- [Optional] Include the source files that the PDF file is generated from. -- Add the new PDF file to the correct folder in `test/`, and add a new function in the corresponding Python file -- Run `P2H_TEST_GEN=1 test/test.py test_issueXXX` to generate the reference, assuming that the new function is called `test_issueXXX` diff --git a/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html b/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html deleted file mode 100644 index 6fee4fd..0000000 --- a/test/browser_tests/fontfile3_opentype/fontfile3_opentype.html +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - - - - - - - -
-
PDFClown
Generated by PDF Clown on Sat Mar 05 20:06:01 CET 2011
For more info, visit http://www.pdfclown.org
Welcome
This is a sample document
that merely demonstrates
some basic graphics
features supported by
PDF Clown.
Enjoy!
PS: As promised, since version 0.0.3 PDF Clown has supported embedded latin
OpenFont/TrueType and non-embedded Type 1 fonts along with paragraph construction facilities
through the BlockComposer class.
Since version 0.0.4 the content stream stack has been completed, providing fully object-oriented
access to the graphics objects that describe the contents on a page. It's a great step towards
a whole bunch of possibilities, such as text extraction/replacement, that next releases will
progressively exploit.
Since version 0.0.6 it has supported Unicode for OpenFont/TrueType fonts.
This page was crafted with the nice
LazyDog font
(by Paul Neave, www.neave.com)
Source: http://www.wikipedia.org/
-
- - diff --git a/test/browser_tests/geneve_1564/geneve_1564.html b/test/browser_tests/geneve_1564/geneve_1564.html deleted file mode 100644 index f65a931..0000000 --- a/test/browser_tests/geneve_1564/geneve_1564.html +++ /dev/null @@ -1,738 +0,0 @@ - - - - - - - - - - - - - -
-
1
Le premier lire de Moyſe,
Di Geneſe.
.
Ce premier lire comprend l’origine caſes de totes choſes, principalement la creation de l’homme, q’il a eſté d
commencement, ſa chete releement : comment d’n tos ont eſté procreés, por lers enormes pechés Die
les a conſmés, par le delge, reſeré hi, dont la ſemence a rempli tote la terre. Pis il deſcrit les ies, fais, reli-
gion, lignees des ſaints Patriarches, qi ont eſc deant la Loy : Les benediions, promees, alliances d Sei-
gner faies aecicex : Comment de le la terre de Chanaan ſont deſcends en Epte. Acns ont appelé ce lire, le
lire des Iſtes. Totefois ceci a obten entre nos predeceers nos, q’il eſt appelé Geneſe, qi eſt n mot Grec,
gnifiant generation origine : d’atant q’en iceli eſt deſcrite l’origine procreation de totes choſes : nom-
mément des Peres anciens, qi ont eſté tant deant q’apres le delge, e eſgard à deſcen-
d d’icex ſelon la chair.
.
I
Creation d ciel de la terre, II, 10. de tot ce qi y eſt
comprins. 3.14. De la lmiere a, 26 de l’homme, 18
qel tot eſt abietti. 2.2. 18 Die benit totes ſes œ-
res, 31 q’il a accomplies en x iors.
1
Ie
a
crea
b
a com
mence -
ment
c
le
ciel & la
terre.
2 Or la
terre eſ-
toit ſans
forme, &
vide, & les tenebres eſtoyent ſr les
abyſmes : & l’Eſprit de Die
d
eſtoit
eſpand par des les eax.
3 Adonc Die dît,
2
’il y ait lmie-
re.
e
Et la lmiere ft.
4 Et Die vid q
̃
la lmiere eſtoit bon-
ne : & ſepara la lmiere des tenebres.
5 Et Die appela la lmiere ior,& les
tenebres ni. Lors ft fai le
f
ſoir &
le matin d premier ior.
6 Pis Die dît,
3
’il y ait ne
g
eſ-
tende entre les eax, & qelle ſepare
les
h
eax daec les eax.
7 Die donc fit leſtende, & diiſa
I
Ce premier cha-
pitre eſt fort diffi-
cile : & por cette
caſe, il eſtoit de-
fend entre les He
briex de le lire &
interpreter deant
laage de trente
ans.
a
Fit de rien, &
ſans acne ma-
tiere.
1
Iob 38.4, Pſea.
33.6, 89.12.,
135.5, Eccleſtiaſti.
13.1, A. 14-15,
17.14
b
Tot premiere-
ment, & aãt q’il
y et acne crea-
tre, Iean 1.10.
2
Hebr. 11.3.
c
Le ciel & la
terre, les eax, les
abyſmes, ſe pren-
nent ici por vne
meſme choſe : aſç.
por ne matiere
cõfſe & ſans for-
me, q
̃
Die forma
& agença apres
par ſa Parole.
d
O, ſe mo-
voit. Ceſt, ſoſte-
noit et conſeroit
en ſon eſtre cette
matiere confſe.
Car il eſt impo-
ble, q
̃
acne cho-
ſe apres aoir eſté
faies,pie ſb-
ſter n ſel mo-
ment, Die ne la
ſoſtient & cõſer-
ve par ſa vert,
Pſea. 130.
e
Cette lmiere
neſtoit point en-
core a ſoleil, car
il naoit pas eſté
creé, mais eſtoit en
la main de Die,
ayãt ſon ordre ſc-
cef aec les tene-
bres, por faire le
ior & la ni &
ce iſqes a qa-
trieme ior, qe
Die fit le ſoleil
por eſtre miniſtre
& diſpenſater de
cette lmiere, aec
la lne & eſtoilles.
3
Pſea. 33.6,
136.5.
Ierem. 10.11
51.15.
f
Ici eſt la caſe
les eax, qi eſtoyent ſos leſtende,
daec celles, qi eſtoyent ſr leſten-
de. Et ft ain fai.
8 EtDie appela leſtende, Ciel. Lors
ft fai le ſoir & le matin d ſecond
ior.
9 Pis Die dît,
4 i
e les eax, qi
ſont ſos le ciel, ſoyent aemblees en
n lie, & qe le ſec apparoie. Et ft
ain fai.
10 EtDie appeꝉale ſec,Terre,& laem
blee des eax, mers. Et Die vid qe
celà eſtoit bon.
11 Et Die dît, e la terre prodiſe
verdre, herbe prodiſant ſemence, &
arbre friier, faiſant fri ſelon ſon
eſpece, leqel ait ſa ſemẽce en ſoy-meſ-
me ſr la terre. Et ft ain fai.
12 La terre dõc prodit verdre, her-
be prodiſant ſemẽce ſelon ſon eſpece,
& arbre ſans fri, leqel aoit ſa
ſemence en ſoymeſme ſelon ſon eſpe-
ce. Et Die vid qe celà eſtoit bon.
13 Lors ft fai le ſoir & le matin d
troieme ior.
14 Apres Die dît,
5 k
’il y ait lmi
naires en leſtende d ciel, por ſepa-
rer la ni d ior : & ſoyẽt en
l
gnes,
a en
porqoy les He-
briex cõmencent
le ior natrel le
ſoir apres le ſoleil
cochant.
g
Ce mot d’Eſtẽ
de, comprẽd tot
ce qi ſe voit par
des nos, tãt en
la region celeſte,
qelementaire.
4
Pſea. 33.7.
h
Il eſt ici parlé
de dex manieres
deax : asçaoir,
celles q ſont ſos
leſtende, comme
la mer, les flees,
& atres qi ſont
ſr la terre & cel-
les, qi ſont ſr
leſtende, comme
ſont les nees plei-
nes dea ça hat
en lair par des
nos. Die a mis
entre ces dex for
ces deax ne grã
de eſtende, qon
appelle le ciel : de
nos appelons
les oiſeax d ciel.
i
Ceci appartiẽt a
ſecõd ior, aqel
Die ſepara, & fit
apparoir la terre d
milie des eax.
k
Il inſtite n
noel ordre en
natre, qand il
fat & ordonne le
ſoleil diſtribter
de cette lmiere
q’il aoit creée
aant li, & aant
la lne & les eſ-
toilles.
5
Pſea. 136.7
l
Ceſt por -
gnifier dierſes di-
ſpotions qe les
corps ĩferiers ſe-
lon lordre de na-
tre ont des corps
celeſtes, cõme ca
ſes ſecõdes ordon
nees de Die à ce-
là. En qoy to-
teſfois fat fir c-
rioté & ſperſti-
tion q
̃
les hõmes
ont cõtroee ſr
celà.
-
- - diff --git a/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html b/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html deleted file mode 100644 index 37621de..0000000 --- a/test/browser_tests/svg_background_with_page_rotation_issue402/svg_background_with_page_rotation_issue402.html +++ /dev/null @@ -1,641 +0,0 @@ - - - - - - - - - - - - - -
-
Airports & AAL -
A
irport Authorization List
Airway Manual
Airport Authorization List
R = Regular F = Fueling A = Alternate AO = Off-Line Alternate (T) = ETOPS Alternate
[
SA
Q]
= S
p
ecial Air
p
ort
Q
ualification
[
T
Q]
= Theater
Q
ualification ~ or blank = Emer
g
enc
y
Air
p
ort
ICAO Location
IATA
Longest Rwy
24 Hrs
Precision App
A319
A320
A330-200
A330-300
B717
B737-700
B737-800
B737-900
B747
B757
B757-200ER
B757-300ER
B767-300
B767-300ER
B767-300ET
B767-400
B777-200ER
B777-200LR
MD88
MD90
ENCN KRISTIANSAND, NO KRS 6.6 N Y (T) (T)
ENGMOSLO, NO OSL11.8YY~~AOAO~~~~~AOAOAO(T)AO~AOAOAO~~
ENSB SVALBARD, NO [SAQ] LYR 8.1 Y Y (T) (T) (T)
ENVATRONDHEIM, NO TRD 9.0YY~~(T)(T)~~~~~~AO~(T)AO~(T)AOAO~~
ENZV STAVANGER, NO SVG 8.3 Y Y (T) (T) (T) (T) (T)
EPWA
WARSAW PL
WAW
12 1
Y
Y
AO
AO
AO
AO
EPWA
WARSAW
,
PL
WAW
12
.
1
Y
Y
~~
AO
AO
~~~~~~~~~
AO
~
AO
~~~~
ESGGGOTEBORG, SE GOT10.8YN~~~~~~~~~~AO~~AO~AO~~~~
ESMSMALMO, SE MMX9.1YY~~AOAO~~~~~~AO~~AO~AO~~~~
ESOW VAESTERAAS, STOCKHOLM, SE VST 8.4 N N ~~~~~~~~~~AO~~AO~AO~~~~
ESSA ARLANDA, STOCKHOLM, SE [TQ] ARN 10.8 Y Y ~ ~ F F ~~~~~~R~~R~~~~~~
ESSD BORLANGE, SE BLE 7.5 N Y
ETAR RAMSTEIN, DE RMS 10.4 Y Y
EVRA RIGA, LV RIX 10.4 Y Y
FABLBLOEMFONTEIN, ZA BFN 8.3NN~~~~~~~~~~~~~AO~AOAOAO~~
FACT CAPE TOWN, ZA CPT 10.5 Y Y ~~~~~~~~~~~~~AO~AOAOAO~~
FALEDURBAN, ZA DUR12.1YY~~~~~~~~ ~~~~AO~AOAOAO~~
FAOR JOHANNESBURG, ZA [TQ] JNB 14.4 Y Y ~~~~~~~~~~~~~A~ARR~~
FBSKGABORONE, BW GBE13.1NY~~~~~~~~~~~~~AO~AOAOAO~~
FCBB BRAZZAVILLE, CG BZV 10.8 Y Y
FCPP POINTE NOIRE, CG PNR 8.5 Y Y
FGSL MALABO, GQ SSG 9.6 Y Y
FHAW ASCENSION, SH ASI 10.0 Y N (T) (T) (T) (T) (T) (T)
FKKD DOUALA, CM DLA 9.3 Y Y
FKYS YAOUNDE, CM NSI 11.1 Y N
FNLU LUANDA, AO LAD 12.1 Y N (T) (T) (T) (T) (T) (T) (T)
March 28, 2014 OPS-6TA.AD&AAL.2.11
Copyright © Delta Air Lines, Inc. See title page for details.
-
- - diff --git a/test/browser_tests/with_form/with_form.html b/test/browser_tests/with_form/with_form.html deleted file mode 100644 index 91f3c1b..0000000 --- a/test/browser_tests/with_form/with_form.html +++ /dev/null @@ -1,216 +0,0 @@ - - - - - - - - - - - - - -
-
Éditions « À Reproduire » Internet : www.envolee.com
Question de textes 4
7
Nom
Mona veut un chien
4 Que veut dire la mère de Mona quand elle dit : « C’est beaucoup de travail, avoir un chien » ?
a) Mona doit faire plus de recherche avant d’être prête à avoir un chien.
b) Les chiens travaillent fort afi n d’être de bons animaux de compagnie pour les gens.
c) Les chiens ont besoin de nourriture et d’exercice. Il faut aussi ramasser leurs dégâts.
d) Mona devra se reposer plus si elle a un chien.
5 Comment Mona a-t-elle acquis autant de connaissances sur les chiens ?
a) En écoutant son enseignante à l’école.
b) En visitant un site Web.
c) En écrivant à la Société protectrice des animaux.
d) En regardant une vidéo sur les chiens.
6 Pourquoi Mona veut-elle un Jack Russell ?
7 Que devra faire Mona même si elle est fatiguée ou qu’il pleut ?
8 Décris physiquement le chien que Mona veut choisir.
9 Quand fait-elle ses recherches sur le Web ?
10 Que contient le site Web préféré de Mona ? Nomme deux éléments.
REPÉRAGE
-
-
-
-
- - - - - - -
-
-
-
- -
-
- - diff --git a/test/start_xvfb.sh b/test/start_xvfb.sh deleted file mode 100755 index 9664154..0000000 --- a/test/start_xvfb.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1920x16 diff --git a/test/test_local_browser.py b/test/test_local_browser.py deleted file mode 100755 index 1db8b60..0000000 --- a/test/test_local_browser.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python - -# Run browsers tests with a local Firefox - -import unittest - -from selenium import webdriver -from selenium.webdriver.common.by import By -from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.support import expected_conditions -from browser_tests import BrowserTests - -# class test_local_browser(BrowserTests, unittest.TestCase): -# @classmethod -# def setUpClass(cls): -# super(test_local_browser, cls).setUpClass() -# if not cls.GENERATING_MODE: -# cls.browser = webdriver.Firefox() -# cls.browser.maximize_window() -# size = cls.browser.get_window_size() -# assert ((size['width'] >= cls.BROWSER_WIDTH) and (size['height'] >= cls.BROWSER_HEIGHT)), 'Screen is not large enough' -# cls.browser.set_window_size(cls.BROWSER_WIDTH, cls.BROWSER_HEIGHT) -# -# @classmethod -# def tearDownClass(cls): -# if not cls.GENERATING_MODE: -# cls.browser.quit() -# super(test_local_browser, cls).tearDownClass() -# -# def generate_image(self, html_file, png_file, page_must_load=True): -# self.browser.get('file://' + html_file) -# try: -# WebDriverWait(self.browser, 5).until(expected_conditions.presence_of_element_located((By.ID, 'page-container'))) -# except: -# if page_must_load: -# raise -# self.browser.save_screenshot(png_file) -# -# if __name__ == '__main__': -# unittest.main()