From 12f1eb15ca3fed6310402847559a7c99d3c77847 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Sat, 2 Apr 2022 17:14:10 -0400 Subject: [PATCH] Programmatically apply new formatting to code Run this: for i in **/*.cc **/*.c **/*.h **/*.hh; do clang-format < $i >| $i.new && mv $i.new $i done --- examples/pdf-attach-file.cc | 134 +- examples/pdf-bookmarks.cc | 168 +- examples/pdf-c-objects.c | 53 +- examples/pdf-count-strings.cc | 38 +- examples/pdf-create.cc | 223 +- examples/pdf-custom-filter.cc | 158 +- examples/pdf-double-page-size.cc | 56 +- examples/pdf-filter-tokens.cc | 72 +- examples/pdf-invert-images.cc | 71 +- examples/pdf-linearize.c | 49 +- examples/pdf-mod-info.cc | 149 +- examples/pdf-name-number-tree.cc | 78 +- examples/pdf-npages.cc | 21 +- examples/pdf-overlay-page.cc | 47 +- examples/pdf-parse-content.cc | 36 +- examples/pdf-set-form-values.cc | 38 +- examples/pdf-split-pages.cc | 35 +- examples/qpdf-job.cc | 50 +- examples/qpdfjob-c.c | 20 +- fuzz/ascii85_fuzzer.cc | 12 +- fuzz/dct_fuzzer.cc | 14 +- fuzz/flate_fuzzer.cc | 10 +- fuzz/hex_fuzzer.cc | 12 +- fuzz/lzw_fuzzer.cc | 10 +- fuzz/pngpredictor_fuzzer.cc | 10 +- fuzz/qpdf_fuzzer.cc | 85 +- fuzz/runlength_fuzzer.cc | 10 +- fuzz/standalone_fuzz_target_runner.cc | 6 +- fuzz/tiffpredictor_fuzzer.cc | 14 +- include/qpdf/Buffer.hh | 2 +- include/qpdf/BufferInputSource.hh | 10 +- include/qpdf/Constants.h | 81 +- include/qpdf/DLL.h | 2 +- include/qpdf/InputSource.hh | 20 +- include/qpdf/JSON.hh | 25 +- include/qpdf/Pipeline.hh | 2 +- include/qpdf/Pl_Buffer.hh | 4 +- include/qpdf/Pl_Count.hh | 2 +- include/qpdf/Pl_DCT.hh | 29 +- include/qpdf/Pl_Flate.hh | 7 +- include/qpdf/Pl_QPDFTokenizer.hh | 11 +- include/qpdf/Pl_RunLength.hh | 3 +- include/qpdf/PointerHolder.hh | 74 +- include/qpdf/QIntC.hh | 140 +- include/qpdf/QPDF.hh | 523 ++-- include/qpdf/QPDFAcroFormDocumentHelper.hh | 43 +- include/qpdf/QPDFAnnotationObjectHelper.hh | 9 +- include/qpdf/QPDFCryptoImpl.hh | 15 +- include/qpdf/QPDFCryptoProvider.hh | 21 +- include/qpdf/QPDFDocumentHelper.hh | 6 +- .../qpdf/QPDFEmbeddedFileDocumentHelper.hh | 12 +- include/qpdf/QPDFExc.hh | 24 +- include/qpdf/QPDFFileSpecObjectHelper.hh | 19 +- include/qpdf/QPDFFormFieldObjectHelper.hh | 4 +- include/qpdf/QPDFJob.hh | 76 +- include/qpdf/QPDFMatrix.hh | 18 +- include/qpdf/QPDFNameTreeObjectHelper.hh | 28 +- include/qpdf/QPDFNumberTreeObjectHelper.hh | 27 +- include/qpdf/QPDFObject.hh | 22 +- include/qpdf/QPDFObjectHandle.hh | 263 +- include/qpdf/QPDFObjectHelper.hh | 6 +- include/qpdf/QPDFOutlineDocumentHelper.hh | 7 +- include/qpdf/QPDFOutlineObjectHelper.hh | 2 +- include/qpdf/QPDFPageDocumentHelper.hh | 11 +- include/qpdf/QPDFPageLabelDocumentHelper.hh | 9 +- include/qpdf/QPDFPageObjectHelper.hh | 67 +- include/qpdf/QPDFStreamFilter.hh | 2 +- include/qpdf/QPDFSystemError.hh | 11 +- include/qpdf/QPDFTokenizer.hh | 61 +- include/qpdf/QPDFUsage.hh | 2 +- include/qpdf/QPDFWriter.hh | 268 +- include/qpdf/QPDFXRefEntry.hh | 6 +- include/qpdf/QTC.hh | 2 +- include/qpdf/QUtil.hh | 82 +- include/qpdf/qpdf-c.h | 261 +- include/qpdf/qpdfjob-c.h | 1 - libqpdf/AES_PDF_native.cc | 73 +- libqpdf/BitStream.cc | 31 +- libqpdf/BitWriter.cc | 10 +- libqpdf/Buffer.cc | 18 +- libqpdf/BufferInputSource.cc | 66 +- libqpdf/ClosedFileInputSource.cc | 12 +- libqpdf/ContentNormalizer.cc | 48 +- libqpdf/FileInputSource.cc | 70 +- libqpdf/InputSource.cc | 104 +- libqpdf/InsecureRandomDataProvider.cc | 18 +- libqpdf/JSON.cc | 708 ++---- libqpdf/JSONHandler.cc | 60 +- libqpdf/MD5.cc | 73 +- libqpdf/NNTree.cc | 637 ++--- libqpdf/OffsetInputSource.cc | 23 +- libqpdf/PDFVersion.cc | 26 +- libqpdf/Pipeline.cc | 3 +- libqpdf/Pl_AES_PDF.cc | 122 +- libqpdf/Pl_ASCII85Decoder.cc | 77 +- libqpdf/Pl_ASCIIHexDecoder.cc | 63 +- libqpdf/Pl_Buffer.cc | 37 +- libqpdf/Pl_Concatenate.cc | 1 - libqpdf/Pl_Count.cc | 3 +- libqpdf/Pl_DCT.cc | 204 +- libqpdf/Pl_Flate.cc | 171 +- libqpdf/Pl_LZWDecoder.cc | 115 +- libqpdf/Pl_MD5.cc | 18 +- libqpdf/Pl_PNGFilter.cc | 120 +- libqpdf/Pl_QPDFTokenizer.cc | 43 +- libqpdf/Pl_RC4.cc | 15 +- libqpdf/Pl_RunLength.cc | 99 +- libqpdf/Pl_SHA2.cc | 30 +- libqpdf/Pl_StdioFile.cc | 21 +- libqpdf/Pl_TIFFPredictor.cc | 63 +- libqpdf/QPDF.cc | 2117 +++++++--------- libqpdf/QPDFAcroFormDocumentHelper.cc | 609 ++--- libqpdf/QPDFAnnotationObjectHelper.cc | 95 +- libqpdf/QPDFArgParser.cc | 530 ++-- libqpdf/QPDFCryptoProvider.cc | 26 +- libqpdf/QPDFCrypto_gnutls.cc | 135 +- libqpdf/QPDFCrypto_native.cc | 29 +- libqpdf/QPDFCrypto_openssl.cc | 68 +- libqpdf/QPDFEFStreamObjectHelper.cc | 55 +- libqpdf/QPDFEmbeddedFileDocumentHelper.cc | 46 +- libqpdf/QPDFExc.cc | 44 +- libqpdf/QPDFFileSpecObjectHelper.cc | 64 +- libqpdf/QPDFFormFieldObjectHelper.cc | 465 ++-- libqpdf/QPDFJob.cc | 2252 +++++++---------- libqpdf/QPDFJob_argv.cc | 166 +- libqpdf/QPDFJob_config.cc | 289 +-- libqpdf/QPDFJob_json.cc | 184 +- libqpdf/QPDFMatrix.cc | 55 +- libqpdf/QPDFNameTreeObjectHelper.cc | 42 +- libqpdf/QPDFNumberTreeObjectHelper.cc | 55 +- libqpdf/QPDFObjGen.cc | 8 +- libqpdf/QPDFObjectHandle.cc | 1832 ++++++-------- libqpdf/QPDFOutlineDocumentHelper.cc | 60 +- libqpdf/QPDFOutlineObjectHelper.cc | 36 +- libqpdf/QPDFPageDocumentHelper.cc | 122 +- libqpdf/QPDFPageLabelDocumentHelper.cc | 48 +- libqpdf/QPDFPageObjectHelper.cc | 719 ++---- libqpdf/QPDFSystemError.cc | 14 +- libqpdf/QPDFTokenizer.cc | 528 ++-- libqpdf/QPDFWriter.cc | 2147 ++++++++-------- libqpdf/QPDFXRefEntry.cc | 17 +- libqpdf/QPDF_Array.cc | 24 +- libqpdf/QPDF_Dictionary.cc | 56 +- libqpdf/QPDF_Name.cc | 21 +- libqpdf/QPDF_Real.cc | 23 +- libqpdf/QPDF_Stream.cc | 450 ++-- libqpdf/QPDF_String.cc | 99 +- libqpdf/QPDF_encryption.cc | 1043 ++++---- libqpdf/QPDF_linearization.cc | 1384 +++++----- libqpdf/QPDF_optimization.cc | 380 ++- libqpdf/QPDF_pages.cc | 178 +- libqpdf/QTC.cc | 19 +- libqpdf/QUtil.cc | 1745 ++++++------- libqpdf/RC4.cc | 2 +- libqpdf/RC4_native.cc | 24 +- libqpdf/ResourceFinder.cc | 17 +- libqpdf/SF_FlateLzwDecode.cc | 94 +- libqpdf/SHA2_native.cc | 61 +- libqpdf/SecureRandomDataProvider.cc | 70 +- libqpdf/SparseOHArray.cc | 68 +- libqpdf/qpdf-c.cc | 1406 +++++----- libqpdf/qpdf/AES_PDF_native.hh | 8 +- libqpdf/qpdf/CryptoRandomDataProvider.hh | 2 +- libqpdf/qpdf/InsecureRandomDataProvider.hh | 2 +- libqpdf/qpdf/JSONHandler.hh | 31 +- libqpdf/qpdf/MD5.hh | 19 +- libqpdf/qpdf/MD5_native.hh | 12 +- libqpdf/qpdf/NNTree.hh | 52 +- libqpdf/qpdf/Pl_AES_PDF.hh | 11 +- libqpdf/qpdf/Pl_LZWDecoder.hh | 6 +- libqpdf/qpdf/Pl_MD5.hh | 2 +- libqpdf/qpdf/Pl_PNGFilter.hh | 15 +- libqpdf/qpdf/Pl_RC4.hh | 9 +- libqpdf/qpdf/Pl_TIFFPredictor.hh | 11 +- libqpdf/qpdf/QPDFArgParser.hh | 42 +- libqpdf/qpdf/QPDFCrypto_gnutls.hh | 15 +- libqpdf/qpdf/QPDFCrypto_native.hh | 19 +- libqpdf/qpdf/QPDFCrypto_openssl.hh | 23 +- libqpdf/qpdf/QPDF_Array.hh | 4 +- libqpdf/qpdf/QPDF_Dictionary.hh | 2 +- libqpdf/qpdf/QPDF_Stream.hh | 57 +- libqpdf/qpdf/RC4.hh | 6 +- libqpdf/qpdf/RC4_native.hh | 4 +- libqpdf/qpdf/ResourceFinder.hh | 10 +- libqpdf/qpdf/SF_ASCII85Decode.hh | 14 +- libqpdf/qpdf/SF_ASCIIHexDecode.hh | 14 +- libqpdf/qpdf/SF_DCTDecode.hh | 16 +- libqpdf/qpdf/SF_FlateLzwDecode.hh | 2 +- libqpdf/qpdf/SF_RunLengthDecode.hh | 13 +- libqpdf/qpdf/SecureRandomDataProvider.hh | 2 +- libqpdf/qpdf/SparseOHArray.hh | 3 +- libqpdf/qpdf/bits_functions.hh | 123 +- libqpdf/qpdf/rijndael.h | 28 +- libqpdf/qpdfjob-c.cc | 28 +- libtests/aes.cc | 97 +- libtests/arg_parser.cc | 105 +- libtests/ascii85.cc | 20 +- libtests/bits.cc | 45 +- libtests/buffer.cc | 37 +- libtests/closed_file_input_source.cc | 16 +- libtests/concatenate.cc | 19 +- libtests/cxx11.cc | 169 +- libtests/dct_compress.cc | 48 +- libtests/dct_uncompress.cc | 23 +- libtests/flate.cc | 29 +- libtests/hex.cc | 22 +- libtests/input_source.cc | 79 +- libtests/json.cc | 112 +- libtests/json_handler.cc | 61 +- libtests/json_parse.cc | 15 +- libtests/lzw.cc | 26 +- libtests/main_from_wmain.cc | 22 +- libtests/matrix.cc | 64 +- libtests/md5.cc | 25 +- libtests/nntree.cc | 142 +- libtests/numrange.cc | 24 +- libtests/pdf_version.cc | 17 +- libtests/pointer_holder.cc | 21 +- libtests/predictors.cc | 75 +- libtests/qintc.cc | 73 +- libtests/qutil.cc | 408 ++- libtests/random.cc | 41 +- libtests/rc4.cc | 35 +- libtests/runlength.cc | 23 +- libtests/sha2.cc | 118 +- libtests/sparse_array.cc | 3 +- pkg-test/qpdf-version.cc | 4 +- qpdf/fix-qdf.cc | 274 +- qpdf/pdf_from_scratch.cc | 59 +- qpdf/qpdf-ctest.c | 1105 ++++---- qpdf/qpdf.cc | 54 +- qpdf/qpdfjob-ctest.c | 12 +- qpdf/sizes.cc | 6 +- qpdf/test_driver.cc | 1761 ++++++------- qpdf/test_large_file.cc | 145 +- qpdf/test_parsedoffset.cc | 165 +- qpdf/test_pdf_doc_encoding.cc | 25 +- qpdf/test_pdf_unicode.cc | 29 +- qpdf/test_renumber.cc | 305 +-- qpdf/test_shell_glob.cc | 33 +- qpdf/test_tokenizer.cc | 238 +- qpdf/test_unicode_filenames.cc | 35 +- qpdf/test_xref.cc | 67 +- zlib-flate/zlib-flate.cc | 71 +- 244 files changed, 15234 insertions(+), 18975 deletions(-) diff --git a/examples/pdf-attach-file.cc b/examples/pdf-attach-file.cc index 2cc30262..964d247d 100644 --- a/examples/pdf-attach-file.cc +++ b/examples/pdf-attach-file.cc @@ -1,11 +1,11 @@ #include -#include -#include #include #include +#include +#include -#include #include +#include // // This example attaches a file to an input file, adds a page to the @@ -17,9 +17,11 @@ static char const* whoami = 0; -static void usage(std::string const& msg) +static void +usage(std::string const& msg) { - std::cerr << msg << std::endl << std::endl + std::cerr << msg << std::endl + << std::endl << "Usage: " << whoami << " options" << std::endl << "Options:" << std::endl << " --infile infile.pdf" << std::endl @@ -30,33 +32,36 @@ static void usage(std::string const& msg) exit(2); } -static void process(char const* infilename, char const* password, - char const* attachment, char const* mimetype, - char const* outfilename) +static void +process( + char const* infilename, + char const* password, + char const* attachment, + char const* mimetype, + char const* outfilename) { QPDF q; q.processFile(infilename, password); // Create an indirect object for the built-in Helvetica font. This // uses the qpdf literal syntax introduced in qpdf 10.6. - auto f1 = q.makeIndirectObject( - "<<" - " /Type /Font" - " /Subtype /Type1" - " /Name /F1" - " /BaseFont /Helvetica" - " /Encoding /WinAnsiEncoding" - ">>"_qpdf); + auto f1 = q.makeIndirectObject("<<" + " /Type /Font" + " /Subtype /Type1" + " /Name /F1" + " /BaseFont /Helvetica" + " /Encoding /WinAnsiEncoding" + ">>"_qpdf); // Create a resources dictionary with fonts. This uses the new // parse introduced in qpdf 10.2 that takes a QPDF* and allows // indirect object references. - auto resources = q.makeIndirectObject( - QPDFObjectHandle::parse( - &q, - "<<" - " /Font <<" - " /F1 " + f1.unparse() + + auto resources = q.makeIndirectObject(QPDFObjectHandle::parse( + &q, + "<<" + " /Font <<" + " /F1 " + + f1.unparse() + " >>" ">>")); @@ -66,8 +71,7 @@ static void process(char const* infilename, char const* password, << std::endl; auto fs = QPDFFileSpecObjectHelper::createFileSpec(q, key, attachment); - if (mimetype) - { + if (mimetype) { // Get an embedded file stream and set mimetype auto ef = QPDFEFStreamObjectHelper(fs.getEmbeddedFileStream()); ef.setSubtype(mimetype); @@ -102,17 +106,16 @@ static void process(char const* infilename, char const* password, apdict.replaceKey("/Type", "/XObject"_qpdf); apdict.replaceKey("/Subtype", "/Form"_qpdf); apdict.replaceKey("/BBox", "[ 0 0 20 20 ]"_qpdf); - auto annot = q.makeIndirectObject( - QPDFObjectHandle::parse( - &q, - "<<" - " /AP <<" - " /N " + ap.unparse() + + auto annot = q.makeIndirectObject(QPDFObjectHandle::parse( + &q, + "<<" + " /AP <<" + " /N " + + ap.unparse() + " >>" - " /Contents " - + QPDFObjectHandle::newUnicodeString(attachment).unparse() + - " /FS " + fs.getObjectHandle().unparse() + - " /NM " + + " /Contents " + + QPDFObjectHandle::newUnicodeString(attachment).unparse() + + " /FS " + fs.getObjectHandle().unparse() + " /NM " + QPDFObjectHandle::newUnicodeString(attachment).unparse() + " /Rect [ 72 700 92 720 ]" " /Subtype /FileAttachment" @@ -134,12 +137,16 @@ static void process(char const* infilename, char const* password, auto page = QPDFObjectHandle::parse( &q, "<<" - " /Annots [ " + annot.unparse() + " ]" - " /Contents " + contents.unparse() + - " /MediaBox [0 0 612 792]" - " /Resources " + resources.unparse() + - " /Type /Page" - ">>"); + " /Annots [ " + + annot.unparse() + + " ]" + " /Contents " + + contents.unparse() + + " /MediaBox [0 0 612 792]" + " /Resources " + + resources.unparse() + + " /Type /Page" + ">>"); // Add the page. q.addPage(page, true); @@ -151,7 +158,8 @@ static void process(char const* infilename, char const* password, w.write(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); @@ -162,64 +170,46 @@ int main(int argc, char* argv[]) char const* mimetype = 0; auto check_arg = [](char const* arg, std::string const& msg) { - if (arg == nullptr) - { + if (arg == nullptr) { usage(msg); } }; - for (int i = 1; i < argc; ++i) - { + for (int i = 1; i < argc; ++i) { char* arg = argv[i]; - char* next = argv[i+1]; - if (strcmp(arg, "--infile") == 0) - { + char* next = argv[i + 1]; + if (strcmp(arg, "--infile") == 0) { check_arg(next, "--infile takes an argument"); infilename = next; ++i; - } - else if (strcmp(arg, "--password") == 0) - { + } else if (strcmp(arg, "--password") == 0) { check_arg(next, "--password takes an argument"); password = next; ++i; - } - else if (strcmp(arg, "--attachment") == 0) - { + } else if (strcmp(arg, "--attachment") == 0) { check_arg(next, "--attachment takes an argument"); attachment = next; ++i; - } - else if (strcmp(arg, "--outfile") == 0) - { + } else if (strcmp(arg, "--outfile") == 0) { check_arg(next, "--outfile takes an argument"); outfilename = next; ++i; - } - else if (strcmp(arg, "--mimetype") == 0) - { + } else if (strcmp(arg, "--mimetype") == 0) { check_arg(next, "--mimetype takes an argument"); mimetype = next; ++i; - } - else - { + } else { usage("unknown argument " + std::string(arg)); } } - if (! (infilename && attachment && outfilename)) - { + if (!(infilename && attachment && outfilename)) { usage("required arguments were not provided"); } - try - { + try { process(infilename, password, attachment, mimetype, outfilename); - } - catch (std::exception &e) - { - std::cerr << whoami << " exception: " - << e.what() << std::endl; + } catch (std::exception& e) { + std::cerr << whoami << " exception: " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-bookmarks.cc b/examples/pdf-bookmarks.cc index e049e423..de0af8e6 100644 --- a/examples/pdf-bookmarks.cc +++ b/examples/pdf-bookmarks.cc @@ -1,12 +1,12 @@ -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include #include +#include +#include +#include +#include // This program demonstrates extraction of bookmarks using the qpdf // outlines API. Note that all the information shown by this program @@ -20,67 +20,62 @@ static bool show_open = false; static bool show_targets = false; static std::map page_map; -void usage() +void +usage() { - std::cerr << "Usage: " << whoami << " [options] file.pdf [password]" - << std::endl - << "Options:" << std::endl - << " --numbers give bookmarks outline-style numbers" - << std::endl - << " --lines draw lines to show bookmark hierarchy" - << std::endl - << " --show-open indicate whether a bookmark is initially open" - << std::endl - << " --show-targets show target if possible" - << std::endl; + std::cerr + << "Usage: " << whoami << " [options] file.pdf [password]" << std::endl + << "Options:" << std::endl + << " --numbers give bookmarks outline-style numbers" + << std::endl + << " --lines draw lines to show bookmark hierarchy" + << std::endl + << " --show-open indicate whether a bookmark is initially open" + << std::endl + << " --show-targets show target if possible" << std::endl; exit(2); } -void print_lines(std::vector& numbers) +void +print_lines(std::vector& numbers) { - for (unsigned int i = 0; i < numbers.size() - 1; ++i) - { - if (numbers.at(i)) - { + for (unsigned int i = 0; i < numbers.size() - 1; ++i) { + if (numbers.at(i)) { std::cout << "| "; - } - else - { + } else { std::cout << " "; } } } -void generate_page_map(QPDF& qpdf) +void +generate_page_map(QPDF& qpdf) { QPDFPageDocumentHelper dh(qpdf); int n = 0; - for (auto const& page : dh.getAllPages()) - { + for (auto const& page : dh.getAllPages()) { page_map[page.getObjectHandle().getObjGen()] = ++n; } } -void show_bookmark_details(QPDFOutlineObjectHelper outline, - std::vector numbers) +void +show_bookmark_details(QPDFOutlineObjectHelper outline, std::vector numbers) { // No default so gcc will warn on missing tag - switch (style) - { - case st_none: + switch (style) { + case st_none: QTC::TC("examples", "pdf-bookmarks none"); break; - case st_numbers: + case st_numbers: QTC::TC("examples", "pdf-bookmarks numbers"); - for (auto const& number : numbers) - { + for (auto const& number : numbers) { std::cout << number << "."; } std::cout << " "; break; - case st_lines: + case st_lines: QTC::TC("examples", "pdf-bookmarks lines"); print_lines(numbers); std::cout << "|" << std::endl; @@ -89,42 +84,32 @@ void show_bookmark_details(QPDFOutlineObjectHelper outline, break; } - if (show_open) - { + if (show_open) { int count = outline.getCount(); - if (count) - { + if (count) { QTC::TC("examples", "pdf-bookmarks has count"); - if (count > 0) - { + if (count > 0) { // hierarchy is open at this point QTC::TC("examples", "pdf-bookmarks open"); std::cout << "(v) "; - } - else - { + } else { QTC::TC("examples", "pdf-bookmarks closed"); std::cout << "(>) "; } - } - else - { + } else { QTC::TC("examples", "pdf-bookmarks no count"); std::cout << "( ) "; } } - if (show_targets) - { + if (show_targets) { QTC::TC("examples", "pdf-bookmarks targets"); std::string target = "unknown"; QPDFObjectHandle dest_page = outline.getDestPage(); - if (! dest_page.isNull()) - { + if (!dest_page.isNull()) { QTC::TC("examples", "pdf-bookmarks dest"); QPDFObjGen og = dest_page.getObjGen(); - if (page_map.count(og)) - { + if (page_map.count(og)) { target = QUtil::int_to_string(page_map[og]); } } @@ -134,8 +119,9 @@ void show_bookmark_details(QPDFOutlineObjectHelper outline, std::cout << outline.getTitle() << std::endl; } -void extract_bookmarks(std::vector outlines, - std::vector& numbers) +void +extract_bookmarks( + std::vector outlines, std::vector& numbers) { // For style == st_numbers, numbers.at(n) contains the numerical // label for the outline, so we count up from 1. @@ -144,8 +130,7 @@ void extract_bookmarks(std::vector outlines, // is, so we count up to zero. numbers.push_back( (style == st_lines) ? -QIntC::to_int(outlines.size()) : 0); - for (auto& outline : outlines) - { + for (auto& outline : outlines) { ++(numbers.back()); show_bookmark_details(outline, numbers); extract_bookmarks(outline.getKids(), numbers); @@ -153,87 +138,64 @@ void extract_bookmarks(std::vector outlines, numbers.pop_back(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { std::cout << whoami << " version 1.5" << std::endl; exit(0); } int arg; - for (arg = 1; arg < argc; ++arg) - { - if (argv[arg][0] == '-') - { - if (strcmp(argv[arg], "--numbers") == 0) - { + for (arg = 1; arg < argc; ++arg) { + if (argv[arg][0] == '-') { + if (strcmp(argv[arg], "--numbers") == 0) { style = st_numbers; - } - else if (strcmp(argv[arg], "--lines") == 0) - { + } else if (strcmp(argv[arg], "--lines") == 0) { style = st_lines; - } - else if (strcmp(argv[arg], "--show-open") == 0) - { + } else if (strcmp(argv[arg], "--show-open") == 0) { show_open = true; - } - else if (strcmp(argv[arg], "--show-targets") == 0) - { + } else if (strcmp(argv[arg], "--show-targets") == 0) { show_targets = true; - } - else - { + } else { usage(); } - } - else - { + } else { break; } } - if (arg >= argc) - { + if (arg >= argc) { usage(); } char const* filename = argv[arg++]; char const* password = ""; - if (arg < argc) - { + if (arg < argc) { password = argv[arg++]; } - if (arg != argc) - { + if (arg != argc) { usage(); } - try - { + try { QPDF qpdf; qpdf.processFile(filename, password); QPDFOutlineDocumentHelper odh(qpdf); - if (odh.hasOutlines()) - { + if (odh.hasOutlines()) { std::vector numbers; - if (show_targets) - { + if (show_targets) { generate_page_map(qpdf); } extract_bookmarks(odh.getTopLevelOutlines(), numbers); - } - else - { + } else { std::cout << filename << " has no bookmarks" << std::endl; } - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << " processing file " << filename << ": " << e.what() << std::endl; exit(2); diff --git a/examples/pdf-c-objects.c b/examples/pdf-c-objects.c index c616997a..78a4a746 100644 --- a/examples/pdf-c-objects.c +++ b/examples/pdf-c-objects.c @@ -10,7 +10,8 @@ static char const* whoami = 0; -static void usage() +static void +usage() { fprintf(stderr, "Usage: %s infile infile-password outfile\n", whoami); exit(2); @@ -33,12 +34,9 @@ modify_file(qpdf_data qpdf) /* 0 is never a valid qpdf_oh */ qpdf_oh pagemode = 0; if (qpdf_oh_is_dictionary( - qpdf, qpdf_oh_get_key(qpdf, root, "/PageLabels"))) - { + qpdf, qpdf_oh_get_key(qpdf, root, "/PageLabels"))) { pagemode = qpdf_oh_new_name(qpdf, "/UseOutlines"); - } - else - { + } else { pagemode = qpdf_oh_new_null(qpdf); } qpdf_oh_replace_or_remove_key(qpdf, root, "/PageMode", pagemode); @@ -46,7 +44,8 @@ modify_file(qpdf_data qpdf) return QPDF_TRUE; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { char* infile = NULL; char* password = NULL; @@ -56,21 +55,15 @@ int main(int argc, char* argv[]) int errors = 0; char* p = 0; - if ((p = strrchr(argv[0], '/')) != NULL) - { + if ((p = strrchr(argv[0], '/')) != NULL) { whoami = p + 1; - } - else if ((p = strrchr(argv[0], '\\')) != NULL) - { + } else if ((p = strrchr(argv[0], '\\')) != NULL) { whoami = p + 1; - } - else - { + } else { whoami = argv[0]; } - if (argc != 4) - { + if (argc != 4) { usage(); } @@ -80,33 +73,29 @@ int main(int argc, char* argv[]) if (((qpdf_read(qpdf, infile, password) & QPDF_ERRORS) == 0) && modify_file(qpdf) && - ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) - { + ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) { /* Use static ID for testing only. For production, a * non-static ID is used. See also * qpdf_set_deterministic_ID. */ qpdf_set_static_ID(qpdf, QPDF_TRUE); /* for testing only */ qpdf_write(qpdf); } - while (qpdf_more_warnings(qpdf)) - { + while (qpdf_more_warnings(qpdf)) { warnings = 1; - printf("warning: %s\n", - qpdf_get_error_full_text(qpdf, qpdf_next_warning(qpdf))); + printf( + "warning: %s\n", + qpdf_get_error_full_text(qpdf, qpdf_next_warning(qpdf))); } - if (qpdf_has_error(qpdf)) - { + if (qpdf_has_error(qpdf)) { errors = 1; - printf("error: %s\n", - qpdf_get_error_full_text(qpdf, qpdf_get_error(qpdf))); + printf( + "error: %s\n", + qpdf_get_error_full_text(qpdf, qpdf_get_error(qpdf))); } qpdf_cleanup(&qpdf); - if (errors) - { + if (errors) { return 2; - } - else if (warnings) - { + } else if (warnings) { return 3; } diff --git a/examples/pdf-count-strings.cc b/examples/pdf-count-strings.cc index 4a1a8e4e..a52b7a37 100644 --- a/examples/pdf-count-strings.cc +++ b/examples/pdf-count-strings.cc @@ -5,23 +5,23 @@ // #include -#include #include +#include +#include #include +#include #include #include #include -#include -#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile" << std::endl - << "Applies token filters to infile" - << std::endl; + << "Applies token filters to infile" << std::endl; exit(2); } @@ -47,8 +47,7 @@ void StringCounter::handleToken(QPDFTokenizer::Token const& token) { // Count string tokens - if (token.getType() == QPDFTokenizer::tt_string) - { + if (token.getType() == QPDFTokenizer::tt_string) { ++this->count; } // Preserve input verbatim by passing each token to any specified @@ -71,36 +70,31 @@ StringCounter::getCount() const return this->count; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 2) - { + if (argc != 2) { usage(); } char const* infilename = argv[1]; - try - { + try { QPDF pdf; pdf.processFile(infilename); int pageno = 0; - for (auto& page : QPDFPageDocumentHelper(pdf).getAllPages()) - { + for (auto& page : QPDFPageDocumentHelper(pdf).getAllPages()) { ++pageno; // Pass the contents of a page through our string counter. // If it's an even page, capture the output. This // illustrates that you may capture any output generated // by the filter, or you may ignore it. StringCounter counter; - if (pageno % 2) - { + if (pageno % 2) { // Ignore output for odd pages. page.filterContents(&counter); - } - else - { + } else { // Write output to stdout for even pages. Pl_StdioFile out("stdout", stdout); std::cout << "% Contents of page " << pageno << std::endl; @@ -110,9 +104,7 @@ int main(int argc, char* argv[]) std::cout << "Page " << pageno << ": strings = " << counter.getCount() << std::endl; } - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-create.cc b/examples/pdf-create.cc index b5d87618..5274d0a2 100644 --- a/examples/pdf-create.cc +++ b/examples/pdf-create.cc @@ -5,20 +5,20 @@ // StreamDataProvider with different types of filters. // +#include +#include +#include +#include #include +#include #include #include #include -#include #include -#include -#include -#include -#include #include #include -#include #include +#include static char const* whoami = 0; @@ -27,11 +27,10 @@ static char const* whoami = 0; class ImageProvider: public QPDFObjectHandle::StreamDataProvider { public: - ImageProvider(std::string const& color_space, - std::string const& filter); + ImageProvider(std::string const& color_space, std::string const& filter); virtual ~ImageProvider(); - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); size_t getWidth() const; size_t getHeight() const; @@ -45,8 +44,8 @@ class ImageProvider: public QPDFObjectHandle::StreamDataProvider J_COLOR_SPACE j_color_space; }; -ImageProvider::ImageProvider(std::string const& color_space, - std::string const& filter) : +ImageProvider::ImageProvider( + std::string const& color_space, std::string const& filter) : width(400), stripe_height(80), color_space(color_space), @@ -54,8 +53,7 @@ ImageProvider::ImageProvider(std::string const& color_space, n_stripes(6), j_color_space(JCS_UNKNOWN) { - if (color_space == "/DeviceCMYK") - { + if (color_space == "/DeviceCMYK") { j_color_space = JCS_CMYK; stripes.push_back(std::string("\xff\x00\x00\x00", 4)); stripes.push_back(std::string("\x00\xff\x00\x00", 4)); @@ -63,9 +61,7 @@ ImageProvider::ImageProvider(std::string const& color_space, stripes.push_back(std::string("\xff\x00\xff\x00", 4)); stripes.push_back(std::string("\xff\xff\x00\x00", 4)); stripes.push_back(std::string("\x00\x00\x00\xff", 4)); - } - else if (color_space == "/DeviceRGB") - { + } else if (color_space == "/DeviceRGB") { j_color_space = JCS_RGB; stripes.push_back(std::string("\xff\x00\x00", 3)); stripes.push_back(std::string("\x00\xff\x00", 3)); @@ -73,9 +69,7 @@ ImageProvider::ImageProvider(std::string const& color_space, stripes.push_back(std::string("\xff\x00\xff", 3)); stripes.push_back(std::string("\xff\xff\x00", 3)); stripes.push_back(std::string("\x00\x00\x00", 3)); - } - else if (color_space == "/DeviceGray") - { + } else if (color_space == "/DeviceGray") { j_color_space = JCS_GRAYSCALE; stripes.push_back(std::string("\xee", 1)); stripes.push_back(std::string("\xcc", 1)); @@ -103,34 +97,31 @@ ImageProvider::getHeight() const } void -ImageProvider::provideStreamData(int objid, int generation, - Pipeline* pipeline) +ImageProvider::provideStreamData(int objid, int generation, Pipeline* pipeline) { std::vector> to_delete; Pipeline* p = pipeline; std::shared_ptr p_new; - if (filter == "/DCTDecode") - { + if (filter == "/DCTDecode") { p_new = std::make_shared( - "image encoder", pipeline, - QIntC::to_uint(width), QIntC::to_uint(getHeight()), - QIntC::to_int(stripes[0].length()), j_color_space); + "image encoder", + pipeline, + QIntC::to_uint(width), + QIntC::to_uint(getHeight()), + QIntC::to_int(stripes[0].length()), + j_color_space); to_delete.push_back(p_new); p = p_new.get(); - } - else if (filter == "/RunLengthDecode") - { + } else if (filter == "/RunLengthDecode") { p_new = std::make_shared( "image encoder", pipeline, Pl_RunLength::a_encode); to_delete.push_back(p_new); p = p_new.get(); } - for (size_t i = 0; i < n_stripes; ++i) - { - for (size_t j = 0; j < width * stripe_height; ++j) - { + for (size_t i = 0; i < n_stripes; ++i) { + for (size_t j = 0; j < width * stripe_height; ++j) { p->write( QUtil::unsigned_char_pointer(stripes[i].c_str()), stripes[i].length()); @@ -139,36 +130,43 @@ ImageProvider::provideStreamData(int objid, int generation, p->finish(); } -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " filename" << std::endl << "Creates a simple PDF and writes it to filename" << std::endl; exit(2); } -static QPDFObjectHandle createPageContents(QPDF& pdf, std::string const& text) +static QPDFObjectHandle +createPageContents(QPDF& pdf, std::string const& text) { // Create a stream that displays our image and the given text in // our font. - std::string contents = - "BT /F1 24 Tf 72 320 Td (" + text + ") Tj ET\n" + std::string contents = "BT /F1 24 Tf 72 320 Td (" + text + + ") Tj ET\n" "q 244 0 0 144 184 100 cm /Im1 Do Q\n"; return QPDFObjectHandle::newStream(&pdf, contents); } -QPDFObjectHandle newName(std::string const& name) +QPDFObjectHandle +newName(std::string const& name) { return QPDFObjectHandle::newName(name); } -QPDFObjectHandle newInteger(size_t val) +QPDFObjectHandle +newInteger(size_t val) { return QPDFObjectHandle::newInteger(QIntC::to_int(val)); } -void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, - std::string const& color_space, - std::string const& filter) +void +add_page( + QPDFPageDocumentHelper& dh, + QPDFObjectHandle font, + std::string const& color_space, + std::string const& filter) { QPDF& pdf(dh.getQPDF()); @@ -193,9 +191,8 @@ void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, image.replaceDict(image_dict); // Provide the stream data. - image.replaceStreamData(provider, - QPDFObjectHandle::parse(filter), - QPDFObjectHandle::newNull()); + image.replaceStreamData( + provider, QPDFObjectHandle::parse(filter), QPDFObjectHandle::newNull()); // Create direct objects as needed by the page dictionary. QPDFObjectHandle procset = "[/PDF /Text /ImageC]"_qpdf; @@ -212,15 +209,14 @@ void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, resources.replaceKey("/XObject", xobject); // Create the page content stream - QPDFObjectHandle contents = createPageContents( - pdf, color_space + " with filter " + filter); + QPDFObjectHandle contents = + createPageContents(pdf, color_space + " with filter " + filter); // Create the page dictionary - QPDFObjectHandle page = pdf.makeIndirectObject( - "<<" - " /Type /Page" - " /MediaBox [0 0 612 392]" - ">>"_qpdf); + QPDFObjectHandle page = pdf.makeIndirectObject("<<" + " /Type /Page" + " /MediaBox [0 0 612 392]" + ">>"_qpdf); page.replaceKey("/Contents", contents); page.replaceKey("/Resources", resources); @@ -228,9 +224,11 @@ void add_page(QPDFPageDocumentHelper& dh, QPDFObjectHandle font, dh.addPage(page, false); } -static void check(char const* filename, - std::vector const& color_spaces, - std::vector const& filters) +static void +check( + char const* filename, + std::vector const& color_spaces, + std::vector const& filters) { // Each stream is compressed the way it is supposed to be. We will // add additional tests in qpdf.test to exercise QPDFWriter more @@ -253,17 +251,14 @@ static void check(char const* filename, QPDF pdf; pdf.processFile(filename); auto pages = QPDFPageDocumentHelper(pdf).getAllPages(); - if (n_color_spaces * n_filters != pages.size()) - { + if (n_color_spaces * n_filters != pages.size()) { throw std::logic_error("incorrect number of pages"); } size_t pageno = 1; bool errors = false; - for (auto& page : pages) - { + for (auto& page : pages) { auto images = page.getImages(); - if (images.size() != 1) - { + if (images.size() != 1) { throw std::logic_error("incorrect number of images on page"); } @@ -273,8 +268,7 @@ static void check(char const* filename, std::string desired_filter = filters[(pageno - 1) % n_filters]; // In the default mode, QPDFWriter will compress with // /FlateDecode if no filters are provided. - if (desired_filter == "null") - { + if (desired_filter == "null") { desired_filter = "/FlateDecode"; } QPDFObjectHandle image = images.begin()->second; @@ -282,40 +276,34 @@ static void check(char const* filename, QPDFObjectHandle color_space = image_dict.getKey("/ColorSpace"); QPDFObjectHandle filter = image_dict.getKey("/Filter"); bool this_errors = false; - if (! filter.isNameAndEquals(desired_filter)) - { + if (!filter.isNameAndEquals(desired_filter)) { this_errors = errors = true; std::cout << "page " << pageno << ": expected filter " - << desired_filter << "; actual filter = " - << filter.unparse() << std::endl; + << desired_filter + << "; actual filter = " << filter.unparse() << std::endl; } - if (! color_space.isNameAndEquals(desired_color_space)) - { + if (!color_space.isNameAndEquals(desired_color_space)) { this_errors = errors = true; std::cout << "page " << pageno << ": expected color space " - << desired_color_space << "; actual color space = " - << color_space.unparse() << std::endl; + << desired_color_space + << "; actual color space = " << color_space.unparse() + << std::endl; } - if (! this_errors) - { + if (!this_errors) { // Check image data - auto actual_data = - image.getStreamData(qpdf_dl_all); + auto actual_data = image.getStreamData(qpdf_dl_all); ImageProvider* p = new ImageProvider(desired_color_space, "null"); PointerHolder provider(p); Pl_Buffer b_p("get image data"); provider->provideStreamData(0, 0, &b_p); PointerHolder desired_data(b_p.getBuffer()); - if (desired_data->getSize() != actual_data->getSize()) - { - std::cout << "page " << pageno - << ": image data length mismatch" << std::endl; + if (desired_data->getSize() != actual_data->getSize()) { + std::cout << "page " << pageno << ": image data length mismatch" + << std::endl; this_errors = errors = true; - } - else - { + } else { // Compare bytes. For JPEG, allow a certain number of // the bytes to be off desired by more than a given // tolerance. Any of the samples may be a little off @@ -326,25 +314,20 @@ static void check(char const* filename, unsigned char const* desired_bytes = desired_data->getBuffer(); size_t len = actual_data->getSize(); unsigned int mismatches = 0; - int tolerance = ( - desired_filter == "/DCTDecode" ? 10 : 0); - size_t threshold = ( - desired_filter == "/DCTDecode" ? len / 40U : 0); - for (size_t i = 0; i < len; ++i) - { + int tolerance = (desired_filter == "/DCTDecode" ? 10 : 0); + size_t threshold = + (desired_filter == "/DCTDecode" ? len / 40U : 0); + for (size_t i = 0; i < len; ++i) { int delta = actual_bytes[i] - desired_bytes[i]; - if ((delta > tolerance) || (delta < -tolerance)) - { + if ((delta > tolerance) || (delta < -tolerance)) { ++mismatches; } } - if (mismatches > threshold) - { - std::cout << "page " << pageno - << ": " << desired_color_space << ", " - << desired_filter - << ": mismatches: " << mismatches - << " of " << len << std::endl; + if (mismatches > threshold) { + std::cout << "page " << pageno << ": " + << desired_color_space << ", " << desired_filter + << ": mismatches: " << mismatches << " of " << len + << std::endl; this_errors = errors = true; } } @@ -352,17 +335,15 @@ static void check(char const* filename, ++pageno; } - if (errors) - { + if (errors) { throw std::logic_error("errors found"); - } - else - { + } else { std::cout << "all checks passed" << std::endl; } } -static void create_pdf(char const* filename) +static void +create_pdf(char const* filename) { QPDF pdf; @@ -371,14 +352,13 @@ static void create_pdf(char const* filename) // Add an indirect object to contain a font descriptor for the // built-in Helvetica font. - QPDFObjectHandle font = pdf.makeIndirectObject( - "<<" - " /Type /Font" - " /Subtype /Type1" - " /Name /F1" - " /BaseFont /Helvetica" - " /Encoding /WinAnsiEncoding" - ">>"_qpdf); + QPDFObjectHandle font = pdf.makeIndirectObject("<<" + " /Type /Font" + " /Subtype /Type1" + " /Name /F1" + " /BaseFont /Helvetica" + " /Encoding /WinAnsiEncoding" + ">>"_qpdf); std::vector color_spaces; color_spaces.push_back("/DeviceCMYK"); @@ -389,10 +369,8 @@ static void create_pdf(char const* filename) filters.push_back("/DCTDecode"); filters.push_back("/RunLengthDecode"); QPDFPageDocumentHelper dh(pdf); - for (auto const& color_space : color_spaces) - { - for (auto const& filter : filters) - { + for (auto const& color_space : color_spaces) { + for (auto const& filter : filters) { add_page(dh, font, color_space, filter); } } @@ -405,22 +383,19 @@ static void create_pdf(char const* filename) check(filename, color_spaces, filters); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 2) - { + if (argc != 2) { usage(); } char const* filename = argv[1]; - try - { + try { create_pdf(filename); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-custom-filter.cc b/examples/pdf-custom-filter.cc index b986cfcc..b6d88684 100644 --- a/examples/pdf-custom-filter.cc +++ b/examples/pdf-custom-filter.cc @@ -1,7 +1,7 @@ #include -#include -#include #include +#include +#include #include #include @@ -39,7 +39,6 @@ static char const* whoami = 0; - class Pl_XOR: public Pipeline { // This class implements a Pipeline for the made-up XOR decoder. @@ -66,8 +65,7 @@ Pl_XOR::Pl_XOR(char const* identifier, Pipeline* next, unsigned char key) : void Pl_XOR::write(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { unsigned char p = data[i] ^ this->key; getNext()->write(&p, 1); } @@ -118,8 +116,7 @@ SF_XORDecode::setDecodeParms(QPDFObjectHandle decode_parms) // to handle the /JBIG2Globals key, which points to a stream. See // comments in SF_XORDecode::registerStream for additional notes // on this. - try - { + try { // Expect /DecodeParms to be a dictionary with a /KeyStream // key that points to a one-byte stream whose single byte is // the key. If we are successful at retrieving the key, return @@ -129,17 +126,14 @@ SF_XORDecode::setDecodeParms(QPDFObjectHandle decode_parms) // implementations, look at the classes whose names start with // SF_ in the qpdf library implementation. auto buf = decode_parms.getKey("/KeyStream").getStreamData(); - if (buf->getSize() != 1) - { + if (buf->getSize() != 1) { return false; } this->key = buf->getBuffer()[0]; return true; - } - catch (std::exception& e) - { - std::cerr << "Error extracting key for /XORDecode: " - << e.what() << std::endl; + } catch (std::exception& e) { + std::cerr << "Error extracting key for /XORDecode: " << e.what() + << std::endl; } return false; } @@ -206,17 +200,19 @@ class StreamReplacer: public QPDFObjectHandle::StreamDataProvider public: StreamReplacer(QPDF* pdf); virtual ~StreamReplacer() = default; - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline) override; + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline) override; void registerStream( QPDFObjectHandle stream, PointerHolder self); private: - bool maybeReplace(QPDFObjGen const& og, - QPDFObjectHandle& stream, Pipeline* pipeline, - QPDFObjectHandle* dict_updates); + bool maybeReplace( + QPDFObjGen const& og, + QPDFObjectHandle& stream, + Pipeline* pipeline, + QPDFObjectHandle* dict_updates); // Hang onto a reference to the QPDF object containing the streams // we are replacing. We need this to create a new stream. @@ -238,10 +234,11 @@ StreamReplacer::StreamReplacer(QPDF* pdf) : } bool -StreamReplacer::maybeReplace(QPDFObjGen const& og, - QPDFObjectHandle& stream, - Pipeline* pipeline, - QPDFObjectHandle* dict_updates) +StreamReplacer::maybeReplace( + QPDFObjGen const& og, + QPDFObjectHandle& stream, + Pipeline* pipeline, + QPDFObjectHandle* dict_updates) { // As described in the class comments, this method is called // twice. Before writing has started pipeline is nullptr, and @@ -276,8 +273,7 @@ StreamReplacer::maybeReplace(QPDFObjGen const& og, // density. auto dict = stream.getDict(); auto mark = dict.getKey("/DoXOR"); - if (! (mark.isBool() && mark.getBoolValue())) - { + if (!(mark.isBool() && mark.getBoolValue())) { return false; } @@ -288,17 +284,13 @@ StreamReplacer::maybeReplace(QPDFObjGen const& og, // it's a good idea to make sure we can retrieve the filtered data // if we are going to need it later. PointerHolder out; - try - { + try { out = stream.getStreamData(); - } - catch (...) - { + } catch (...) { return false; } - if (dict_updates) - { + if (dict_updates) { // It's not safe to make any modifications to any objects // during the writing process since the updated objects may // have already been written. In this mode, when dict_updates @@ -309,16 +301,15 @@ StreamReplacer::maybeReplace(QPDFObjGen const& og, // changes. For example, an image resampler might change the // dimensions or other properties of the image. dict_updates->replaceKey( - "/OrigLength", QPDFObjectHandle::newInteger( - QIntC::to_longlong(out->getSize()))); + "/OrigLength", + QPDFObjectHandle::newInteger(QIntC::to_longlong(out->getSize()))); // We are also storing the "key" that we will access when // writing the data. this->keys[og] = QIntC::to_uchar( (og.getObj() * QIntC::to_int(out->getSize())) & 0xff); } - if (pipeline) - { + if (pipeline) { unsigned char key = this->keys[og]; Pl_XOR p("xor", pipeline, key); p.write(out->getBuffer(), out->getSize()); @@ -338,8 +329,7 @@ StreamReplacer::registerStream( // example, we are just iterating through objects, but if we were // doing something like iterating through images on pages, we // might realistically encounter the same stream more than once. - if (this->copied_streams.count(og) > 0) - { + if (this->copied_streams.count(og) > 0) { return; } // Store something in copied_streams so that we don't @@ -352,19 +342,14 @@ StreamReplacer::registerStream( // so, supplies dictionary updates we should make. bool should_replace = false; QPDFObjectHandle dict_updates = QPDFObjectHandle::newDictionary(); - try - { + try { should_replace = maybeReplace(og, stream, nullptr, &dict_updates); - } - catch (std::exception& e) - { + } catch (std::exception& e) { stream.warnIfPossible( - std::string("exception while attempting to replace: ") + - e.what()); + std::string("exception while attempting to replace: ") + e.what()); } - if (should_replace) - { + if (should_replace) { // Copy the stream so we can get to the original data from the // stream data provider. This doesn't actually copy any data, // but the copy retains the original stream data after the @@ -372,14 +357,13 @@ StreamReplacer::registerStream( this->copied_streams[og] = stream.copyStream(); // Update the stream dictionary with any changes. auto dict = stream.getDict(); - for (auto const& k: dict_updates.getKeys()) - { + for (auto const& k : dict_updates.getKeys()) { dict.replaceKey(k, dict_updates.getKey(k)); } // Create the key stream that will be referenced from // /DecodeParms. We have to do this now since you can't modify // or create objects during write. - char p[1] = { static_cast(this->keys[og]) }; + char p[1] = {static_cast(this->keys[og])}; std::string p_str(p, 1); QPDFObjectHandle dp_stream = QPDFObjectHandle::newStream(this->pdf, p_str); @@ -388,23 +372,19 @@ StreamReplacer::registerStream( QPDFObjectHandle decode_parms = QPDFObjectHandle::newDictionary({{"/KeyStream", dp_stream}}); stream.replaceStreamData( - self, - QPDFObjectHandle::newName("/XORDecode"), - decode_parms); + self, QPDFObjectHandle::newName("/XORDecode"), decode_parms); // Further, if /ProtectXOR = true, we disable filtering on write // so that QPDFWriter will not decode the stream even though we // have registered a stream filter for /XORDecode. auto protect = dict.getKey("/ProtectXOR"); - if (protect.isBool() && protect.getBoolValue()) - { + if (protect.isBool() && protect.getBoolValue()) { stream.setFilterOnWrite(false); } } } void -StreamReplacer::provideStreamData(int objid, int generation, - Pipeline* pipeline) +StreamReplacer::provideStreamData(int objid, int generation, Pipeline* pipeline) { QPDFObjGen og(objid, generation); QPDFObjectHandle orig = this->copied_streams[og]; @@ -412,8 +392,7 @@ StreamReplacer::provideStreamData(int objid, int generation, // dict_updates. In this mode, maybeReplace doesn't make any // changes. We have to hand it the original stream data, which we // get from copied_streams. - if (! maybeReplace(og, orig, pipeline, nullptr)) - { + if (!maybeReplace(og, orig, pipeline, nullptr)) { // Since this only gets called for streams we already // determined we are replacing, a false return would indicate // a logic error. @@ -422,8 +401,9 @@ StreamReplacer::provideStreamData(int objid, int generation, } } -static void process(char const* infilename, char const* outfilename, - bool decode_specialized) +static void +process( + char const* infilename, char const* outfilename, bool decode_specialized) { QPDF qpdf; qpdf.processFile(infilename); @@ -434,10 +414,8 @@ static void process(char const* infilename, char const* outfilename, StreamReplacer* replacer = new StreamReplacer(&qpdf); PointerHolder p(replacer); - for (auto& o: qpdf.getAllObjects()) - { - if (o.isStream()) - { + for (auto& o : qpdf.getAllObjects()) { + if (o.isStream()) { // Call registerStream for every stream. Only ones that // registerStream decides to replace will actually be // replaced. @@ -446,70 +424,58 @@ static void process(char const* infilename, char const* outfilename, } QPDFWriter w(qpdf, outfilename); - if (decode_specialized) - { + if (decode_specialized) { w.setDecodeLevel(qpdf_dl_specialized); } // For the test suite, use static IDs. w.setStaticID(true); // for testing only w.write(); - std::cout << whoami << ": new file written to " << outfilename - << std::endl; + std::cout << whoami << ": new file written to " << outfilename << std::endl; } -static void usage() +static void +usage() { - std::cerr - << "\n" - << "Usage: " << whoami << " [--decode-specialized] infile outfile\n" - << std::endl; + std::cerr << "\n" + << "Usage: " << whoami + << " [--decode-specialized] infile outfile\n" + << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); char const* infilename = 0; char const* outfilename = 0; bool decode_specialized = false; - for (int i = 1; i < argc; ++i) - { - if (strcmp(argv[i], "--decode-specialized") == 0) - { + for (int i = 1; i < argc; ++i) { + if (strcmp(argv[i], "--decode-specialized") == 0) { decode_specialized = true; - } - else if (! infilename) - { + } else if (!infilename) { infilename = argv[i]; - } - else if (! outfilename) - { + } else if (!outfilename) { outfilename = argv[i]; - } - else - { + } else { usage(); } } - if (! (infilename && outfilename)) - { + if (!(infilename && outfilename)) { usage(); } - try - { + try { // Register our fictitious filter. This enables QPDFWriter to // decode our streams. This is not a real filter, so no real // PDF reading application would be able to interpret it. This // is just for illustrative purposes. QPDF::registerStreamFilter( - "/XORDecode", []{ return std::make_shared(); }); + "/XORDecode", [] { return std::make_shared(); }); // Do the actual processing. process(infilename, outfilename, decode_specialized); - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << ": exception: " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-double-page-size.cc b/examples/pdf-double-page-size.cc index a2f79301..37e07ff8 100644 --- a/examples/pdf-double-page-size.cc +++ b/examples/pdf-double-page-size.cc @@ -1,16 +1,17 @@ -#include -#include -#include +#include #include #include #include -#include -#include #include +#include +#include +#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]" << std::endl @@ -21,45 +22,43 @@ void usage() // If there is a box of name box_name, replace it with a new box whose // elements are double the values of the original box. -static void doubleBoxSize(QPDFPageObjectHelper& page, char const* box_name) +static void +doubleBoxSize(QPDFPageObjectHelper& page, char const* box_name) { // We need to use getAttribute rather than getKey as some boxes could // be inherited. auto box = page.getAttribute(box_name, true); - if (box.isNull()) - { + if (box.isNull()) { return; } - if (! box.isRectangle()) - { - throw std::runtime_error(std::string("box ") + box_name + - " is not an array of four elements"); + if (!box.isRectangle()) { + throw std::runtime_error( + std::string("box ") + box_name + + " is not an array of four elements"); } std::vector doubled; - for (auto& item : box.aitems()) - { + for (auto& item : box.aitems()) { doubled.push_back( QPDFObjectHandle::newReal(item.getNumericValue() * 2.0, 2)); } - page.getObjectHandle() - .replaceKey(box_name, QPDFObjectHandle::newArray(doubled)); + page.getObjectHandle().replaceKey( + box_name, QPDFObjectHandle::newArray(doubled)); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); // For test suite bool static_id = false; - if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) - { + if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) { static_id = true; --argc; ++argv; } - if (! ((argc == 3) || (argc == 4))) - { + if (!((argc == 3) || (argc == 4))) { usage(); } @@ -70,13 +69,11 @@ int main(int argc, char* argv[]) // Text to prepend to each page's contents std::string content = "2 0 0 2 0 0 cm\n"; - try - { + try { QPDF qpdf; qpdf.processFile(infilename, password); - for (auto& page : QPDFPageDocumentHelper(qpdf).getAllPages()) - { + for (auto& page : QPDFPageDocumentHelper(qpdf).getAllPages()) { // Prepend the buffer to the page's contents page.addPageContents( QPDFObjectHandle::newStream(&qpdf, content), true); @@ -91,8 +88,7 @@ int main(int argc, char* argv[]) // Write out a new file QPDFWriter w(qpdf, outfilename); - if (static_id) - { + if (static_id) { // For the test suite, uncompress streams and use static IDs. w.setStaticID(true); // for testing only w.setStreamDataMode(qpdf_s_uncompress); @@ -100,9 +96,7 @@ int main(int argc, char* argv[]) w.write(); std::cout << whoami << ": new file written to " << outfilename << std::endl; - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; exit(2); diff --git a/examples/pdf-filter-tokens.cc b/examples/pdf-filter-tokens.cc index 02c3829e..39950752 100644 --- a/examples/pdf-filter-tokens.cc +++ b/examples/pdf-filter-tokens.cc @@ -5,22 +5,23 @@ // QPDFObjectHandle::TokenFilter with filterContents. // -#include -#include -#include #include #include +#include +#include +#include #include +#include #include #include -#include #include -#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile outfile" << std::endl << "Applies token filters to infile and writes outfile" @@ -52,14 +53,11 @@ StringReverser::handleToken(QPDFTokenizer::Token const& token) // strings. It's just intended to give a simple example of a // pretty minimal filter and to show an example of writing a // constructed token. - if (token.getType() == QPDFTokenizer::tt_string) - { + if (token.getType() == QPDFTokenizer::tt_string) { std::string value = token.getValue(); std::reverse(value.begin(), value.end()); writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_string, value)); - } - else - { + } else { writeToken(token); } } @@ -90,15 +88,17 @@ class ColorToGray: public QPDFObjectHandle::TokenFilter bool ColorToGray::isNumeric(QPDFTokenizer::token_type_e token_type) { - return ((token_type == QPDFTokenizer::tt_integer) || - (token_type == QPDFTokenizer::tt_real)); + return ( + (token_type == QPDFTokenizer::tt_integer) || + (token_type == QPDFTokenizer::tt_real)); } bool ColorToGray::isIgnorable(QPDFTokenizer::token_type_e token_type) { - return ((token_type == QPDFTokenizer::tt_space) || - (token_type == QPDFTokenizer::tt_comment)); + return ( + (token_type == QPDFTokenizer::tt_space) || + (token_type == QPDFTokenizer::tt_comment)); } double @@ -134,33 +134,28 @@ ColorToGray::handleToken(QPDFTokenizer::Token const& token) // kinds of operands, replace the command. Flush any additional // accumulated tokens to keep the stack only four tokens deep. - while ((! this->all_stack.empty()) && - isIgnorable(this->all_stack.at(0).getType())) - { + while ((!this->all_stack.empty()) && + isIgnorable(this->all_stack.at(0).getType())) { writeToken(this->all_stack.at(0)); this->all_stack.pop_front(); } this->all_stack.push_back(token); QPDFTokenizer::token_type_e token_type = token.getType(); - if (! isIgnorable(token_type)) - { + if (!isIgnorable(token_type)) { this->stack.push_back(token); if ((this->stack.size() == 4) && (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "rg")) && (isNumeric(this->stack.at(0).getType())) && (isNumeric(this->stack.at(1).getType())) && - (isNumeric(this->stack.at(2).getType()))) - { + (isNumeric(this->stack.at(2).getType()))) { double r = numericValue(this->stack.at(0)); double g = numericValue(this->stack.at(1)); double b = numericValue(this->stack.at(2)); double gray = ((0.3 * r) + (0.59 * b) + (0.11 * g)); - if (gray > 1.0) - { + if (gray > 1.0) { gray = 1.0; } - if (gray < 0.0) - { + if (gray < 0.0) { gray = 0.0; } write(QUtil::double_to_string(gray, 3)); @@ -169,8 +164,7 @@ ColorToGray::handleToken(QPDFTokenizer::Token const& token) this->all_stack.clear(); } } - if (this->stack.size() == 4) - { + if (this->stack.size() == 4) { writeToken(this->all_stack.at(0)); this->all_stack.pop_front(); this->stack.pop_front(); @@ -181,33 +175,31 @@ void ColorToGray::handleEOF() { // Flush out any remaining accumulated tokens. - while (! this->all_stack.empty()) - { + while (!this->all_stack.empty()) { writeToken(this->all_stack.at(0)); this->all_stack.pop_front(); } } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 3) - { + if (argc != 3) { usage(); } char const* infilename = argv[1]; char const* outfilename = argv[2]; - try - { + try { QPDF pdf; pdf.processFile(infilename); std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { // Attach two token filters to each page of this file. // When the file is written, or when the pages' contents // are retrieved in any other way, the filters will be @@ -222,11 +214,9 @@ int main(int argc, char* argv[]) } QPDFWriter w(pdf, outfilename); - w.setStaticID(true); // for testing only + w.setStaticID(true); // for testing only w.write(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-invert-images.cc b/examples/pdf-invert-images.cc index def1dd19..df9e7362 100644 --- a/examples/pdf-invert-images.cc +++ b/examples/pdf-invert-images.cc @@ -1,17 +1,18 @@ -#include -#include -#include +#include +#include #include #include #include -#include -#include #include -#include +#include +#include +#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf [in-password]" << std::endl @@ -35,8 +36,8 @@ class ImageInverter: public QPDFObjectHandle::StreamDataProvider virtual ~ImageInverter() { } - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline) override; + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline) override; void registerImage( QPDFObjectHandle image, @@ -64,8 +65,7 @@ ImageInverter::registerImage( // generation number. Recall that a single image object may be // used more than once, so no need to update the same stream // multiple times. - if (this->copied_images.count(og) > 0) - { + if (this->copied_images.count(og) > 0) { return; } this->copied_images[og] = image.copyStream(); @@ -79,14 +79,12 @@ ImageInverter::registerImage( // filterable in the input QPDF object, so we don't have to deal // with it explicitly here. We could explicitly use /DCTDecode and // write through a DCT filter if we wanted. - image.replaceStreamData(self, - QPDFObjectHandle::newNull(), - QPDFObjectHandle::newNull()); + image.replaceStreamData( + self, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); } void -ImageInverter::provideStreamData(int objid, int generation, - Pipeline* pipeline) +ImageInverter::provideStreamData(int objid, int generation, Pipeline* pipeline) { // Use the object and generation number supplied to look up the // image data. Then invert the image data and write the inverted @@ -97,29 +95,27 @@ ImageInverter::provideStreamData(int objid, int generation, size_t size = data->getSize(); unsigned char* buf = data->getBuffer(); unsigned char ch; - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { ch = QIntC::to_uchar(0xff - buf[i]); pipeline->write(&ch, 1); } pipeline->finish(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); // For test suite bool static_id = false; - if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) - { + if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) { static_id = true; --argc; ++argv; } - if (! ((argc == 3) || (argc == 4))) - { + if (!((argc == 3) || (argc == 4))) { usage(); } @@ -127,8 +123,7 @@ int main(int argc, char* argv[]) char const* outfilename = argv[2]; char const* password = (argc == 4) ? argv[3] : ""; - try - { + try { QPDF qpdf; qpdf.processFile(infilename, password); @@ -139,18 +134,15 @@ int main(int argc, char* argv[]) std::vector pages = QPDFPageDocumentHelper(qpdf).getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); // Get all images on the page. - std::map images = - page.getImages(); - for (auto& iter2: images) - { + std::map images = page.getImages(); + for (auto& iter2 : images) { QPDFObjectHandle& image = iter2.second; QPDFObjectHandle image_dict = image.getDict(); - QPDFObjectHandle color_space = - image_dict.getKey("/ColorSpace"); + QPDFObjectHandle color_space = image_dict.getKey("/ColorSpace"); QPDFObjectHandle bits_per_component = image_dict.getKey("/BitsPerComponent"); @@ -159,12 +151,10 @@ int main(int argc, char* argv[]) // pipeStreamData with a null pipeline to determine // whether the image is filterable. Directly inspect // keys to determine the image type. - if (image.pipeStreamData(0, qpdf_ef_compress, - qpdf_dl_all) && + if (image.pipeStreamData(0, qpdf_ef_compress, qpdf_dl_all) && color_space.isNameAndEquals("/DeviceGray") && bits_per_component.isInteger() && - (bits_per_component.getIntValue() == 8)) - { + (bits_per_component.getIntValue() == 8)) { inv->registerImage(image, p); } } @@ -172,8 +162,7 @@ int main(int argc, char* argv[]) // Write out a new file QPDFWriter w(qpdf, outfilename); - if (static_id) - { + if (static_id) { // For the test suite, uncompress streams and use static // IDs. w.setStaticID(true); // for testing only @@ -181,9 +170,7 @@ int main(int argc, char* argv[]) w.write(); std::cout << whoami << ": new file written to " << outfilename << std::endl; - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; exit(2); diff --git a/examples/pdf-linearize.c b/examples/pdf-linearize.c index 2b099066..f972fa71 100644 --- a/examples/pdf-linearize.c +++ b/examples/pdf-linearize.c @@ -9,18 +9,21 @@ static char const* whoami = 0; -static void usage() +static void +usage() { fprintf(stderr, "Usage: %s infile infile-password outfile\n", whoami); exit(2); } -static void write_progress(int percent, void* data) +static void +write_progress(int percent, void* data) { printf("%s progress: %d%%\n", (char const*)(data), percent); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { char* infile = NULL; char* password = NULL; @@ -30,21 +33,15 @@ int main(int argc, char* argv[]) int errors = 0; char* p = 0; - if ((p = strrchr(argv[0], '/')) != NULL) - { + if ((p = strrchr(argv[0], '/')) != NULL) { whoami = p + 1; - } - else if ((p = strrchr(argv[0], '\\')) != NULL) - { + } else if ((p = strrchr(argv[0], '\\')) != NULL) { whoami = p + 1; - } - else - { + } else { whoami = argv[0]; } - if (argc != 4) - { + if (argc != 4) { usage(); } @@ -53,8 +50,7 @@ int main(int argc, char* argv[]) outfile = argv[3]; if (((qpdf_read(qpdf, infile, password) & QPDF_ERRORS) == 0) && - ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) - { + ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) { /* Use static ID for testing only. For production, a * non-static ID is used. See also * qpdf_set_deterministic_ID. */ @@ -63,25 +59,22 @@ int main(int argc, char* argv[]) qpdf_register_progress_reporter(qpdf, write_progress, infile); qpdf_write(qpdf); } - while (qpdf_more_warnings(qpdf)) - { + while (qpdf_more_warnings(qpdf)) { warnings = 1; - printf("warning: %s\n", - qpdf_get_error_full_text(qpdf, qpdf_next_warning(qpdf))); + printf( + "warning: %s\n", + qpdf_get_error_full_text(qpdf, qpdf_next_warning(qpdf))); } - if (qpdf_has_error(qpdf)) - { + if (qpdf_has_error(qpdf)) { errors = 1; - printf("error: %s\n", - qpdf_get_error_full_text(qpdf, qpdf_get_error(qpdf))); + printf( + "error: %s\n", + qpdf_get_error_full_text(qpdf, qpdf_get_error(qpdf))); } qpdf_cleanup(&qpdf); - if (errors) - { + if (errors) { return 2; - } - else if (warnings) - { + } else if (warnings) { return 3; } diff --git a/examples/pdf-mod-info.cc b/examples/pdf-mod-info.cc index 4ee4cdd0..8666474f 100644 --- a/examples/pdf-mod-info.cc +++ b/examples/pdf-mod-info.cc @@ -1,49 +1,43 @@ // Author: Vitaliy Pavlyuk #include -#include #include -#include +#include #include +#include #include -#include -#include #include +#include +#include static char const* version = "1.1"; static char const* whoami = 0; -void usage() +void +usage() { - std::cerr - << "Usage: " << whoami - << " --in in_file [--out out_file] [--key key [--val val]?]+\n" - << "Modifies/Adds/Removes PDF /Info entries in the in_file\n" - << "and stores the result in out_file\n" - << "Special mode: " << whoami << " --dump file\n" - << "dumps all /Info entries to stdout\n"; + std::cerr << "Usage: " << whoami + << " --in in_file [--out out_file] [--key key [--val val]?]+\n" + << "Modifies/Adds/Removes PDF /Info entries in the in_file\n" + << "and stores the result in out_file\n" + << "Special mode: " << whoami << " --dump file\n" + << "dumps all /Info entries to stdout\n"; exit(2); } -void dumpInfoDict(QPDF& pdf, - std::ostream& os = std::cout, - std::string const& sep = ":\t") +void +dumpInfoDict( + QPDF& pdf, std::ostream& os = std::cout, std::string const& sep = ":\t") { QPDFObjectHandle trailer = pdf.getTrailer(); - if (trailer.hasKey("/Info")) - { - for (auto& it: trailer.getKey("/Info").ditems()) - { + if (trailer.hasKey("/Info")) { + for (auto& it : trailer.getKey("/Info").ditems()) { std::string val; - if (it.second.isString()) - { + if (it.second.isString()) { val = it.second.getStringValue(); - } - else if (it.second.isName()) - { + } else if (it.second.isName()) { val = it.second.getName(); - } - else // according to PDF Spec 1.5, shouldn't happen + } else // according to PDF Spec 1.5, shouldn't happen { val = it.second.unparseResolved(); } @@ -52,36 +46,32 @@ void dumpInfoDict(QPDF& pdf, } } -void pdfDumpInfoDict(char const* fname) +void +pdfDumpInfoDict(char const* fname) { - try - { + try { QPDF pdf; pdf.processFile(fname); dumpInfoDict(pdf); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - bool static_id = false; std::map Keys; whoami = QUtil::getWhoami(argv[0]); - if ((argc == 2) && (! strcmp(argv[1], "--version")) ) - { + if ((argc == 2) && (!strcmp(argv[1], "--version"))) { std::cout << whoami << " version " << version << std::endl; exit(0); } - if ((argc == 3) && (! strcmp(argv[1], "--dump"))) - { + if ((argc == 3) && (!strcmp(argv[1], "--dump"))) { QTC::TC("examples", "pdf-mod-info --dump"); pdfDumpInfoDict(argv[2]); exit(0); @@ -91,59 +81,43 @@ int main(int argc, char* argv[]) char* fl_out = 0; std::string cur_key; - for (int i = 1; i < argc; ++i) - { - if ((! strcmp(argv[i], "--in")) && (++i < argc)) - { + for (int i = 1; i < argc; ++i) { + if ((!strcmp(argv[i], "--in")) && (++i < argc)) { fl_in = argv[i]; - } - else if ((! strcmp(argv[i], "--out")) && (++i < argc)) - { + } else if ((!strcmp(argv[i], "--out")) && (++i < argc)) { fl_out = argv[i]; - } - else if (! strcmp(argv[i], "--static-id")) // don't document + } else if (!strcmp(argv[i], "--static-id")) // don't document { static_id = true; // this should be used in test suites only - } - else if ((! strcmp(argv[i], "--key")) && (++i < argc)) - { + } else if ((!strcmp(argv[i], "--key")) && (++i < argc)) { QTC::TC("examples", "pdf-mod-info -key"); cur_key = argv[i]; - if (! ((cur_key.length() > 0) && (cur_key.at(0) == '/'))) - { + if (!((cur_key.length() > 0) && (cur_key.at(0) == '/'))) { cur_key = "/" + cur_key; } Keys[cur_key] = ""; - } - else if ((! strcmp(argv[i], "--val")) && (++i < argc)) - { - if (cur_key.empty()) - { + } else if ((!strcmp(argv[i], "--val")) && (++i < argc)) { + if (cur_key.empty()) { QTC::TC("examples", "pdf-mod-info usage wrong val"); usage(); } QTC::TC("examples", "pdf-mod-info -val"); Keys[cur_key] = argv[i]; cur_key.clear(); - } - else - { + } else { QTC::TC("examples", "pdf-mod-info usage junk"); usage(); } } - if (! fl_in) - { + if (!fl_in) { QTC::TC("examples", "pdf-mod-info no in file"); usage(); } - if (! fl_out) - { + if (!fl_out) { QTC::TC("examples", "pdf-mod-info in-place"); fl_out = fl_in; } - if (Keys.size() == 0) - { + if (Keys.size() == 0) { QTC::TC("examples", "pdf-mod-info no keys"); usage(); } @@ -151,8 +125,7 @@ int main(int argc, char* argv[]) std::string fl_tmp = fl_out; fl_tmp += ".tmp"; - try - { + try { QPDF file; file.processFile(fl_in); @@ -160,28 +133,22 @@ int main(int argc, char* argv[]) QPDFObjectHandle fileinfo; for (std::map::const_iterator it = - Keys.begin(); Keys.end() != it; ++it) - { - if (! fileinfo.isInitialized()) - { - if (filetrailer.hasKey("/Info")) - { + Keys.begin(); + Keys.end() != it; + ++it) { + if (!fileinfo.isInitialized()) { + if (filetrailer.hasKey("/Info")) { QTC::TC("examples", "pdf-mod-info has info"); fileinfo = filetrailer.getKey("/Info"); - } - else - { + } else { QTC::TC("examples", "pdf-mod-info file no info"); fileinfo = QPDFObjectHandle::newDictionary(); filetrailer.replaceKey("/Info", fileinfo); } } - if (it->second == "") - { + if (it->second == "") { fileinfo.removeKey(it->first); - } - else - { + } else { QPDFObjectHandle elt = fileinfo.newString(it->second); elt.makeDirect(); fileinfo.replaceKey(it->first, elt); @@ -192,21 +159,17 @@ int main(int argc, char* argv[]) w.setLinearization(true); w.setStaticID(static_id); // for testing only w.write(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } - try - { - (void) remove(fl_out); - QUtil::os_wrapper("rename " + fl_tmp + " " + std::string(fl_out), - rename(fl_tmp.c_str(), fl_out)); - } - catch (std::exception& e) - { + try { + (void)remove(fl_out); + QUtil::os_wrapper( + "rename " + fl_tmp + " " + std::string(fl_out), + rename(fl_tmp.c_str(), fl_out)); + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-name-number-tree.cc b/examples/pdf-name-number-tree.cc index d8bb233e..347bfb69 100644 --- a/examples/pdf-name-number-tree.cc +++ b/examples/pdf-name-number-tree.cc @@ -3,26 +3,26 @@ #include #include #include -#include #include +#include static char const* whoami = 0; -void usage() +void +usage() { - std::cerr << "Usage: " << whoami << " outfile.pdf" - << std::endl + std::cerr << "Usage: " << whoami << " outfile.pdf" << std::endl << "Create some name/number trees and write to a file" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 2) - { + if (argc != 2) { usage(); } @@ -62,8 +62,8 @@ int main(int argc, char* argv[]) name_tree.insert("R", QPDFObjectHandle::newUnicodeString("rook")); name_tree.insert("B", QPDFObjectHandle::newUnicodeString("bishop")); name_tree.insert("N", QPDFObjectHandle::newUnicodeString("knight")); - auto iter = name_tree.insert( - "P", QPDFObjectHandle::newUnicodeString("pawn")); + auto iter = + name_tree.insert("P", QPDFObjectHandle::newUnicodeString("pawn")); // Look at the iterator std::cout << "just inserted " << iter->first << " -> " << iter->second.unparse() << std::endl; @@ -77,28 +77,24 @@ int main(int argc, char* argv[]) // Use range-for iteration std::cout << "Name tree items:" << std::endl; - for (auto i: name_tree) - { - std::cout << " " << i.first << " -> " - << i.second.unparse() << std::endl; + for (auto i : name_tree) { + std::cout << " " << i.first << " -> " << i.second.unparse() + << std::endl; } // This is a small tree, so everything will be at the root. We can // look at it using dictionary and array iterators. std::cout << "Keys in name tree object:" << std::endl; QPDFObjectHandle names; - for (auto const& i: name_tree_oh.ditems()) - { + for (auto const& i : name_tree_oh.ditems()) { std::cout << i.first << std::endl; - if (i.first == "/Names") - { + if (i.first == "/Names") { names = i.second; } } // Values in names array: std::cout << "Values in names:" << std::endl; - for (auto& i: names.aitems()) - { + for (auto& i : names.aitems()) { std::cout << " " << i.unparse() << std::endl; } @@ -112,8 +108,8 @@ int main(int argc, char* argv[]) // 10.2 API iter = name_tree.find("Q"); - std::cout << "Q: " << iter->first << " -> " - << iter->second.unparse() << std::endl; + std::cout << "Q: " << iter->first << " -> " << iter->second.unparse() + << std::endl; iter = name_tree.find("W"); std::cout << "W found: " << (iter != name_tree.end()) << std::endl; // Allow find to return predecessor @@ -146,22 +142,18 @@ int main(int argc, char* argv[]) auto number_tree_oh = number_tree.getObjectHandle(); example.replaceKey("/NumberTree", number_tree_oh); auto iter2 = number_tree.begin(); - for (int i = 7; i <= 350; i += 7) - { - iter2.insertAfter(i, QPDFObjectHandle::newString( - "-" + QUtil::int_to_string(i) + "-")); + for (int i = 7; i <= 350; i += 7) { + iter2.insertAfter( + i, + QPDFObjectHandle::newString("-" + QUtil::int_to_string(i) + "-")); } std::cout << "Numbers:" << std::endl; int n = 1; - for (auto& i: number_tree) - { + for (auto& i : number_tree) { std::cout << i.first << " -> " << i.second.getUTF8Value(); - if (n % 5) - { + if (n % 5) { std::cout << ", "; - } - else - { + } else { std::cout << std::endl; } ++n; @@ -171,28 +163,20 @@ int main(int argc, char* argv[]) // advances. This makes it possible to filter while iterating. // Remove all items that are multiples of 5. iter2 = number_tree.begin(); - while (iter2 != number_tree.end()) - { - if (iter2->first % 5 == 0) - { - iter2.remove(); // also advances - } - else - { + while (iter2 != number_tree.end()) { + if (iter2->first % 5 == 0) { + iter2.remove(); // also advances + } else { ++iter2; } } std::cout << "Numbers after filtering:" << std::endl; n = 1; - for (auto& i: number_tree) - { + for (auto& i : number_tree) { std::cout << i.first << " -> " << i.second.getUTF8Value(); - if (n % 5) - { + if (n % 5) { std::cout << ", "; - } - else - { + } else { std::cout << std::endl; } ++n; diff --git a/examples/pdf-npages.cc b/examples/pdf-npages.cc index 93378c71..f430935c 100644 --- a/examples/pdf-npages.cc +++ b/examples/pdf-npages.cc @@ -1,46 +1,43 @@ #include -#include #include +#include #include #include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " filename" << std::endl << "Prints the number of pages in filename" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { std::cout << whoami << " version 1.3" << std::endl; exit(0); } - if (argc != 2) - { + if (argc != 2) { usage(); } char const* filename = argv[1]; - try - { + try { QPDF pdf; pdf.processFile(filename); QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle pages = root.getKey("/Pages"); QPDFObjectHandle count = pages.getKey("/Count"); std::cout << count.getIntValue() << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-overlay-page.cc b/examples/pdf-overlay-page.cc index 5d5468f1..64a8d48f 100644 --- a/examples/pdf-overlay-page.cc +++ b/examples/pdf-overlay-page.cc @@ -1,11 +1,11 @@ -#include -#include -#include #include #include #include #include #include +#include +#include +#include // This program demonstrates use of form XObjects to overlay a page // from one file onto all pages of another file. The qpdf program's @@ -14,19 +14,17 @@ static char const* whoami = 0; -void usage() +void +usage() { - std::cerr << "Usage: " << whoami << " infile pagefile outfile" - << std::endl + std::cerr << "Usage: " << whoami << " infile pagefile outfile" << std::endl << "Stamp page 1 of pagefile on every page of infile," - << " writing to outfile" - << std::endl; + << " writing to outfile" << std::endl; exit(2); } -static void stamp_page(char const* infile, - char const* stampfile, - char const* outfile) +static void +stamp_page(char const* infile, char const* stampfile, char const* outfile) { QPDF inpdf; inpdf.processFile(infile); @@ -45,8 +43,8 @@ static void stamp_page(char const* infile, std::vector pages = QPDFPageDocumentHelper(inpdf).getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& ph = *iter; // Find a unique resource name for the new form XObject @@ -57,11 +55,9 @@ static void stamp_page(char const* infile, // Generate content to place the form XObject centered within // destination page's trim box. QPDFMatrix m; - std::string content = - ph.placeFormXObject( - stamp_fo, name, ph.getTrimBox().getArrayAsRectangle(), m); - if (! content.empty()) - { + std::string content = ph.placeFormXObject( + stamp_fo, name, ph.getTrimBox().getArrayAsRectangle(), m); + if (!content.empty()) { // Append the content to the page's content. Surround the // original content with q...Q to the new content from the // page's original content. @@ -80,28 +76,25 @@ static void stamp_page(char const* infile, } QPDFWriter w(inpdf, outfile); - w.setStaticID(true); // for testing only + w.setStaticID(true); // for testing only w.write(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 4) - { + if (argc != 4) { usage(); } char const* infile = argv[1]; char const* stampfile = argv[2]; char const* outfile = argv[3]; - try - { + try { stamp_page(infile, stampfile, outfile); - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-parse-content.cc b/examples/pdf-parse-content.cc index dbe3a451..f1f7ab55 100644 --- a/examples/pdf-parse-content.cc +++ b/examples/pdf-parse-content.cc @@ -1,16 +1,17 @@ #include -#include #include +#include +#include #include #include #include #include -#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " filename page-number" << std::endl << "Prints a dump of the objects in the content streams" @@ -38,17 +39,14 @@ ParserCallbacks::contentSize(size_t size) } void -ParserCallbacks::handleObject(QPDFObjectHandle obj, - size_t offset, size_t length) +ParserCallbacks::handleObject( + QPDFObjectHandle obj, size_t offset, size_t length) { std::cout << obj.getTypeName() << ", offset=" << offset << ", length=" << length << ": "; - if (obj.isInlineImage()) - { + if (obj.isInlineImage()) { std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << std::endl; - } - else - { + } else { std::cout << obj.unparse() << std::endl; } } @@ -59,34 +57,30 @@ ParserCallbacks::handleEOF() std::cout << "-EOF-" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 3) - { + if (argc != 3) { usage(); } char const* filename = argv[1]; int pageno = QUtil::string_to_int(argv[2]); - try - { + try { QPDF pdf; pdf.processFile(filename); std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); - if ((pageno < 1) || (QIntC::to_size(pageno) > pages.size())) - { + if ((pageno < 1) || (QIntC::to_size(pageno) > pages.size())) { usage(); } - QPDFPageObjectHelper& page = pages.at(QIntC::to_size(pageno-1)); + QPDFPageObjectHelper& page = pages.at(QIntC::to_size(pageno - 1)); ParserCallbacks cb; page.parseContents(&cb); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } diff --git a/examples/pdf-set-form-values.cc b/examples/pdf-set-form-values.cc index eab24e4f..10394c7b 100644 --- a/examples/pdf-set-form-values.cc +++ b/examples/pdf-set-form-values.cc @@ -1,16 +1,17 @@ -#include -#include -#include -#include #include -#include #include +#include #include #include +#include +#include +#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile.pdf outfile.pdf value" << std::endl @@ -19,13 +20,12 @@ void usage() exit(2); } - -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 4) - { + if (argc != 4) { usage(); } @@ -39,8 +39,7 @@ int main(int argc, char* argv[]) // to illustrate use of the helper classes around interactive // forms. - try - { + try { QPDF qpdf; qpdf.processFile(infilename); @@ -55,8 +54,8 @@ int main(int argc, char* argv[]) std::vector pages = pdh.getAllPages(); for (std::vector::iterator page_iter = pages.begin(); - page_iter != pages.end(); ++page_iter) - { + page_iter != pages.end(); + ++page_iter) { // Get all widget annotations for each page. Widget // annotations are the ones that contain the details of // what's in a form field. @@ -64,14 +63,13 @@ int main(int argc, char* argv[]) afdh.getWidgetAnnotationsForPage(*page_iter); for (std::vector::iterator annot_iter = annotations.begin(); - annot_iter != annotations.end(); ++annot_iter) - { + annot_iter != annotations.end(); + ++annot_iter) { // For each annotation, find its associated field. If // it's a text field, set its value. QPDFFormFieldObjectHelper ffh = afdh.getFieldForAnnotation(*annot_iter); - if (ffh.getFieldType() == "/Tx") - { + if (ffh.getFieldType() == "/Tx") { // Set the value. Passing false as the second // value prevents qpdf from setting // /NeedAppearances to true (but will not turn it @@ -92,9 +90,7 @@ int main(int argc, char* argv[]) QPDFWriter w(qpdf, outfilename); w.setStaticID(true); // for testing only w.write(); - } - catch (std::exception &e) - { + } catch (std::exception& e) { std::cerr << whoami << " processing file " << infilename << ": " << e.what() << std::endl; exit(2); diff --git a/examples/pdf-split-pages.cc b/examples/pdf-split-pages.cc index c79177ee..a8e65260 100644 --- a/examples/pdf-split-pages.cc +++ b/examples/pdf-split-pages.cc @@ -4,22 +4,21 @@ // does. // +#include #include #include #include #include -#include +#include #include #include #include -#include static bool static_id = false; -static void process(char const* whoami, - char const* infile, - std::string outprefix) +static void +process(char const* whoami, char const* infile, std::string outprefix) { QPDF inpdf; inpdf.processFile(infile); @@ -29,8 +28,8 @@ static void process(char const* whoami, QIntC::to_int(QUtil::uint_to_string(pages.size()).length()); int pageno = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); std::string outfile = outprefix + QUtil::int_to_string(++pageno, pageno_len) + ".pdf"; @@ -38,8 +37,7 @@ static void process(char const* whoami, outpdf.emptyPDF(); QPDFPageDocumentHelper(outpdf).addPage(page, false); QPDFWriter outpdfw(outpdf, outfile.c_str()); - if (static_id) - { + if (static_id) { // For the test suite, uncompress streams and use static // IDs. outpdfw.setStaticID(true); // for testing only @@ -49,34 +47,31 @@ static void process(char const* whoami, } } -void usage(char const* whoami) +void +usage(char const* whoami) { std::cerr << "Usage: " << whoami << " infile outprefix" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { char const* whoami = QUtil::getWhoami(argv[0]); // For test suite - if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) - { + if ((argc > 1) && (strcmp(argv[1], " --static-id") == 0)) { static_id = true; --argc; ++argv; } - if (argc != 3) - { + if (argc != 3) { usage(whoami); } - try - { + try { process(whoami, argv[1], argv[2]); - } - catch (std::exception const& e) - { + } catch (std::exception const& e) { std::cerr << whoami << ": exception: " << e.what() << std::endl; return 2; } diff --git a/examples/qpdf-job.cc b/examples/qpdf-job.cc index ecebca3b..b71b612a 100644 --- a/examples/qpdf-job.cc +++ b/examples/qpdf-job.cc @@ -1,34 +1,32 @@ +#include #include #include -#include -#include #include +#include // This program is a simple demonstration of different ways to use the // QPDFJob API. static char const* whoami = 0; -static void usage() +static void +usage() { - std::cerr - << "Usage: " << whoami << std::endl - << "This program linearizes the first page of in.pdf to out1.pdf," - << " out2.pdf, and" - << std::endl - << " out3.pdf, each demonstrating a different way to use the" - << " QPDFJob API" - << std::endl; + std::cerr << "Usage: " << whoami << std::endl + << "This program linearizes the first page of in.pdf to out1.pdf," + << " out2.pdf, and" << std::endl + << " out3.pdf, each demonstrating a different way to use the" + << " QPDFJob API" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); - if (argc != 1) - { + if (argc != 1) { usage(); } @@ -39,8 +37,7 @@ int main(int argc, char* argv[]) // Note that staticId is used for testing only. - try - { + try { // Use the config API QPDFJob j; j.config() @@ -54,15 +51,12 @@ int main(int argc, char* argv[]) ->checkConfiguration(); j.run(); std::cout << "out1 status: " << j.getExitCode() << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; return 2; } - try - { + try { char const* new_argv[] = { whoami, "in.pdf", @@ -73,21 +67,17 @@ int main(int argc, char* argv[]) "1", "--", "--static-id", - nullptr - }; + nullptr}; QPDFJob j; j.initializeFromArgv(new_argv); j.run(); std::cout << "out2 status: " << j.getExitCode() << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; return 2; } - try - { + try { // Use the JSON API QPDFJob j; j.initializeFromJson(R"({ @@ -105,9 +95,7 @@ int main(int argc, char* argv[]) )"); j.run(); std::cout << "out3 status: " << j.getExitCode() << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; return 2; } diff --git a/examples/qpdfjob-c.c b/examples/qpdfjob-c.c index ad81655a..ee2ef4ab 100644 --- a/examples/qpdfjob-c.c +++ b/examples/qpdfjob-c.c @@ -10,13 +10,15 @@ static char const* whoami = 0; -static void usage() +static void +usage() { fprintf(stderr, "Usage: %s infile outfile\n", whoami); exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { char* infile = NULL; char* outfile = NULL; @@ -24,21 +26,15 @@ int main(int argc, char* argv[]) int r = 0; char* p = 0; - if ((p = strrchr(argv[0], '/')) != NULL) - { + if ((p = strrchr(argv[0], '/')) != NULL) { whoami = p + 1; - } - else if ((p = strrchr(argv[0], '\\')) != NULL) - { + } else if ((p = strrchr(argv[0], '\\')) != NULL) { whoami = p + 1; - } - else - { + } else { whoami = argv[0]; } - if (argc != 3) - { + if (argc != 3) { usage(); } diff --git a/fuzz/ascii85_fuzzer.cc b/fuzz/ascii85_fuzzer.cc index 40422e5b..daf6628c 100644 --- a/fuzz/ascii85_fuzzer.cc +++ b/fuzz/ascii85_fuzzer.cc @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/dct_fuzzer.cc b/fuzz/dct_fuzzer.cc index b051819a..6e42ef6d 100644 --- a/fuzz/dct_fuzzer.cc +++ b/fuzz/dct_fuzzer.cc @@ -1,8 +1,8 @@ -#include #include +#include +#include #include #include -#include class FuzzHelper { @@ -35,17 +35,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { #ifndef _WIN32 // Used by jpeg library to work around false positives in memory diff --git a/fuzz/flate_fuzzer.cc b/fuzz/flate_fuzzer.cc index 700f7cd7..97e10dd2 100644 --- a/fuzz/flate_fuzzer.cc +++ b/fuzz/flate_fuzzer.cc @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/hex_fuzzer.cc b/fuzz/hex_fuzzer.cc index b1ad2199..0ce7b2e0 100644 --- a/fuzz/hex_fuzzer.cc +++ b/fuzz/hex_fuzzer.cc @@ -1,5 +1,5 @@ -#include #include +#include #include #include @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/lzw_fuzzer.cc b/fuzz/lzw_fuzzer.cc index da31f41b..5e017507 100644 --- a/fuzz/lzw_fuzzer.cc +++ b/fuzz/lzw_fuzzer.cc @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/pngpredictor_fuzzer.cc b/fuzz/pngpredictor_fuzzer.cc index 8a8c5d7d..7a39c8ec 100644 --- a/fuzz/pngpredictor_fuzzer.cc +++ b/fuzz/pngpredictor_fuzzer.cc @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/qpdf_fuzzer.cc b/fuzz/qpdf_fuzzer.cc index 9f0d5d39..3c76bbc9 100644 --- a/fuzz/qpdf_fuzzer.cc +++ b/fuzz/qpdf_fuzzer.cc @@ -1,22 +1,30 @@ +#include +#include +#include #include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include #include class DiscardContents: public QPDFObjectHandle::ParserCallbacks { public: - virtual ~DiscardContents() {} - virtual void handleObject(QPDFObjectHandle) {} - virtual void handleEOF() {} + virtual ~DiscardContents() + { + } + virtual void + handleObject(QPDFObjectHandle) + { + } + virtual void + handleEOF() + { + } }; class FuzzHelper @@ -66,16 +74,11 @@ FuzzHelper::getWriter(PointerHolder qpdf) void FuzzHelper::doWrite(PointerHolder w) { - try - { + try { w->write(); - } - catch (QPDFExc const& e) - { + } catch (QPDFExc const& e) { std::cerr << e.what() << std::endl; - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << e.what() << std::endl; } } @@ -133,14 +136,12 @@ FuzzHelper::testPages() std::vector pages = pdh.getAllPages(); DiscardContents discard_contents; int pageno = 0; - for (std::vector::iterator iter = - pages.begin(); - iter != pages.end(); ++iter) - { + for (std::vector::iterator iter = pages.begin(); + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); ++pageno; - try - { + try { page.coalesceContentStreams(); page.parseContents(&discard_contents); page.getImages(); @@ -153,16 +154,13 @@ FuzzHelper::testPages() afdh.getWidgetAnnotationsForPage(page); for (std::vector::iterator annot_iter = annotations.begin(); - annot_iter != annotations.end(); ++annot_iter) - { + annot_iter != annotations.end(); + ++annot_iter) { QPDFAnnotationObjectHelper& aoh = *annot_iter; afdh.getFieldForAnnotation(aoh); } - } - catch (QPDFExc& e) - { - std::cerr << "page " << pageno << ": " - << e.what() << std::endl; + } catch (QPDFExc& e) { + std::cerr << "page " << pageno << ": " << e.what() << std::endl; } } } @@ -171,16 +169,15 @@ void FuzzHelper::testOutlines() { PointerHolder q = getQpdf(); - std::list > queue; + std::list> queue; QPDFOutlineDocumentHelper odh(*q); queue.push_back(odh.getTopLevelOutlines()); - while (! queue.empty()) - { + while (!queue.empty()) { std::vector& outlines = *(queue.begin()); for (std::vector::iterator iter = outlines.begin(); - iter != outlines.end(); ++iter) - { + iter != outlines.end(); + ++iter) { QPDFOutlineObjectHelper& ol = *iter; ol.getDestPage(); queue.push_back(ol.getKids()); @@ -208,21 +205,17 @@ FuzzHelper::run() // std::runtime_error. Throwing any other kind of exception, // segfaulting, or having a memory error (when built with // appropriate sanitizers) will all cause abnormal exit. - try - { + try { doChecks(); - } - catch (QPDFExc const& e) - { + } catch (QPDFExc const& e) { std::cerr << "QPDFExc: " << e.what() << std::endl; - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { #ifndef _WIN32 // Used by jpeg library to work around false positives in memory diff --git a/fuzz/runlength_fuzzer.cc b/fuzz/runlength_fuzzer.cc index bacd3dd8..3ff3f587 100644 --- a/fuzz/runlength_fuzzer.cc +++ b/fuzz/runlength_fuzzer.cc @@ -34,17 +34,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/fuzz/standalone_fuzz_target_runner.cc b/fuzz/standalone_fuzz_target_runner.cc index 65905c14..066764a2 100644 --- a/fuzz/standalone_fuzz_target_runner.cc +++ b/fuzz/standalone_fuzz_target_runner.cc @@ -4,10 +4,10 @@ extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size); -int main(int argc, char **argv) +int +main(int argc, char** argv) { - for (int i = 1; i < argc; i++) - { + for (int i = 1; i < argc; i++) { PointerHolder file_buf; size_t size = 0; QUtil::read_file_into_memory(argv[i], file_buf, size); diff --git a/fuzz/tiffpredictor_fuzzer.cc b/fuzz/tiffpredictor_fuzzer.cc index 35d2f415..61c24e57 100644 --- a/fuzz/tiffpredictor_fuzzer.cc +++ b/fuzz/tiffpredictor_fuzzer.cc @@ -26,8 +26,8 @@ void FuzzHelper::doChecks() { Pl_Discard discard; - Pl_TIFFPredictor p("decoder", &discard, - Pl_TIFFPredictor::a_decode, 16, 1, 8); + Pl_TIFFPredictor p( + "decoder", &discard, Pl_TIFFPredictor::a_decode, 16, 1, 8); p.write(const_cast(data), size); p.finish(); } @@ -35,17 +35,15 @@ FuzzHelper::doChecks() void FuzzHelper::run() { - try - { + try { doChecks(); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::cerr << "runtime_error: " << e.what() << std::endl; } } -extern "C" int LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) +extern "C" int +LLVMFuzzerTestOneInput(unsigned char const* data, size_t size) { FuzzHelper f(data, size); f.run(); diff --git a/include/qpdf/Buffer.hh b/include/qpdf/Buffer.hh index 345e5aaa..4bddc1ef 100644 --- a/include/qpdf/Buffer.hh +++ b/include/qpdf/Buffer.hh @@ -25,8 +25,8 @@ #include #include -#include #include +#include class Buffer { diff --git a/include/qpdf/BufferInputSource.hh b/include/qpdf/BufferInputSource.hh index ac6ed8dc..7f94b8e8 100644 --- a/include/qpdf/BufferInputSource.hh +++ b/include/qpdf/BufferInputSource.hh @@ -22,8 +22,8 @@ #ifndef QPDF_BUFFERINPUTSOURCE_HH #define QPDF_BUFFERINPUTSOURCE_HH -#include #include +#include class BufferInputSource: public InputSource { @@ -31,11 +31,11 @@ class BufferInputSource: public InputSource // If own_memory is true, BufferInputSource will delete the buffer // when finished with it. Otherwise, the caller owns the memory. QPDF_DLL - BufferInputSource(std::string const& description, Buffer* buf, - bool own_memory = false); + BufferInputSource( + std::string const& description, Buffer* buf, bool own_memory = false); QPDF_DLL - BufferInputSource(std::string const& description, - std::string const& contents); + BufferInputSource( + std::string const& description, std::string const& contents); QPDF_DLL virtual ~BufferInputSource(); QPDF_DLL diff --git a/include/qpdf/Constants.h b/include/qpdf/Constants.h index ab3ca1fe..c50a9563 100644 --- a/include/qpdf/Constants.h +++ b/include/qpdf/Constants.h @@ -29,16 +29,15 @@ /* Error Codes */ -enum qpdf_error_code_e -{ +enum qpdf_error_code_e { qpdf_e_success = 0, - qpdf_e_internal, /* logic/programming error -- indicates bug */ - qpdf_e_system, /* I/O error, memory error, etc. */ - qpdf_e_unsupported, /* PDF feature not (yet) supported by qpdf */ - qpdf_e_password, /* incorrect password for encrypted file */ - qpdf_e_damaged_pdf, /* syntax errors or other damage in PDF */ - qpdf_e_pages, /* erroneous or unsupported pages structure */ - qpdf_e_object, /* type/bounds errors accessing objects */ + qpdf_e_internal, /* logic/programming error -- indicates bug */ + qpdf_e_system, /* I/O error, memory error, etc. */ + qpdf_e_unsupported, /* PDF feature not (yet) supported by qpdf */ + qpdf_e_password, /* incorrect password for encrypted file */ + qpdf_e_damaged_pdf, /* syntax errors or other damage in PDF */ + qpdf_e_pages, /* erroneous or unsupported pages structure */ + qpdf_e_object, /* type/bounds errors accessing objects */ }; /* Object Types */ @@ -75,62 +74,56 @@ enum qpdf_object_type_e { /* Write Parameters. See QPDFWriter.hh for details. */ -enum qpdf_object_stream_e -{ - qpdf_o_disable = 0, /* disable object streams */ - qpdf_o_preserve, /* preserve object streams */ - qpdf_o_generate /* generate object streams */ +enum qpdf_object_stream_e { + qpdf_o_disable = 0, /* disable object streams */ + qpdf_o_preserve, /* preserve object streams */ + qpdf_o_generate /* generate object streams */ }; -enum qpdf_stream_data_e -{ - qpdf_s_uncompress = 0, /* uncompress stream data */ - qpdf_s_preserve, /* preserve stream data compression */ - qpdf_s_compress /* compress stream data */ +enum qpdf_stream_data_e { + qpdf_s_uncompress = 0, /* uncompress stream data */ + qpdf_s_preserve, /* preserve stream data compression */ + qpdf_s_compress /* compress stream data */ }; /* Stream data flags */ /* See pipeStreamData in QPDFObjectHandle.hh for details on these flags. */ -enum qpdf_stream_encode_flags_e -{ - qpdf_ef_compress = 1 << 0, /* compress uncompressed streams */ +enum qpdf_stream_encode_flags_e { + qpdf_ef_compress = 1 << 0, /* compress uncompressed streams */ qpdf_ef_normalize = 1 << 1, /* normalize content stream */ }; -enum qpdf_stream_decode_level_e -{ +enum qpdf_stream_decode_level_e { /* These must be in order from less to more decoding. */ - qpdf_dl_none = 0, /* preserve all stream filters */ - qpdf_dl_generalized, /* decode general-purpose filters */ - qpdf_dl_specialized, /* also decode other non-lossy filters */ - qpdf_dl_all /* also decode lossy filters */ + qpdf_dl_none = 0, /* preserve all stream filters */ + qpdf_dl_generalized, /* decode general-purpose filters */ + qpdf_dl_specialized, /* also decode other non-lossy filters */ + qpdf_dl_all /* also decode lossy filters */ }; /* R3 Encryption Parameters */ -enum qpdf_r3_print_e -{ - qpdf_r3p_full = 0, /* allow all printing */ - qpdf_r3p_low, /* allow only low-resolution printing */ - qpdf_r3p_none /* allow no printing */ +enum qpdf_r3_print_e { + qpdf_r3p_full = 0, /* allow all printing */ + qpdf_r3p_low, /* allow only low-resolution printing */ + qpdf_r3p_none /* allow no printing */ }; /* qpdf_r3_modify_e doesn't allow the full flexibility of the spec. It * corresponds to options in Acrobat 5's menus. The new interface in * QPDFWriter offers more granularity and no longer uses this type. */ -enum qpdf_r3_modify_e /* Allowed changes: */ +enum qpdf_r3_modify_e /* Allowed changes: */ { - qpdf_r3m_all = 0, /* All editing */ - qpdf_r3m_annotate, /* Comments, fill forms, signing, assembly */ - qpdf_r3m_form, /* Fill forms, signing, assembly */ - qpdf_r3m_assembly, /* Only document assembly */ - qpdf_r3m_none /* No modifications */ + qpdf_r3m_all = 0, /* All editing */ + qpdf_r3m_annotate, /* Comments, fill forms, signing, assembly */ + qpdf_r3m_form, /* Fill forms, signing, assembly */ + qpdf_r3m_assembly, /* Only document assembly */ + qpdf_r3m_none /* No modifications */ }; /* Form field flags from the PDF spec */ -enum pdf_form_field_flag_e -{ +enum pdf_form_field_flag_e { /* flags that apply to all form fields */ ff_all_read_only = 1 << 0, ff_all_required = 1 << 1, @@ -162,8 +155,7 @@ enum pdf_form_field_flag_e /* Annotation flags from the PDF spec */ -enum pdf_annotation_flag_e -{ +enum pdf_annotation_flag_e { an_invisible = 1 << 0, an_hidden = 1 << 1, an_print = 1 << 2, @@ -177,8 +169,7 @@ enum pdf_annotation_flag_e }; /* Encryption/password status for QPDFJob */ -enum qpdf_encryption_status_e -{ +enum qpdf_encryption_status_e { qpdf_es_encrypted = 1 << 0, qpdf_es_password_incorrect = 1 << 1 }; diff --git a/include/qpdf/DLL.h b/include/qpdf/DLL.h index ca9d57a7..5c2c77d7 100644 --- a/include/qpdf/DLL.h +++ b/include/qpdf/DLL.h @@ -32,7 +32,7 @@ #if (defined _WIN32 || defined __CYGWIN__) && defined(DLL_EXPORT) # define QPDF_DLL __declspec(dllexport) #elif defined __GNUC__ -# define QPDF_DLL __attribute__ ((visibility ("default"))) +# define QPDF_DLL __attribute__((visibility("default"))) #else # define QPDF_DLL #endif diff --git a/include/qpdf/InputSource.hh b/include/qpdf/InputSource.hh index 500e2518..044dc385 100644 --- a/include/qpdf/InputSource.hh +++ b/include/qpdf/InputSource.hh @@ -23,12 +23,12 @@ #define QPDF_INPUTSOURCE_HH #include -#include #include +#include +#include #include #include -#include class QPDF_DLL_CLASS InputSource { @@ -71,13 +71,17 @@ class QPDF_DLL_CLASS InputSource // methods return true and leave the input source positioned // wherever check() left it at the end of the matching pattern. QPDF_DLL - bool findFirst(char const* start_chars, - qpdf_offset_t offset, size_t len, - Finder& finder); + bool findFirst( + char const* start_chars, + qpdf_offset_t offset, + size_t len, + Finder& finder); QPDF_DLL - bool findLast(char const* start_chars, - qpdf_offset_t offset, size_t len, - Finder& finder); + bool findLast( + char const* start_chars, + qpdf_offset_t offset, + size_t len, + Finder& finder); virtual qpdf_offset_t findAndSkipNextEOL() = 0; virtual std::string const& getName() const = 0; diff --git a/include/qpdf/JSON.hh b/include/qpdf/JSON.hh index 55a3ec73..2f54721c 100644 --- a/include/qpdf/JSON.hh +++ b/include/qpdf/JSON.hh @@ -38,12 +38,12 @@ #include #include -#include -#include -#include -#include #include +#include +#include #include +#include +#include class JSON { @@ -134,14 +134,13 @@ class JSON f_optional = 1 << 0, }; QPDF_DLL - bool checkSchema(JSON schema, unsigned long flags, - std::list& errors); + bool checkSchema( + JSON schema, unsigned long flags, std::list& errors); // Same as passing 0 for flags QPDF_DLL bool checkSchema(JSON schema, std::list& errors); - // Create a JSON object from a string. QPDF_DLL static JSON parse(std::string const&); @@ -198,11 +197,12 @@ class JSON JSON(std::shared_ptr); - static bool - checkSchemaInternal(JSON_value* this_v, JSON_value* sch_v, - unsigned long flags, - std::list& errors, - std::string prefix); + static bool checkSchemaInternal( + JSON_value* this_v, + JSON_value* sch_v, + unsigned long flags, + std::list& errors, + std::string prefix); class Members { @@ -222,5 +222,4 @@ class JSON PointerHolder m; }; - #endif // JSON_HH diff --git a/include/qpdf/Pipeline.hh b/include/qpdf/Pipeline.hh index e1adc284..3b06b406 100644 --- a/include/qpdf/Pipeline.hh +++ b/include/qpdf/Pipeline.hh @@ -47,8 +47,8 @@ #include #include -#include #include +#include class QPDF_DLL_CLASS Pipeline { diff --git a/include/qpdf/Pl_Buffer.hh b/include/qpdf/Pl_Buffer.hh index b2777033..70f5e29b 100644 --- a/include/qpdf/Pl_Buffer.hh +++ b/include/qpdf/Pl_Buffer.hh @@ -33,9 +33,9 @@ // For this pipeline, "next" may be null. If a next pointer is // provided, this pipeline will also pass the data through to it. +#include #include #include -#include #include @@ -68,7 +68,7 @@ class Pl_Buffer: public Pipeline // a buffer of size *len allocated with malloc(). It is the // caller's responsibility to call free() on the buffer. QPDF_DLL - void getMallocBuffer(unsigned char **buf, size_t* len); + void getMallocBuffer(unsigned char** buf, size_t* len); private: class Members diff --git a/include/qpdf/Pl_Count.hh b/include/qpdf/Pl_Count.hh index ba5520fd..b21153d4 100644 --- a/include/qpdf/Pl_Count.hh +++ b/include/qpdf/Pl_Count.hh @@ -25,8 +25,8 @@ // This pipeline is reusable; i.e., it is safe to call write() after // calling finish(). -#include #include +#include class Pl_Count: public Pipeline { diff --git a/include/qpdf/Pl_DCT.hh b/include/qpdf/Pl_DCT.hh index be714bc7..55ca4ff9 100644 --- a/include/qpdf/Pl_DCT.hh +++ b/include/qpdf/Pl_DCT.hh @@ -52,12 +52,14 @@ class Pl_DCT: public Pipeline // Constructor for compressing image data QPDF_DLL - Pl_DCT(char const* identifier, Pipeline* next, - JDIMENSION image_width, - JDIMENSION image_height, - int components, - J_COLOR_SPACE color_space, - CompressConfig* config_callback = 0); + Pl_DCT( + char const* identifier, + Pipeline* next, + JDIMENSION image_width, + JDIMENSION image_height, + int components, + J_COLOR_SPACE color_space, + CompressConfig* config_callback = 0); QPDF_DLL virtual ~Pl_DCT(); @@ -82,13 +84,14 @@ class Pl_DCT: public Pipeline ~Members(); private: - Members(action_e action, - char const* buf_description, - JDIMENSION image_width = 0, - JDIMENSION image_height = 0, - int components = 1, - J_COLOR_SPACE color_space = JCS_GRAYSCALE, - CompressConfig* config_callback = 0); + Members( + action_e action, + char const* buf_description, + JDIMENSION image_width = 0, + JDIMENSION image_height = 0, + int components = 1, + J_COLOR_SPACE color_space = JCS_GRAYSCALE, + CompressConfig* config_callback = 0); Members(Members const&); action_e action; diff --git a/include/qpdf/Pl_Flate.hh b/include/qpdf/Pl_Flate.hh index 188cf7fa..74d21c5a 100644 --- a/include/qpdf/Pl_Flate.hh +++ b/include/qpdf/Pl_Flate.hh @@ -35,8 +35,11 @@ class Pl_Flate: public Pipeline enum action_e { a_inflate, a_deflate }; QPDF_DLL - Pl_Flate(char const* identifier, Pipeline* next, - action_e action, unsigned int out_bufsize = def_bufsize); + Pl_Flate( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int out_bufsize = def_bufsize); QPDF_DLL virtual ~Pl_Flate(); diff --git a/include/qpdf/Pl_QPDFTokenizer.hh b/include/qpdf/Pl_QPDFTokenizer.hh index 0a95f0ba..58a218b5 100644 --- a/include/qpdf/Pl_QPDFTokenizer.hh +++ b/include/qpdf/Pl_QPDFTokenizer.hh @@ -24,10 +24,10 @@ #include -#include +#include #include #include -#include +#include #include @@ -48,9 +48,10 @@ class Pl_QPDFTokenizer: public Pipeline // pipeline that the token filter writes to. If next is not // provided, any output written by the filter will be discarded. QPDF_DLL - Pl_QPDFTokenizer(char const* identifier, - QPDFObjectHandle::TokenFilter* filter, - Pipeline* next = 0); + Pl_QPDFTokenizer( + char const* identifier, + QPDFObjectHandle::TokenFilter* filter, + Pipeline* next = 0); QPDF_DLL virtual ~Pl_QPDFTokenizer(); QPDF_DLL diff --git a/include/qpdf/Pl_RunLength.hh b/include/qpdf/Pl_RunLength.hh index 307703ef..6761bfeb 100644 --- a/include/qpdf/Pl_RunLength.hh +++ b/include/qpdf/Pl_RunLength.hh @@ -30,8 +30,7 @@ class Pl_RunLength: public Pipeline enum action_e { a_encode, a_decode }; QPDF_DLL - Pl_RunLength(char const* identifier, Pipeline* next, - action_e action); + Pl_RunLength(char const* identifier, Pipeline* next, action_e action); QPDF_DLL virtual ~Pl_RunLength(); diff --git a/include/qpdf/PointerHolder.hh b/include/qpdf/PointerHolder.hh index 45236456..fb186778 100644 --- a/include/qpdf/PointerHolder.hh +++ b/include/qpdf/PointerHolder.hh @@ -187,18 +187,16 @@ class PointerHolder } ~Data() { - if (array) - { - delete [] this->pointer; - } - else - { + if (array) { + delete[] this->pointer; + } else { delete this->pointer; } } T* pointer; bool array; int refcount; + private: Data(Data const&) = delete; Data& operator=(Data const&) = delete; @@ -208,7 +206,7 @@ class PointerHolder #if POINTERHOLDER_TRANSITION >= 1 explicit #endif // POINTERHOLDER_TRANSITION >= 1 - PointerHolder(T* pointer = 0) + PointerHolder(T* pointer = 0) { this->init(new Data(pointer, false)); } @@ -222,16 +220,17 @@ class PointerHolder { this->copy(rhs); } - PointerHolder& operator=(PointerHolder const& rhs) + PointerHolder& + operator=(PointerHolder const& rhs) { - if (this != &rhs) - { + if (this != &rhs) { this->destroy(); this->copy(rhs); } return *this; } - PointerHolder& operator=(decltype(nullptr)) + PointerHolder& + operator=(decltype(nullptr)) { this->operator=(PointerHolder()); return *this; @@ -240,21 +239,25 @@ class PointerHolder { this->destroy(); } - bool operator==(PointerHolder const& rhs) const + bool + operator==(PointerHolder const& rhs) const { return this->data->pointer == rhs.data->pointer; } - bool operator==(decltype(nullptr)) const + bool + operator==(decltype(nullptr)) const { return this->data->pointer == nullptr; } - bool operator<(PointerHolder const& rhs) const + bool + operator<(PointerHolder const& rhs) const { return this->data->pointer < rhs.data->pointer; } // get() is for interface compatibility with std::shared_ptr - T* get() const + T* + get() const { return this->data->pointer; } @@ -264,70 +267,79 @@ class PointerHolder #if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder::get() instead of getPointer()")]] #endif // POINTERHOLDER_TRANSITION >= 2 - T* getPointer() + T* + getPointer() { return this->data->pointer; } #if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use PointerHolder::get() instead of getPointer()")]] #endif // POINTERHOLDER_TRANSITION >= 2 - T const* getPointer() const + T const* + getPointer() const { return this->data->pointer; } #if POINTERHOLDER_TRANSITION >= 2 [[deprecated("use use_count() instead of getRefcount()")]] #endif // POINTERHOLDER_TRANSITION >= 2 - int getRefcount() const + int + getRefcount() const { return this->data->refcount; } // use_count() is for compatibility with std::shared_ptr - long use_count() + long + use_count() { return static_cast(this->data->refcount); } - T const& operator*() const + T const& + operator*() const { return *this->data->pointer; } - T& operator*() + T& + operator*() { return *this->data->pointer; } - T const* operator->() const + T const* + operator->() const { return this->data->pointer; } - T* operator->() + T* + operator->() { return this->data->pointer; } private: - void init(Data* data) + void + init(Data* data) { this->data = data; ++this->data->refcount; } - void copy(PointerHolder const& rhs) + void + copy(PointerHolder const& rhs) { this->init(rhs.data); } - void destroy() + void + destroy() { bool gone = false; { - if (--this->data->refcount == 0) - { + if (--this->data->refcount == 0) { gone = true; } } - if (gone) - { + if (gone) { delete this->data; } } @@ -335,7 +347,7 @@ class PointerHolder Data* data; }; -template +template inline PointerHolder make_pointer_holder(_Args&&... __args) { diff --git a/include/qpdf/QIntC.hh b/include/qpdf/QIntC.hh index 484bae1a..ce2f47e9 100644 --- a/include/qpdf/QIntC.hh +++ b/include/qpdf/QIntC.hh @@ -24,12 +24,12 @@ #include #include -#include +#include #include #include -#include -#include #include +#include +#include #include // This namespace provides safe integer conversion that detects @@ -51,9 +51,11 @@ namespace QIntC // QIntC = qpdf Integer Conversion // throws a range_error otherwise. This class is specialized for // each permutation of signed/unsigned for the From and To // classes. - template ::is_signed, - bool To_signed = std::numeric_limits::is_signed> + template < + typename From, + typename To, + bool From_signed = std::numeric_limits::is_signed, + bool To_signed = std::numeric_limits::is_signed> class IntConverter { }; @@ -62,17 +64,16 @@ namespace QIntC // QIntC = qpdf Integer Conversion class IntConverter { public: - static To convert(From const& i) + static To + convert(From const& i) { // From and To are both unsigned. - if (i > std::numeric_limits::max()) - { + if (i > std::numeric_limits::max()) { std::ostringstream msg; msg.imbue(std::locale::classic()); - msg << "integer out of range converting " << i - << " from a " - << sizeof(From) << "-byte unsigned type to a " - << sizeof(To) << "-byte unsigned type"; + msg << "integer out of range converting " << i << " from a " + << sizeof(From) << "-byte unsigned type to a " << sizeof(To) + << "-byte unsigned type"; throw std::range_error(msg.str()); } return static_cast(i); @@ -83,18 +84,17 @@ namespace QIntC // QIntC = qpdf Integer Conversion class IntConverter { public: - static To convert(From const& i) + static To + convert(From const& i) { // From and To are both signed. if ((i < std::numeric_limits::min()) || - (i > std::numeric_limits::max())) - { + (i > std::numeric_limits::max())) { std::ostringstream msg; msg.imbue(std::locale::classic()); - msg << "integer out of range converting " << i - << " from a " - << sizeof(From) << "-byte signed type to a " - << sizeof(To) << "-byte signed type"; + msg << "integer out of range converting " << i << " from a " + << sizeof(From) << "-byte signed type to a " << sizeof(To) + << "-byte signed type"; throw std::range_error(msg.str()); } return static_cast(i); @@ -105,20 +105,19 @@ namespace QIntC // QIntC = qpdf Integer Conversion class IntConverter { public: - static To convert(From const& i) + static To + convert(From const& i) { // From is signed, and To is unsigned. If i > 0, it's safe to // convert it to the corresponding unsigned type and to // compare with To's max. auto ii = static_cast::type>(i); - if ((i < 0) || (ii > std::numeric_limits::max())) - { + if ((i < 0) || (ii > std::numeric_limits::max())) { std::ostringstream msg; msg.imbue(std::locale::classic()); - msg << "integer out of range converting " << i - << " from a " - << sizeof(From) << "-byte signed type to a " - << sizeof(To) << "-byte unsigned type"; + msg << "integer out of range converting " << i << " from a " + << sizeof(From) << "-byte signed type to a " << sizeof(To) + << "-byte unsigned type"; throw std::range_error(msg.str()); } return static_cast(i); @@ -129,20 +128,19 @@ namespace QIntC // QIntC = qpdf Integer Conversion class IntConverter { public: - static To convert(From const& i) + static To + convert(From const& i) { // From is unsigned, and to is signed. Convert To's max to the // unsigned version of To and compare i against that. auto maxval = static_cast::type>( std::numeric_limits::max()); - if (i > maxval) - { + if (i > maxval) { std::ostringstream msg; msg.imbue(std::locale::classic()); - msg << "integer out of range converting " << i - << " from a " - << sizeof(From) << "-byte unsigned type to a " - << sizeof(To) << "-byte signed type"; + msg << "integer out of range converting " << i << " from a " + << sizeof(From) << "-byte unsigned type to a " << sizeof(To) + << "-byte signed type"; throw std::range_error(msg.str()); } return static_cast(i); @@ -152,97 +150,105 @@ namespace QIntC // QIntC = qpdf Integer Conversion // Specific converters. The return type of each function must match // the second template parameter to IntConverter. template - char to_char(T const& i) + char + to_char(T const& i) { return IntConverter::convert(i); } template - unsigned char to_uchar(T const& i) + unsigned char + to_uchar(T const& i) { return IntConverter::convert(i); } template - short to_short(T const& i) + short + to_short(T const& i) { return IntConverter::convert(i); } template - unsigned short to_ushort(T const& i) + unsigned short + to_ushort(T const& i) { return IntConverter::convert(i); } template - int to_int(T const& i) + int + to_int(T const& i) { return IntConverter::convert(i); } template - unsigned int to_uint(T const& i) + unsigned int + to_uint(T const& i) { return IntConverter::convert(i); } template - size_t to_size(T const& i) + size_t + to_size(T const& i) { return IntConverter::convert(i); } template - qpdf_offset_t to_offset(T const& i) + qpdf_offset_t + to_offset(T const& i) { return IntConverter::convert(i); } template - long to_long(T const& i) + long + to_long(T const& i) { - return IntConverter::convert(i); + return IntConverter::convert(i); } template - unsigned long to_ulong(T const& i) + unsigned long + to_ulong(T const& i) { - return IntConverter::convert(i); + return IntConverter::convert(i); } template - long long to_longlong(T const& i) + long long + to_longlong(T const& i) { return IntConverter::convert(i); } template - unsigned long long to_ulonglong(T const& i) + unsigned long long + to_ulonglong(T const& i) { return IntConverter::convert(i); } template - void range_check(T const& cur, T const& delta) + void + range_check(T const& cur, T const& delta) { - if ((delta > 0) != (cur > 0)) - { + if ((delta > 0) != (cur > 0)) { return; } - if ((delta > 0) && - ((std::numeric_limits::max() - cur) < delta)) - { + if ((delta > 0) && ((std::numeric_limits::max() - cur) < delta)) { std::ostringstream msg; msg.imbue(std::locale::classic()); msg << "adding " << delta << " to " << cur << " would cause an integer overflow"; throw std::range_error(msg.str()); - } - else if ((delta < 0) && - ((std::numeric_limits::min() - cur) > delta)) - { + } else if ( + (delta < 0) && ((std::numeric_limits::min() - cur) > delta)) { std::ostringstream msg; msg.imbue(std::locale::classic()); msg << "adding " << delta << " to " << cur @@ -252,25 +258,21 @@ namespace QIntC // QIntC = qpdf Integer Conversion } template - void range_check_substract(T const& cur, T const& delta) + void + range_check_substract(T const& cur, T const& delta) { - if ((delta >= 0) == (cur >= 0)) - { + if ((delta >= 0) == (cur >= 0)) { return; } - if ((delta > 0) && - ((std::numeric_limits::min() + delta) > cur)) - { + if ((delta > 0) && ((std::numeric_limits::min() + delta) > cur)) { std::ostringstream msg; msg.imbue(std::locale::classic()); msg << "subtracting " << delta << " from " << cur << " would cause an integer underflow"; throw std::range_error(msg.str()); - } - else if ((delta < 0) && - ((std::numeric_limits::max() + delta) < cur)) - { + } else if ( + (delta < 0) && ((std::numeric_limits::max() + delta) < cur)) { std::ostringstream msg; msg.imbue(std::locale::classic()); msg << "subtracting " << delta << " from " << cur @@ -278,6 +280,6 @@ namespace QIntC // QIntC = qpdf Integer Conversion throw std::range_error(msg.str()); } } -}; +}; // namespace QIntC #endif // QINTC_HH diff --git a/include/qpdf/QPDF.hh b/include/qpdf/QPDF.hh index efb0db95..d1d9f268 100644 --- a/include/qpdf/QPDF.hh +++ b/include/qpdf/QPDF.hh @@ -25,26 +25,25 @@ #include #include +#include +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include class QPDF_Stream; class BitStream; @@ -87,24 +86,29 @@ class QPDF // file will be closed at the end. Otherwise, the caller is // responsible for closing the file. QPDF_DLL - void processFile(char const* description, FILE* file, - bool close_file, char const* password = 0); + void processFile( + char const* description, + FILE* file, + bool close_file, + char const* password = 0); // Parse a PDF file loaded into a memory buffer. This works // exactly like processFile except that the PDF file is in memory // instead of on disk. The description appears in any warning or // error message in place of the file name. QPDF_DLL - void processMemoryFile(char const* description, - char const* buf, size_t length, - char const* password = 0); + void processMemoryFile( + char const* description, + char const* buf, + size_t length, + char const* password = 0); // Parse a PDF file loaded from a custom InputSource. If you have // your own method of retrieving a PDF file, you can subclass // InputSource and use this method. QPDF_DLL - void processInputSource(PointerHolder, - char const* password = 0); + void + processInputSource(PointerHolder, char const* password = 0); // Close or otherwise release the input source. Once this has been // called, no other methods of qpdf can be called safely except @@ -149,7 +153,7 @@ class QPDF QPDF_DLL static void registerStreamFilter( std::string const& filter_name, - std::function ()> factory); + std::function()> factory); // Parameter settings @@ -312,8 +316,7 @@ class QPDF QPDF_DLL void swapObjects(QPDFObjGen const& og1, QPDFObjGen const& og2); QPDF_DLL - void swapObjects(int objid1, int generation1, - int objid2, int generation2); + void swapObjects(int objid1, int generation1, int objid2, int generation2); // Replace a reserved object. This is a wrapper around // replaceObject but it guarantees that the underlying object is a @@ -321,8 +324,7 @@ class QPDF // to replacement. QPDF_DLL void - replaceReserved(QPDFObjectHandle reserved, - QPDFObjectHandle replacement); + replaceReserved(QPDFObjectHandle reserved, QPDFObjectHandle replacement); // Copy an object from another QPDF to this one. Starting with // qpdf version 8.3.0, it is no longer necessary to keep the @@ -377,13 +379,19 @@ class QPDF class EncryptionData { public: - // This class holds data read from the encryption dictionary. - EncryptionData(int V, int R, int Length_bytes, int P, - std::string const& O, std::string const& U, - std::string const& OE, std::string const& UE, - std::string const& Perms, - std::string const& id1, bool encrypt_metadata) : + EncryptionData( + int V, + int R, + int Length_bytes, + int P, + std::string const& O, + std::string const& U, + std::string const& OE, + std::string const& UE, + std::string const& Perms, + std::string const& id1, + bool encrypt_metadata) : V(V), R(R), Length_bytes(Length_bytes), @@ -412,11 +420,12 @@ class QPDF void setO(std::string const&); void setU(std::string const&); - void setV5EncryptionParameters(std::string const& O, - std::string const& OE, - std::string const& U, - std::string const& UE, - std::string const& Perms); + void setV5EncryptionParameters( + std::string const& O, + std::string const& OE, + std::string const& U, + std::string const& UE, + std::string const& Perms); private: EncryptionData(EncryptionData const&) = delete; @@ -442,10 +451,13 @@ class QPDF bool isEncrypted(int& R, int& P); QPDF_DLL - bool isEncrypted(int& R, int& P, int& V, - encryption_method_e& stream_method, - encryption_method_e& string_method, - encryption_method_e& file_method); + bool isEncrypted( + int& R, + int& P, + int& V, + encryption_method_e& stream_method, + encryption_method_e& string_method, + encryption_method_e& file_method); QPDF_DLL bool ownerPasswordMatched() const; @@ -480,26 +492,44 @@ class QPDF static void trim_user_password(std::string& user_password); QPDF_DLL static std::string compute_data_key( - std::string const& encryption_key, int objid, int generation, - bool use_aes, int encryption_V, int encryption_R); + std::string const& encryption_key, + int objid, + int generation, + bool use_aes, + int encryption_V, + int encryption_R); QPDF_DLL static std::string compute_encryption_key( std::string const& password, EncryptionData const& data); QPDF_DLL static void compute_encryption_O_U( - char const* user_password, char const* owner_password, - int V, int R, int key_len, int P, bool encrypt_metadata, + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + int P, + bool encrypt_metadata, std::string const& id1, - std::string& O, std::string& U); + std::string& O, + std::string& U); QPDF_DLL static void compute_encryption_parameters_V5( - char const* user_password, char const* owner_password, - int V, int R, int key_len, int P, bool encrypt_metadata, + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + int P, + bool encrypt_metadata, std::string const& id1, std::string& encryption_key, - std::string& O, std::string& U, - std::string& OE, std::string& UE, std::string& Perms); + std::string& O, + std::string& U, + std::string& OE, + std::string& UE, + std::string& Perms); // Return the full user password as stored in the PDF file. For // files encrypted with 40-bit or 128-bit keys, the user password // can be recovered when the file is opened using the owner @@ -587,8 +617,9 @@ class QPDF // keys. This is used by QPDFWriter to avoid creation of dangling // objects for stream dictionary keys it will be regenerating. QPDF_DLL - void optimize(std::map const& object_stream_data, - bool allow_changes = true); + void optimize( + std::map const& object_stream_data, + bool allow_changes = true); // ABI: make function optional and merge overloaded versions QPDF_DLL void optimize( @@ -650,8 +681,8 @@ class QPDF QPDF_DLL void addPage(QPDFObjectHandle newpage, bool first); QPDF_DLL - void addPageAt(QPDFObjectHandle newpage, bool before, - QPDFObjectHandle refpage); + void + addPageAt(QPDFObjectHandle newpage, bool before, QPDFObjectHandle refpage); QPDF_DLL void removePage(QPDFObjectHandle page); // End legacy page helpers @@ -661,9 +692,10 @@ class QPDF class Writer { friend class QPDFWriter; - private: - static void getLinearizedParts( + private: + static void + getLinearizedParts( QPDF& qpdf, std::map const& object_stream_data, std::vector& part4, @@ -672,28 +704,32 @@ class QPDF std::vector& part8, std::vector& part9) { - qpdf.getLinearizedParts(object_stream_data, - part4, part6, part7, part8, part9); + qpdf.getLinearizedParts( + object_stream_data, part4, part6, part7, part8, part9); } - static void generateHintStream( + static void + generateHintStream( QPDF& qpdf, std::map const& xref, std::map const& lengths, std::map const& obj_renumber, PointerHolder& hint_stream, - int& S, int& O) + int& S, + int& O) { - return qpdf.generateHintStream(xref, lengths, obj_renumber, - hint_stream, S, O); + return qpdf.generateHintStream( + xref, lengths, obj_renumber, hint_stream, S, O); } - static void getObjectStreamData(QPDF& qpdf, std::map& omap) + static void + getObjectStreamData(QPDF& qpdf, std::map& omap) { qpdf.getObjectStreamData(omap); } - static std::vector getCompressibleObjGens(QPDF& qpdf) + static std::vector + getCompressibleObjGens(QPDF& qpdf) { return qpdf.getCompressibleObjGens(); } @@ -704,13 +740,15 @@ class QPDF class Resolver { friend class QPDFObjectHandle; + private: - static PointerHolder resolve( - QPDF* qpdf, int objid, int generation) + static PointerHolder + resolve(QPDF* qpdf, int objid, int generation) { return qpdf->resolve(objid, generation); } - static bool objectChanged( + static bool + objectChanged( QPDF* qpdf, QPDFObjGen const& og, PointerHolder& oph) { return qpdf->objectChanged(og, oph); @@ -723,10 +761,13 @@ class QPDF class StreamCopier { friend class QPDFObjectHandle; + private: - static void copyStreamData(QPDF* qpdf, - QPDFObjectHandle const& dest, - QPDFObjectHandle const& src) + static void + copyStreamData( + QPDF* qpdf, + QPDFObjectHandle const& dest, + QPDFObjectHandle const& src) { qpdf->copyStreamData(dest, src); } @@ -738,19 +779,18 @@ class QPDF class ParseGuard { friend class QPDFObjectHandle; + private: ParseGuard(QPDF* qpdf) : qpdf(qpdf) { - if (qpdf) - { + if (qpdf) { qpdf->inParse(true); } } ~ParseGuard() { - if (qpdf) - { + if (qpdf) { qpdf->inParse(false); } } @@ -762,17 +802,29 @@ class QPDF class Pipe { friend class QPDF_Stream; + private: - static bool pipeStreamData(QPDF* qpdf, int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle dict, - Pipeline* pipeline, - bool suppress_warnings, - bool will_retry) + static bool + pipeStreamData( + QPDF* qpdf, + int objid, + int generation, + qpdf_offset_t offset, + size_t length, + QPDFObjectHandle dict, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) { return qpdf->pipeStreamData( - objid, generation, offset, length, dict, pipeline, - suppress_warnings, will_retry); + objid, + generation, + offset, + length, + dict, + pipeline, + suppress_warnings, + will_retry); } }; friend class Pipe; @@ -788,9 +840,10 @@ class QPDF end_after_space(0) { } - ObjCache(PointerHolder object, - qpdf_offset_t end_before_space, - qpdf_offset_t end_after_space) : + ObjCache( + PointerHolder object, + qpdf_offset_t end_before_space, + qpdf_offset_t end_after_space) : object(object), end_before_space(end_before_space), end_after_space(end_after_space) @@ -813,6 +866,7 @@ class QPDF class EncryptionParameters { friend class QPDF; + public: EncryptionParameters(); @@ -839,6 +893,7 @@ class QPDF class ForeignStreamData { friend class QPDF; + public: ForeignStreamData( PointerHolder encp, @@ -867,18 +922,21 @@ class QPDF { } virtual bool provideStreamData( - int objid, int generation, Pipeline* pipeline, - bool suppress_warnings, bool will_retry) override; - void registerForeignStream(QPDFObjGen const& local_og, - QPDFObjectHandle foreign_stream); - void registerForeignStream(QPDFObjGen const& local_og, - PointerHolder); + int objid, + int generation, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) override; + void registerForeignStream( + QPDFObjGen const& local_og, QPDFObjectHandle foreign_stream); + void registerForeignStream( + QPDFObjGen const& local_og, PointerHolder); private: QPDF& destination_qpdf; std::map foreign_streams; - std::map > foreign_stream_data; + std::map> + foreign_stream_data; }; class StringDecrypter: public QPDFObjectHandle::StringDecrypter @@ -911,6 +969,7 @@ class QPDF { this->qpdf->m->resolving.erase(og); } + private: QPDF* qpdf; QPDFObjGen og; @@ -922,56 +981,72 @@ class QPDF void setTrailer(QPDFObjectHandle obj); void read_xref(qpdf_offset_t offset); void reconstruct_xref(QPDFExc& e); - bool parse_xrefFirst(std::string const& line, - int& obj, int& num, int& bytes); - bool parse_xrefEntry(std::string const& line, - qpdf_offset_t& f1, int& f2, char& type); + bool + parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes); + bool parse_xrefEntry( + std::string const& line, qpdf_offset_t& f1, int& f2, char& type); qpdf_offset_t read_xrefTable(qpdf_offset_t offset); qpdf_offset_t read_xrefStream(qpdf_offset_t offset); - qpdf_offset_t processXRefStream( - qpdf_offset_t offset, QPDFObjectHandle& xref_stream); - void insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2, - bool overwrite = false); - void setLastObjectDescription(std::string const& description, - int objid, int generation); + qpdf_offset_t + processXRefStream(qpdf_offset_t offset, QPDFObjectHandle& xref_stream); + void insertXrefEntry( + int obj, int f0, qpdf_offset_t f1, int f2, bool overwrite = false); + void setLastObjectDescription( + std::string const& description, int objid, int generation); QPDFObjectHandle readObject( - PointerHolder, std::string const& description, - int objid, int generation, bool in_object_stream); + PointerHolder, + std::string const& description, + int objid, + int generation, + bool in_object_stream); size_t recoverStreamLength( - PointerHolder input, int objid, int generation, + PointerHolder input, + int objid, + int generation, qpdf_offset_t stream_offset); - QPDFTokenizer::Token readToken(PointerHolder, - size_t max_len = 0); + QPDFTokenizer::Token + readToken(PointerHolder, size_t max_len = 0); QPDFObjectHandle readObjectAtOffset( bool attempt_recovery, - qpdf_offset_t offset, std::string const& description, - int exp_objid, int exp_generation, - int& act_objid, int& act_generation); + qpdf_offset_t offset, + std::string const& description, + int exp_objid, + int exp_generation, + int& act_objid, + int& act_generation); bool objectChanged(QPDFObjGen const& og, PointerHolder& oph); PointerHolder resolve(int objid, int generation); void resolveObjectsInStream(int obj_stream_number); void stopOnError(std::string const& message); // Calls finish() on the pipeline when done but does not delete it - bool pipeStreamData(int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle dict, - Pipeline* pipeline, - bool suppress_warnings, - bool will_retry); + bool pipeStreamData( + int objid, + int generation, + qpdf_offset_t offset, + size_t length, + QPDFObjectHandle dict, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry); bool pipeForeignStreamData( PointerHolder, - Pipeline*, bool suppress_warnings, bool will_retry); - static bool pipeStreamData(PointerHolder encp, - PointerHolder file, - QPDF& qpdf_for_warning, - int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle dict, - Pipeline* pipeline, - bool suppress_warnings, - bool will_retry); + Pipeline*, + bool suppress_warnings, + bool will_retry); + static bool pipeStreamData( + PointerHolder encp, + PointerHolder file, + QPDF& qpdf_for_warning, + int objid, + int generation, + qpdf_offset_t offset, + size_t length, + QPDFObjectHandle dict, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry); // For QPDFWriter: @@ -985,11 +1060,13 @@ class QPDF std::vector& part8, std::vector& part9); - void generateHintStream(std::map const& xref, - std::map const& lengths, - std::map const& obj_renumber, - PointerHolder& hint_stream, - int& S, int& O); + void generateHintStream( + std::map const& xref, + std::map const& lengths, + std::map const& obj_renumber, + PointerHolder& hint_stream, + int& S, + int& O); // Map object to object stream that contains it void getObjectStreamData(std::map&); @@ -1000,45 +1077,51 @@ class QPDF // methods to support page handling - void getAllPagesInternal(QPDFObjectHandle cur_pages, - std::vector& result, - std::set& visited, - std::set& seen); + void getAllPagesInternal( + QPDFObjectHandle cur_pages, + std::vector& result, + std::set& visited, + std::set& seen); void insertPage(QPDFObjectHandle newpage, int pos); void flattenPagesTree(); - void insertPageobjToPage(QPDFObjectHandle const& obj, int pos, - bool check_duplicate); + void insertPageobjToPage( + QPDFObjectHandle const& obj, int pos, bool check_duplicate); // methods to support encryption -- implemented in QPDF_encryption.cc - static encryption_method_e interpretCF( - PointerHolder encp, QPDFObjectHandle); + static encryption_method_e + interpretCF(PointerHolder encp, QPDFObjectHandle); void initializeEncryption(); static std::string getKeyForObject( PointerHolder encp, - int objid, int generation, bool use_aes); + int objid, + int generation, + bool use_aes); void decryptString(std::string&, int objid, int generation); static std::string compute_encryption_key_from_password( std::string const& password, EncryptionData const& data); static std::string recover_encryption_key_with_password( std::string const& password, EncryptionData const& data); static std::string recover_encryption_key_with_password( - std::string const& password, EncryptionData const& data, + std::string const& password, + EncryptionData const& data, bool& perms_valid); static void decryptStream( PointerHolder encp, PointerHolder file, - QPDF& qpdf_for_warning, Pipeline*& pipeline, - int objid, int generation, + QPDF& qpdf_for_warning, + Pipeline*& pipeline, + int objid, + int generation, QPDFObjectHandle& stream_dict, std::vector>& heap); // Methods to support object copying - void reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, - bool top); + void + reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top); QPDFObjectHandle replaceForeignIndirectObjects( QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top); - void copyStreamData( - QPDFObjectHandle dest_stream, QPDFObjectHandle src_stream); + void + copyStreamData(QPDFObjectHandle dest_stream, QPDFObjectHandle src_stream); // Linearization Hint table structures. // Naming conventions: @@ -1065,14 +1148,14 @@ class QPDF { } - int delta_nobjects; // 1 - qpdf_offset_t delta_page_length; // 2 - int nshared_objects; // 3 + int delta_nobjects; // 1 + qpdf_offset_t delta_page_length; // 2 + int nshared_objects; // 3 // vectors' sizes = nshared_objects - std::vector shared_identifiers; // 4 - std::vector shared_numerators; // 5 - qpdf_offset_t delta_content_offset; // 6 - qpdf_offset_t delta_content_length; // 7 + std::vector shared_identifiers; // 4 + std::vector shared_numerators; // 5 + qpdf_offset_t delta_content_offset; // 6 + qpdf_offset_t delta_content_length; // 7 }; // PDF 1.4: Table F.3 @@ -1095,19 +1178,19 @@ class QPDF { } - int min_nobjects; // 1 - qpdf_offset_t first_page_offset; // 2 - int nbits_delta_nobjects; // 3 - int min_page_length; // 4 - int nbits_delta_page_length; // 5 - int min_content_offset; // 6 - int nbits_delta_content_offset; // 7 - int min_content_length; // 8 - int nbits_delta_content_length; // 9 - int nbits_nshared_objects; // 10 - int nbits_shared_identifier; // 11 - int nbits_shared_numerator; // 12 - int shared_denominator; // 13 + int min_nobjects; // 1 + qpdf_offset_t first_page_offset; // 2 + int nbits_delta_nobjects; // 3 + int min_page_length; // 4 + int nbits_delta_page_length; // 5 + int min_content_offset; // 6 + int nbits_delta_content_offset; // 7 + int min_content_length; // 8 + int nbits_delta_content_length; // 9 + int nbits_nshared_objects; // 10 + int nbits_shared_identifier; // 11 + int nbits_shared_numerator; // 12 + int shared_denominator; // 13 // vector size is npages std::vector entries; }; @@ -1123,9 +1206,9 @@ class QPDF } // Item 3 is a 128-bit signature (unsupported by Acrobat) - int delta_group_length; // 1 - int signature_present; // 2 -- always 0 - int nobjects_minus_one; // 4 -- always 0 + int delta_group_length; // 1 + int signature_present; // 2 -- always 0 + int nobjects_minus_one; // 4 -- always 0 }; // PDF 1.4: Table F.5 @@ -1142,13 +1225,13 @@ class QPDF { } - int first_shared_obj; // 1 - qpdf_offset_t first_shared_offset; // 2 - int nshared_first_page; // 3 - int nshared_total; // 4 - int nbits_nobjects; // 5 - int min_group_length; // 6 - int nbits_delta_group_length; // 7 + int first_shared_obj; // 1 + qpdf_offset_t first_shared_offset; // 2 + int nshared_first_page; // 3 + int nshared_total; // 4 + int nbits_nobjects; // 5 + int min_group_length; // 6 + int nbits_delta_group_length; // 7 // vector size is nshared_total std::vector entries; }; @@ -1164,10 +1247,10 @@ class QPDF { } - int first_object; // 1 - qpdf_offset_t first_object_offset; // 2 - int nobjects; // 3 - int group_length; // 4 + int first_object; // 1 + qpdf_offset_t first_object_offset; // 2 + int nobjects; // 3 + int group_length; // 4 }; // Other linearization data structures @@ -1261,15 +1344,13 @@ class QPDF // No need for CHGeneric -- HGeneric is fine as is. - // Data structures to support optimization -- implemented in // QPDF_optimization.cc class ObjUser { public: - enum user_e - { + enum user_e { ou_bad, ou_page, ou_thumb, @@ -1293,8 +1374,8 @@ class QPDF bool operator<(ObjUser const&) const; user_e ou_type; - int pageno; // if ou_page; - std::string key; // if ou_trailer_key or ou_root_key + int pageno; // if ou_page; + std::string key; // if ou_trailer_key or ou_root_key }; class PatternFinder: public InputSource::Finder @@ -1308,7 +1389,8 @@ class QPDF virtual ~PatternFinder() { } - virtual bool check() + virtual bool + check() { return (this->qpdf.*checker)(); } @@ -1328,8 +1410,8 @@ class QPDF void readLinearizationData(); bool checkLinearizationInternal(); void dumpLinearizationDataInternal(); - QPDFObjectHandle readHintStream( - Pipeline&, qpdf_offset_t offset, size_t length); + QPDFObjectHandle + readHintStream(Pipeline&, qpdf_offset_t offset, size_t length); void readHPageOffset(BitStream); void readHSharedObject(BitStream); void readHGeneric(BitStream, HGeneric&); @@ -1337,30 +1419,32 @@ class QPDF qpdf_offset_t getLinearizationOffset(QPDFObjGen const&); QPDFObjectHandle getUncompressedObject( QPDFObjectHandle&, std::map const& object_stream_data); - int lengthNextN(int first_object, int n, - std::list& errors); - void checkHPageOffset(std::list& errors, - std::list& warnings, - std::vector const& pages, - std::map& idx_to_obj); - void checkHSharedObject(std::list& warnings, - std::list& errors, - std::vector const& pages, - std::map& idx_to_obj); + int lengthNextN(int first_object, int n, std::list& errors); + void checkHPageOffset( + std::list& errors, + std::list& warnings, + std::vector const& pages, + std::map& idx_to_obj); + void checkHSharedObject( + std::list& warnings, + std::list& errors, + std::vector const& pages, + std::map& idx_to_obj); void checkHOutlines(std::list& warnings); void dumpHPageOffset(); void dumpHSharedObject(); void dumpHGeneric(HGeneric&); qpdf_offset_t adjusted_offset(qpdf_offset_t offset); QPDFObjectHandle objGenToIndirect(QPDFObjGen const&); - void calculateLinearizationData( - std::map const& object_stream_data); + void + calculateLinearizationData(std::map const& object_stream_data); void pushOutlinesToPart( std::vector& part, std::set& lc_outlines, std::map const& object_stream_data); int outputLengthNextN( - int in_object, int n, + int in_object, + int n, std::map const& lengths, std::map const& obj_renumber); void calculateHPageOffset( @@ -1379,37 +1463,46 @@ class QPDF void writeHSharedObject(BitWriter&); void writeHGeneric(BitWriter&, HGeneric&); - // Methods to support optimization - void pushInheritedAttributesToPage(bool allow_changes, - bool warn_skipped_keys); + void + pushInheritedAttributesToPage(bool allow_changes, bool warn_skipped_keys); void pushInheritedAttributesToPageInternal( QPDFObjectHandle, - std::map >&, + std::map>&, std::vector& all_pages, - bool allow_changes, bool warn_skipped_keys, + bool allow_changes, + bool warn_skipped_keys, std::set& visited); void updateObjectMaps( - ObjUser const& ou, QPDFObjectHandle oh, + ObjUser const& ou, + QPDFObjectHandle oh, std::function skip_stream_parameters); void updateObjectMapsInternal( - ObjUser const& ou, QPDFObjectHandle oh, + ObjUser const& ou, + QPDFObjectHandle oh, std::function skip_stream_parameters, - std::set& visited, bool top, + std::set& visited, + bool top, int depth); void filterCompressedObjects(std::map const& object_stream_data); // Type conversion helper methods - template static qpdf_offset_t toO(T const& i) + template + static qpdf_offset_t + toO(T const& i) { return QIntC::to_offset(i); } - template static size_t toS(T const& i) + template + static size_t + toS(T const& i) { return QIntC::to_size(i); } - template static int toI(T const& i) + template + static int + toI(T const& i) { return QIntC::to_int(i); } @@ -1490,8 +1583,8 @@ class QPDF std::vector part9; // Optimization data - std::map > obj_user_to_objects; - std::map > object_to_obj_users; + std::map> obj_user_to_objects; + std::map> object_to_obj_users; }; // Keep all member variables inside the Members object, which we diff --git a/include/qpdf/QPDFAcroFormDocumentHelper.hh b/include/qpdf/QPDFAcroFormDocumentHelper.hh index dc4b05ad..236b2835 100644 --- a/include/qpdf/QPDFAcroFormDocumentHelper.hh +++ b/include/qpdf/QPDFAcroFormDocumentHelper.hh @@ -67,7 +67,6 @@ // the "/AcroForm" field entry until you find the annotation // dictionary. - #include #include @@ -144,8 +143,7 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper // information to be accurate, any changes to field names must be // done through setFormFieldName() above. QPDF_DLL - std::set - getFieldsWithQualifiedName(std::string const& name); + std::set getFieldsWithQualifiedName(std::string const& name); // Return the annotations associated with a terminal field. Note // that in the case of a field having a single annotation, the @@ -153,17 +151,17 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper // object for the field. QPDF_DLL std::vector - getAnnotationsForField(QPDFFormFieldObjectHelper); + getAnnotationsForField(QPDFFormFieldObjectHelper); // Return annotations of subtype /Widget for a page. QPDF_DLL std::vector - getWidgetAnnotationsForPage(QPDFPageObjectHelper); + getWidgetAnnotationsForPage(QPDFPageObjectHelper); // Return top-level form fields for a page. QPDF_DLL std::vector - getFormFieldsForPage(QPDFPageObjectHelper); + getFormFieldsForPage(QPDFPageObjectHelper); // Return the terminal field that is associated with this // annotation. If the annotation dictionary is merged with the @@ -173,8 +171,7 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper // not be an associated field, and this method will return a // helper associated with a null object (isNull() == true). QPDF_DLL - QPDFFormFieldObjectHelper - getFieldForAnnotation(QPDFAnnotationObjectHelper); + QPDFFormFieldObjectHelper getFieldForAnnotation(QPDFAnnotationObjectHelper); // Return the current value of /NeedAppearances. If // /NeedAppearances is missing, return false as that is how PDF @@ -260,30 +257,33 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper // happens with qpdf --split-pages. [[deprecated("Use fixCopiedAnnotations instead")]] // ABI: delete this method - QPDF_DLL - void copyFieldsFromForeignPage( + QPDF_DLL void + copyFieldsFromForeignPage( QPDFPageObjectHelper foreign_page, QPDFAcroFormDocumentHelper& foreign_afdh, std::vector* copied_fields = nullptr); private: void analyze(); - void traverseField(QPDFObjectHandle field, - QPDFObjectHandle parent, - int depth, std::set& visited); + void traverseField( + QPDFObjectHandle field, + QPDFObjectHandle parent, + int depth, + std::set& visited); QPDFObjectHandle getOrCreateAcroForm(); void adjustInheritedFields( QPDFObjectHandle obj, - bool override_da, std::string const& from_default_da, - bool override_q, int from_default_q); + bool override_da, + std::string const& from_default_da, + bool override_q, + int from_default_q); void adjustDefaultAppearances( QPDFObjectHandle obj, - std::map> const& dr_map); + std::map> const& + dr_map); void adjustAppearanceStream( QPDFObjectHandle stream, - std::map> dr_map); + std::map> dr_map); class Members { @@ -298,9 +298,8 @@ class QPDFAcroFormDocumentHelper: public QPDFDocumentHelper Members(Members const&); bool cache_valid; - std::map - > field_to_annotations; + std::map> + field_to_annotations; std::map annotation_to_field; std::map field_to_name; std::map> name_to_fields; diff --git a/include/qpdf/QPDFAnnotationObjectHelper.hh b/include/qpdf/QPDFAnnotationObjectHelper.hh index 480688e0..26ee050a 100644 --- a/include/qpdf/QPDFAnnotationObjectHelper.hh +++ b/include/qpdf/QPDFAnnotationObjectHelper.hh @@ -22,8 +22,8 @@ #ifndef QPDFANNOTATIONOBJECTHELPER_HH #define QPDFANNOTATIONOBJECTHELPER_HH -#include #include +#include #include @@ -78,8 +78,8 @@ class QPDFAnnotationObjectHelper: public QPDFObjectHelper // which appearance stream is desired. If not specified, the // appearance state in "/AS" will used. QPDF_DLL - QPDFObjectHandle getAppearanceStream(std::string const& which, - std::string const& state = ""); + QPDFObjectHandle getAppearanceStream( + std::string const& which, std::string const& state = ""); // Generate text suitable for addition to the containing page's // content stream that draws this annotation's appearance stream @@ -96,7 +96,8 @@ class QPDFAnnotationObjectHelper: public QPDFObjectHelper // preparing to print. QPDF_DLL std::string getPageContentForAppearance( - std::string const& name, int rotate, + std::string const& name, + int rotate, int required_flags = 0, int forbidden_flags = an_invisible | an_hidden); diff --git a/include/qpdf/QPDFCryptoImpl.hh b/include/qpdf/QPDFCryptoImpl.hh index 43d2f170..bf3c9087 100644 --- a/include/qpdf/QPDFCryptoImpl.hh +++ b/include/qpdf/QPDFCryptoImpl.hh @@ -77,19 +77,22 @@ class QPDF_DLL_CLASS QPDFCryptoImpl virtual void RC4_init(unsigned char const* key_data, int key_len = -1) = 0; // out_data = 0 means to encrypt/decrypt in place QPDF_DLL - virtual void RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0) = 0; + virtual void RC4_process( + unsigned char* in_data, size_t len, unsigned char* out_data = 0) = 0; QPDF_DLL virtual void RC4_finalize() = 0; static size_t constexpr rijndael_buf_size = 16; QPDF_DLL virtual void rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block) = 0; + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block) = 0; QPDF_DLL - virtual void rijndael_process( - unsigned char* in_data, unsigned char* out_data) = 0; + virtual void + rijndael_process(unsigned char* in_data, unsigned char* out_data) = 0; QPDF_DLL virtual void rijndael_finalize() = 0; }; diff --git a/include/qpdf/QPDFCryptoProvider.hh b/include/qpdf/QPDFCryptoProvider.hh index 057f6624..d8577859 100644 --- a/include/qpdf/QPDFCryptoProvider.hh +++ b/include/qpdf/QPDFCryptoProvider.hh @@ -24,11 +24,11 @@ #include #include -#include -#include -#include -#include #include +#include +#include +#include +#include // This class is part of qpdf's pluggable crypto provider support. // Most users won't need to know or care about this class, but you can @@ -38,7 +38,6 @@ class QPDFCryptoProvider { public: - // Methods for getting and registering crypto implementations. // These methods are not thread-safe. @@ -50,15 +49,13 @@ class QPDFCryptoProvider // Return an instance of the crypto provider registered using the // given name. QPDF_DLL - static std::shared_ptr - getImpl(std::string const& name); + static std::shared_ptr getImpl(std::string const& name); // Register the given type (T) as a crypto implementation. T must // be derived from QPDFCryptoImpl and must have a constructor that // takes no arguments. - template - QPDF_DLL - static void registerImpl(std::string const& name); + template + QPDF_DLL static void registerImpl(std::string const& name); // Set the crypto provider registered with the given name as the // default crypto implementation. @@ -83,7 +80,7 @@ class QPDFCryptoProvider std::shared_ptr getImpl_internal(std::string const& name) const; - template + template void registerImpl_internal(std::string const& name); void setDefaultProvider_internal(std::string const& name); @@ -100,7 +97,7 @@ class QPDFCryptoProvider Members(Members const&) = delete; Members& operator=(Members const&) = delete; - typedef std::function ()> provider_fn; + typedef std::function()> provider_fn; std::string default_provider; std::map providers; }; diff --git a/include/qpdf/QPDFDocumentHelper.hh b/include/qpdf/QPDFDocumentHelper.hh index c198089a..d33e90b8 100644 --- a/include/qpdf/QPDFDocumentHelper.hh +++ b/include/qpdf/QPDFDocumentHelper.hh @@ -49,12 +49,14 @@ class QPDFDocumentHelper { } QPDF_DLL - QPDF& getQPDF() + QPDF& + getQPDF() { return this->qpdf; } QPDF_DLL - QPDF const& getQPDF() const + QPDF const& + getQPDF() const { return this->qpdf; } diff --git a/include/qpdf/QPDFEmbeddedFileDocumentHelper.hh b/include/qpdf/QPDFEmbeddedFileDocumentHelper.hh index 9691bfe6..73d5f041 100644 --- a/include/qpdf/QPDFEmbeddedFileDocumentHelper.hh +++ b/include/qpdf/QPDFEmbeddedFileDocumentHelper.hh @@ -24,13 +24,13 @@ #include -#include -#include -#include #include +#include +#include +#include -#include #include +#include // This class provides a higher level interface around document-level // file attachments, also known as embedded files. These are discussed @@ -48,8 +48,8 @@ class QPDFEmbeddedFileDocumentHelper: public QPDFDocumentHelper bool hasEmbeddedFiles() const; QPDF_DLL - std::map> getEmbeddedFiles(); + std::map> + getEmbeddedFiles(); // If an embedded file with the given name exists, return a // (shared) pointer to it. Otherwise, return nullptr. diff --git a/include/qpdf/QPDFExc.hh b/include/qpdf/QPDFExc.hh index 6a46aff8..1d88bcf9 100644 --- a/include/qpdf/QPDFExc.hh +++ b/include/qpdf/QPDFExc.hh @@ -22,22 +22,23 @@ #ifndef QPDFEXC_HH #define QPDFEXC_HH +#include #include #include -#include -#include #include +#include class QPDF_DLL_CLASS QPDFExc: public std::runtime_error { public: QPDF_DLL - QPDFExc(qpdf_error_code_e error_code, - std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message); + QPDFExc( + qpdf_error_code_e error_code, + std::string const& filename, + std::string const& object, + qpdf_offset_t offset, + std::string const& message); QPDF_DLL virtual ~QPDFExc() noexcept { @@ -65,10 +66,11 @@ class QPDF_DLL_CLASS QPDFExc: public std::runtime_error std::string const& getMessageDetail() const; private: - static std::string createWhat(std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message); + static std::string createWhat( + std::string const& filename, + std::string const& object, + qpdf_offset_t offset, + std::string const& message); // This class does not use the Members pattern to avoid needless // memory allocations during exception handling. diff --git a/include/qpdf/QPDFFileSpecObjectHelper.hh b/include/qpdf/QPDFFileSpecObjectHelper.hh index 9f442145..87c94399 100644 --- a/include/qpdf/QPDFFileSpecObjectHelper.hh +++ b/include/qpdf/QPDFFileSpecObjectHelper.hh @@ -26,8 +26,8 @@ #include -#include #include +#include // This class provides a higher level interface around File // Specification dictionaries, which are discussed in section 7.11 of @@ -77,22 +77,16 @@ class QPDFFileSpecObjectHelper: public QPDFObjectHelper // filename, and attach the contents of the specified file as data // in an embedded file stream. QPDF_DLL - static - QPDFFileSpecObjectHelper createFileSpec( - QPDF& qpdf, - std::string const& filename, - std::string const& fullpath); + static QPDFFileSpecObjectHelper createFileSpec( + QPDF& qpdf, std::string const& filename, std::string const& fullpath); // Create a new filespec as an indirect object with the given // unicode filename and embedded file stream. The file name will // be used as both /UF and /F. If you need to override, call // setFilename. QPDF_DLL - static - QPDFFileSpecObjectHelper createFileSpec( - QPDF& qpdf, - std::string const& filename, - QPDFEFStreamObjectHelper); + static QPDFFileSpecObjectHelper createFileSpec( + QPDF& qpdf, std::string const& filename, QPDFEFStreamObjectHelper); QPDF_DLL QPDFFileSpecObjectHelper& setDescription(std::string const&); @@ -103,8 +97,7 @@ class QPDFFileSpecObjectHelper: public QPDFObjectHelper // might happen to have. QPDF_DLL QPDFFileSpecObjectHelper& setFilename( - std::string const& unicode_name, - std::string const& compat_name = ""); + std::string const& unicode_name, std::string const& compat_name = ""); private: class Members diff --git a/include/qpdf/QPDFFormFieldObjectHelper.hh b/include/qpdf/QPDFFormFieldObjectHelper.hh index 64a3a81e..871816ab 100644 --- a/include/qpdf/QPDFFormFieldObjectHelper.hh +++ b/include/qpdf/QPDFFormFieldObjectHelper.hh @@ -185,8 +185,8 @@ class QPDFFormFieldObjectHelper: public QPDFObjectHelper // of a field, use QPDFAcroFormDocumentHelper::setFormFieldName // instead. QPDF_DLL - void setFieldAttribute(std::string const& key, - std::string const& utf8_value); + void + setFieldAttribute(std::string const& key, std::string const& utf8_value); // Set /V (field value) to the given value. If need_appearances is // true and the field type is either /Tx (text) or /Ch (choice), diff --git a/include/qpdf/QPDFJob.hh b/include/qpdf/QPDFJob.hh index acaa956b..510c6d18 100644 --- a/include/qpdf/QPDFJob.hh +++ b/include/qpdf/QPDFJob.hh @@ -22,22 +22,21 @@ #ifndef QPDFJOB_HH #define QPDFJOB_HH -#include #include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include #include +#include #include +#include +#include class QPDFWriter; @@ -79,8 +78,8 @@ class QPDFJob // about converting arguments to UTF-8. This method will mutate // arguments that are passed to it. QPDF_DLL - void initializeFromArgv(char const* const argv[], - char const* progname_env = nullptr); + void initializeFromArgv( + char const* const argv[], char const* progname_env = nullptr); // Initialize a QPDFJob from json. Passing partial = true prevents // this method from doing the final checks (calling @@ -155,9 +154,10 @@ class QPDFJob struct PageSpec { - PageSpec(std::string const& filename, - char const* password, - std::string const& range); + PageSpec( + std::string const& filename, + char const* password, + std::string const& range); std::string filename; std::shared_ptr password; @@ -203,13 +203,14 @@ class QPDFJob { friend class QPDFJob; friend class Config; + public: QPDF_DLL Config* endAddAttachment(); QPDF_DLL AttConfig* file(std::string const& parameter); -# include +#include private: AttConfig(Config*); @@ -223,13 +224,14 @@ class QPDFJob { friend class QPDFJob; friend class Config; + public: QPDF_DLL Config* endCopyAttachmentsFrom(); QPDF_DLL CopyAttConfig* file(std::string const& parameter); -# include +#include private: CopyAttConfig(Config*); @@ -243,15 +245,17 @@ class QPDFJob { friend class QPDFJob; friend class Config; + public: QPDF_DLL Config* endPages(); QPDF_DLL - PagesConfig* pageSpec(std::string const& filename, - std::string const& range, - char const* password = nullptr); + PagesConfig* pageSpec( + std::string const& filename, + std::string const& range, + char const* password = nullptr); -# include +#include private: PagesConfig(Config*); @@ -264,13 +268,14 @@ class QPDFJob { friend class QPDFJob; friend class Config; + public: QPDF_DLL Config* endUnderlayOverlay(); QPDF_DLL UOConfig* file(std::string const& parameter); -# include +#include private: UOConfig(Config*); @@ -283,13 +288,14 @@ class QPDFJob { friend class QPDFJob; friend class Config; + public: QPDF_DLL Config* endEncrypt(); QPDF_DLL EncConfig* file(std::string const& parameter); -# include +#include private: EncConfig(Config*); @@ -301,6 +307,7 @@ class QPDFJob class Config { friend class QPDFJob; + public: // Proxy to QPDFJob::checkConfiguration() QPDF_DLL @@ -331,7 +338,7 @@ class QPDFJob std::string const& user_password, std::string const& owner_password); -# include +#include private: Config() = delete; @@ -444,32 +451,37 @@ class QPDFJob // Basic file processing std::shared_ptr processFile( - char const* filename, char const* password, - bool used_for_input); + char const* filename, char const* password, bool used_for_input); std::shared_ptr processInputSource( - PointerHolder is, char const* password, + PointerHolder is, + char const* password, bool used_for_input); std::shared_ptr doProcess( std::function fn, - char const* password, bool empty, bool used_for_input); + char const* password, + bool empty, + bool used_for_input); std::shared_ptr doProcessOnce( std::function fn, - char const* password, bool empty, bool used_for_input); + char const* password, + bool empty, + bool used_for_input); // Transformations void setQPDFOptions(QPDF& pdf); void handlePageSpecs( - QPDF& pdf, bool& warnings, + QPDF& pdf, + bool& warnings, std::vector>& page_heap); bool shouldRemoveUnreferencedResources(QPDF& pdf); void handleRotations(QPDF& pdf); - void getUOPagenos(UnderOverlay& uo, - std::map >& pagenos); + void + getUOPagenos(UnderOverlay& uo, std::map>& pagenos); void handleUnderOverlay(QPDF& pdf); void doUnderOverlayForPage( QPDF& pdf, UnderOverlay& uo, - std::map >& pagenos, + std::map>& pagenos, size_t page_idx, std::map& fo, std::vector& pages, diff --git a/include/qpdf/QPDFMatrix.hh b/include/qpdf/QPDFMatrix.hh index ecf13bb3..f0516dbd 100644 --- a/include/qpdf/QPDFMatrix.hh +++ b/include/qpdf/QPDFMatrix.hh @@ -22,8 +22,8 @@ #ifndef QPDFMATRIX_HH #define QPDFMATRIX_HH -#include #include +#include #include // This class represents a PDF transformation matrix using a tuple @@ -41,8 +41,7 @@ class QPDFMatrix QPDF_DLL QPDFMatrix(); QPDF_DLL - QPDFMatrix(double a, double b, double c, - double d, double e, double f); + QPDFMatrix(double a, double b, double c, double d, double e, double f); QPDF_DLL QPDFMatrix(QPDFObjectHandle::Matrix const&); @@ -83,21 +82,22 @@ class QPDFMatrix // bounds the polygon resulting from transforming the four // corners. QPDF_DLL - QPDFObjectHandle::Rectangle transformRectangle( - QPDFObjectHandle::Rectangle r) const; + QPDFObjectHandle::Rectangle + transformRectangle(QPDFObjectHandle::Rectangle r) const; // ABI: delete non-const version QPDF_DLL - QPDFObjectHandle::Rectangle transformRectangle( - QPDFObjectHandle::Rectangle r); + QPDFObjectHandle::Rectangle + transformRectangle(QPDFObjectHandle::Rectangle r); // operator== tests for exact equality, not considering deltas for // floating point. QPDF_DLL bool operator==(QPDFMatrix const& rhs) const; QPDF_DLL - bool operator!=(QPDFMatrix const& rhs) const + bool + operator!=(QPDFMatrix const& rhs) const { - return ! operator==(rhs); + return !operator==(rhs); } double a; diff --git a/include/qpdf/QPDFNameTreeObjectHelper.hh b/include/qpdf/QPDFNameTreeObjectHelper.hh index baa6e5e9..1523b142 100644 --- a/include/qpdf/QPDFNameTreeObjectHelper.hh +++ b/include/qpdf/QPDFNameTreeObjectHelper.hh @@ -22,11 +22,11 @@ #ifndef QPDFNAMETREEOBJECTHELPER_HH #define QPDFNAMETREEOBJECTHELPER_HH -#include #include +#include +#include #include #include -#include #include @@ -48,16 +48,14 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper // The qpdf object is required so that this class can issue // warnings, attempt repairs, and add indirect objects. QPDF_DLL - QPDFNameTreeObjectHelper(QPDFObjectHandle, QPDF&, - bool auto_repair = true); + QPDFNameTreeObjectHelper(QPDFObjectHandle, QPDF&, bool auto_repair = true); // ABI: Legacy Constructor will be removed in QPDF 11. A // QPDFNameTreeObjectHelper constructed in this way can't be // modified or repaired and will silently ignore problems in the // structure. - [[deprecated("use constructor that takes QPDF&")]] - QPDF_DLL - QPDFNameTreeObjectHelper(QPDFObjectHandle); + [[deprecated("use constructor that takes QPDF&")]] QPDF_DLL + QPDFNameTreeObjectHelper(QPDFObjectHandle); // Create an empty name tree QPDF_DLL @@ -80,6 +78,7 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper class iterator { friend class QPDFNameTreeObjectHelper; + public: typedef std::pair T; using iterator_category = std::bidirectional_iterator_tag; @@ -94,7 +93,8 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper QPDF_DLL iterator& operator++(); QPDF_DLL - iterator operator++(int) + iterator + operator++(int) { iterator t = *this; ++(*this); @@ -103,7 +103,8 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper QPDF_DLL iterator& operator--(); QPDF_DLL - iterator operator--(int) + iterator + operator--(int) { iterator t = *this; --(*this); @@ -116,9 +117,10 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper QPDF_DLL bool operator==(iterator const& other) const; QPDF_DLL - bool operator!=(iterator const& other) const + bool + operator!=(iterator const& other) const { - return ! operator==(other); + return !operator==(other); } // DANGER: this method can create inconsistent trees if not @@ -162,8 +164,8 @@ class QPDFNameTreeObjectHelper: public QPDFObjectHelper // Find the entry with the given key. If return_prev_if_not_found // is true and the item is not found, return the next lower item. QPDF_DLL - iterator find(std::string const& key, - bool return_prev_if_not_found = false); + iterator + find(std::string const& key, bool return_prev_if_not_found = false); // Insert a new item. If the key already exists, it is replaced. QPDF_DLL diff --git a/include/qpdf/QPDFNumberTreeObjectHelper.hh b/include/qpdf/QPDFNumberTreeObjectHelper.hh index cfe20b72..0f0acf06 100644 --- a/include/qpdf/QPDFNumberTreeObjectHelper.hh +++ b/include/qpdf/QPDFNumberTreeObjectHelper.hh @@ -22,8 +22,8 @@ #ifndef QPDFNUMBERTREEOBJECTHELPER_HH #define QPDFNUMBERTREEOBJECTHELPER_HH -#include #include +#include #include #include @@ -45,16 +45,15 @@ class QPDFNumberTreeObjectHelper: public QPDFObjectHelper // The qpdf object is required so that this class can issue // warnings, attempt repairs, and add indirect objects. QPDF_DLL - QPDFNumberTreeObjectHelper(QPDFObjectHandle, QPDF&, - bool auto_repair = true); + QPDFNumberTreeObjectHelper( + QPDFObjectHandle, QPDF&, bool auto_repair = true); // ABI: Legacy Constructor will be removed in QPDF 11. A // QPDFNumberTreeObjectHelper constructed in this way can't be // modified or repaired and will silently ignore problems in the // structure. - [[deprecated("use constructor that takes QPDF&")]] - QPDF_DLL - QPDFNumberTreeObjectHelper(QPDFObjectHandle); + [[deprecated("use constructor that takes QPDF&")]] QPDF_DLL + QPDFNumberTreeObjectHelper(QPDFObjectHandle); // ABI: = default QPDF_DLL @@ -93,12 +92,13 @@ class QPDFNumberTreeObjectHelper: public QPDFObjectHelper // oh to the value with index 3, and set offset to 2 (5 - 3). See // also find(). QPDF_DLL - bool findObjectAtOrBelow(numtree_number idx, QPDFObjectHandle& oh, - numtree_number& offset); + bool findObjectAtOrBelow( + numtree_number idx, QPDFObjectHandle& oh, numtree_number& offset); class iterator { friend class QPDFNumberTreeObjectHelper; + public: typedef std::pair T; using iterator_category = std::bidirectional_iterator_tag; @@ -113,7 +113,8 @@ class QPDFNumberTreeObjectHelper: public QPDFObjectHelper QPDF_DLL iterator& operator++(); QPDF_DLL - iterator operator++(int) + iterator + operator++(int) { iterator t = *this; ++(*this); @@ -122,7 +123,8 @@ class QPDFNumberTreeObjectHelper: public QPDFObjectHelper QPDF_DLL iterator& operator--(); QPDF_DLL - iterator operator--(int) + iterator + operator--(int) { iterator t = *this; --(*this); @@ -135,9 +137,10 @@ class QPDFNumberTreeObjectHelper: public QPDFObjectHelper QPDF_DLL bool operator==(iterator const& other) const; QPDF_DLL - bool operator!=(iterator const& other) const + bool + operator!=(iterator const& other) const { - return ! operator==(other); + return !operator==(other); } // DANGER: this method can create inconsistent trees if not diff --git a/include/qpdf/QPDFObject.hh b/include/qpdf/QPDFObject.hh index d01ea8ed..9487e8f5 100644 --- a/include/qpdf/QPDFObject.hh +++ b/include/qpdf/QPDFObject.hh @@ -22,10 +22,10 @@ #ifndef QPDFOBJECT_HH #define QPDFOBJECT_HH -#include -#include -#include #include +#include +#include +#include #include @@ -62,7 +62,9 @@ class QPDF_DLL_CLASS QPDFObject static constexpr object_type_e ot_operator = ::ot_operator; static constexpr object_type_e ot_inlineimage = ::ot_inlineimage; - virtual ~QPDFObject() {} + virtual ~QPDFObject() + { + } virtual std::string unparse() = 0; virtual JSON getJSON() = 0; @@ -78,11 +80,12 @@ class QPDF_DLL_CLASS QPDFObject { friend class QPDF; friend class QPDFObjectHandle; + private: - static void releaseResolved(QPDFObject* o) + static void + releaseResolved(QPDFObject* o) { - if (o) - { + if (o) { o->releaseResolved(); } } @@ -97,7 +100,10 @@ class QPDF_DLL_CLASS QPDFObject qpdf_offset_t getParsedOffset(); protected: - virtual void releaseResolved() {} + virtual void + releaseResolved() + { + } private: QPDFObject(QPDFObject const&) = delete; diff --git a/include/qpdf/QPDFObjectHandle.hh b/include/qpdf/QPDFObjectHandle.hh index e536c3cc..f304aacf 100644 --- a/include/qpdf/QPDFObjectHandle.hh +++ b/include/qpdf/QPDFObjectHandle.hh @@ -22,21 +22,21 @@ #ifndef QPDFOBJECTHANDLE_HH #define QPDFOBJECTHANDLE_HH +#include #include #include -#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include #include #include +#include +#include #include #include @@ -117,12 +117,15 @@ class QPDFObjectHandle // version of the method, which should also return a boolean // indicating whether it ran without errors. QPDF_DLL - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); QPDF_DLL virtual bool provideStreamData( - int objid, int generation, Pipeline* pipeline, - bool suppress_warnings, bool will_retry); + int objid, + int generation, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry); QPDF_DLL bool supportsRetry(); @@ -183,8 +186,10 @@ class QPDFObjectHandle class PipelineAccessor { friend class Pl_QPDFTokenizer; + private: - static void setPipeline(TokenFilter* f, Pipeline* p) + static void + setPipeline(TokenFilter* f, Pipeline* p) { f->setPipeline(p); } @@ -230,8 +235,8 @@ class QPDFObjectHandle QPDF_DLL virtual void handleObject(QPDFObjectHandle); QPDF_DLL - virtual void handleObject( - QPDFObjectHandle, size_t offset, size_t length); + virtual void + handleObject(QPDFObjectHandle, size_t offset, size_t length); virtual void handleEOF() = 0; @@ -261,8 +266,7 @@ class QPDFObjectHandle ury(0.0) { } - Rectangle(double llx, double lly, - double urx, double ury) : + Rectangle(double llx, double lly, double urx, double ury) : llx(llx), lly(lly), urx(urx), @@ -292,8 +296,7 @@ class QPDFObjectHandle f(0.0) { } - Matrix(double a, double b, double c, - double d, double e, double f) : + Matrix(double a, double b, double c, double d, double e, double f) : a(a), b(b), c(c), @@ -316,8 +319,7 @@ class QPDFObjectHandle QPDF_DLL QPDFObjectHandle(QPDFObjectHandle const&) = default; QPDF_DLL - QPDFObjectHandle& - operator=(QPDFObjectHandle const&) = default; + QPDFObjectHandle& operator=(QPDFObjectHandle const&) = default; QPDF_DLL bool isInitialized() const; @@ -381,14 +383,14 @@ class QPDFObjectHandle // True if the object is a dictionary of the specified type and // subtype, if any. QPDF_DLL - bool isDictionaryOfType(std::string const& type, - std::string const& subtype = ""); + bool isDictionaryOfType( + std::string const& type, std::string const& subtype = ""); // True if the object is a stream of the specified type and // subtype, if any. QPDF_DLL - bool isStreamOfType(std::string const& type, - std::string const& subtype = ""); + bool + isStreamOfType(std::string const& type, std::string const& subtype = ""); // Public factory methods @@ -406,8 +408,9 @@ class QPDFObjectHandle // in the message of any QPDFExc exception thrown for invalid // syntax. See also the global `operator ""_qpdf` defined below. QPDF_DLL - static QPDFObjectHandle parse(std::string const& object_str, - std::string const& object_description = ""); + static QPDFObjectHandle parse( + std::string const& object_str, + std::string const& object_description = ""); // Construct an object of any type from a string representation of // the object. Indirect object syntax (obj gen R) is allowed and @@ -419,9 +422,10 @@ class QPDFObjectHandle // object, which will just be the first number and will report // that there is trailing data at the end of the string. QPDF_DLL - static QPDFObjectHandle parse(QPDF* context, - std::string const& object_str, - std::string const& object_description = ""); + static QPDFObjectHandle parse( + QPDF* context, + std::string const& object_str, + std::string const& object_description = ""); // Construct an object as above by reading from the given // InputSource at its current position and using the tokenizer you @@ -429,11 +433,13 @@ class QPDFObjectHandle // This method is intended to be called by QPDF for parsing // objects that are ready from the object's input stream. QPDF_DLL - static QPDFObjectHandle parse(PointerHolder input, - std::string const& object_description, - QPDFTokenizer&, bool& empty, - StringDecrypter* decrypter, - QPDF* context); + static QPDFObjectHandle parse( + PointerHolder input, + std::string const& object_description, + QPDFTokenizer&, + bool& empty, + StringDecrypter* decrypter, + QPDF* context); // Return the offset where the object was found when parsed. A // negative value means that the object was created without @@ -449,8 +455,8 @@ class QPDFObjectHandle // error messages will also be more useful because the page object // information will be known. QPDF_DLL - static void parseContentStream(QPDFObjectHandle stream_or_array, - ParserCallbacks* callbacks); + static void parseContentStream( + QPDFObjectHandle stream_or_array, ParserCallbacks* callbacks); // When called on a stream or stream array that is some page's // content streams, do the same as pipePageContents. This method @@ -469,8 +475,10 @@ class QPDFObjectHandle // Pl_Concatenate and then call manualFinish() on the // Pl_Concatenate pipeline at the end. QPDF_DLL - void pipeContentStreams(Pipeline* p, std::string const& description, - std::string& all_description); + void pipeContentStreams( + Pipeline* p, + std::string const& description, + std::string& all_description); // As of qpdf 8, it is possible to add custom token filters to a // stream. The tokenized stream data is passed through the token @@ -525,8 +533,8 @@ class QPDFObjectHandle // ABI: combine with other newReal by adding trim_trailing_zeroes // above as an optional parameter with a default of true. QPDF_DLL - static QPDFObjectHandle newReal(double value, int decimal_places, - bool trim_trailing_zeroes); + static QPDFObjectHandle + newReal(double value, int decimal_places, bool trim_trailing_zeroes); // Note about name objects: qpdf's internal representation of a // PDF name is a sequence of bytes, excluding the NUL character, // and starting with a slash. Name objects as represented in the @@ -562,8 +570,8 @@ class QPDFObjectHandle QPDF_DLL static QPDFObjectHandle newArray(); QPDF_DLL - static QPDFObjectHandle newArray( - std::vector const& items); + static QPDFObjectHandle + newArray(std::vector const& items); QPDF_DLL static QPDFObjectHandle newArray(Rectangle const&); QPDF_DLL @@ -573,8 +581,8 @@ class QPDFObjectHandle QPDF_DLL static QPDFObjectHandle newDictionary(); QPDF_DLL - static QPDFObjectHandle newDictionary( - std::map const& items); + static QPDFObjectHandle + newDictionary(std::map const& items); // Create an array from a rectangle. Equivalent to the rectangle // form of newArray. @@ -646,8 +654,8 @@ class QPDFObjectHandle // with proper context in some cases where it would otherwise // raise exceptions. QPDF_DLL - void setObjectDescription(QPDF* owning_qpdf, - std::string const& object_description); + void setObjectDescription( + QPDF* owning_qpdf, std::string const& object_description); QPDF_DLL bool hasObjectDescription(); @@ -959,8 +967,8 @@ class QPDFObjectHandle // ABI: remove this version and make resource_names default to // nullptr. QPDF_DLL - std::string getUniqueResourceName(std::string const& prefix, - int& min_suffix); + std::string + getUniqueResourceName(std::string const& prefix, int& min_suffix); // Return the QPDF object that owns an indirect object. Returns // null for a direct object. @@ -1081,8 +1089,8 @@ class QPDFObjectHandle // Returns filtered (uncompressed) stream data. Throws an // exception if the stream is filtered and we can't decode it. QPDF_DLL - PointerHolder getStreamData( - qpdf_stream_decode_level_e level = qpdf_dl_generalized); + PointerHolder + getStreamData(qpdf_stream_decode_level_e level = qpdf_dl_generalized); // Returns unfiltered (raw) stream data. QPDF_DLL @@ -1146,21 +1154,24 @@ class QPDFObjectHandle // Return value is overall success, even if filtering is not // requested. QPDF_DLL - bool pipeStreamData(Pipeline*, bool* filtering_attempted, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings = false, - bool will_retry = false); + bool pipeStreamData( + Pipeline*, + bool* filtering_attempted, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings = false, + bool will_retry = false); // Legacy version. Return value is whether filtering was // attempted. There is no way to determine success if filtering // was not attempted. QPDF_DLL - bool pipeStreamData(Pipeline*, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings = false, - bool will_retry = false); + bool pipeStreamData( + Pipeline*, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings = false, + bool will_retry = false); // Legacy pipeStreamData. This maps to the the flags-based // pipeStreamData as follows: @@ -1170,8 +1181,7 @@ class QPDFObjectHandle // compress = true -> encode_flags |= qpdf_sf_compress // Return value is whether filtering was attempted. QPDF_DLL - bool pipeStreamData(Pipeline*, bool filter, - bool normalize, bool compress); + bool pipeStreamData(Pipeline*, bool filter, bool normalize, bool compress); // Replace a stream's dictionary. The new dictionary must be // consistent with the stream's data. This is most appropriately @@ -1190,18 +1200,20 @@ class QPDFObjectHandle // interpreted as if the data read from the file, after any // decryption filters have been applied, is as presented. QPDF_DLL - void replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + void replaceStreamData( + PointerHolder data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); // Replace the stream's stream data with the given string. // This method will create a copy of the data rather than using // the user-provided buffer as in the PointerHolder version // of replaceStreamData. QPDF_DLL - void replaceStreamData(std::string const& data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + void replaceStreamData( + std::string const& data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); // As above, replace this stream's stream data. Instead of // directly providing a buffer with the stream data, call the @@ -1229,9 +1241,10 @@ class QPDFObjectHandle // parameter. You can also simplify your code by not having to // compute the length in advance. QPDF_DLL - void replaceStreamData(PointerHolder provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + void replaceStreamData( + PointerHolder provider, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); // Starting in qpdf 10.2, you can use C++-11 function objects // instead of StreamDataProvider. @@ -1240,16 +1253,16 @@ class QPDFObjectHandle // a one-liner to replace stream data with the contents of a file, // pass QUtil::file_provider(filename) as provider. QPDF_DLL - void replaceStreamData(std::function provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + void replaceStreamData( + std::function provider, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); // The provider should write the stream data to the pipeline, // returning true if it succeeded without errors. QPDF_DLL void replaceStreamData( - std::function provider, + std::function + provider, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); @@ -1321,8 +1334,8 @@ class QPDFObjectHandle // descriptions. See comments on setObjectDescription for // additional details. QPDF_DLL - void warnIfPossible(std::string const& warning, - bool throw_if_no_description = false); + void warnIfPossible( + std::string const& warning, bool throw_if_no_description = false); // Initializers for objects. This Factory class gives the QPDF // class specific permission to call factory methods without @@ -1330,16 +1343,22 @@ class QPDFObjectHandle class Factory { friend class QPDF; + private: - static QPDFObjectHandle newIndirect(QPDF* qpdf, - int objid, int generation) + static QPDFObjectHandle + newIndirect(QPDF* qpdf, int objid, int generation) { return QPDFObjectHandle::newIndirect(qpdf, objid, generation); } // object must be dictionary object - static QPDFObjectHandle newStream( - QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, qpdf_offset_t offset, size_t length) + static QPDFObjectHandle + newStream( + QPDF* qpdf, + int objid, + int generation, + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, + size_t length) { return QPDFObjectHandle::newStream( qpdf, objid, generation, stream_dict, offset, length); @@ -1352,8 +1371,10 @@ class QPDFObjectHandle class ObjAccessor { friend class QPDF; + private: - static PointerHolder getObject(QPDFObjectHandle& o) + static PointerHolder + getObject(QPDFObjectHandle& o) { o.dereference(); return o.obj; @@ -1368,8 +1389,10 @@ class QPDFObjectHandle friend class QPDF_Dictionary; friend class QPDF_Stream; friend class SparseOHArray; + private: - static void releaseResolved(QPDFObjectHandle& o) + static void + releaseResolved(QPDFObjectHandle& o) { o.releaseResolved(); } @@ -1433,14 +1456,13 @@ class QPDFObjectHandle // Indicate if this is an image. If exclude_imagemask is true, // don't count image masks as images. QPDF_DLL - bool isImage(bool exclude_imagemask=true); + bool isImage(bool exclude_imagemask = true); private: QPDFObjectHandle(QPDF*, int objid, int generation); QPDFObjectHandle(QPDFObject*); - enum parser_state_e - { + enum parser_state_e { st_top, st_start, st_stop, @@ -1452,31 +1474,41 @@ class QPDFObjectHandle // Private object factory methods static QPDFObjectHandle newIndirect(QPDF*, int objid, int generation); static QPDFObjectHandle newStream( - QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, qpdf_offset_t offset, size_t length); + QPDF* qpdf, + int objid, + int generation, + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, + size_t length); - void typeWarning(char const* expected_type, - std::string const& warning); + void typeWarning(char const* expected_type, std::string const& warning); void objectWarning(std::string const& warning); void assertType(char const* type_name, bool istype); void dereference(); - void copyObject(std::set& visited, bool cross_indirect, - bool first_level_only, bool stop_at_streams); + void copyObject( + std::set& visited, + bool cross_indirect, + bool first_level_only, + bool stop_at_streams); void shallowCopyInternal(QPDFObjectHandle& oh, bool first_level_only); void releaseResolved(); static void setObjectDescriptionFromInput( - QPDFObjectHandle, QPDF*, std::string const&, - PointerHolder, qpdf_offset_t); + QPDFObjectHandle, + QPDF*, + std::string const&, + PointerHolder, + qpdf_offset_t); static QPDFObjectHandle parseInternal( PointerHolder input, std::string const& object_description, - QPDFTokenizer& tokenizer, bool& empty, - StringDecrypter* decrypter, QPDF* context, + QPDFTokenizer& tokenizer, + bool& empty, + StringDecrypter* decrypter, + QPDF* context, bool content_stream); void setParsedOffset(qpdf_offset_t offset); void parseContentStream_internal( - std::string const& description, - ParserCallbacks* callbacks); + std::string const& description, ParserCallbacks* callbacks); static void parseContentStream_data( PointerHolder, std::string const& description, @@ -1493,7 +1525,7 @@ class QPDFObjectHandle // a substantial performance penalty since QPDFObjectHandle // objects are copied around so frequently. QPDF* qpdf; - int objid; // 0 for direct object + int objid; // 0 for direct object int generation; PointerHolder obj; bool reserved; @@ -1507,7 +1539,7 @@ class QPDFObjectHandle // If this is causing problems in your code, define // QPDF_NO_QPDF_STRING to prevent the declaration from being here. QPDF_DLL -QPDFObjectHandle operator ""_qpdf(char const* v, size_t len); +QPDFObjectHandle operator""_qpdf(char const* v, size_t len); #endif // QPDF_NO_QPDF_STRING class QPDFObjectHandle::QPDFDictItems @@ -1531,6 +1563,7 @@ class QPDFObjectHandle::QPDFDictItems class iterator { friend class QPDFDictItems; + public: typedef std::pair T; using iterator_category = std::bidirectional_iterator_tag; @@ -1544,7 +1577,8 @@ class QPDFObjectHandle::QPDFDictItems QPDF_DLL iterator& operator++(); QPDF_DLL - iterator operator++(int) + iterator + operator++(int) { iterator t = *this; ++(*this); @@ -1553,7 +1587,8 @@ class QPDFObjectHandle::QPDFDictItems QPDF_DLL iterator& operator--(); QPDF_DLL - iterator operator--(int) + iterator + operator--(int) { iterator t = *this; --(*this); @@ -1566,9 +1601,10 @@ class QPDFObjectHandle::QPDFDictItems QPDF_DLL bool operator==(iterator const& other) const; QPDF_DLL - bool operator!=(iterator const& other) const + bool + operator!=(iterator const& other) const { - return ! operator==(other); + return !operator==(other); } private: @@ -1626,6 +1662,7 @@ class QPDFObjectHandle::QPDFArrayItems class iterator { friend class QPDFArrayItems; + public: typedef QPDFObjectHandle T; using iterator_category = std::bidirectional_iterator_tag; @@ -1639,7 +1676,8 @@ class QPDFObjectHandle::QPDFArrayItems QPDF_DLL iterator& operator++(); QPDF_DLL - iterator operator++(int) + iterator + operator++(int) { iterator t = *this; ++(*this); @@ -1648,7 +1686,8 @@ class QPDFObjectHandle::QPDFArrayItems QPDF_DLL iterator& operator--(); QPDF_DLL - iterator operator--(int) + iterator + operator--(int) { iterator t = *this; --(*this); @@ -1661,9 +1700,10 @@ class QPDFObjectHandle::QPDFArrayItems QPDF_DLL bool operator==(iterator const& other) const; QPDF_DLL - bool operator!=(iterator const& other) const + bool + operator!=(iterator const& other) const { - return ! operator==(other); + return !operator==(other); } private: @@ -1700,5 +1740,4 @@ class QPDFObjectHandle::QPDFArrayItems QPDFObjectHandle oh; }; - #endif // QPDFOBJECTHANDLE_HH diff --git a/include/qpdf/QPDFObjectHelper.hh b/include/qpdf/QPDFObjectHelper.hh index f8e3cc21..32577681 100644 --- a/include/qpdf/QPDFObjectHelper.hh +++ b/include/qpdf/QPDFObjectHelper.hh @@ -50,12 +50,14 @@ class QPDFObjectHelper { } QPDF_DLL - QPDFObjectHandle getObjectHandle() + QPDFObjectHandle + getObjectHandle() { return this->oh; } QPDF_DLL - QPDFObjectHandle const getObjectHandle() const + QPDFObjectHandle const + getObjectHandle() const { return this->oh; } diff --git a/include/qpdf/QPDFOutlineDocumentHelper.hh b/include/qpdf/QPDFOutlineDocumentHelper.hh index 5b2dca54..60079718 100644 --- a/include/qpdf/QPDFOutlineDocumentHelper.hh +++ b/include/qpdf/QPDFOutlineDocumentHelper.hh @@ -23,8 +23,8 @@ #define QPDFOUTLINEDOCUMENTHELPER_HH #include -#include #include +#include #include #include @@ -58,8 +58,7 @@ class QPDFOutlineDocumentHelper: public QPDFDocumentHelper // the name tree pointed to by the /Dests key of the names // dictionary. QPDF_DLL - QPDFObjectHandle - resolveNamedDest(QPDFObjectHandle name); + QPDFObjectHandle resolveNamedDest(QPDFObjectHandle name); // Return a list outlines that are known to target the specified // page @@ -99,7 +98,7 @@ class QPDFOutlineDocumentHelper: public QPDFDocumentHelper std::set seen; QPDFObjectHandle dest_dict; PointerHolder names_dest; - std::map > by_page; + std::map> by_page; }; PointerHolder m; diff --git a/include/qpdf/QPDFOutlineObjectHelper.hh b/include/qpdf/QPDFOutlineObjectHelper.hh index 3f310eeb..e8ed414d 100644 --- a/include/qpdf/QPDFOutlineObjectHelper.hh +++ b/include/qpdf/QPDFOutlineObjectHelper.hh @@ -22,8 +22,8 @@ #ifndef QPDFOUTLINEOBJECTHELPER_HH #define QPDFOUTLINEOBJECTHELPER_HH -#include #include +#include #include class QPDFOutlineDocumentHelper; diff --git a/include/qpdf/QPDFPageDocumentHelper.hh b/include/qpdf/QPDFPageDocumentHelper.hh index 5db8ef6d..d8b2e915 100644 --- a/include/qpdf/QPDFPageDocumentHelper.hh +++ b/include/qpdf/QPDFPageDocumentHelper.hh @@ -22,9 +22,9 @@ #ifndef QPDFPAGEDOCUMENTHELPER_HH #define QPDFPAGEDOCUMENTHELPER_HH +#include #include #include -#include #include @@ -106,8 +106,10 @@ class QPDFPageDocumentHelper: public QPDFDocumentHelper // Add new page before or after refpage. See comments for addPage // for details about what newpage should be. QPDF_DLL - void addPageAt(QPDFPageObjectHelper newpage, bool before, - QPDFPageObjectHelper refpage); + void addPageAt( + QPDFPageObjectHelper newpage, + bool before, + QPDFPageObjectHelper refpage); // Remove page from the pdf. QPDF_DLL @@ -126,8 +128,7 @@ class QPDFPageDocumentHelper: public QPDFDocumentHelper // those flags. QPDF_DLL void flattenAnnotations( - int required_flags = 0, - int forbidden_flags = an_invisible | an_hidden); + int required_flags = 0, int forbidden_flags = an_invisible | an_hidden); private: void flattenAnnotationsForPage( diff --git a/include/qpdf/QPDFPageLabelDocumentHelper.hh b/include/qpdf/QPDFPageLabelDocumentHelper.hh index 3e7652f1..6922e0a9 100644 --- a/include/qpdf/QPDFPageLabelDocumentHelper.hh +++ b/include/qpdf/QPDFPageLabelDocumentHelper.hh @@ -77,10 +77,11 @@ class QPDFPageLabelDocumentHelper: public QPDFDocumentHelper // behavior facilitates using this function to incrementally build // up a page labels tree when merging files. QPDF_DLL - void - getLabelsForPageRange(long long start_idx, long long end_idx, - long long new_start_idx, - std::vector& new_labels); + void getLabelsForPageRange( + long long start_idx, + long long end_idx, + long long new_start_idx, + std::vector& new_labels); private: class Members diff --git a/include/qpdf/QPDFPageObjectHelper.hh b/include/qpdf/QPDFPageObjectHelper.hh index ec446772..961bac4b 100644 --- a/include/qpdf/QPDFPageObjectHelper.hh +++ b/include/qpdf/QPDFPageObjectHelper.hh @@ -22,9 +22,9 @@ #ifndef QPDFPAGEOBJECTHELPER_HH #define QPDFPAGEOBJECTHELPER_HH -#include #include #include +#include #include @@ -57,23 +57,19 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // going to modify the returned object and want the modifications // to apply to the current page/form XObject only. QPDF_DLL - QPDFObjectHandle - getAttribute(std::string const& name, bool copy_if_shared); + QPDFObjectHandle getAttribute(std::string const& name, bool copy_if_shared); // Return the TrimBox. If not defined, fall back to CropBox QPDF_DLL - QPDFObjectHandle - getTrimBox(bool copy_if_shared = false); + QPDFObjectHandle getTrimBox(bool copy_if_shared = false); // Return the CropBox. If not defined, fall back to MediaBox QPDF_DLL - QPDFObjectHandle - getCropBox(bool copy_if_shared = false); + QPDFObjectHandle getCropBox(bool copy_if_shared = false); // Return the MediaBox QPDF_DLL - QPDFObjectHandle - getMediaBox(bool copy_if_shared = false); + QPDFObjectHandle getMediaBox(bool copy_if_shared = false); // Iterate through XObjects, possibly recursing into form // XObjects. This works with pages or form XObjects. Call action @@ -86,24 +82,27 @@ class QPDFPageObjectHelper: public QPDFObjectHelper QPDF_DLL void forEachXObject( bool recursive, - std::function action, - std::function selector=nullptr); + std::function action, + std::function selector = nullptr); // Only call action for images QPDF_DLL void forEachImage( bool recursive, - std::function action); + std::function action); // Only call action for form XObjects QPDF_DLL void forEachFormXObject( bool recursive, - std::function action); + std::function action); // Returns an empty map if there are no images or no resources. // Prior to qpdf 8.4.0, this function did not support inherited @@ -142,8 +141,8 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // only_subtype is non-empty, only include annotations of the // given subtype. QPDF_DLL - std::vector getAnnotations( - std::string const& only_subtype = ""); + std::vector + getAnnotations(std::string const& only_subtype = ""); // Returns a vector of stream objects representing the content // streams for the given page. This routine allows the caller to @@ -203,13 +202,13 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // contents, as happens with addContentTokenFilter. See // examples/pdf-count-strings.cc for an example. QPDF_DLL - void filterContents(QPDFObjectHandle::TokenFilter* filter, - Pipeline* next = 0); + void + filterContents(QPDFObjectHandle::TokenFilter* filter, Pipeline* next = 0); // Old name -- calls filterContents() QPDF_DLL - void filterPageContents(QPDFObjectHandle::TokenFilter* filter, - Pipeline* next = 0); + void filterPageContents( + QPDFObjectHandle::TokenFilter* filter, Pipeline* next = 0); // Pipe a page's contents through the given pipeline. This method // works whether the contents are a single stream or an array of @@ -303,7 +302,8 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // behavior. QPDF_DLL std::string placeFormXObject( - QPDFObjectHandle fo, std::string const& name, + QPDFObjectHandle fo, + std::string const& name, QPDFObjectHandle::Rectangle rect, bool invert_transformations = true, bool allow_shrink = true, @@ -313,7 +313,8 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // matrix that was used. QPDF_DLL std::string placeFormXObject( - QPDFObjectHandle fo, std::string const& name, + QPDFObjectHandle fo, + std::string const& name, QPDFObjectHandle::Rectangle rect, QPDFMatrix& cm, bool invert_transformations = true, @@ -326,9 +327,11 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // placeFormXObject. QPDF_DLL QPDFMatrix getMatrixForFormXObjectPlacement( - QPDFObjectHandle fo, QPDFObjectHandle::Rectangle rect, + QPDFObjectHandle fo, + QPDFObjectHandle::Rectangle rect, bool invert_transformations = true, - bool allow_shrink = true, bool allow_expand = false); + bool allow_shrink = true, + bool allow_expand = false); // If a page is rotated using /Rotate in the page's dictionary, // instead rotate the page by the same amount by altering the @@ -372,13 +375,13 @@ class QPDFPageObjectHelper: public QPDFObjectHelper // these outside and pass them in. QPDF_DLL void copyAnnotations( - QPDFPageObjectHelper from_page, QPDFMatrix const& cm = QPDFMatrix(), + QPDFPageObjectHelper from_page, + QPDFMatrix const& cm = QPDFMatrix(), QPDFAcroFormDocumentHelper* afdh = nullptr, QPDFAcroFormDocumentHelper* from_afdh = nullptr); private: - static bool - removeUnreferencedResourcesHelper( + static bool removeUnreferencedResourcesHelper( QPDFPageObjectHelper ph, std::set& unresolved); class Members diff --git a/include/qpdf/QPDFStreamFilter.hh b/include/qpdf/QPDFStreamFilter.hh index 31a8b317..a9daf028 100644 --- a/include/qpdf/QPDFStreamFilter.hh +++ b/include/qpdf/QPDFStreamFilter.hh @@ -23,8 +23,8 @@ #define QPDFSTREAMFILTER_HH #include -#include #include +#include class QPDF_DLL_CLASS QPDFStreamFilter { diff --git a/include/qpdf/QPDFSystemError.hh b/include/qpdf/QPDFSystemError.hh index 92c88329..b8595e09 100644 --- a/include/qpdf/QPDFSystemError.hh +++ b/include/qpdf/QPDFSystemError.hh @@ -22,19 +22,18 @@ #ifndef QPDFSYSTEMERROR_HH #define QPDFSYSTEMERROR_HH +#include #include #include -#include -#include #include +#include class QPDF_DLL_CLASS QPDFSystemError: public std::runtime_error { public: QPDF_DLL - QPDFSystemError(std::string const& description, - int system_errno); + QPDFSystemError(std::string const& description, int system_errno); QPDF_DLL virtual ~QPDFSystemError() noexcept; @@ -48,8 +47,8 @@ class QPDF_DLL_CLASS QPDFSystemError: public std::runtime_error int getErrno() const; private: - static std::string createWhat(std::string const& description, - int system_errno); + static std::string + createWhat(std::string const& description, int system_errno); // This class does not use the Members pattern to avoid needless // memory allocations during exception handling. diff --git a/include/qpdf/QPDFTokenizer.hh b/include/qpdf/QPDFTokenizer.hh index 0202d43f..8adc7db9 100644 --- a/include/qpdf/QPDFTokenizer.hh +++ b/include/qpdf/QPDFTokenizer.hh @@ -27,9 +27,9 @@ #include #include -#include -#include #include +#include +#include class QPDFTokenizer { @@ -38,8 +38,7 @@ class QPDFTokenizer // the tokenizer. tt_eof was introduced in QPDF version 4.1. // tt_space, tt_comment, and tt_inline_image were added in QPDF // version 8. - enum token_type_e - { + enum token_type_e { tt_bad, tt_array_close, tt_array_open, @@ -63,39 +62,50 @@ class QPDFTokenizer class Token { public: - Token() : type(tt_bad) {} + Token() : + type(tt_bad) + { + } QPDF_DLL Token(token_type_e type, std::string const& value); - Token(token_type_e type, std::string const& value, - std::string raw_value, std::string error_message) : + Token( + token_type_e type, + std::string const& value, + std::string raw_value, + std::string error_message) : type(type), value(value), raw_value(raw_value), error_message(error_message) { } - token_type_e getType() const + token_type_e + getType() const { return this->type; } - std::string const& getValue() const + std::string const& + getValue() const { return this->value; } - std::string const& getRawValue() const + std::string const& + getRawValue() const { return this->raw_value; } - std::string const& getErrorMessage() const + std::string const& + getErrorMessage() const { return this->error_message; } - bool operator==(Token const& rhs) const + bool + operator==(Token const& rhs) const { // Ignore fields other than type and value - return ((this->type != tt_bad) && - (this->type == rhs.type) && - (this->value == rhs.value)); + return ( + (this->type != tt_bad) && (this->type == rhs.type) && + (this->value == rhs.value)); } private: @@ -162,10 +172,11 @@ class QPDFTokenizer // offset" as returned by input->getLastOffset() points to the // beginning of the token. QPDF_DLL - Token readToken(PointerHolder input, - std::string const& context, - bool allow_bad = false, - size_t max_len = 0); + Token readToken( + PointerHolder input, + std::string const& context, + bool allow_bad = false, + size_t max_len = 0); // Calling this method puts the tokenizer in a state for reading // inline images. You should call this method after reading the @@ -188,8 +199,16 @@ class QPDFTokenizer void findEI(PointerHolder input); enum state_e { - st_top, st_in_space, st_in_comment, st_in_string, st_lt, st_gt, - st_literal, st_in_hexstring, st_inline_image, st_token_ready + st_top, + st_in_space, + st_in_comment, + st_in_string, + st_lt, + st_gt, + st_literal, + st_in_hexstring, + st_inline_image, + st_token_ready }; class Members diff --git a/include/qpdf/QPDFUsage.hh b/include/qpdf/QPDFUsage.hh index 064dc24e..eacfd97b 100644 --- a/include/qpdf/QPDFUsage.hh +++ b/include/qpdf/QPDFUsage.hh @@ -24,8 +24,8 @@ #include -#include #include +#include class QPDF_DLL_CLASS QPDFUsage: public std::runtime_error { diff --git a/include/qpdf/QPDFWriter.hh b/include/qpdf/QPDFWriter.hh index 1f8fc360..369bc946 100644 --- a/include/qpdf/QPDFWriter.hh +++ b/include/qpdf/QPDFWriter.hh @@ -29,24 +29,24 @@ #include #include -#include -#include #include -#include -#include #include #include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include class QPDF; class Pl_Count; @@ -372,72 +372,104 @@ class QPDFWriter // it unless you have to. QPDF_DLL void setR2EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_print, bool allow_modify, - bool allow_extract, bool allow_annotate); + char const* user_password, + char const* owner_password, + bool allow_print, + bool allow_modify, + bool allow_extract, + bool allow_annotate); // R3 uses RC4, which is a weak cryptographic algorithm. Don't use // it unless you have to. QPDF_DLL void setR3EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, qpdf_r3_print_e print); // R4 uses RC4, which is a weak cryptographic algorithm, when // use_aes=false. Don't use it unless you have to. QPDF_DLL void setR4EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, - qpdf_r3_print_e print, bool encrypt_metadata, bool use_aes); + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, + qpdf_r3_print_e print, + bool encrypt_metadata, + bool use_aes); // R5 is deprecated. Do not use it for production use. Writing // R5 is supported by qpdf primarily to generate test files for // applications that may need to test R5 support. QPDF_DLL void setR5EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, - qpdf_r3_print_e print, bool encrypt_metadata); + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, + qpdf_r3_print_e print, + bool encrypt_metadata); QPDF_DLL void setR6EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, - qpdf_r3_print_e print, bool encrypt_metadata_aes); + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, + qpdf_r3_print_e print, + bool encrypt_metadata_aes); // Pre qpdf 8.4.0 API - [[deprecated("see newer API above")]] - QPDF_DLL - void setR3EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify); - [[deprecated("see newer API above")]] - QPDF_DLL - void setR4EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, - bool encrypt_metadata, bool use_aes); - [[deprecated("see newer API above")]] - QPDF_DLL - void setR5EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, + [[deprecated("see newer API above")]] QPDF_DLL void + setR3EncryptionParameters( + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify); + [[deprecated("see newer API above")]] QPDF_DLL void + setR4EncryptionParameters( + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, + bool encrypt_metadata, + bool use_aes); + [[deprecated("see newer API above")]] QPDF_DLL void + setR5EncryptionParameters( + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, bool encrypt_metadata); - [[deprecated("see newer API above")]] - QPDF_DLL - void setR6EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, + [[deprecated("see newer API above")]] QPDF_DLL void + setR6EncryptionParameters( + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, bool encrypt_metadata_aes); // Create linearized output. Disables qdf mode, content @@ -496,11 +528,11 @@ class QPDFWriter private: // flags used by unparseObject - static int const f_stream = 1 << 0; - static int const f_filtered = 1 << 1; - static int const f_in_ostream = 1 << 2; - static int const f_hex_string = 1 << 3; - static int const f_no_encryption = 1 << 4; + static int const f_stream = 1 << 0; + static int const f_filtered = 1 << 1; + static int const f_in_ostream = 1 << 2; + static int const f_hex_string = 1 << 3; + static int const f_no_encryption = 1 << 4; enum trailer_e { t_normal, t_lin_first, t_lin_second }; @@ -516,9 +548,9 @@ class QPDFWriter class PipelinePopper { friend class QPDFWriter; + public: - PipelinePopper(QPDFWriter* qw, - PointerHolder* bp = 0) : + PipelinePopper(QPDFWriter* qw, PointerHolder* bp = 0) : qw(qw), bp(bp) { @@ -545,15 +577,24 @@ class QPDFWriter std::vector& offsets, int first_obj); void writeObjectStream(QPDFObjectHandle object); void writeObject(QPDFObjectHandle object, int object_stream_index = -1); - void writeTrailer(trailer_e which, int size, - bool xref_stream, qpdf_offset_t prev, - int linearization_pass); - bool willFilterStream(QPDFObjectHandle stream, - bool& compress_stream, bool& is_metadata, - PointerHolder* stream_data); - void unparseObject(QPDFObjectHandle object, int level, int flags, - // for stream dictionaries - size_t stream_length = 0, bool compress = false); + void writeTrailer( + trailer_e which, + int size, + bool xref_stream, + qpdf_offset_t prev, + int linearization_pass); + bool willFilterStream( + QPDFObjectHandle stream, + bool& compress_stream, + bool& is_metadata, + PointerHolder* stream_data); + void unparseObject( + QPDFObjectHandle object, + int level, + int flags, + // for stream dictionaries + size_t stream_length = 0, + bool compress = false); void unparseChild(QPDFObjectHandle child, int level, int flags); void initializeSpecialStreams(); void preserveObjectStreams(); @@ -562,23 +603,39 @@ class QPDFWriter void generateID(); void interpretR3EncryptionParameters( std::set& bits_to_clear, - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, - qpdf_r3_print_e print, qpdf_r3_modify_e modify); - void disableIncompatibleEncryption(int major, int minor, - int extension_level); + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify); + void + disableIncompatibleEncryption(int major, int minor, int extension_level); void parseVersion(std::string const& version, int& major, int& minor) const; int compareVersions(int major1, int minor1, int major2, int minor2) const; void setEncryptionParameters( - char const* user_password, char const* owner_password, - int V, int R, int key_len, std::set& bits_to_clear); + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + std::set& bits_to_clear); void setEncryptionParametersInternal( - int V, int R, int key_len, int P, - std::string const& O, std::string const& U, - std::string const& OE, std::string const& UE, std::string const& Perms, - std::string const& id1, std::string const& user_password, + int V, + int R, + int key_len, + int P, + std::string const& O, + std::string const& U, + std::string const& OE, + std::string const& UE, + std::string const& Perms, + std::string const& id1, + std::string const& user_password, std::string const& encryption_key); void setDataKey(int objid); int openObject(int objid = 0); @@ -595,10 +652,13 @@ class QPDFWriter void doWriteSetup(); void writeHeader(); void writeHintStream(int hint_id); + qpdf_offset_t + writeXRefTable(trailer_e which, int first, int last, int size); qpdf_offset_t writeXRefTable( - trailer_e which, int first, int last, int size); - qpdf_offset_t writeXRefTable( - trailer_e which, int first, int last, int size, + trailer_e which, + int first, + int last, + int size, // for linearization qpdf_offset_t prev, bool suppress_offsets, @@ -607,11 +667,21 @@ class QPDFWriter qpdf_offset_t hint_length, int linearization_pass); qpdf_offset_t writeXRefStream( - int objid, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size); + int objid, + int max_id, + qpdf_offset_t max_offset, + trailer_e which, + int first, + int last, + int size); qpdf_offset_t writeXRefStream( - int objid, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size, + int objid, + int max_id, + qpdf_offset_t max_offset, + trailer_e which, + int first, + int last, + int size, // for linearization qpdf_offset_t prev, int hint_id, @@ -627,7 +697,7 @@ class QPDFWriter // popped. Pipeline* pushPipeline(Pipeline*); void activatePipelineStack(PipelinePopper&); - void initializePipelineStack(Pipeline *); + void initializePipelineStack(Pipeline*); void adjustAESStreamLength(size_t& length); void pushEncryptionFilter(PipelinePopper&); @@ -635,8 +705,8 @@ class QPDFWriter void pushMD5Pipeline(PipelinePopper&); void computeDeterministicIDData(); - void discardGeneration(std::map const& in, - std::map& out); + void discardGeneration( + std::map const& in, std::map& out); class Members { @@ -681,8 +751,8 @@ class QPDFWriter int encryption_V; int encryption_R; - std::string id1; // for /ID key of - std::string id2; // trailer dictionary + std::string id1; // for /ID key of + std::string id2; // trailer dictionary std::string final_pdf_version; int final_extension_level; std::string min_pdf_version; @@ -707,7 +777,7 @@ class QPDFWriter std::map page_object_to_seq; std::map contents_to_page_seq; std::map object_to_object_stream; - std::map > object_stream_to_objects; + std::map> object_stream_to_objects; std::list pipeline_stack; unsigned long long next_stack_id; bool deterministic_id; diff --git a/include/qpdf/QPDFXRefEntry.hh b/include/qpdf/QPDFXRefEntry.hh index 78056312..8ed39d94 100644 --- a/include/qpdf/QPDFXRefEntry.hh +++ b/include/qpdf/QPDFXRefEntry.hh @@ -42,11 +42,11 @@ class QPDFXRefEntry QPDF_DLL int getType() const; QPDF_DLL - qpdf_offset_t getOffset() const; // only for type 1 + qpdf_offset_t getOffset() const; // only for type 1 QPDF_DLL - int getObjStreamNumber() const; // only for type 2 + int getObjStreamNumber() const; // only for type 2 QPDF_DLL - int getObjStreamIndex() const; // only for type 2 + int getObjStreamIndex() const; // only for type 2 private: // This class does not use the Members pattern to avoid a memory diff --git a/include/qpdf/QTC.hh b/include/qpdf/QTC.hh index e9b8565e..1fa55901 100644 --- a/include/qpdf/QTC.hh +++ b/include/qpdf/QTC.hh @@ -28,6 +28,6 @@ namespace QTC { QPDF_DLL void TC(char const* const scope, char const* const ccase, int n = 0); -}; +}; // namespace QTC #endif // QTC_HH diff --git a/include/qpdf/QUtil.hh b/include/qpdf/QUtil.hh index c1c22110..37eea484 100644 --- a/include/qpdf/QUtil.hh +++ b/include/qpdf/QUtil.hh @@ -23,16 +23,16 @@ #define QUTIL_HH #include -#include #include -#include -#include -#include -#include +#include #include +#include #include +#include #include +#include #include +#include class RandomDataProvider; class Pipeline; @@ -48,16 +48,16 @@ namespace QUtil QPDF_DLL std::string int_to_string_base(long long, int base, int length = 0); QPDF_DLL - std::string uint_to_string_base(unsigned long long, int base, - int length = 0); + std::string + uint_to_string_base(unsigned long long, int base, int length = 0); QPDF_DLL std::string double_to_string(double, int decimal_places = 0); // ABI: combine with other double_to_string by adding // trim_trailing_zeroes above as an optional parameter with a // default of true. QPDF_DLL - std::string double_to_string(double, int decimal_places, - bool trim_trailing_zeroes); + std::string + double_to_string(double, int decimal_places, bool trim_trailing_zeroes); // These string to number methods throw std::runtime_error on // underflow/overflow. @@ -217,8 +217,14 @@ namespace QUtil QPDFTime() = default; QPDFTime(QPDFTime const&) = default; QPDFTime& operator=(QPDFTime const&) = default; - QPDFTime(int year, int month, int day, int hour, - int minute, int second, int tz_delta) : + QPDFTime( + int year, + int month, + int day, + int hour, + int minute, + int second, + int tz_delta) : year(year), month(month), day(day), @@ -228,13 +234,13 @@ namespace QUtil tz_delta(tz_delta) { } - int year; // actual year, no 1900 stuff - int month; // 1--12 - int day; // 1--31 + int year; // actual year, no 1900 stuff + int month; // 1--12 + int day; // 1--31 int hour; int minute; int second; - int tz_delta; // minutes before UTC + int tz_delta; // minutes before UTC }; QPDF_DLL @@ -284,17 +290,16 @@ namespace QUtil // encoding system by replacing all unsupported characters with // the given unknown_char. QPDF_DLL - std::string utf8_to_ascii( - std::string const& utf8, char unknown_char = '?'); + std::string utf8_to_ascii(std::string const& utf8, char unknown_char = '?'); QPDF_DLL - std::string utf8_to_win_ansi( - std::string const& utf8, char unknown_char = '?'); + std::string + utf8_to_win_ansi(std::string const& utf8, char unknown_char = '?'); QPDF_DLL - std::string utf8_to_mac_roman( - std::string const& utf8, char unknown_char = '?'); + std::string + utf8_to_mac_roman(std::string const& utf8, char unknown_char = '?'); QPDF_DLL - std::string utf8_to_pdf_doc( - std::string const& utf8, char unknown_char = '?'); + std::string + utf8_to_pdf_doc(std::string const& utf8, char unknown_char = '?'); // These versions return true if the conversion was successful and // false if any unrepresentable characters were found and had to @@ -338,10 +343,11 @@ namespace QUtil // the PDF spec requires UTF-16 to be UTF-16BE, qpdf (and just // about everything else) accepts UTF-16LE (as of 10.6.2). QPDF_DLL - void analyze_encoding(std::string const& str, - bool& has_8bit_chars, - bool& is_valid_utf8, - bool& is_utf16); + void analyze_encoding( + std::string const& str, + bool& has_8bit_chars, + bool& is_valid_utf8, + bool& is_utf16); // Try to compensate for previously incorrectly encoded strings. // We want to compensate for the following errors: @@ -398,14 +404,14 @@ namespace QUtil // Filename is UTF-8 encoded, even on Windows, as described in the // comments for safe_fopen. QPDF_DLL - std::list read_lines_from_file( - char const* filename, bool preserve_eol = false); + std::list + read_lines_from_file(char const* filename, bool preserve_eol = false); QPDF_DLL - std::list read_lines_from_file( - std::istream&, bool preserve_eol = false); + std::list + read_lines_from_file(std::istream&, bool preserve_eol = false); QPDF_DLL - std::list read_lines_from_file( - FILE*, bool preserve_eol = false); + std::list + read_lines_from_file(FILE*, bool preserve_eol = false); QPDF_DLL void read_lines_from_file( std::function next_char, @@ -420,7 +426,7 @@ namespace QUtil // platforms, so we have to give it a name that is not likely to // be a macro anywhere. QPDF_DLL - int str_compare_nocase(char const *, char const *); + int str_compare_nocase(char const*, char const*); // These routines help the tokenizer recognize certain character // classes without using ctype, which we avoid because of locale @@ -454,13 +460,13 @@ namespace QUtil // another main. QPDF_DLL int call_main_from_wmain( - int argc, wchar_t* argv[], - std::function realmain); + int argc, wchar_t* argv[], std::function realmain); QPDF_DLL int call_main_from_wmain( - int argc, wchar_t const* const argv[], + int argc, + wchar_t const* const argv[], std::function realmain); #endif // QPDF_NO_WCHAR_T -}; +}; // namespace QUtil #endif // QUTIL_HH diff --git a/include/qpdf/qpdf-c.h b/include/qpdf/qpdf-c.h index af7e83f8..9c7557ab 100644 --- a/include/qpdf/qpdf-c.h +++ b/include/qpdf/qpdf-c.h @@ -137,9 +137,9 @@ * https://github.com/qpdf/qpdf/issues/new. */ +#include #include #include -#include #include #ifdef __cplusplus @@ -154,13 +154,13 @@ extern "C" { * that the values below can be logically orred together. */ typedef int QPDF_ERROR_CODE; -# define QPDF_SUCCESS 0 -# define QPDF_WARNINGS 1 << 0 -# define QPDF_ERRORS 1 << 1 +#define QPDF_SUCCESS 0 +#define QPDF_WARNINGS 1 << 0 +#define QPDF_ERRORS 1 << 1 typedef int QPDF_BOOL; -# define QPDF_TRUE 1 -# define QPDF_FALSE 0 +#define QPDF_TRUE 1 +#define QPDF_FALSE 0 /* From qpdf 10.5: call this method to signal to the library that * you are explicitly handling errors from functions that don't @@ -273,8 +273,8 @@ extern "C" { * pointer or an empty string as the password. */ QPDF_DLL - QPDF_ERROR_CODE qpdf_read(qpdf_data qpdf, char const* filename, - char const* password); + QPDF_ERROR_CODE + qpdf_read(qpdf_data qpdf, char const* filename, char const* password); /* Calling qpdf_read_memory causes processMemoryFile to be called * in the C++ API. Otherwise, it behaves in the same way as @@ -283,11 +283,12 @@ extern "C" { * library. */ QPDF_DLL - QPDF_ERROR_CODE qpdf_read_memory(qpdf_data qpdf, - char const* description, - char const* buffer, - unsigned long long size, - char const* password); + QPDF_ERROR_CODE qpdf_read_memory( + qpdf_data qpdf, + char const* description, + char const* buffer, + unsigned long long size, + char const* password); /* Calling qpdf_empty_pdf initializes this qpdf object with an * empty PDF, making it possible to create a PDF from scratch @@ -409,24 +410,23 @@ extern "C" { unsigned char const* qpdf_get_buffer(qpdf_data qpdf); QPDF_DLL - void qpdf_set_object_stream_mode(qpdf_data qpdf, - enum qpdf_object_stream_e mode); + void + qpdf_set_object_stream_mode(qpdf_data qpdf, enum qpdf_object_stream_e mode); QPDF_DLL - void qpdf_set_stream_data_mode(qpdf_data qpdf, - enum qpdf_stream_data_e mode); + void + qpdf_set_stream_data_mode(qpdf_data qpdf, enum qpdf_stream_data_e mode); QPDF_DLL void qpdf_set_compress_streams(qpdf_data qpdf, QPDF_BOOL value); + QPDF_DLL + void qpdf_set_decode_level( + qpdf_data qpdf, enum qpdf_stream_decode_level_e level); QPDF_DLL - void qpdf_set_decode_level(qpdf_data qpdf, - enum qpdf_stream_decode_level_e level); - - QPDF_DLL - void qpdf_set_preserve_unreferenced_objects( - qpdf_data qpdf, QPDF_BOOL value); + void + qpdf_set_preserve_unreferenced_objects(qpdf_data qpdf, QPDF_BOOL value); QPDF_DLL void qpdf_set_newline_before_endstream(qpdf_data qpdf, QPDF_BOOL value); @@ -453,77 +453,120 @@ extern "C" { void qpdf_set_static_aes_IV(qpdf_data qpdf, QPDF_BOOL value); QPDF_DLL - void qpdf_set_suppress_original_object_IDs( - qpdf_data qpdf, QPDF_BOOL value); + void qpdf_set_suppress_original_object_IDs(qpdf_data qpdf, QPDF_BOOL value); QPDF_DLL void qpdf_set_preserve_encryption(qpdf_data qpdf, QPDF_BOOL value); QPDF_DLL void qpdf_set_r2_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_print, QPDF_BOOL allow_modify, - QPDF_BOOL allow_extract, QPDF_BOOL allow_annotate); + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_print, + QPDF_BOOL allow_modify, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_annotate); QPDF_DLL void qpdf_set_r3_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, enum qpdf_r3_print_e print); QPDF_DLL void qpdf_set_r4_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, enum qpdf_r3_print_e print, - QPDF_BOOL encrypt_metadata, QPDF_BOOL use_aes); + QPDF_BOOL encrypt_metadata, + QPDF_BOOL use_aes); QPDF_DLL void qpdf_set_r5_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, - enum qpdf_r3_print_e print, QPDF_BOOL encrypt_metadata); + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, + enum qpdf_r3_print_e print, + QPDF_BOOL encrypt_metadata); QPDF_DLL void qpdf_set_r6_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, - enum qpdf_r3_print_e print, QPDF_BOOL encrypt_metadata); + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, + enum qpdf_r3_print_e print, + QPDF_BOOL encrypt_metadata); /* Pre 8.4.0 encryption API */ QPDF_DLL void qpdf_set_r3_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - enum qpdf_r3_print_e print, enum qpdf_r3_modify_e modify); + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + enum qpdf_r3_print_e print, + enum qpdf_r3_modify_e modify); QPDF_DLL void qpdf_set_r4_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - enum qpdf_r3_print_e print, enum qpdf_r3_modify_e modify, - QPDF_BOOL encrypt_metadata, QPDF_BOOL use_aes); + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + enum qpdf_r3_print_e print, + enum qpdf_r3_modify_e modify, + QPDF_BOOL encrypt_metadata, + QPDF_BOOL use_aes); QPDF_DLL void qpdf_set_r5_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - enum qpdf_r3_print_e print, enum qpdf_r3_modify_e modify, + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + enum qpdf_r3_print_e print, + enum qpdf_r3_modify_e modify, QPDF_BOOL encrypt_metadata); QPDF_DLL void qpdf_set_r6_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - enum qpdf_r3_print_e print, enum qpdf_r3_modify_e modify, + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + enum qpdf_r3_print_e print, + enum qpdf_r3_modify_e modify, QPDF_BOOL encrypt_metadata); QPDF_DLL @@ -648,8 +691,8 @@ extern "C" { QPDF_DLL qpdf_oh qpdf_make_indirect_object(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - void qpdf_replace_object( - qpdf_data qpdf, int objid, int generation, qpdf_oh oh); + void + qpdf_replace_object(qpdf_data qpdf, int objid, int generation, qpdf_oh oh); /* Wrappers around QPDFObjectHandle methods. Be sure to read * corresponding comments in QPDFObjectHandle.hh to understand @@ -690,8 +733,8 @@ extern "C" { QPDF_BOOL qpdf_oh_is_scalar(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_is_name_and_equals( - qpdf_data qpdf, qpdf_oh oh, char const* name); + QPDF_BOOL + qpdf_oh_is_name_and_equals(qpdf_data qpdf, qpdf_oh oh, char const* name); QPDF_DLL QPDF_BOOL qpdf_oh_is_dictionary_of_type( @@ -711,19 +754,18 @@ extern "C" { QPDF_DLL QPDF_BOOL qpdf_oh_get_bool_value(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_get_value_as_bool( - qpdf_data qpdf, qpdf_oh oh, QPDF_BOOL* value); + QPDF_BOOL + qpdf_oh_get_value_as_bool(qpdf_data qpdf, qpdf_oh oh, QPDF_BOOL* value); QPDF_DLL long long qpdf_oh_get_int_value(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_get_value_as_longlong( - qpdf_data qpdf, qpdf_oh oh, long long* value); + QPDF_BOOL + qpdf_oh_get_value_as_longlong(qpdf_data qpdf, qpdf_oh oh, long long* value); QPDF_DLL int qpdf_oh_get_int_value_as_int(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_get_value_as_int( - qpdf_data qpdf, qpdf_oh oh, int* value); + QPDF_BOOL qpdf_oh_get_value_as_int(qpdf_data qpdf, qpdf_oh oh, int* value); QPDF_DLL unsigned long long qpdf_oh_get_uint_value(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL @@ -732,8 +774,8 @@ extern "C" { QPDF_DLL unsigned int qpdf_oh_get_uint_value_as_uint(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_get_value_as_uint( - qpdf_data qpdf, qpdf_oh oh, unsigned int* value); + QPDF_BOOL + qpdf_oh_get_value_as_uint(qpdf_data qpdf, qpdf_oh oh, unsigned int* value); QPDF_DLL char const* qpdf_oh_get_real_value(qpdf_data qpdf, qpdf_oh oh); @@ -746,8 +788,8 @@ extern "C" { QPDF_DLL double qpdf_oh_get_numeric_value(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - QPDF_BOOL qpdf_oh_get_value_as_number( - qpdf_data qpdf, qpdf_oh oh, double* value); + QPDF_BOOL + qpdf_oh_get_value_as_number(qpdf_data qpdf, qpdf_oh oh, double* value); QPDF_DLL char const* qpdf_oh_get_name(qpdf_data qpdf, qpdf_oh oh); @@ -782,11 +824,11 @@ extern "C" { QPDF_BOOL qpdf_oh_get_value_as_utf8( qpdf_data qpdf, qpdf_oh oh, char const** value, size_t* length); QPDF_DLL - char const* qpdf_oh_get_binary_string_value( - qpdf_data qpdf, qpdf_oh oh, size_t* length); + char const* + qpdf_oh_get_binary_string_value(qpdf_data qpdf, qpdf_oh oh, size_t* length); QPDF_DLL - char const* qpdf_oh_get_binary_utf8_value( - qpdf_data qpdf, qpdf_oh oh, size_t* length); + char const* + qpdf_oh_get_binary_utf8_value(qpdf_data qpdf, qpdf_oh oh, size_t* length); QPDF_DLL int qpdf_oh_get_array_n_items(qpdf_data qpdf, qpdf_oh oh); @@ -822,12 +864,12 @@ extern "C" { QPDF_DLL qpdf_oh qpdf_oh_get_key(qpdf_data qpdf, qpdf_oh oh, char const* key); QPDF_DLL - qpdf_oh qpdf_oh_get_key_if_dict( - qpdf_data qpdf, qpdf_oh oh, char const* key); + qpdf_oh + qpdf_oh_get_key_if_dict(qpdf_data qpdf, qpdf_oh oh, char const* key); QPDF_DLL - QPDF_BOOL qpdf_oh_is_or_has_name( - qpdf_data qpdf, qpdf_oh oh, char const* key); + QPDF_BOOL + qpdf_oh_is_or_has_name(qpdf_data qpdf, qpdf_oh oh, char const* key); QPDF_DLL qpdf_oh qpdf_oh_new_uninitialized(qpdf_data qpdf); @@ -840,8 +882,8 @@ extern "C" { QPDF_DLL qpdf_oh qpdf_oh_new_real_from_string(qpdf_data qpdf, char const* value); QPDF_DLL - qpdf_oh qpdf_oh_new_real_from_double(qpdf_data qpdf, - double value, int decimal_places); + qpdf_oh qpdf_oh_new_real_from_double( + qpdf_data qpdf, double value, int decimal_places); QPDF_DLL qpdf_oh qpdf_oh_new_name(qpdf_data qpdf, char const* name); QPDF_DLL @@ -852,9 +894,9 @@ extern "C" { * contain atrbitary binary data including embedded null characters. */ QPDF_DLL - qpdf_oh qpdf_oh_new_binary_string( - qpdf_data qpdf, char const* str, size_t length); - QPDF_DLL + qpdf_oh + qpdf_oh_new_binary_string(qpdf_data qpdf, char const* str, size_t length); + QPDF_DLL qpdf_oh qpdf_oh_new_binary_unicode_string( qpdf_data qpdf, char const* str, size_t length); QPDF_DLL @@ -867,7 +909,7 @@ extern "C" { * comments in QPDFObjectHandle.hh for newStream() for additional * notes. You must call qpdf_oh_replace_stream_data to provide * data for the stream. See STREAM FUNCTIONS below. - */ + */ QPDF_DLL qpdf_oh qpdf_oh_new_stream(qpdf_data qpdf); @@ -875,8 +917,8 @@ extern "C" { void qpdf_oh_make_direct(qpdf_data qpdf, qpdf_oh oh); QPDF_DLL - void qpdf_oh_set_array_item(qpdf_data qpdf, qpdf_oh oh, - int at, qpdf_oh item); + void + qpdf_oh_set_array_item(qpdf_data qpdf, qpdf_oh oh, int at, qpdf_oh item); QPDF_DLL void qpdf_oh_insert_item(qpdf_data qpdf, qpdf_oh oh, int at, qpdf_oh item); QPDF_DLL @@ -885,13 +927,13 @@ extern "C" { void qpdf_oh_erase_item(qpdf_data qpdf, qpdf_oh oh, int at); QPDF_DLL - void qpdf_oh_replace_key(qpdf_data qpdf, qpdf_oh oh, - char const* key, qpdf_oh item); + void qpdf_oh_replace_key( + qpdf_data qpdf, qpdf_oh oh, char const* key, qpdf_oh item); QPDF_DLL void qpdf_oh_remove_key(qpdf_data qpdf, qpdf_oh oh, char const* key); QPDF_DLL - void qpdf_oh_replace_or_remove_key(qpdf_data qpdf, qpdf_oh oh, - char const* key, qpdf_oh item); + void qpdf_oh_replace_or_remove_key( + qpdf_data qpdf, qpdf_oh oh, char const* key, qpdf_oh item); QPDF_DLL qpdf_oh qpdf_oh_get_dict(qpdf_data qpdf, qpdf_oh oh); @@ -946,9 +988,12 @@ extern "C" { */ QPDF_DLL QPDF_ERROR_CODE qpdf_oh_get_stream_data( - qpdf_data qpdf, qpdf_oh stream_oh, - enum qpdf_stream_decode_level_e decode_level, QPDF_BOOL* filtered, - unsigned char** bufp, size_t* len); + qpdf_data qpdf, + qpdf_oh stream_oh, + enum qpdf_stream_decode_level_e decode_level, + QPDF_BOOL* filtered, + unsigned char** bufp, + size_t* len); /* This function returns the concatenation of all of a page's * content streams as a single, dynamically allocated buffer. As @@ -957,17 +1002,19 @@ extern "C" { */ QPDF_DLL QPDF_ERROR_CODE qpdf_oh_get_page_content_data( - qpdf_data qpdf, qpdf_oh page_oh, - unsigned char** bufp, size_t* len); + qpdf_data qpdf, qpdf_oh page_oh, unsigned char** bufp, size_t* len); /* The data pointed to by bufp will be copied by the library. It * does not need to remain valid after the call returns. */ QPDF_DLL void qpdf_oh_replace_stream_data( - qpdf_data qpdf, qpdf_oh stream_oh, - unsigned char const* buf, size_t len, - qpdf_oh filter, qpdf_oh decode_parms); + qpdf_data qpdf, + qpdf_oh stream_oh, + unsigned char const* buf, + size_t len, + qpdf_oh filter, + qpdf_oh decode_parms); /* PAGE FUNCTIONS */ @@ -1018,14 +1065,17 @@ extern "C" { QPDF_DLL QPDF_ERROR_CODE qpdf_add_page( qpdf_data qpdf, - qpdf_data newpage_qpdf, qpdf_oh newpage, + qpdf_data newpage_qpdf, + qpdf_oh newpage, QPDF_BOOL first); /* addPageAt() */ QPDF_DLL QPDF_ERROR_CODE qpdf_add_page_at( qpdf_data qpdf, - qpdf_data newpage_qpdf, qpdf_oh newpage, - QPDF_BOOL before, qpdf_oh refpage); + qpdf_data newpage_qpdf, + qpdf_oh newpage, + QPDF_BOOL before, + qpdf_oh refpage); /* removePage() */ QPDF_DLL QPDF_ERROR_CODE qpdf_remove_page(qpdf_data qpdf, qpdf_oh page); @@ -1033,5 +1083,4 @@ extern "C" { } #endif - #endif /* QPDF_C_H */ diff --git a/include/qpdf/qpdfjob-c.h b/include/qpdf/qpdfjob-c.h index fdc3511c..93ab3e28 100644 --- a/include/qpdf/qpdfjob-c.h +++ b/include/qpdf/qpdfjob-c.h @@ -75,5 +75,4 @@ extern "C" { } #endif - #endif /* QPDFJOB_C_H */ diff --git a/libqpdf/AES_PDF_native.cc b/libqpdf/AES_PDF_native.cc index b0900f70..a6addb53 100644 --- a/libqpdf/AES_PDF_native.cc +++ b/libqpdf/AES_PDF_native.cc @@ -1,18 +1,21 @@ #include -#include -#include -#include -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include -AES_PDF_native::AES_PDF_native(bool encrypt, unsigned char const* key, - size_t key_bytes, bool cbc_mode, - unsigned char* cbc_block) : +AES_PDF_native::AES_PDF_native( + bool encrypt, + unsigned char const* key, + size_t key_bytes, + bool cbc_mode, + unsigned char* cbc_block) : encrypt(encrypt), cbc_mode(cbc_mode), cbc_block(cbc_block), @@ -24,15 +27,12 @@ AES_PDF_native::AES_PDF_native(bool encrypt, unsigned char const* key, size_t rk_bytes = RKLENGTH(keybits) * sizeof(uint32_t); std::memcpy(this->key.get(), key, key_bytes); std::memset(this->rk.get(), 0, rk_bytes); - if (encrypt) - { - this->nrounds = rijndaelSetupEncrypt( - this->rk.get(), this->key.get(), keybits); - } - else - { - this->nrounds = rijndaelSetupDecrypt( - this->rk.get(), this->key.get(), keybits); + if (encrypt) { + this->nrounds = + rijndaelSetupEncrypt(this->rk.get(), this->key.get(), keybits); + } else { + this->nrounds = + rijndaelSetupDecrypt(this->rk.get(), this->key.get(), keybits); } } @@ -43,35 +43,24 @@ AES_PDF_native::~AES_PDF_native() void AES_PDF_native::update(unsigned char* in_data, unsigned char* out_data) { - if (this->encrypt) - { - if (this->cbc_mode) - { - for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) - { + if (this->encrypt) { + if (this->cbc_mode) { + for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) { in_data[i] ^= this->cbc_block[i]; } } - rijndaelEncrypt(this->rk.get(), - this->nrounds, in_data, out_data); - if (this->cbc_mode) - { - memcpy(this->cbc_block, out_data, - QPDFCryptoImpl::rijndael_buf_size); + rijndaelEncrypt(this->rk.get(), this->nrounds, in_data, out_data); + if (this->cbc_mode) { + memcpy( + this->cbc_block, out_data, QPDFCryptoImpl::rijndael_buf_size); } - } - else - { - rijndaelDecrypt(this->rk.get(), - this->nrounds, in_data, out_data); - if (this->cbc_mode) - { - for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) - { + } else { + rijndaelDecrypt(this->rk.get(), this->nrounds, in_data, out_data); + if (this->cbc_mode) { + for (size_t i = 0; i < QPDFCryptoImpl::rijndael_buf_size; ++i) { out_data[i] ^= this->cbc_block[i]; } - memcpy(this->cbc_block, in_data, - QPDFCryptoImpl::rijndael_buf_size); + memcpy(this->cbc_block, in_data, QPDFCryptoImpl::rijndael_buf_size); } } } diff --git a/libqpdf/BitStream.cc b/libqpdf/BitStream.cc index d0e991df..504e35c4 100644 --- a/libqpdf/BitStream.cc +++ b/libqpdf/BitStream.cc @@ -18,8 +18,7 @@ BitStream::reset() { p = start; bit_offset = 7; - if (QIntC::to_uint(nbytes) > static_cast(-1) / 8) - { + if (QIntC::to_uint(nbytes) > static_cast(-1) / 8) { throw std::runtime_error("array too large for bitstream"); } bits_available = 8 * nbytes; @@ -28,22 +27,18 @@ BitStream::reset() unsigned long long BitStream::getBits(size_t nbits) { - return read_bits(this->p, this->bit_offset, - this->bits_available, nbits); + return read_bits(this->p, this->bit_offset, this->bits_available, nbits); } long long BitStream::getBitsSigned(size_t nbits) { - unsigned long long bits = read_bits(this->p, this->bit_offset, - this->bits_available, nbits); + unsigned long long bits = + read_bits(this->p, this->bit_offset, this->bits_available, nbits); long long result = 0; - if (static_cast(bits) > 1LL << (nbits - 1)) - { - result = static_cast(bits -(1ULL << nbits)); - } - else - { + if (static_cast(bits) > 1LL << (nbits - 1)) { + result = static_cast(bits - (1ULL << nbits)); + } else { result = static_cast(bits); } return result; @@ -52,20 +47,16 @@ BitStream::getBitsSigned(size_t nbits) int BitStream::getBitsInt(size_t nbits) { - return static_cast( - QIntC::to_uint( - read_bits(this->p, this->bit_offset, - this->bits_available, nbits))); + return static_cast(QIntC::to_uint( + read_bits(this->p, this->bit_offset, this->bits_available, nbits))); } void BitStream::skipToNextByte() { - if (bit_offset != 7) - { + if (bit_offset != 7) { size_t bits_to_skip = bit_offset + 1; - if (bits_available < bits_to_skip) - { + if (bits_available < bits_to_skip) { throw std::logic_error( "INTERNAL ERROR: overflow skipping to next byte in bitstream"); } diff --git a/libqpdf/BitWriter.cc b/libqpdf/BitWriter.cc index 9d324734..25585924 100644 --- a/libqpdf/BitWriter.cc +++ b/libqpdf/BitWriter.cc @@ -21,12 +21,9 @@ void BitWriter::writeBitsSigned(long long val, size_t bits) { unsigned long long uval = 0; - if (val < 0) - { + if (val < 0) { uval = (1ULL << bits) + static_cast(val); - } - else - { + } else { uval = static_cast(val); } writeBits(uval, bits); @@ -41,8 +38,7 @@ BitWriter::writeBitsInt(int val, size_t bits) void BitWriter::flush() { - if (bit_offset < 7) - { + if (bit_offset < 7) { size_t bits_to_write = bit_offset + 1; write_bits(this->ch, this->bit_offset, 0, bits_to_write, this->pl); } diff --git a/libqpdf/Buffer.cc b/libqpdf/Buffer.cc index 1c014041..af35803a 100644 --- a/libqpdf/Buffer.cc +++ b/libqpdf/Buffer.cc @@ -7,21 +7,17 @@ Buffer::Members::Members(size_t size, unsigned char* buf, bool own_memory) : size(size), buf(0) { - if (own_memory) - { + if (own_memory) { this->buf = (size ? new unsigned char[size] : 0); - } - else - { + } else { this->buf = buf; } } Buffer::Members::~Members() { - if (this->own_memory) - { - delete [] this->buf; + if (this->own_memory) { + delete[] this->buf; } } @@ -55,11 +51,9 @@ Buffer::operator=(Buffer const& rhs) void Buffer::copy(Buffer const& rhs) { - if (this != &rhs) - { + if (this != &rhs) { this->m = PointerHolder(new Members(rhs.m->size, 0, true)); - if (this->m->size) - { + if (this->m->size) { memcpy(this->m->buf, rhs.m->buf, this->m->size); } } diff --git a/libqpdf/BufferInputSource.cc b/libqpdf/BufferInputSource.cc index 66b34f54..25e0d7c1 100644 --- a/libqpdf/BufferInputSource.cc +++ b/libqpdf/BufferInputSource.cc @@ -1,15 +1,14 @@ #include #include -#include -#include #include #include #include +#include +#include -BufferInputSource::Members::Members(bool own_memory, - std::string const& description, - Buffer* buf) : +BufferInputSource::Members::Members( + bool own_memory, std::string const& description, Buffer* buf) : own_memory(own_memory), description(description), buf(buf), @@ -22,14 +21,14 @@ BufferInputSource::Members::~Members() { } -BufferInputSource::BufferInputSource(std::string const& description, - Buffer* buf, bool own_memory) : +BufferInputSource::BufferInputSource( + std::string const& description, Buffer* buf, bool own_memory) : m(new Members(own_memory, description, buf)) { } -BufferInputSource::BufferInputSource(std::string const& description, - std::string const& contents) : +BufferInputSource::BufferInputSource( + std::string const& description, std::string const& contents) : m(new Members(true, description, 0)) { this->m->buf = new Buffer(contents.length()); @@ -40,8 +39,7 @@ BufferInputSource::BufferInputSource(std::string const& description, BufferInputSource::~BufferInputSource() { - if (this->m->own_memory) - { + if (this->m->own_memory) { delete this->m->buf; } } @@ -49,13 +47,11 @@ BufferInputSource::~BufferInputSource() qpdf_offset_t BufferInputSource::findAndSkipNextEOL() { - if (this->m->cur_offset < 0) - { + if (this->m->cur_offset < 0) { throw std::logic_error("INTERNAL ERROR: BufferInputSource offset < 0"); } qpdf_offset_t end_pos = this->m->max_offset; - if (this->m->cur_offset >= end_pos) - { + if (this->m->cur_offset >= end_pos) { this->last_offset = end_pos; this->m->cur_offset = end_pos; return end_pos; @@ -66,24 +62,19 @@ BufferInputSource::findAndSkipNextEOL() unsigned char const* end = buffer + end_pos; unsigned char const* p = buffer + this->m->cur_offset; - while ((p < end) && !((*p == '\r') || (*p == '\n'))) - { + while ((p < end) && !((*p == '\r') || (*p == '\n'))) { ++p; } - if (p < end) - { + if (p < end) { result = p - buffer; this->m->cur_offset = result + 1; ++p; while ((this->m->cur_offset < end_pos) && - ((*p == '\r') || (*p == '\n'))) - { + ((*p == '\r') || (*p == '\n'))) { ++p; ++this->m->cur_offset; } - } - else - { + } else { this->m->cur_offset = end_pos; result = end_pos; } @@ -105,30 +96,28 @@ BufferInputSource::tell() void BufferInputSource::seek(qpdf_offset_t offset, int whence) { - switch (whence) - { - case SEEK_SET: + switch (whence) { + case SEEK_SET: this->m->cur_offset = offset; break; - case SEEK_END: + case SEEK_END: QIntC::range_check(this->m->max_offset, offset); this->m->cur_offset = this->m->max_offset + offset; break; - case SEEK_CUR: + case SEEK_CUR: QIntC::range_check(this->m->cur_offset, offset); this->m->cur_offset += offset; break; - default: + default: throw std::logic_error( "INTERNAL ERROR: invalid argument to BufferInputSource::seek"); break; } - if (this->m->cur_offset < 0) - { + if (this->m->cur_offset < 0) { throw std::runtime_error( this->m->description + ": seek before beginning of buffer"); } @@ -143,20 +132,18 @@ BufferInputSource::rewind() size_t BufferInputSource::read(char* buffer, size_t length) { - if (this->m->cur_offset < 0) - { + if (this->m->cur_offset < 0) { throw std::logic_error("INTERNAL ERROR: BufferInputSource offset < 0"); } qpdf_offset_t end_pos = this->m->max_offset; - if (this->m->cur_offset >= end_pos) - { + if (this->m->cur_offset >= end_pos) { this->last_offset = end_pos; return 0; } this->last_offset = this->m->cur_offset; - size_t len = std::min( - QIntC::to_size(end_pos - this->m->cur_offset), length); + size_t len = + std::min(QIntC::to_size(end_pos - this->m->cur_offset), length); memcpy(buffer, this->m->buf->getBuffer() + this->m->cur_offset, len); this->m->cur_offset += QIntC::to_offset(len); return len; @@ -165,8 +152,7 @@ BufferInputSource::read(char* buffer, size_t length) void BufferInputSource::unreadCh(char ch) { - if (this->m->cur_offset > 0) - { + if (this->m->cur_offset > 0) { --this->m->cur_offset; } } diff --git a/libqpdf/ClosedFileInputSource.cc b/libqpdf/ClosedFileInputSource.cc index 5625002f..a4c52c92 100644 --- a/libqpdf/ClosedFileInputSource.cc +++ b/libqpdf/ClosedFileInputSource.cc @@ -25,8 +25,7 @@ ClosedFileInputSource::~ClosedFileInputSource() void ClosedFileInputSource::before() { - if (0 == this->m->fis.get()) - { + if (0 == this->m->fis.get()) { this->m->fis = make_pointer_holder(); this->m->fis->setFilename(this->m->filename.c_str()); this->m->fis->seek(this->m->offset, SEEK_SET); @@ -39,8 +38,7 @@ ClosedFileInputSource::after() { this->last_offset = this->m->fis->getLastOffset(); this->m->offset = this->m->fis->tell(); - if (this->m->stay_open) - { + if (this->m->stay_open) { return; } this->m->fis = 0; @@ -82,8 +80,7 @@ void ClosedFileInputSource::rewind() { this->m->offset = 0; - if (this->m->fis.get()) - { + if (this->m->fis.get()) { this->m->fis->rewind(); } } @@ -110,8 +107,7 @@ void ClosedFileInputSource::stayOpen(bool val) { this->m->stay_open = val; - if ((! val) && this->m->fis.get()) - { + if ((!val) && this->m->fis.get()) { after(); } } diff --git a/libqpdf/ContentNormalizer.cc b/libqpdf/ContentNormalizer.cc index 1793c6f3..d7f3cbd7 100644 --- a/libqpdf/ContentNormalizer.cc +++ b/libqpdf/ContentNormalizer.cc @@ -18,57 +18,46 @@ ContentNormalizer::handleToken(QPDFTokenizer::Token const& token) std::string value = token.getRawValue(); QPDFTokenizer::token_type_e token_type = token.getType(); - if (token_type == QPDFTokenizer::tt_bad) - { + if (token_type == QPDFTokenizer::tt_bad) { this->any_bad_tokens = true; this->last_token_was_bad = true; - } - else if (token_type != QPDFTokenizer::tt_eof) - { + } else if (token_type != QPDFTokenizer::tt_eof) { this->last_token_was_bad = false; } - switch (token_type) - { - case QPDFTokenizer::tt_space: + switch (token_type) { + case QPDFTokenizer::tt_space: { size_t len = value.length(); - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { char ch = value.at(i); - if (ch == '\r') - { - if ((i + 1 < len) && (value.at(i + 1) == '\n')) - { + if (ch == '\r') { + if ((i + 1 < len) && (value.at(i + 1) == '\n')) { // ignore - } - else - { + } else { write("\n"); } - } - else - { + } else { write(&ch, 1); } } } break; - case QPDFTokenizer::tt_string: + case QPDFTokenizer::tt_string: // Replacing string and name tokens in this way normalizes // their representation as this will automatically handle // quoting of unprintable characters, etc. - writeToken(QPDFTokenizer::Token( - QPDFTokenizer::tt_string, token.getValue())); + writeToken( + QPDFTokenizer::Token(QPDFTokenizer::tt_string, token.getValue())); break; - case QPDFTokenizer::tt_name: - writeToken(QPDFTokenizer::Token( - QPDFTokenizer::tt_name, token.getValue())); + case QPDFTokenizer::tt_name: + writeToken( + QPDFTokenizer::Token(QPDFTokenizer::tt_name, token.getValue())); break; - default: + default: writeToken(token); break; } @@ -77,8 +66,7 @@ ContentNormalizer::handleToken(QPDFTokenizer::Token const& token) if (((token_type == QPDFTokenizer::tt_string) || (token_type == QPDFTokenizer::tt_name)) && ((value.find('\r') != std::string::npos) || - (value.find('\n') != std::string::npos))) - { + (value.find('\n') != std::string::npos))) { write("\n"); } } @@ -90,7 +78,7 @@ ContentNormalizer::anyBadTokens() const } bool -ContentNormalizer::lastTokenWasBad()const +ContentNormalizer::lastTokenWasBad() const { return this->last_token_was_bad; } diff --git a/libqpdf/FileInputSource.cc b/libqpdf/FileInputSource.cc index b64df811..26ce20e6 100644 --- a/libqpdf/FileInputSource.cc +++ b/libqpdf/FileInputSource.cc @@ -1,9 +1,9 @@ #include -#include -#include #include +#include #include +#include FileInputSource::Members::Members(bool close_file) : close_file(close_file), @@ -13,8 +13,7 @@ FileInputSource::Members::Members(bool close_file) : FileInputSource::Members::~Members() { - if (this->file && this->close_file) - { + if (this->file && this->close_file) { fclose(this->file); } } @@ -33,8 +32,7 @@ FileInputSource::setFilename(char const* filename) } void -FileInputSource::setFile( - char const* description, FILE* filep, bool close_file) +FileInputSource::setFile(char const* description, FILE* filep, bool close_file) { this->m = PointerHolder(new Members(close_file)); this->m->filename = description; @@ -52,35 +50,26 @@ FileInputSource::findAndSkipNextEOL() qpdf_offset_t result = 0; bool done = false; char buf[10240]; - while (! done) - { + while (!done) { qpdf_offset_t cur_offset = QUtil::tell(this->m->file); size_t len = this->read(buf, sizeof(buf)); - if (len == 0) - { + if (len == 0) { done = true; result = this->tell(); - } - else - { + } else { char* p1 = static_cast(memchr(buf, '\r', len)); char* p2 = static_cast(memchr(buf, '\n', len)); char* p = (p1 && p2) ? std::min(p1, p2) : p1 ? p1 : p2; - if (p) - { + if (p) { result = cur_offset + (p - buf); // We found \r or \n. Keep reading until we get past // \r and \n characters. this->seek(result + 1, SEEK_SET); char ch; - while (! done) - { - if (this->read(&ch, 1) == 0) - { + while (!done) { + if (this->read(&ch, 1) == 0) { done = true; - } - else if (! ((ch == '\r') || (ch == '\n'))) - { + } else if (!((ch == '\r') || (ch == '\n'))) { this->unreadCh(ch); done = true; } @@ -106,11 +95,11 @@ FileInputSource::tell() void FileInputSource::seek(qpdf_offset_t offset, int whence) { - QUtil::os_wrapper(std::string("seek to ") + - this->m->filename + ", offset " + - QUtil::int_to_string(offset) + " (" + - QUtil::int_to_string(whence) + ")", - QUtil::seek(this->m->file, offset, whence)); + QUtil::os_wrapper( + std::string("seek to ") + this->m->filename + ", offset " + + QUtil::int_to_string(offset) + " (" + QUtil::int_to_string(whence) + + ")", + QUtil::seek(this->m->file, offset, whence)); } void @@ -124,18 +113,16 @@ FileInputSource::read(char* buffer, size_t length) { this->last_offset = this->tell(); size_t len = fread(buffer, 1, length, this->m->file); - if (len == 0) - { - if (ferror(this->m->file)) - { - throw QPDFExc(qpdf_e_system, - this->m->filename, "", - this->last_offset, - std::string("read ") + - QUtil::uint_to_string(length) + " bytes"); - } - else if (length > 0) - { + if (len == 0) { + if (ferror(this->m->file)) { + throw QPDFExc( + qpdf_e_system, + this->m->filename, + "", + this->last_offset, + std::string("read ") + QUtil::uint_to_string(length) + + " bytes"); + } else if (length > 0) { this->seek(0, SEEK_END); this->last_offset = this->tell(); } @@ -146,6 +133,7 @@ FileInputSource::read(char* buffer, size_t length) void FileInputSource::unreadCh(char ch) { - QUtil::os_wrapper(this->m->filename + ": unread character", - ungetc(static_cast(ch), this->m->file)); + QUtil::os_wrapper( + this->m->filename + ": unread character", + ungetc(static_cast(ch), this->m->file)); } diff --git a/libqpdf/InputSource.cc b/libqpdf/InputSource.cc index 3520ebf2..56e941eb 100644 --- a/libqpdf/InputSource.cc +++ b/libqpdf/InputSource.cc @@ -1,10 +1,10 @@ #include -#include -#include -#include #include #include +#include +#include +#include InputSource::Members::Members() { @@ -45,17 +45,15 @@ InputSource::readLine(size_t max_line_length) qpdf_offset_t eol = this->findAndSkipNextEOL(); this->last_offset = offset; size_t line_length = QIntC::to_size(eol - offset); - if (line_length < max_line_length) - { + if (line_length < max_line_length) { buf[line_length] = '\0'; } return std::string(buf); } bool -InputSource::findFirst(char const* start_chars, - qpdf_offset_t offset, size_t len, - Finder& finder) +InputSource::findFirst( + char const* start_chars, qpdf_offset_t offset, size_t len, Finder& finder) { // Basic approach: search for the first character of start_chars // starting from offset but not going past len (if len != 0). Once @@ -74,8 +72,7 @@ InputSource::findFirst(char const* start_chars, // To enable us to guarantee null-termination, save an extra byte // so that buf[size] is valid memory. size_t size = sizeof(buf) - 1; - if ((strlen(start_chars) < 1) || (strlen(start_chars) > size)) - { + if ((strlen(start_chars) < 1) || (strlen(start_chars) > size)) { throw std::logic_error( "InputSource::findSource called with" " too small or too large of a character sequence"); @@ -90,8 +87,7 @@ InputSource::findFirst(char const* start_chars, // that will cause return on the next pass. Eventually we will // either be out of range or hit EOF, either of which forces us to // return. - while (true) - { + while (true) { // Do we need to read more data? Pretend size = 5, buf starts // at 0, and start_chars has 3 characters. buf[5] is valid and // null. If p == 2, start_chars could be buf[2] through @@ -99,12 +95,12 @@ InputSource::findFirst(char const* start_chars, // If p points to buf[size], since strlen(start_chars) is // always >= 1, this overflow test will be correct for that // case regardless of start_chars. - if ((p == 0) || ((p + strlen(start_chars)) > (buf + bytes_read))) - { - if (p) - { - QTC::TC("libtests", "InputSource read next block", - ((p == buf + bytes_read) ? 0 : 1)); + if ((p == 0) || ((p + strlen(start_chars)) > (buf + bytes_read))) { + if (p) { + QTC::TC( + "libtests", + "InputSource read next block", + ((p == buf + bytes_read) ? 0 : 1)); buf_offset += (p - buf); } this->seek(buf_offset, SEEK_SET); @@ -113,10 +109,11 @@ InputSource::findFirst(char const* start_chars, // we could guarantee null termination as an extra // protection against overrun when using string functions. bytes_read = this->read(buf, size); - if (bytes_read < strlen(start_chars)) - { - QTC::TC("libtests", "InputSource find EOF", - bytes_read == 0 ? 0 : 1); + if (bytes_read < strlen(start_chars)) { + QTC::TC( + "libtests", + "InputSource find EOF", + bytes_read == 0 ? 0 : 1); return false; } memset(buf + bytes_read, '\0', 1 + (size - bytes_read)); @@ -124,29 +121,24 @@ InputSource::findFirst(char const* start_chars, } // Search for the first character. - if ((p = static_cast( - memchr(p, start_chars[0], - bytes_read - QIntC::to_size(p - buf)))) != 0) - { - if (p == buf) - { + if ((p = static_cast(memchr( + p, start_chars[0], bytes_read - QIntC::to_size(p - buf)))) != + 0) { + if (p == buf) { QTC::TC("libtests", "InputSource found match at buf[0]"); } // Found first letter. - if (len != 0) - { + if (len != 0) { // Make sure it's in range. size_t p_relative_offset = QIntC::to_size((p - buf) + (buf_offset - offset)); - if (p_relative_offset >= len) - { + if (p_relative_offset >= len) { // out of range QTC::TC("libtests", "InputSource out of range"); return false; } } - if ((p + strlen(start_chars)) > (buf + bytes_read)) - { + if ((p + strlen(start_chars)) > (buf + bytes_read)) { // If there are not enough bytes left in the file for // start_chars, we will detect this on the next pass // as EOF and return. @@ -157,30 +149,26 @@ InputSource::findFirst(char const* start_chars, // See if p points to a sequence matching start_chars. We // already checked above to make sure we are not going to // overrun memory. - if (strncmp(p, start_chars, strlen(start_chars)) == 0) - { + if (strncmp(p, start_chars, strlen(start_chars)) == 0) { // Call finder.check() with the input source // positioned to the point of the match. this->seek(buf_offset + (p - buf), SEEK_SET); - if (finder.check()) - { + if (finder.check()) { return true; + } else { + QTC::TC( + "libtests", + "InputSource start_chars matched but not check"); } - else - { - QTC::TC("libtests", "InputSource start_chars matched but not check"); - } - } - else - { - QTC::TC("libtests", "InputSource first char matched but not string"); + } else { + QTC::TC( + "libtests", + "InputSource first char matched but not string"); } // This occurrence of the first character wasn't a match. // Skip over it and keep searching. ++p; - } - else - { + } else { // Trigger reading the next block p = buf + bytes_read; } @@ -189,30 +177,24 @@ InputSource::findFirst(char const* start_chars, } bool -InputSource::findLast(char const* start_chars, - qpdf_offset_t offset, size_t len, - Finder& finder) +InputSource::findLast( + char const* start_chars, qpdf_offset_t offset, size_t len, Finder& finder) { bool found = false; qpdf_offset_t after_found_offset = 0; qpdf_offset_t cur_offset = offset; size_t cur_len = len; - while (this->findFirst(start_chars, cur_offset, cur_len, finder)) - { - if (found) - { + while (this->findFirst(start_chars, cur_offset, cur_len, finder)) { + if (found) { QTC::TC("libtests", "InputSource findLast found more than one"); - } - else - { + } else { found = true; } after_found_offset = this->tell(); cur_offset = after_found_offset; cur_len = len - QIntC::to_size((cur_offset - offset)); } - if (found) - { + if (found) { this->seek(after_found_offset, SEEK_SET); } return found; diff --git a/libqpdf/InsecureRandomDataProvider.cc b/libqpdf/InsecureRandomDataProvider.cc index 4077a35f..b29b0f9f 100644 --- a/libqpdf/InsecureRandomDataProvider.cc +++ b/libqpdf/InsecureRandomDataProvider.cc @@ -1,7 +1,7 @@ #include -#include #include +#include #include InsecureRandomDataProvider::InsecureRandomDataProvider() : @@ -16,8 +16,7 @@ InsecureRandomDataProvider::~InsecureRandomDataProvider() void InsecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { data[i] = static_cast((this->random() & 0xff0) >> 4); } } @@ -25,13 +24,12 @@ InsecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) long InsecureRandomDataProvider::random() { - if (! this->seeded_random) - { + if (!this->seeded_random) { // Seed the random number generator with something simple, but // just to be interesting, don't use the unmodified current // time. It would be better if this were a more secure seed. - unsigned int seed = static_cast( - QUtil::get_current_time() ^ 0xcccc); + unsigned int seed = + static_cast(QUtil::get_current_time() ^ 0xcccc); #ifdef HAVE_RANDOM ::srandom(seed); #else @@ -40,11 +38,11 @@ InsecureRandomDataProvider::random() this->seeded_random = true; } -# ifdef HAVE_RANDOM +#ifdef HAVE_RANDOM return ::random(); -# else +#else return rand(); -# endif +#endif } RandomDataProvider* diff --git a/libqpdf/JSON.cc b/libqpdf/JSON.cc index 3f96ab5d..4f2a14d9 100644 --- a/libqpdf/JSON.cc +++ b/libqpdf/JSON.cc @@ -1,9 +1,9 @@ #include -#include #include -#include +#include #include +#include JSON::Members::~Members() { @@ -27,27 +27,23 @@ JSON::JSON_dictionary::~JSON_dictionary() { } -std::string JSON::JSON_dictionary::unparse(size_t depth) const +std::string +JSON::JSON_dictionary::unparse(size_t depth) const { std::string result = "{"; bool first = true; - for (auto const& iter: members) - { - if (first) - { + for (auto const& iter : members) { + if (first) { first = false; - } - else - { + } else { result.append(1, ','); } result.append(1, '\n'); result.append(2 * (1 + depth), ' '); - result += ("\"" + iter.first + "\": " + - iter.second->unparse(1 + depth)); + result += + ("\"" + iter.first + "\": " + iter.second->unparse(1 + depth)); } - if (! first) - { + if (!first) { result.append(1, '\n'); result.append(2 * depth, ' '); } @@ -59,26 +55,22 @@ JSON::JSON_array::~JSON_array() { } -std::string JSON::JSON_array::unparse(size_t depth) const +std::string +JSON::JSON_array::unparse(size_t depth) const { std::string result = "["; bool first = true; - for (auto const& element: elements) - { - if (first) - { + for (auto const& element : elements) { + if (first) { first = false; - } - else - { + } else { result.append(1, ','); } result.append(1, '\n'); result.append(2 * (1 + depth), ' '); result += element->unparse(1 + depth); } - if (! first) - { + if (!first) { result.append(1, '\n'); result.append(2 * depth, ' '); } @@ -96,7 +88,8 @@ JSON::JSON_string::~JSON_string() { } -std::string JSON::JSON_string::unparse(size_t) const +std::string +JSON::JSON_string::unparse(size_t) const { return "\"" + encoded + "\""; } @@ -120,7 +113,8 @@ JSON::JSON_number::~JSON_number() { } -std::string JSON::JSON_number::unparse(size_t) const +std::string +JSON::JSON_number::unparse(size_t) const { return encoded; } @@ -134,7 +128,8 @@ JSON::JSON_bool::~JSON_bool() { } -std::string JSON::JSON_bool::unparse(size_t) const +std::string +JSON::JSON_bool::unparse(size_t) const { return value ? "true" : "false"; } @@ -143,7 +138,8 @@ JSON::JSON_null::~JSON_null() { } -std::string JSON::JSON_null::unparse(size_t) const +std::string +JSON::JSON_null::unparse(size_t) const { return "null"; } @@ -151,12 +147,9 @@ std::string JSON::JSON_null::unparse(size_t) const std::string JSON::unparse() const { - if (0 == this->m->value.get()) - { + if (0 == this->m->value.get()) { return "null"; - } - else - { + } else { return this->m->value->unparse(0); } } @@ -166,39 +159,34 @@ JSON::encode_string(std::string const& str) { std::string result; size_t len = str.length(); - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { unsigned char ch = static_cast(str.at(i)); - switch (ch) - { - case '\\': + switch (ch) { + case '\\': result += "\\\\"; break; - case '\"': + case '\"': result += "\\\""; break; - case '\b': + case '\b': result += "\\b"; break; - case '\f': + case '\f': result += "\\f"; break; - case '\n': + case '\n': result += "\\n"; break; - case '\r': + case '\r': result += "\\r"; break; - case '\t': + case '\t': result += "\\t"; break; - default: - if (ch < 32) - { + default: + if (ch < 32) { result += "\\u" + QUtil::int_to_string_base(ch, 16, 4); - } - else - { + } else { result.append(1, static_cast(ch)); } } @@ -215,19 +203,14 @@ JSON::makeDictionary() JSON JSON::addDictionaryMember(std::string const& key, JSON const& val) { - JSON_dictionary* obj = dynamic_cast( - this->m->value.get()); - if (0 == obj) - { + JSON_dictionary* obj = dynamic_cast(this->m->value.get()); + if (0 == obj) { throw std::runtime_error( "JSON::addDictionaryMember called on non-dictionary"); } - if (val.m->value.get()) - { + if (val.m->value.get()) { obj->members[encode_string(key)] = val.m->value; - } - else - { + } else { obj->members[encode_string(key)] = std::make_shared(); } return obj->members[encode_string(key)]; @@ -242,18 +225,13 @@ JSON::makeArray() JSON JSON::addArrayElement(JSON const& val) { - JSON_array* arr = dynamic_cast( - this->m->value.get()); - if (0 == arr) - { + JSON_array* arr = dynamic_cast(this->m->value.get()); + if (0 == arr) { throw std::runtime_error("JSON::addArrayElement called on non-array"); } - if (val.m->value.get()) - { + if (val.m->value.get()) { arr->elements.push_back(val.m->value); - } - else - { + } else { arr->elements.push_back(std::make_shared()); } return arr->elements.back(); @@ -298,23 +276,21 @@ JSON::makeNull() bool JSON::isArray() const { - return nullptr != dynamic_cast( - this->m->value.get()); + return nullptr != dynamic_cast(this->m->value.get()); } bool JSON::isDictionary() const { - return nullptr != dynamic_cast( - this->m->value.get()); + return nullptr != + dynamic_cast(this->m->value.get()); } bool JSON::getString(std::string& utf8) const { auto v = dynamic_cast(this->m->value.get()); - if (v == nullptr) - { + if (v == nullptr) { return false; } utf8 = v->utf8; @@ -325,8 +301,7 @@ bool JSON::getNumber(std::string& value) const { auto v = dynamic_cast(this->m->value.get()); - if (v == nullptr) - { + if (v == nullptr) { return false; } value = v->encoded; @@ -337,8 +312,7 @@ bool JSON::getBool(bool& value) const { auto v = dynamic_cast(this->m->value.get()); - if (v == nullptr) - { + if (v == nullptr) { return false; } value = v->value; @@ -348,8 +322,7 @@ JSON::getBool(bool& value) const bool JSON::isNull() const { - if (dynamic_cast(this->m->value.get())) - { + if (dynamic_cast(this->m->value.get())) { return true; } return false; @@ -360,12 +333,10 @@ JSON::forEachDictItem( std::function fn) const { auto v = dynamic_cast(this->m->value.get()); - if (v == nullptr) - { + if (v == nullptr) { return false; } - for (auto const& k: v->members) - { + for (auto const& k : v->members) { fn(k.first, JSON(k.second)); } return true; @@ -375,12 +346,10 @@ bool JSON::forEachArrayItem(std::function fn) const { auto v = dynamic_cast(this->m->value.get()); - if (v == nullptr) - { + if (v == nullptr) { return false; } - for (auto const& i: v->elements) - { + for (auto const& i : v->elements) { fn(JSON(i)); } return true; @@ -389,25 +358,25 @@ JSON::forEachArrayItem(std::function fn) const bool JSON::checkSchema(JSON schema, std::list& errors) { - return checkSchemaInternal(this->m->value.get(), - schema.m->value.get(), - 0, errors, ""); + return checkSchemaInternal( + this->m->value.get(), schema.m->value.get(), 0, errors, ""); } bool -JSON::checkSchema(JSON schema, unsigned long flags, - std::list& errors) +JSON::checkSchema( + JSON schema, unsigned long flags, std::list& errors) { - return checkSchemaInternal(this->m->value.get(), - schema.m->value.get(), - flags, errors, ""); + return checkSchemaInternal( + this->m->value.get(), schema.m->value.get(), flags, errors, ""); } bool -JSON::checkSchemaInternal(JSON_value* this_v, JSON_value* sch_v, - unsigned long flags, - std::list& errors, - std::string prefix) +JSON::checkSchemaInternal( + JSON_value* this_v, + JSON_value* sch_v, + unsigned long flags, + std::list& errors, + std::string prefix) { JSON_array* this_arr = dynamic_cast(this_v); JSON_dictionary* this_dict = dynamic_cast(this_v); @@ -418,20 +387,15 @@ JSON::checkSchemaInternal(JSON_value* this_v, JSON_value* sch_v, JSON_string* sch_str = dynamic_cast(sch_v); std::string err_prefix; - if (prefix.empty()) - { + if (prefix.empty()) { err_prefix = "top-level object"; - } - else - { + } else { err_prefix = "json key \"" + prefix + "\""; } std::string pattern_key; - if (sch_dict) - { - if (! this_dict) - { + if (sch_dict) { + if (!this_dict) { QTC::TC("libtests", "JSON wanted dictionary"); errors.push_back(err_prefix + " is supposed to be a dictionary"); return false; @@ -440,44 +404,36 @@ JSON::checkSchemaInternal(JSON_value* this_v, JSON_value* sch_v, std::string key; if ((members.size() == 1) && ((key = members.begin()->first, key.length() > 2) && - (key.at(0) == '<') && - (key.at(key.length() - 1) == '>'))) - { + (key.at(0) == '<') && (key.at(key.length() - 1) == '>'))) { pattern_key = key; } } - if (sch_dict && (! pattern_key.empty())) - { + if (sch_dict && (!pattern_key.empty())) { auto pattern_schema = sch_dict->members[pattern_key].get(); - for (auto const& iter: this_dict->members) - { + for (auto const& iter : this_dict->members) { std::string const& key = iter.first; checkSchemaInternal( - this_dict->members[key].get(), pattern_schema, - flags, errors, prefix + "." + key); + this_dict->members[key].get(), + pattern_schema, + flags, + errors, + prefix + "." + key); } - } - else if (sch_dict) - { - for (auto& iter: sch_dict->members) - { + } else if (sch_dict) { + for (auto& iter : sch_dict->members) { std::string const& key = iter.first; - if (this_dict->members.count(key)) - { + if (this_dict->members.count(key)) { checkSchemaInternal( this_dict->members[key].get(), iter.second.get(), - flags, errors, prefix + "." + key); - } - else - { - if (flags & f_optional) - { + flags, + errors, + prefix + "." + key); + } else { + if (flags & f_optional) { QTC::TC("libtests", "JSON optional key"); - } - else - { + } else { QTC::TC("libtests", "JSON key missing in object"); errors.push_back( err_prefix + ": key \"" + key + @@ -485,55 +441,49 @@ JSON::checkSchemaInternal(JSON_value* this_v, JSON_value* sch_v, } } } - for (auto const& iter: this_dict->members) - { + for (auto const& iter : this_dict->members) { std::string const& key = iter.first; - if (sch_dict->members.count(key) == 0) - { + if (sch_dict->members.count(key) == 0) { QTC::TC("libtests", "JSON key extra in object"); errors.push_back( err_prefix + ": key \"" + key + "\" is not present in schema but appears in object"); } } - } - else if (sch_arr) - { - if (! this_arr) - { + } else if (sch_arr) { + if (!this_arr) { QTC::TC("libtests", "JSON wanted array"); errors.push_back(err_prefix + " is supposed to be an array"); return false; } - if (sch_arr->elements.size() != 1) - { + if (sch_arr->elements.size() != 1) { QTC::TC("libtests", "JSON schema array error"); - errors.push_back(err_prefix + - " schema array contains other than one item"); + errors.push_back( + err_prefix + " schema array contains other than one item"); return false; } int i = 0; - for (auto const& element: this_arr->elements) - { + for (auto const& element : this_arr->elements) { checkSchemaInternal( element.get(), sch_arr->elements.at(0).get(), - flags, errors, prefix + "." + QUtil::int_to_string(i)); + flags, + errors, + prefix + "." + QUtil::int_to_string(i)); ++i; } - } - else if (! sch_str) - { + } else if (!sch_str) { QTC::TC("libtests", "JSON schema other type"); - errors.push_back(err_prefix + - " schema value is not dictionary, array, or string"); + errors.push_back( + err_prefix + " schema value is not dictionary, array, or string"); return false; } return errors.empty(); } -namespace { +namespace +{ class JSONParser { public: @@ -597,7 +547,7 @@ namespace { std::vector ps_stack; std::string dict_key; }; -} +} // namespace std::string JSONParser::decode_string(std::string const& str) @@ -606,8 +556,7 @@ JSONParser::decode_string(std::string const& str) // is called, so errors are logic errors instead of runtime // errors. size_t len = str.length(); - if ((len < 2) || (str.at(0) != '"') || (str.at(len-1) != '"')) - { + if ((len < 2) || (str.at(0) != '"') || (str.at(len - 1) != '"')) { throw std::logic_error( "JSON Parse: decode_string called with other than \"...\""); } @@ -616,48 +565,43 @@ JSONParser::decode_string(std::string const& str) ++s; len -= 2; std::string result; - for (size_t i = 0; i < len; ++i) - { - if (s[i] == '\\') - { - if (i + 1 >= len) - { + for (size_t i = 0; i < len; ++i) { + if (s[i] == '\\') { + if (i + 1 >= len) { throw std::logic_error("JSON parse: nothing after \\"); } char ch = s[++i]; - switch (ch) - { - case '\\': - case '\"': - case '/': + switch (ch) { + case '\\': + case '\"': + case '/': // \/ is allowed in json input, but so is /, so we // don't map / to \/ in output. result.append(1, ch); break; - case 'b': + case 'b': result.append(1, '\b'); break; - case 'f': + case 'f': result.append(1, '\f'); break; - case 'n': + case 'n': result.append(1, '\n'); break; - case 'r': + case 'r': result.append(1, '\r'); break; - case 't': + case 't': result.append(1, '\t'); break; - case 'u': - if (i + 4 >= len) - { + case 'u': + if (i + 4 >= len) { throw std::logic_error( "JSON parse: not enough characters after \\u"); } { std::string hex = - QUtil::hex_decode(std::string(s+i+1, s+i+5)); + QUtil::hex_decode(std::string(s + i + 1, s + i + 5)); i += 4; unsigned char high = static_cast(hex.at(0)); unsigned char low = static_cast(hex.at(1)); @@ -667,52 +611,40 @@ JSONParser::decode_string(std::string const& str) result += QUtil::toUTF8(codepoint); } break; - default: - throw std::logic_error( - "JSON parse: bad character after \\"); + default: + throw std::logic_error("JSON parse: bad character after \\"); break; } - } - else - { + } else { result.append(1, s[i]); } } return result; } -void JSONParser::getToken() +void +JSONParser::getToken() { - while (p < end) - { - if (*p == 0) - { + while (p < end) { + if (*p == 0) { QTC::TC("libtests", "JSON parse null character"); throw std::runtime_error( "JSON: null character at offset " + QUtil::int_to_string(p - cstr)); } - switch (lex_state) - { - case ls_top: - if (*p == '"') - { + switch (lex_state) { + case ls_top: + if (*p == '"') { tok_start = p; tok_end = nullptr; lex_state = ls_string; - } - else if (QUtil::is_space(*p)) - { + } else if (QUtil::is_space(*p)) { // ignore - } - else if ((*p >= 'a') && (*p <= 'z')) - { + } else if ((*p >= 'a') && (*p <= 'z')) { tok_start = p; tok_end = nullptr; lex_state = ls_alpha; - } - else if (*p == '-') - { + } else if (*p == '-') { tok_start = p; tok_end = nullptr; lex_state = ls_number; @@ -721,9 +653,7 @@ void JSONParser::getToken() number_after_e = 0; number_saw_point = false; number_saw_e = false; - } - else if ((*p >= '0') && (*p <= '9')) - { + } else if ((*p >= '0') && (*p <= '9')) { tok_start = p; tok_end = nullptr; lex_state = ls_number; @@ -732,9 +662,7 @@ void JSONParser::getToken() number_after_e = 0; number_saw_point = false; number_saw_e = false; - } - else if (*p == '.') - { + } else if (*p == '.') { tok_start = p; tok_end = nullptr; lex_state = ls_number; @@ -743,14 +671,10 @@ void JSONParser::getToken() number_after_e = 0; number_saw_point = true; number_saw_e = false; - } - else if (strchr("{}[]:,", *p)) - { + } else if (strchr("{}[]:,", *p)) { tok_start = p; tok_end = p + 1; - } - else - { + } else { QTC::TC("libtests", "JSON parse bad character"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -758,82 +682,53 @@ void JSONParser::getToken() } break; - case ls_number: - if ((*p >= '0') && (*p <= '9')) - { - if (number_saw_e) - { + case ls_number: + if ((*p >= '0') && (*p <= '9')) { + if (number_saw_e) { ++number_after_e; - } - else if (number_saw_point) - { + } else if (number_saw_point) { ++number_after_point; - } - else - { + } else { ++number_before_point; } - } - else if (*p == '.') - { - if (number_saw_e) - { + } else if (*p == '.') { + if (number_saw_e) { QTC::TC("libtests", "JSON parse point after e"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": numeric literal: decimal point after e"); - } - else if (number_saw_point) - { + } else if (number_saw_point) { QTC::TC("libtests", "JSON parse duplicate point"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": numeric literal: decimal point already seen"); - } - else - { + } else { number_saw_point = true; } - } - else if (*p == 'e') - { - if (number_saw_e) - { + } else if (*p == 'e') { + if (number_saw_e) { QTC::TC("libtests", "JSON parse duplicate e"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": numeric literal: e already seen"); - } - else - { + } else { number_saw_e = true; } - } - else if ((*p == '+') || (*p == '-')) - { - if (number_saw_e && (number_after_e == 0)) - { + } else if ((*p == '+') || (*p == '-')) { + if (number_saw_e && (number_after_e == 0)) { // okay - } - else - { + } else { QTC::TC("libtests", "JSON parse unexpected sign"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": numeric literal: unexpected sign"); } - } - else if (QUtil::is_space(*p)) - { + } else if (QUtil::is_space(*p)) { tok_end = p; - } - else if (strchr("{}[]:,", *p)) - { + } else if (strchr("{}[]:,", *p)) { tok_end = p; --p; - } - else - { + } else { QTC::TC("libtests", "JSON parse numeric bad character"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -842,22 +737,15 @@ void JSONParser::getToken() } break; - case ls_alpha: - if ((*p >= 'a') && (*p <= 'z')) - { + case ls_alpha: + if ((*p >= 'a') && (*p <= 'z')) { // okay - } - else if (QUtil::is_space(*p)) - { + } else if (QUtil::is_space(*p)) { tok_end = p; - } - else if (strchr("{}[]:,", *p)) - { + } else if (strchr("{}[]:,", *p)) { tok_end = p; --p; - } - else - { + } else { QTC::TC("libtests", "JSON parse keyword bad character"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -865,36 +753,27 @@ void JSONParser::getToken() } break; - case ls_string: - if (*p == '"') - { + case ls_string: + if (*p == '"') { tok_end = p + 1; - } - else if (*p == '\\') - { + } else if (*p == '\\') { lex_state = ls_backslash; } break; - case ls_backslash: + case ls_backslash: /* cSpell: ignore bfnrt */ - if (strchr("\\\"/bfnrt", *p)) - { + if (strchr("\\\"/bfnrt", *p)) { lex_state = ls_string; - } - else if (*p == 'u') - { - if (p + 4 >= end) - { + } else if (*p == 'u') { + if (p + 4 >= end) { QTC::TC("libtests", "JSON parse premature end of u"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": \\u must be followed by four characters"); } - for (size_t i = 1; i <= 4; ++i) - { - if (! QUtil::is_hex_digit(p[i])) - { + for (size_t i = 1; i <= 4; ++i) { + if (!QUtil::is_hex_digit(p[i])) { QTC::TC("libtests", "JSON parse bad hex after u"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -903,9 +782,7 @@ void JSONParser::getToken() } p += 4; lex_state = ls_string; - } - else - { + } else { QTC::TC("libtests", "JSON parse backslash bad character"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -915,31 +792,27 @@ void JSONParser::getToken() break; } ++p; - if (tok_start && tok_end) - { + if (tok_start && tok_end) { break; } } - if (p == end) - { - if (tok_start && (! tok_end)) - { - switch (lex_state) - { - case ls_top: + if (p == end) { + if (tok_start && (!tok_end)) { + switch (lex_state) { + case ls_top: // Can't happen throw std::logic_error( "tok_start set in ls_top while parsing " + std::string(cstr)); break; - case ls_number: - case ls_alpha: + case ls_number: + case ls_alpha: tok_end = p; break; - case ls_string: - case ls_backslash: + case ls_string: + case ls_backslash: QTC::TC("libtests", "JSON parse unterminated string"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -953,16 +826,14 @@ void JSONParser::getToken() void JSONParser::handleToken() { - if (! (tok_start && tok_end)) - { + if (!(tok_start && tok_end)) { return; } // Get token value. std::string value(tok_start, tok_end); - if (parser_state == ps_done) - { + if (parser_state == ps_done) { QTC::TC("libtests", "JSON parse junk after object"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -971,11 +842,9 @@ JSONParser::handleToken() // Git string value std::string s_value; - if (lex_state == ls_string) - { + if (lex_state == ls_string) { // Token includes the quotation marks - if (tok_end - tok_start < 2) - { + if (tok_end - tok_start < 2) { throw std::logic_error("JSON string length < 2"); } s_value = decode_string(value); @@ -986,28 +855,25 @@ JSONParser::handleToken() std::shared_ptr item; char delimiter = '\0'; - switch (lex_state) - { - case ls_top: - switch (*tok_start) - { - case '{': + switch (lex_state) { + case ls_top: + switch (*tok_start) { + case '{': item = std::make_shared(JSON::makeDictionary()); break; - case '[': + case '[': item = std::make_shared(JSON::makeArray()); break; - default: + default: delimiter = *tok_start; break; } break; - case ls_number: - if (number_saw_point && (number_after_point == 0)) - { + case ls_number: + if (number_saw_point && (number_after_point == 0)) { QTC::TC("libtests", "JSON parse decimal with no digits"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -1015,15 +881,13 @@ JSONParser::handleToken() } if ((number_before_point > 1) && ((tok_start[0] == '0') || - ((tok_start[0] == '-') && (tok_start[1] == '0')))) - { + ((tok_start[0] == '-') && (tok_start[1] == '0')))) { QTC::TC("libtests", "JSON parse leading zero"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": number with leading zero"); } - if ((number_before_point == 0) && (number_after_point == 0)) - { + if ((number_before_point == 0) && (number_after_point == 0)) { QTC::TC("libtests", "JSON parse number no digits"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -1032,21 +896,14 @@ JSONParser::handleToken() item = std::make_shared(JSON::makeNumber(value)); break; - case ls_alpha: - if (value == "true") - { + case ls_alpha: + if (value == "true") { item = std::make_shared(JSON::makeBool(true)); - } - else if (value == "false") - { + } else if (value == "false") { item = std::make_shared(JSON::makeBool(false)); - } - else if (value == "null") - { + } else if (value == "null") { item = std::make_shared(JSON::makeNull()); - } - else - { + } else { QTC::TC("libtests", "JSON parse invalid keyword"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -1054,18 +911,16 @@ JSONParser::handleToken() } break; - case ls_string: + case ls_string: item = std::make_shared(JSON::makeString(s_value)); break; - case ls_backslash: - throw std::logic_error( - "tok_end is set while state = ls_backslash"); + case ls_backslash: + throw std::logic_error("tok_end is set while state = ls_backslash"); break; } - if ((item.get() == nullptr) == (delimiter == '\0')) - { + if ((item.get() == nullptr) == (delimiter == '\0')) { throw std::logic_error( "JSONParser::handleToken: logic error: exactly one of item" " or delimiter must be set"); @@ -1073,39 +928,36 @@ JSONParser::handleToken() // See whether what we have is allowed at this point. - if (item.get()) - { - switch (parser_state) - { - case ps_done: + if (item.get()) { + switch (parser_state) { + case ps_done: throw std::logic_error("can't happen; ps_done already handled"); break; - case ps_dict_after_key: + case ps_dict_after_key: QTC::TC("libtests", "JSON parse expected colon"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": expected ':'"); break; - case ps_dict_after_item: + case ps_dict_after_item: QTC::TC("libtests", "JSON parse expected , or }"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": expected ',' or '}'"); break; - case ps_array_after_item: + case ps_array_after_item: QTC::TC("libtests", "JSON parse expected, or ]"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": expected ',' or ']'"); break; - case ps_dict_begin: - case ps_dict_after_comma: - if (lex_state != ls_string) - { + case ps_dict_begin: + case ps_dict_after_comma: + if (lex_state != ls_string) { QTC::TC("libtests", "JSON parse string as dict key"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + @@ -1113,18 +965,16 @@ JSONParser::handleToken() } break; - case ps_top: - case ps_dict_after_colon: - case ps_array_begin: - case ps_array_after_comma: + case ps_top: + case ps_dict_after_colon: + case ps_array_begin: + case ps_array_after_comma: break; // okay } - } - else if (delimiter == '}') - { - if (! ((parser_state == ps_dict_begin) || - (parser_state == ps_dict_after_item))) + } else if (delimiter == '}') { + if (!((parser_state == ps_dict_begin) || + (parser_state == ps_dict_after_item))) { QTC::TC("libtests", "JSON parse unexpected }"); @@ -1132,11 +982,9 @@ JSONParser::handleToken() "JSON: offset " + QUtil::int_to_string(p - cstr) + ": unexpected dictionary end delimiter"); } - } - else if (delimiter == ']') - { - if (! ((parser_state == ps_array_begin) || - (parser_state == ps_array_after_item))) + } else if (delimiter == ']') { + if (!((parser_state == ps_array_begin) || + (parser_state == ps_array_after_item))) { QTC::TC("libtests", "JSON parse unexpected ]"); @@ -1144,30 +992,22 @@ JSONParser::handleToken() "JSON: offset " + QUtil::int_to_string(p - cstr) + ": unexpected array end delimiter"); } - } - else if (delimiter == ':') - { - if (parser_state != ps_dict_after_key) - { + } else if (delimiter == ':') { + if (parser_state != ps_dict_after_key) { QTC::TC("libtests", "JSON parse unexpected :"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": unexpected colon"); } - } - else if (delimiter == ',') - { - if (! ((parser_state == ps_dict_after_item) || - (parser_state == ps_array_after_item))) - { + } else if (delimiter == ',') { + if (!((parser_state == ps_dict_after_item) || + (parser_state == ps_array_after_item))) { QTC::TC("libtests", "JSON parse unexpected ,"); throw std::runtime_error( "JSON: offset " + QUtil::int_to_string(p - cstr) + ": unexpected comma"); } - } - else if (delimiter != '\0') - { + } else if (delimiter != '\0') { throw std::logic_error("JSONParser::handleToken: bad delimiter"); } @@ -1175,103 +1015,77 @@ JSONParser::handleToken() // whatever we need to do with it. parser_state_e next_state = ps_top; - if (delimiter == ':') - { + if (delimiter == ':') { next_state = ps_dict_after_colon; - } - else if (delimiter == ',') - { - if (parser_state == ps_dict_after_item) - { + } else if (delimiter == ',') { + if (parser_state == ps_dict_after_item) { next_state = ps_dict_after_comma; - } - else if (parser_state == ps_array_after_item) - { + } else if (parser_state == ps_array_after_item) { next_state = ps_array_after_comma; + } else { + throw std::logic_error("JSONParser::handleToken: unexpected parser" + " state for comma"); } - else - { - throw std::logic_error( - "JSONParser::handleToken: unexpected parser" - " state for comma"); - } - } - else if ((delimiter == '}') || (delimiter == ']')) - { + } else if ((delimiter == '}') || (delimiter == ']')) { next_state = ps_stack.back(); ps_stack.pop_back(); - if (next_state != ps_done) - { + if (next_state != ps_done) { stack.pop_back(); } - } - else if (delimiter != '\0') - { + } else if (delimiter != '\0') { throw std::logic_error( "JSONParser::handleToken: unexpected delimiter in transition"); - } - else if (item.get()) - { + } else if (item.get()) { std::shared_ptr tos; - if (! stack.empty()) - { + if (!stack.empty()) { tos = stack.back(); } - switch (parser_state) - { - case ps_dict_begin: - case ps_dict_after_comma: + switch (parser_state) { + case ps_dict_begin: + case ps_dict_after_comma: this->dict_key = s_value; item = nullptr; next_state = ps_dict_after_key; break; - case ps_dict_after_colon: + case ps_dict_after_colon: tos->addDictionaryMember(dict_key, *item); next_state = ps_dict_after_item; break; - case ps_array_begin: - case ps_array_after_comma: + case ps_array_begin: + case ps_array_after_comma: next_state = ps_array_after_item; tos->addArrayElement(*item); break; - case ps_top: + case ps_top: next_state = ps_done; break; - case ps_dict_after_key: - case ps_dict_after_item: - case ps_array_after_item: - case ps_done: + case ps_dict_after_key: + case ps_dict_after_item: + case ps_array_after_item: + case ps_done: throw std::logic_error( "JSONParser::handleToken: unexpected parser state"); } - } - else - { + } else { throw std::logic_error( "JSONParser::handleToken: unexpected null item in transition"); } // Prepare for next token - if (item.get()) - { - if (item->isDictionary()) - { + if (item.get()) { + if (item->isDictionary()) { stack.push_back(item); ps_stack.push_back(next_state); next_state = ps_dict_begin; - } - else if (item->isArray()) - { + } else if (item->isArray()) { stack.push_back(item); ps_stack.push_back(next_state); next_state = ps_array_begin; - } - else if (parser_state == ps_top) - { + } else if (parser_state == ps_top) { stack.push_back(item); } } @@ -1288,13 +1102,11 @@ JSONParser::parse(std::string const& s) end = cstr + s.length(); p = cstr; - while (p < end) - { + while (p < end) { getToken(); handleToken(); } - if (parser_state != ps_done) - { + if (parser_state != ps_done) { QTC::TC("libtests", "JSON parse premature EOF"); throw std::runtime_error("JSON: premature end of input"); } diff --git a/libqpdf/JSONHandler.cc b/libqpdf/JSONHandler.cc index 0a40c710..e12c2b99 100644 --- a/libqpdf/JSONHandler.cc +++ b/libqpdf/JSONHandler.cc @@ -1,8 +1,8 @@ #include -#include -#include #include +#include +#include JSONHandler::JSONHandler() : m(new Members()) @@ -70,9 +70,10 @@ JSONHandler::addFallbackDictHandler(std::shared_ptr fdh) } void -JSONHandler::addArrayHandlers(json_handler_t start_fn, - void_handler_t end_fn, - std::shared_ptr ah) +JSONHandler::addArrayHandlers( + json_handler_t start_fn, + void_handler_t end_fn, + std::shared_ptr ah) { this->m->h.array_start_handler = start_fn; this->m->h.array_end_handler = end_fn; @@ -82,69 +83,55 @@ JSONHandler::addArrayHandlers(json_handler_t start_fn, void JSONHandler::handle(std::string const& path, JSON j) { - if (this->m->h.any_handler) - { + if (this->m->h.any_handler) { this->m->h.any_handler(path, j); return; } bool handled = false; bool bvalue = false; std::string s_value; - if (this->m->h.null_handler && j.isNull()) - { + if (this->m->h.null_handler && j.isNull()) { this->m->h.null_handler(path); handled = true; } - if (this->m->h.string_handler && j.getString(s_value)) - { + if (this->m->h.string_handler && j.getString(s_value)) { this->m->h.string_handler(path, s_value); handled = true; } - if (this->m->h.number_handler && j.getNumber(s_value)) - { + if (this->m->h.number_handler && j.getNumber(s_value)) { this->m->h.number_handler(path, s_value); handled = true; } - if (this->m->h.bool_handler && j.getBool(bvalue)) - { + if (this->m->h.bool_handler && j.getBool(bvalue)) { this->m->h.bool_handler(path, bvalue); handled = true; } - if (this->m->h.dict_start_handler && j.isDictionary()) - { + if (this->m->h.dict_start_handler && j.isDictionary()) { this->m->h.dict_start_handler(path, j); std::string path_base = path; - if (path_base != ".") - { + if (path_base != ".") { path_base += "."; } j.forEachDictItem([&path, &path_base, this]( std::string const& k, JSON v) { auto i = this->m->h.dict_handlers.find(k); - if (i == this->m->h.dict_handlers.end()) - { - if (this->m->h.fallback_dict_handler.get()) - { - this->m->h.fallback_dict_handler->handle( - path_base + k, v); - } - else - { + if (i == this->m->h.dict_handlers.end()) { + if (this->m->h.fallback_dict_handler.get()) { + this->m->h.fallback_dict_handler->handle(path_base + k, v); + } else { QTC::TC("libtests", "JSONHandler unexpected key"); - usage("JSON handler found unexpected key " + k + - " in object at " + path); + usage( + "JSON handler found unexpected key " + k + + " in object at " + path); } - } - else - { + } else { i->second->handle(path_base + k, v); } }); this->m->h.dict_end_handler(path); handled = true; } - if (this->m->h.array_start_handler && j.isArray()) - { + if (this->m->h.array_start_handler && j.isArray()) { this->m->h.array_start_handler(path, j); size_t i = 0; j.forEachArrayItem([&i, &path, this](JSON v) { @@ -156,8 +143,7 @@ JSONHandler::handle(std::string const& path, JSON j) handled = true; } - if (! handled) - { + if (!handled) { // It would be nice to include information about what type the // object was and what types were allowed, but we're relying // on schema validation to make sure input is properly diff --git a/libqpdf/MD5.cc b/libqpdf/MD5.cc index dc4460a0..2119349c 100644 --- a/libqpdf/MD5.cc +++ b/libqpdf/MD5.cc @@ -1,14 +1,14 @@ #include -#include #include #include +#include -#include +#include #include +#include #include #include -#include MD5::MD5() { @@ -28,12 +28,14 @@ MD5::finalize() this->crypto->MD5_finalize(); } -void MD5::reset() +void +MD5::reset() { init(); } -void MD5::encodeString(char const* str) +void +MD5::encodeString(char const* str) { size_t len = strlen(str); crypto->MD5_init(); @@ -41,79 +43,78 @@ void MD5::encodeString(char const* str) crypto->MD5_finalize(); } -void MD5::appendString(char const* input_string) +void +MD5::appendString(char const* input_string) { encodeDataIncrementally(input_string, strlen(input_string)); } -void MD5::encodeDataIncrementally(char const* data, size_t len) +void +MD5::encodeDataIncrementally(char const* data, size_t len) { this->crypto->MD5_update(QUtil::unsigned_char_pointer(data), len); } -void MD5::encodeFile(char const *filename, qpdf_offset_t up_to_offset) +void +MD5::encodeFile(char const* filename, qpdf_offset_t up_to_offset) { char buffer[1024]; - FILE *file = QUtil::safe_fopen(filename, "rb"); + FILE* file = QUtil::safe_fopen(filename, "rb"); size_t len; size_t so_far = 0; size_t to_try = 1024; size_t up_to_size = 0; - if (up_to_offset >= 0) - { + if (up_to_offset >= 0) { up_to_size = QIntC::to_size(up_to_offset); } - do - { - if ((up_to_offset >= 0) && ((so_far + to_try) > up_to_size)) - { + do { + if ((up_to_offset >= 0) && ((so_far + to_try) > up_to_size)) { to_try = up_to_size - so_far; } len = fread(buffer, 1, to_try, file); - if (len > 0) - { + if (len > 0) { encodeDataIncrementally(buffer, len); so_far += len; - if ((up_to_offset >= 0) && (so_far >= up_to_size)) - { + if ((up_to_offset >= 0) && (so_far >= up_to_size)) { break; } } } while (len > 0); - if (ferror(file)) - { + if (ferror(file)) { // Assume, perhaps incorrectly, that errno was set by the // underlying call to read.... - (void) fclose(file); + (void)fclose(file); QUtil::throw_system_error( std::string("MD5: read error on ") + filename); } - (void) fclose(file); + (void)fclose(file); this->crypto->MD5_finalize(); } -void MD5::digest(Digest result) +void +MD5::digest(Digest result) { this->crypto->MD5_finalize(); this->crypto->MD5_digest(result); } -void MD5::print() +void +MD5::print() { Digest digest_val; digest(digest_val); unsigned int i; - for (i = 0; i < 16; ++i) - { + for (i = 0; i < 16; ++i) { printf("%02x", digest_val[i]); } printf("\n"); } -std::string MD5::unparse() +std::string +MD5::unparse() { this->crypto->MD5_finalize(); Digest digest_val; @@ -139,25 +140,23 @@ MD5::getFileChecksum(char const* filename, qpdf_offset_t up_to_offset) } bool -MD5::checkDataChecksum(char const* const checksum, - char const* buf, size_t len) +MD5::checkDataChecksum(char const* const checksum, char const* buf, size_t len) { std::string actual_checksum = getDataChecksum(buf, len); return (checksum == actual_checksum); } bool -MD5::checkFileChecksum(char const* const checksum, - char const* filename, qpdf_offset_t up_to_offset) +MD5::checkFileChecksum( + char const* const checksum, + char const* filename, + qpdf_offset_t up_to_offset) { bool result = false; - try - { + try { std::string actual_checksum = getFileChecksum(filename, up_to_offset); result = (checksum == actual_checksum); - } - catch (std::runtime_error const&) - { + } catch (std::runtime_error const&) { // Ignore -- return false } return result; diff --git a/libqpdf/NNTree.cc b/libqpdf/NNTree.cc index ceb69c8d..c85ac4cf 100644 --- a/libqpdf/NNTree.cc +++ b/libqpdf/NNTree.cc @@ -9,8 +9,7 @@ static std::string get_description(QPDFObjectHandle& node) { std::string result("Name/Number tree node"); - if (node.isIndirect()) - { + if (node.isIndirect()) { result += " (object " + QUtil::int_to_string(node.getObjectID()) + ")"; } return result; @@ -21,11 +20,13 @@ warn(QPDF* qpdf, QPDFObjectHandle& node, std::string const& msg) { // ABI: in qpdf 11, change to a reference. - if (qpdf) - { + if (qpdf) { qpdf->warn(QPDFExc( - qpdf_e_damaged_pdf, - qpdf->getFilename(), get_description(node), 0, msg)); + qpdf_e_damaged_pdf, + qpdf->getFilename(), + get_description(node), + 0, + msg)); } } @@ -34,13 +35,14 @@ error(QPDF* qpdf, QPDFObjectHandle& node, std::string const& msg) { // ABI: in qpdf 11, change to a reference. - if (qpdf) - { - throw QPDFExc(qpdf_e_damaged_pdf, - qpdf->getFilename(), get_description(node), 0, msg); - } - else - { + if (qpdf) { + throw QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + get_description(node), + 0, + msg); + } else { throw std::runtime_error(get_description(node) + ": " + msg); } } @@ -73,29 +75,21 @@ NNTreeIterator::updateIValue(bool allow_invalid) // measure, we also call updateIValue in operator* and operator->. bool okay = false; - if ((item_number >= 0) && - this->node.isInitialized() && - this->node.isDictionary()) - { + if ((item_number >= 0) && this->node.isInitialized() && + this->node.isDictionary()) { auto items = this->node.getKey(impl.details.itemsKey()); - if (this->item_number + 1 < items.getArrayNItems()) - { + if (this->item_number + 1 < items.getArrayNItems()) { okay = true; this->ivalue.first = items.getArrayItem(this->item_number); - this->ivalue.second = items.getArrayItem(1+this->item_number); - } - else - { + this->ivalue.second = items.getArrayItem(1 + this->item_number); + } else { error(impl.qpdf, node, "update ivalue: items array is too short"); } } - if (! okay) - { - if (! allow_invalid) - { - throw std::logic_error( - "attempt made to dereference an invalid" - " name/number tree iterator"); + if (!okay) { + if (!allow_invalid) { + throw std::logic_error("attempt made to dereference an invalid" + " name/number tree iterator"); } this->ivalue.first = QPDFObjectHandle(); this->ivalue.second = QPDFObjectHandle(); @@ -114,29 +108,24 @@ NNTreeIterator::getNextKid(PathElement& pe, bool backward) { QPDFObjectHandle result; bool found = false; - while (! found) - { + while (!found) { pe.kid_number += backward ? -1 : 1; auto kids = pe.node.getKey("/Kids"); - if ((pe.kid_number >= 0) && (pe.kid_number < kids.getArrayNItems())) - { + if ((pe.kid_number >= 0) && (pe.kid_number < kids.getArrayNItems())) { result = kids.getArrayItem(pe.kid_number); if (result.isDictionary() && (result.hasKey("/Kids") || - result.hasKey(impl.details.itemsKey()))) - { + result.hasKey(impl.details.itemsKey()))) { found = true; - } - else - { + } else { QTC::TC("qpdf", "NNTree skip invalid kid"); - warn(impl.qpdf, pe.node, - "skipping over invalid kid at index " + - QUtil::int_to_string(pe.kid_number)); + warn( + impl.qpdf, + pe.node, + "skipping over invalid kid at index " + + QUtil::int_to_string(pe.kid_number)); } - } - else - { + } else { result = QPDFObjectHandle::newNull(); found = true; } @@ -153,55 +142,46 @@ NNTreeIterator::valid() const void NNTreeIterator::increment(bool backward) { - if (this->item_number < 0) - { + if (this->item_number < 0) { QTC::TC("qpdf", "NNTree increment end()"); - deepen(impl.oh, ! backward, true); + deepen(impl.oh, !backward, true); return; } bool found_valid_key = false; - while (valid() && (! found_valid_key)) - { + while (valid() && (!found_valid_key)) { this->item_number += backward ? -2 : 2; auto items = this->node.getKey(impl.details.itemsKey()); if ((this->item_number < 0) || - (this->item_number >= items.getArrayNItems())) - { + (this->item_number >= items.getArrayNItems())) { bool found = false; setItemNumber(QPDFObjectHandle(), -1); - while (! (found || this->path.empty())) - { + while (!(found || this->path.empty())) { auto& element = this->path.back(); auto pe_node = getNextKid(element, backward); - if (pe_node.isNull()) - { + if (pe_node.isNull()) { this->path.pop_back(); - } - else - { - found = deepen(pe_node, ! backward, false); + } else { + found = deepen(pe_node, !backward, false); } } } - if (this->item_number >= 0) - { + if (this->item_number >= 0) { items = this->node.getKey(impl.details.itemsKey()); - if (this->item_number + 1 >= items.getArrayNItems()) - { + if (this->item_number + 1 >= items.getArrayNItems()) { QTC::TC("qpdf", "NNTree skip item at end of short items"); - warn(impl.qpdf, this->node, - "items array doesn't have enough elements"); - } - else if (! impl.details.keyValid( - items.getArrayItem(this->item_number))) - { + warn( + impl.qpdf, + this->node, + "items array doesn't have enough elements"); + } else if (!impl.details.keyValid( + items.getArrayItem(this->item_number))) { QTC::TC("qpdf", "NNTree skip invalid key"); - warn(impl.qpdf, this->node, - "item " + QUtil::int_to_string(this->item_number) + - " has the wrong type"); - } - else - { + warn( + impl.qpdf, + this->node, + "item " + QUtil::int_to_string(this->item_number) + + " has the wrong type"); + } else { found_valid_key = true; } } @@ -209,14 +189,12 @@ NNTreeIterator::increment(bool backward) } void -NNTreeIterator::resetLimits(QPDFObjectHandle node, - std::list::iterator parent) +NNTreeIterator::resetLimits( + QPDFObjectHandle node, std::list::iterator parent) { bool done = false; - while (! done) - { - if (parent == this->path.end()) - { + while (!done) { + if (parent == this->path.end()) { QTC::TC("qpdf", "NNTree remove limits from root"); node.removeKey("/Limits"); done = true; @@ -230,65 +208,51 @@ NNTreeIterator::resetLimits(QPDFObjectHandle node, bool changed = true; QPDFObjectHandle first; QPDFObjectHandle last; - if (nitems >= 2) - { + if (nitems >= 2) { first = items.getArrayItem(0); last = items.getArrayItem((nitems - 1) & ~1); - } - else if (nkids > 0) - { + } else if (nkids > 0) { auto first_kid = kids.getArrayItem(0); auto last_kid = kids.getArrayItem(nkids - 1); - if (first_kid.isDictionary() && last_kid.isDictionary()) - { + if (first_kid.isDictionary() && last_kid.isDictionary()) { auto first_limits = first_kid.getKey("/Limits"); auto last_limits = last_kid.getKey("/Limits"); if (first_limits.isArray() && (first_limits.getArrayNItems() >= 2) && last_limits.isArray() && - (last_limits.getArrayNItems() >= 2)) - { + (last_limits.getArrayNItems() >= 2)) { first = first_limits.getArrayItem(0); last = last_limits.getArrayItem(1); } } } - if (first.isInitialized() && last.isInitialized()) - { + if (first.isInitialized() && last.isInitialized()) { auto limits = QPDFObjectHandle::newArray(); limits.appendItem(first); limits.appendItem(last); auto olimits = node.getKey("/Limits"); - if (olimits.isArray() && (olimits.getArrayNItems() == 2)) - { + if (olimits.isArray() && (olimits.getArrayNItems() == 2)) { auto ofirst = olimits.getArrayItem(0); auto olast = olimits.getArrayItem(1); if (impl.details.keyValid(ofirst) && impl.details.keyValid(olast) && (impl.details.compareKeys(first, ofirst) == 0) && - (impl.details.compareKeys(last, olast) == 0)) - { + (impl.details.compareKeys(last, olast) == 0)) { QTC::TC("qpdf", "NNTree limits didn't change"); changed = false; } } - if (changed) - { + if (changed) { node.replaceKey("/Limits", limits); } - } - else - { + } else { QTC::TC("qpdf", "NNTree unable to determine limits"); warn(impl.qpdf, node, "unable to determine limits"); } - if ((! changed) || (parent == this->path.begin())) - { + if ((!changed) || (parent == this->path.begin())) { done = true; - } - else - { + } else { node = parent->node; --parent; } @@ -296,8 +260,8 @@ NNTreeIterator::resetLimits(QPDFObjectHandle node, } void -NNTreeIterator::split(QPDFObjectHandle to_split, - std::list::iterator parent) +NNTreeIterator::split( + QPDFObjectHandle to_split, std::list::iterator parent) { // Split some node along the path to the item pointed to by this // iterator, and adjust the iterator so it points to the same @@ -327,13 +291,10 @@ NNTreeIterator::split(QPDFObjectHandle to_split, // node: A // item_number: 0 - if (! this->impl.qpdf) - { - throw std::logic_error( - "NNTreeIterator::split called with null qpdf"); + if (!this->impl.qpdf) { + throw std::logic_error("NNTreeIterator::split called with null qpdf"); } - if (! valid()) - { + if (!valid()) { throw std::logic_error( "NNTreeIterator::split called an invalid iterator"); } @@ -349,29 +310,23 @@ NNTreeIterator::split(QPDFObjectHandle to_split, int n = 0; std::string key; int threshold = 0; - if (nkids > 0) - { + if (nkids > 0) { QTC::TC("qpdf", "NNTree split kids"); first_half = kids; n = nkids; threshold = impl.split_threshold; key = "/Kids"; - } - else if (nitems > 0) - { + } else if (nitems > 0) { QTC::TC("qpdf", "NNTree split items"); first_half = items; n = nitems; threshold = 2 * impl.split_threshold; key = impl.details.itemsKey(); - } - else - { + } else { throw std::logic_error("NNTreeIterator::split called on invalid node"); } - if (n <= threshold) - { + if (n <= threshold) { return; } @@ -381,8 +336,7 @@ NNTreeIterator::split(QPDFObjectHandle to_split, // CURRENT STATE: tree is in original state; iterator is valid and // unchanged. - if (is_root) - { + if (is_root) { // What we want to do is to create a new node for the second // half of the items and put it in the parent's /Kids array // right after the element that points to the current to_split @@ -404,21 +358,18 @@ NNTreeIterator::split(QPDFObjectHandle to_split, // non-root case so remaining logic can handle them in the // same way. - auto first_node = impl.qpdf->makeIndirectObject( - QPDFObjectHandle::newDictionary()); + auto first_node = + impl.qpdf->makeIndirectObject(QPDFObjectHandle::newDictionary()); first_node.replaceKey(key, first_half); QPDFObjectHandle new_kids = QPDFObjectHandle::newArray(); new_kids.appendItem(first_node); to_split.removeKey("/Limits"); // already shouldn't be there for root to_split.removeKey(impl.details.itemsKey()); to_split.replaceKey("/Kids", new_kids); - if (is_leaf) - { + if (is_leaf) { QTC::TC("qpdf", "NNTree split root + leaf"); this->node = first_node; - } - else - { + } else { QTC::TC("qpdf", "NNTree split root + !leaf"); auto next = this->path.begin(); next->node = first_node; @@ -436,16 +387,15 @@ NNTreeIterator::split(QPDFObjectHandle to_split, // items into the second half array. QPDFObjectHandle second_half = QPDFObjectHandle::newArray(); int start_idx = ((n / 2) & ~1); - while (first_half.getArrayNItems() > start_idx) - { + while (first_half.getArrayNItems() > start_idx) { second_half.appendItem(first_half.getArrayItem(start_idx)); first_half.eraseItem(start_idx); } resetLimits(to_split, parent); // Create a new node to contain the second half - QPDFObjectHandle second_node = impl.qpdf->makeIndirectObject( - QPDFObjectHandle::newDictionary()); + QPDFObjectHandle second_node = + impl.qpdf->makeIndirectObject(QPDFObjectHandle::newDictionary()); second_node.replaceKey(key, second_half); resetLimits(second_node, parent); @@ -464,23 +414,18 @@ NNTreeIterator::split(QPDFObjectHandle to_split, auto cur_elem = parent; ++cur_elem; // points to end() for leaf nodes int old_idx = (is_leaf ? this->item_number : cur_elem->kid_number); - if (old_idx >= start_idx) - { + if (old_idx >= start_idx) { ++parent->kid_number; - if (is_leaf) - { + if (is_leaf) { QTC::TC("qpdf", "NNTree split second half item"); setItemNumber(second_node, this->item_number - start_idx); - } - else - { + } else { QTC::TC("qpdf", "NNTree split second half kid"); cur_elem->node = second_node; cur_elem->kid_number -= start_idx; } } - if (! is_root) - { + if (!is_root) { QTC::TC("qpdf", "NNTree split parent"); auto next = parent->node; resetLimits(next, parent); @@ -493,8 +438,7 @@ std::list::iterator NNTreeIterator::lastPathElement() { auto result = this->path.end(); - if (! this->path.empty()) - { + if (!this->path.empty()) { --result; } return result; @@ -503,8 +447,7 @@ NNTreeIterator::lastPathElement() void NNTreeIterator::insertAfter(QPDFObjectHandle key, QPDFObjectHandle value) { - if (! valid()) - { + if (!valid()) { QTC::TC("qpdf", "NNTree insertAfter inserts first"); impl.insertFirst(key, value); deepen(impl.oh, true, false); @@ -512,12 +455,10 @@ NNTreeIterator::insertAfter(QPDFObjectHandle key, QPDFObjectHandle value) } auto items = this->node.getKey(impl.details.itemsKey()); - if (! items.isArray()) - { + if (!items.isArray()) { error(impl.qpdf, node, "node contains no items array"); } - if (items.getArrayNItems() < this->item_number + 2) - { + if (items.getArrayNItems() < this->item_number + 2) { error(impl.qpdf, node, "insert: items array is too short"); } items.insertItem(this->item_number + 2, key); @@ -533,51 +474,44 @@ NNTreeIterator::remove() // Remove this item, leaving the tree valid and this iterator // pointing to the next item. - if (! valid()) - { + if (!valid()) { throw std::logic_error("attempt made to remove an invalid iterator"); } auto items = this->node.getKey(impl.details.itemsKey()); int nitems = items.getArrayNItems(); - if (this->item_number + 2 > nitems) - { - error(impl.qpdf, this->node, - "found short items array while removing an item"); + if (this->item_number + 2 > nitems) { + error( + impl.qpdf, + this->node, + "found short items array while removing an item"); } items.eraseItem(this->item_number); items.eraseItem(this->item_number); nitems -= 2; - if (nitems > 0) - { + if (nitems > 0) { // There are still items left - if ((this->item_number == 0) || (this->item_number == nitems)) - { + if ((this->item_number == 0) || (this->item_number == nitems)) { // We removed either the first or last item of an items array // that remains non-empty, so we have to adjust limits. QTC::TC("qpdf", "NNTree remove reset limits"); resetLimits(this->node, lastPathElement()); } - if (this->item_number == nitems) - { + if (this->item_number == nitems) { // We removed the last item of a non-empty items array, so // advance to the successor of the previous item. QTC::TC("qpdf", "NNTree erased last item"); this->item_number -= 2; increment(false); - } - else if (this->item_number < nitems) - { + } else if (this->item_number < nitems) { // We don't have to do anything since the removed item's // successor now occupies its former location. QTC::TC("qpdf", "NNTree erased non-last item"); updateIValue(); - } - else - { + } else { // We already checked to ensure this condition would not // happen. throw std::logic_error( @@ -586,8 +520,7 @@ NNTreeIterator::remove() return; } - if (this->path.empty()) - { + if (this->path.empty()) { // Special case: if this is the root node, we can leave it // empty. QTC::TC("qpdf", "NNTree erased all items on leaf/root"); @@ -601,64 +534,50 @@ NNTreeIterator::remove() // remove this node from the parent on up the tree. Then we need // to position ourselves at the removed item's successor. bool done = false; - while (! done) - { + while (!done) { auto element = lastPathElement(); auto parent = element; --parent; auto kids = element->node.getKey("/Kids"); kids.eraseItem(element->kid_number); auto nkids = kids.getArrayNItems(); - if (nkids > 0) - { + if (nkids > 0) { // The logic here is similar to the items case. - if ((element->kid_number == 0) || (element->kid_number == nkids)) - { + if ((element->kid_number == 0) || (element->kid_number == nkids)) { QTC::TC("qpdf", "NNTree erased first or last kid"); resetLimits(element->node, parent); } - if (element->kid_number == nkids) - { + if (element->kid_number == nkids) { // Move to the successor of the last child of the // previous kid. setItemNumber(QPDFObjectHandle(), -1); --element->kid_number; deepen(kids.getArrayItem(element->kid_number), false, true); - if (valid()) - { + if (valid()) { increment(false); - if (! valid()) - { + if (!valid()) { QTC::TC("qpdf", "NNTree erased last item in tree"); - } - else - { + } else { QTC::TC("qpdf", "NNTree erased last kid"); } } - } - else - { + } else { // Next kid is in deleted kid's position QTC::TC("qpdf", "NNTree erased non-last kid"); deepen(kids.getArrayItem(element->kid_number), true, true); } done = true; - } - else if (parent == this->path.end()) - { + } else if (parent == this->path.end()) { // We erased the very last item. Convert the root to an // empty items array. QTC::TC("qpdf", "NNTree non-flat tree is empty after remove"); element->node.removeKey("/Kids"); - element->node.replaceKey(impl.details.itemsKey(), - QPDFObjectHandle::newArray()); + element->node.replaceKey( + impl.details.itemsKey(), QPDFObjectHandle::newArray()); this->path.clear(); setItemNumber(impl.oh, -1); done = true; - } - else - { + } else { // Walk up the tree and continue QTC::TC("qpdf", "NNTree remove walking up tree"); this->path.pop_back(); @@ -697,27 +616,22 @@ NNTreeIterator::operator->() bool NNTreeIterator::operator==(NNTreeIterator const& other) const { - if ((this->item_number == -1) && (other.item_number == -1)) - { + if ((this->item_number == -1) && (other.item_number == -1)) { return true; } - if (this->path.size() != other.path.size()) - { + if (this->path.size() != other.path.size()) { return false; } auto tpi = this->path.begin(); auto opi = other.path.begin(); - while (tpi != this->path.end()) - { - if (tpi->kid_number != opi->kid_number) - { + while (tpi != this->path.end()) { + if (tpi->kid_number != opi->kid_number) { return false; } ++tpi; ++opi; } - if (this->item_number != other.item_number) - { + if (this->item_number != other.item_number) { return false; } return true; @@ -732,8 +646,7 @@ NNTreeIterator::setItemNumber(QPDFObjectHandle const& node, int n) } void -NNTreeIterator::addPathElement(QPDFObjectHandle const& node, - int kid_number) +NNTreeIterator::addPathElement(QPDFObjectHandle const& node, int kid_number) { this->path.push_back(PathElement(node, kid_number)); } @@ -749,33 +662,31 @@ NNTreeIterator::deepen(QPDFObjectHandle node, bool first, bool allow_empty) bool failed = false; std::set seen; - for (auto i: this->path) - { - if (i.node.isIndirect()) - { + for (auto i : this->path) { + if (i.node.isIndirect()) { seen.insert(i.node.getObjGen()); } } - while (! failed) - { - if (node.isIndirect()) - { + while (!failed) { + if (node.isIndirect()) { auto og = node.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { QTC::TC("qpdf", "NNTree deepen: loop"); - warn(impl.qpdf, node, - "loop detected while traversing name/number tree"); + warn( + impl.qpdf, + node, + "loop detected while traversing name/number tree"); failed = true; break; } seen.insert(og); } - if (! node.isDictionary()) - { + if (!node.isDictionary()) { QTC::TC("qpdf", "NNTree node is not a dictionary"); - warn(impl.qpdf, node, - "non-dictionary node while traversing name/number tree"); + warn( + impl.qpdf, + node, + "non-dictionary node while traversing name/number tree"); failed = true; break; } @@ -784,66 +695,61 @@ NNTreeIterator::deepen(QPDFObjectHandle node, bool first, bool allow_empty) int nkids = kids.isArray() ? kids.getArrayNItems() : 0; auto items = node.getKey(impl.details.itemsKey()); int nitems = items.isArray() ? items.getArrayNItems() : 0; - if (nitems > 0) - { + if (nitems > 0) { setItemNumber(node, first ? 0 : nitems - 2); break; - } - else if (nkids > 0) - { + } else if (nkids > 0) { int kid_number = first ? 0 : nkids - 1; addPathElement(node, kid_number); auto next = kids.getArrayItem(kid_number); - if (! next.isIndirect()) - { - if (impl.qpdf && impl.auto_repair) - { + if (!next.isIndirect()) { + if (impl.qpdf && impl.auto_repair) { QTC::TC("qpdf", "NNTree fix indirect kid"); - warn(impl.qpdf, node, - "converting kid number " + - QUtil::int_to_string(kid_number) + - " to an indirect object"); + warn( + impl.qpdf, + node, + "converting kid number " + + QUtil::int_to_string(kid_number) + + " to an indirect object"); next = impl.qpdf->makeIndirectObject(next); kids.setArrayItem(kid_number, next); - } - else - { + } else { QTC::TC("qpdf", "NNTree warn indirect kid"); - warn(impl.qpdf, node, - "kid number " + QUtil::int_to_string(kid_number) + - " is not an indirect object"); + warn( + impl.qpdf, + node, + "kid number " + QUtil::int_to_string(kid_number) + + " is not an indirect object"); } } node = next; - } - else if (allow_empty && items.isArray()) - { + } else if (allow_empty && items.isArray()) { QTC::TC("qpdf", "NNTree deepen found empty"); setItemNumber(node, -1); break; - } - else - { + } else { QTC::TC("qpdf", "NNTree deepen: invalid node"); - warn(impl.qpdf, node, - "name/number tree node has neither non-empty " + - impl.details.itemsKey() + " nor /Kids"); + warn( + impl.qpdf, + node, + "name/number tree node has neither non-empty " + + impl.details.itemsKey() + " nor /Kids"); failed = true; break; } } - if (failed) - { + if (failed) { this->path = opath; return false; } return true; } -NNTreeImpl::NNTreeImpl(NNTreeDetails const& details, - QPDF* qpdf, - QPDFObjectHandle& oh, - bool auto_repair) : +NNTreeImpl::NNTreeImpl( + NNTreeDetails const& details, + QPDF* qpdf, + QPDFObjectHandle& oh, + bool auto_repair) : details(details), qpdf(qpdf), split_threshold(32), @@ -887,19 +793,13 @@ NNTreeImpl::withinLimits(QPDFObjectHandle key, QPDFObjectHandle node) auto limits = node.getKey("/Limits"); if (limits.isArray() && (limits.getArrayNItems() >= 2) && details.keyValid(limits.getArrayItem(0)) && - details.keyValid(limits.getArrayItem(1))) - { - if (details.compareKeys(key, limits.getArrayItem(0)) < 0) - { + details.keyValid(limits.getArrayItem(1))) { + if (details.compareKeys(key, limits.getArrayItem(0)) < 0) { result = -1; - } - else if (details.compareKeys(key, limits.getArrayItem(1)) > 0) - { + } else if (details.compareKeys(key, limits.getArrayItem(1)) > 0) { result = 1; } - } - else - { + } else { QTC::TC("qpdf", "NNTree missing limits"); error(qpdf, node, "node is missing /Limits"); } @@ -908,15 +808,15 @@ NNTreeImpl::withinLimits(QPDFObjectHandle key, QPDFObjectHandle node) int NNTreeImpl::binarySearch( - QPDFObjectHandle key, QPDFObjectHandle items, - int num_items, bool return_prev_if_not_found, - int (NNTreeImpl::*compare)(QPDFObjectHandle& key, - QPDFObjectHandle& arr, - int item)) + QPDFObjectHandle key, + QPDFObjectHandle items, + int num_items, + bool return_prev_if_not_found, + int (NNTreeImpl::*compare)( + QPDFObjectHandle& key, QPDFObjectHandle& arr, int item)) { int max_idx = 1; - while (max_idx < num_items) - { + while (max_idx < num_items) { max_idx <<= 1; } @@ -928,56 +828,40 @@ NNTreeImpl::binarySearch( bool found_leq = false; int status = 0; - while ((! found) && (checks > 0)) - { - if (idx < num_items) - { + while ((!found) && (checks > 0)) { + if (idx < num_items) { status = (this->*compare)(key, items, idx); - if (status >= 0) - { + if (status >= 0) { found_leq = true; found_idx = idx; } - } - else - { + } else { // consider item to be below anything after the top status = -1; } - if (status == 0) - { + if (status == 0) { found = true; - } - else - { + } else { checks >>= 1; - if (checks > 0) - { + if (checks > 0) { step >>= 1; - if (step == 0) - { + if (step == 0) { step = 1; } - if (status < 0) - { + if (status < 0) { idx -= step; - } - else - { + } else { idx += step; } } } } - if (found || (found_leq && return_prev_if_not_found)) - { + if (found || (found_leq && return_prev_if_not_found)) { return found_idx; - } - else - { + } else { return -1; } } @@ -986,13 +870,14 @@ int NNTreeImpl::compareKeyItem( QPDFObjectHandle& key, QPDFObjectHandle& items, int idx) { - if (! ((items.isArray() && (items.getArrayNItems() > (2 * idx)) && - details.keyValid(items.getArrayItem(2 * idx))))) - { + if (!((items.isArray() && (items.getArrayNItems() > (2 * idx)) && + details.keyValid(items.getArrayItem(2 * idx))))) { QTC::TC("qpdf", "NNTree item is wrong type"); - error(qpdf, this->oh, - "item at index " + QUtil::int_to_string(2 * idx) + - " is not the right type"); + error( + qpdf, + this->oh, + "item at index " + QUtil::int_to_string(2 * idx) + + " is not the right type"); } return details.compareKeys(key, items.getArrayItem(2 * idx)); } @@ -1001,25 +886,24 @@ int NNTreeImpl::compareKeyKid( QPDFObjectHandle& key, QPDFObjectHandle& kids, int idx) { - if (! (kids.isArray() && (idx < kids.getArrayNItems()) && - kids.getArrayItem(idx).isDictionary())) - { + if (!(kids.isArray() && (idx < kids.getArrayNItems()) && + kids.getArrayItem(idx).isDictionary())) { QTC::TC("qpdf", "NNTree kid is invalid"); - error(qpdf, this->oh, - "invalid kid at index " + QUtil::int_to_string(idx)); + error( + qpdf, + this->oh, + "invalid kid at index " + QUtil::int_to_string(idx)); } return withinLimits(key, kids.getArrayItem(idx)); } - void NNTreeImpl::repair() { auto new_node = QPDFObjectHandle::newDictionary(); new_node.replaceKey(details.itemsKey(), QPDFObjectHandle::newArray()); NNTreeImpl repl(details, qpdf, new_node, false); - for (auto const& i: *this) - { + for (auto const& i : *this) { repl.insert(i.first, i.second); } this->oh.replaceKey("/Kids", new_node.getKey("/Kids")); @@ -1030,22 +914,18 @@ NNTreeImpl::repair() NNTreeImpl::iterator NNTreeImpl::find(QPDFObjectHandle key, bool return_prev_if_not_found) { - try - { + try { return findInternal(key, return_prev_if_not_found); - } - catch (QPDFExc& e) - { - if (this->auto_repair) - { + } catch (QPDFExc& e) { + if (this->auto_repair) { QTC::TC("qpdf", "NNTree repair"); - warn(qpdf, this->oh, - std::string("attempting to repair after error: ") + e.what()); + warn( + qpdf, + this->oh, + std::string("attempting to repair after error: ") + e.what()); repair(); return findInternal(key, return_prev_if_not_found); - } - else - { + } else { throw e; } } @@ -1056,29 +936,21 @@ NNTreeImpl::findInternal(QPDFObjectHandle key, bool return_prev_if_not_found) { auto first_item = begin(); auto last_item = end(); - if (first_item == end()) - { + if (first_item == end()) { // Empty return end(); - } - else if (first_item.valid() && - details.keyValid(first_item->first) && - details.compareKeys(key, first_item->first) < 0) - { + } else if ( + first_item.valid() && details.keyValid(first_item->first) && + details.compareKeys(key, first_item->first) < 0) { // Before the first key return end(); - } - else if (last_item.valid() && - details.keyValid(last_item->first) && - details.compareKeys(key, last_item->first) > 0) - { + } else if ( + last_item.valid() && details.keyValid(last_item->first) && + details.compareKeys(key, last_item->first) > 0) { // After the last key - if (return_prev_if_not_found) - { + if (return_prev_if_not_found) { return last_item; - } - else - { + } else { return end(); } } @@ -1087,11 +959,9 @@ NNTreeImpl::findInternal(QPDFObjectHandle key, bool return_prev_if_not_found) auto node = this->oh; iterator result(*this); - while (true) - { + while (true) { auto og = node.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { QTC::TC("qpdf", "NNTree loop in find"); error(qpdf, node, "loop detected in find"); } @@ -1101,34 +971,31 @@ NNTreeImpl::findInternal(QPDFObjectHandle key, bool return_prev_if_not_found) int nkids = kids.isArray() ? kids.getArrayNItems() : 0; auto items = node.getKey(details.itemsKey()); int nitems = items.isArray() ? items.getArrayNItems() : 0; - if (nitems > 0) - { + if (nitems > 0) { int idx = binarySearch( - key, items, nitems / 2, return_prev_if_not_found, + key, + items, + nitems / 2, + return_prev_if_not_found, &NNTreeImpl::compareKeyItem); - if (idx >= 0) - { + if (idx >= 0) { result.setItemNumber(node, 2 * idx); } break; - } - else if (nkids > 0) - { + } else if (nkids > 0) { int idx = binarySearch( - key, kids, nkids, true, - &NNTreeImpl::compareKeyKid); - if (idx == -1) - { + key, kids, nkids, true, &NNTreeImpl::compareKeyKid); + if (idx == -1) { QTC::TC("qpdf", "NNTree -1 in binary search"); - error(qpdf, node, - "unexpected -1 from binary search of kids;" - " limits may by wrong"); + error( + qpdf, + node, + "unexpected -1 from binary search of kids;" + " limits may by wrong"); } result.addPathElement(node, idx); node = kids.getArrayItem(idx); - } - else - { + } else { QTC::TC("qpdf", "NNTree bad node during find"); error(qpdf, node, "bad node during find"); } @@ -1142,13 +1009,10 @@ NNTreeImpl::insertFirst(QPDFObjectHandle key, QPDFObjectHandle value) { auto iter = begin(); QPDFObjectHandle items; - if (iter.node.isInitialized() && - iter.node.isDictionary()) - { + if (iter.node.isInitialized() && iter.node.isDictionary()) { items = iter.node.getKey(details.itemsKey()); } - if (! (items.isInitialized() && items.isArray())) - { + if (!(items.isInitialized() && items.isArray())) { QTC::TC("qpdf", "NNTree no valid items node in insertFirst"); error(qpdf, this->oh, "unable to find a valid items node"); } @@ -1164,20 +1028,15 @@ NNTreeImpl::iterator NNTreeImpl::insert(QPDFObjectHandle key, QPDFObjectHandle value) { auto iter = find(key, true); - if (! iter.valid()) - { + if (!iter.valid()) { QTC::TC("qpdf", "NNTree insert inserts first"); return insertFirst(key, value); - } - else if (details.compareKeys(key, iter->first) == 0) - { + } else if (details.compareKeys(key, iter->first) == 0) { QTC::TC("qpdf", "NNTree insert replaces"); auto items = iter.node.getKey(details.itemsKey()); items.setArrayItem(iter.item_number + 1, value); iter.updateIValue(); - } - else - { + } else { QTC::TC("qpdf", "NNTree insert inserts after"); iter.insertAfter(key, value); } @@ -1188,13 +1047,11 @@ bool NNTreeImpl::remove(QPDFObjectHandle key, QPDFObjectHandle* value) { auto iter = find(key, false); - if (! iter.valid()) - { + if (!iter.valid()) { QTC::TC("qpdf", "NNTree remove not found"); return false; } - if (value) - { + if (value) { *value = iter->second; } iter.remove(); diff --git a/libqpdf/OffsetInputSource.cc b/libqpdf/OffsetInputSource.cc index fabca397..4a828386 100644 --- a/libqpdf/OffsetInputSource.cc +++ b/libqpdf/OffsetInputSource.cc @@ -4,13 +4,12 @@ #include #include -OffsetInputSource::OffsetInputSource(PointerHolder proxied, - qpdf_offset_t global_offset) : +OffsetInputSource::OffsetInputSource( + PointerHolder proxied, qpdf_offset_t global_offset) : proxied(proxied), global_offset(global_offset) { - if (global_offset < 0) - { + if (global_offset < 0) { throw std::logic_error( "OffsetInputSource constructed with negative offset"); } @@ -43,25 +42,19 @@ OffsetInputSource::tell() void OffsetInputSource::seek(qpdf_offset_t offset, int whence) { - if (whence == SEEK_SET) - { - if (offset > this->max_safe_offset) - { + if (whence == SEEK_SET) { + if (offset > this->max_safe_offset) { std::ostringstream msg; msg.imbue(std::locale::classic()); - msg << "seeking to " << offset - << " offset by " << global_offset + msg << "seeking to " << offset << " offset by " << global_offset << " would cause an overflow of the offset type"; throw std::range_error(msg.str()); } this->proxied->seek(offset + global_offset, whence); - } - else - { + } else { this->proxied->seek(offset, whence); } - if (tell() < 0) - { + if (tell() < 0) { throw std::runtime_error( "offset input source: seek before beginning of file"); } diff --git a/libqpdf/PDFVersion.cc b/libqpdf/PDFVersion.cc index 18c04716..e30a3d45 100644 --- a/libqpdf/PDFVersion.cc +++ b/libqpdf/PDFVersion.cc @@ -7,7 +7,8 @@ PDFVersion::PDFVersion() : { } -PDFVersion::PDFVersion(int major_version, int minor_version, int extension_level) : +PDFVersion::PDFVersion( + int major_version, int minor_version, int extension_level) : major_version(major_version), minor_version(minor_version), extension_level(extension_level) @@ -17,27 +18,28 @@ PDFVersion::PDFVersion(int major_version, int minor_version, int extension_level bool PDFVersion::operator<(PDFVersion const& rhs) const { - return ((this->major_version < rhs.major_version) ? true : - (this->major_version > rhs.major_version) ? false : - (this->minor_version < rhs.minor_version) ? true : - (this->minor_version > rhs.minor_version) ? false : - (this->extension_level < rhs.extension_level) ? true : - false); + return ( + (this->major_version < rhs.major_version) ? true + : (this->major_version > rhs.major_version) ? false + : (this->minor_version < rhs.minor_version) ? true + : (this->minor_version > rhs.minor_version) ? false + : (this->extension_level < rhs.extension_level) ? true + : false); } bool PDFVersion::operator==(PDFVersion const& rhs) const { - return ((this->major_version == rhs.major_version) && - (this->minor_version == rhs.minor_version) && - (this->extension_level == rhs.extension_level)); + return ( + (this->major_version == rhs.major_version) && + (this->minor_version == rhs.minor_version) && + (this->extension_level == rhs.extension_level)); } void PDFVersion::updateIfGreater(PDFVersion const& other) { - if (*this < other) - { + if (*this < other) { *this = other; } } diff --git a/libqpdf/Pipeline.cc b/libqpdf/Pipeline.cc index 097ed0f2..87dddd5f 100644 --- a/libqpdf/Pipeline.cc +++ b/libqpdf/Pipeline.cc @@ -15,8 +15,7 @@ Pipeline::~Pipeline() Pipeline* Pipeline::getNext(bool allow_null) { - if ((this->next == 0) && (! allow_null)) - { + if ((this->next == 0) && (!allow_null)) { throw std::logic_error( this->identifier + ": Pipeline::getNext() called on pipeline with no next"); diff --git a/libqpdf/Pl_AES_PDF.cc b/libqpdf/Pl_AES_PDF.cc index 581ca9ab..7389cfca 100644 --- a/libqpdf/Pl_AES_PDF.cc +++ b/libqpdf/Pl_AES_PDF.cc @@ -1,19 +1,22 @@ #include -#include -#include -#include -#include #include #include -#include +#include +#include +#include +#include #include +#include bool Pl_AES_PDF::use_static_iv = false; -Pl_AES_PDF::Pl_AES_PDF(char const* identifier, Pipeline* next, - bool encrypt, unsigned char const* key, - size_t key_bytes) : +Pl_AES_PDF::Pl_AES_PDF( + char const* identifier, + Pipeline* next, + bool encrypt, + unsigned char const* key, + size_t key_bytes) : Pipeline(identifier, next), crypto(QPDFCryptoProvider::getImpl()), encrypt(encrypt), @@ -51,11 +54,11 @@ Pl_AES_PDF::disablePadding() void Pl_AES_PDF::setIV(unsigned char const* iv, size_t bytes) { - if (bytes != this->buf_size) - { + if (bytes != this->buf_size) { throw std::logic_error( "Pl_AES_PDF: specified initialization vector" - " size in bytes must be " + QUtil::uint_to_string(bytes)); + " size in bytes must be " + + QUtil::uint_to_string(bytes)); } this->use_specified_iv = true; memcpy(this->specified_iv, iv, bytes); @@ -79,10 +82,8 @@ Pl_AES_PDF::write(unsigned char* data, size_t len) size_t bytes_left = len; unsigned char* p = data; - while (bytes_left > 0) - { - if (this->offset == this->buf_size) - { + while (bytes_left > 0) { + if (this->offset == this->buf_size) { flush(false); } @@ -98,39 +99,32 @@ Pl_AES_PDF::write(unsigned char* data, size_t len) void Pl_AES_PDF::finish() { - if (this->encrypt) - { - if (this->offset == this->buf_size) - { + if (this->encrypt) { + if (this->offset == this->buf_size) { flush(false); } - if (! this->disable_padding) - { + if (!this->disable_padding) { // Pad as described in section 3.5.1 of version 1.7 of the PDF // specification, including providing an entire block of padding // if the input was a multiple of 16 bytes. - unsigned char pad = - QIntC::to_uchar(this->buf_size - this->offset); + unsigned char pad = QIntC::to_uchar(this->buf_size - this->offset); memset(this->inbuf + this->offset, pad, pad); this->offset = this->buf_size; flush(false); } - } - else - { - if (this->offset != this->buf_size) - { + } else { + if (this->offset != this->buf_size) { // This is never supposed to happen as the output is // always supposed to be padded. However, we have // encountered files for which the output is not a // multiple of the block size. In this case, pad with // zeroes and hope for the best. assert(this->buf_size > this->offset); - std::memset(this->inbuf + this->offset, 0, - this->buf_size - this->offset); + std::memset( + this->inbuf + this->offset, 0, this->buf_size - this->offset); this->offset = this->buf_size; } - flush(! this->disable_padding); + flush(!this->disable_padding); } this->crypto->rijndael_finalize(); getNext()->finish(); @@ -139,26 +133,17 @@ Pl_AES_PDF::finish() void Pl_AES_PDF::initializeVector() { - if (use_zero_iv) - { - for (unsigned int i = 0; i < this->buf_size; ++i) - { + if (use_zero_iv) { + for (unsigned int i = 0; i < this->buf_size; ++i) { this->cbc_block[i] = 0; } - } - else if (use_specified_iv) - { + } else if (use_specified_iv) { std::memcpy(this->cbc_block, this->specified_iv, this->buf_size); - } - else if (use_static_iv) - { - for (unsigned int i = 0; i < this->buf_size; ++i) - { + } else if (use_static_iv) { + for (unsigned int i = 0; i < this->buf_size; ++i) { this->cbc_block[i] = static_cast(14U * (1U + i)); } - } - else - { + } else { QUtil::initializeWithRandomBytes(this->cbc_block, this->buf_size); } } @@ -168,30 +153,22 @@ Pl_AES_PDF::flush(bool strip_padding) { assert(this->offset == this->buf_size); - if (first) - { + if (first) { first = false; bool return_after_init = false; - if (this->cbc_mode) - { - if (encrypt) - { + if (this->cbc_mode) { + if (encrypt) { // Set cbc_block to the initialization vector, and if // not zero, write it to the output stream. initializeVector(); - if (! (this->use_zero_iv || this->use_specified_iv)) - { + if (!(this->use_zero_iv || this->use_specified_iv)) { getNext()->write(this->cbc_block, this->buf_size); } - } - else if (this->use_zero_iv || this->use_specified_iv) - { + } else if (this->use_zero_iv || this->use_specified_iv) { // Initialize vector with zeroes; zero vector was not // written to the beginning of the input file. initializeVector(); - } - else - { + } else { // Take the first block of input as the initialization // vector. There's nothing to write at this time. memcpy(this->cbc_block, this->inbuf, this->buf_size); @@ -200,32 +177,29 @@ Pl_AES_PDF::flush(bool strip_padding) } } this->crypto->rijndael_init( - encrypt, this->key.get(), key_bytes, - this->cbc_mode, this->cbc_block); - if (return_after_init) - { + encrypt, + this->key.get(), + key_bytes, + this->cbc_mode, + this->cbc_block); + if (return_after_init) { return; } } this->crypto->rijndael_process(this->inbuf, this->outbuf); unsigned int bytes = this->buf_size; - if (strip_padding) - { + if (strip_padding) { unsigned char last = this->outbuf[this->buf_size - 1]; - if (last <= this->buf_size) - { + if (last <= this->buf_size) { bool strip = true; - for (unsigned int i = 1; i <= last; ++i) - { - if (this->outbuf[this->buf_size - i] != last) - { + for (unsigned int i = 1; i <= last; ++i) { + if (this->outbuf[this->buf_size - i] != last) { strip = false; break; } } - if (strip) - { + if (strip) { bytes -= last; } } diff --git a/libqpdf/Pl_ASCII85Decoder.cc b/libqpdf/Pl_ASCII85Decoder.cc index c8e6d860..5d1bbee2 100644 --- a/libqpdf/Pl_ASCII85Decoder.cc +++ b/libqpdf/Pl_ASCII85Decoder.cc @@ -19,55 +19,41 @@ Pl_ASCII85Decoder::~Pl_ASCII85Decoder() void Pl_ASCII85Decoder::write(unsigned char* buf, size_t len) { - if (eod > 1) - { + if (eod > 1) { return; } - for (size_t i = 0; i < len; ++i) - { - if (eod > 1) - { + for (size_t i = 0; i < len; ++i) { + if (eod > 1) { break; - } - else if (eod == 1) - { - if (buf[i] == '>') - { + } else if (eod == 1) { + if (buf[i] == '>') { flush(); eod = 2; - } - else - { + } else { throw std::runtime_error( "broken end-of-data sequence in base 85 data"); } - } - else - { - switch (buf[i]) - { - case ' ': - case '\f': - case '\v': - case '\t': - case '\r': - case '\n': + } else { + switch (buf[i]) { + case ' ': + case '\f': + case '\v': + case '\t': + case '\r': + case '\n': QTC::TC("libtests", "Pl_ASCII85Decoder ignore space"); // ignore whitespace break; - case '~': + case '~': eod = 1; break; - case 'z': - if (pos != 0) - { + case 'z': + if (pos != 0) { throw std::runtime_error( "unexpected z during base 85 decode"); - } - else - { + } else { QTC::TC("libtests", "Pl_ASCII85Decoder read z"); unsigned char zeroes[4]; memset(zeroes, '\0', 4); @@ -75,17 +61,13 @@ Pl_ASCII85Decoder::write(unsigned char* buf, size_t len) } break; - default: - if ((buf[i] < 33) || (buf[i] > 117)) - { + default: + if ((buf[i] < 33) || (buf[i] > 117)) { throw std::runtime_error( "character out of range during base 85 decode"); - } - else - { + } else { this->inbuf[this->pos++] = buf[i]; - if (pos == 5) - { + if (pos == 5) { flush(); } } @@ -98,28 +80,27 @@ Pl_ASCII85Decoder::write(unsigned char* buf, size_t len) void Pl_ASCII85Decoder::flush() { - if (this->pos == 0) - { + if (this->pos == 0) { QTC::TC("libtests", "Pl_ASCII85Decoder no-op flush"); return; } unsigned long lval = 0; - for (int i = 0; i < 5; ++i) - { + for (int i = 0; i < 5; ++i) { lval *= 85; lval += (this->inbuf[i] - 33U); } unsigned char outbuf[4]; memset(outbuf, 0, 4); - for (int i = 3; i >= 0; --i) - { + for (int i = 3; i >= 0; --i) { outbuf[i] = lval & 0xff; lval >>= 8; } - QTC::TC("libtests", "Pl_ASCII85Decoder partial flush", - (this->pos == 5) ? 0 : 1); + QTC::TC( + "libtests", + "Pl_ASCII85Decoder partial flush", + (this->pos == 5) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. auto t = this->pos - 1; diff --git a/libqpdf/Pl_ASCIIHexDecoder.cc b/libqpdf/Pl_ASCIIHexDecoder.cc index 594d4ed5..654d9449 100644 --- a/libqpdf/Pl_ASCIIHexDecoder.cc +++ b/libqpdf/Pl_ASCIIHexDecoder.cc @@ -1,9 +1,9 @@ #include #include +#include #include #include -#include Pl_ASCIIHexDecoder::Pl_ASCIIHexDecoder(char const* identifier, Pipeline* next) : Pipeline(identifier, next), @@ -22,53 +22,45 @@ Pl_ASCIIHexDecoder::~Pl_ASCIIHexDecoder() void Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) { - if (this->eod) - { + if (this->eod) { return; } - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { char ch = static_cast(toupper(buf[i])); - switch (ch) - { - case ' ': - case '\f': - case '\v': - case '\t': - case '\r': - case '\n': + switch (ch) { + case ' ': + case '\f': + case '\v': + case '\t': + case '\r': + case '\n': QTC::TC("libtests", "Pl_ASCIIHexDecoder ignore space"); // ignore whitespace break; - case '>': + case '>': this->eod = true; flush(); break; - default: - if (((ch >= '0') && (ch <= '9')) || - ((ch >= 'A') && (ch <= 'F'))) - { + default: + if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'F'))) { this->inbuf[this->pos++] = ch; - if (this->pos == 2) - { + if (this->pos == 2) { flush(); } - } - else - { + } else { char t[2]; t[0] = ch; t[1] = 0; throw std::runtime_error( std::string("character out of range" - " during base Hex decode: ") + t); + " during base Hex decode: ") + + t); } break; } - if (this->eod) - { + if (this->eod) { break; } } @@ -77,27 +69,24 @@ Pl_ASCIIHexDecoder::write(unsigned char* buf, size_t len) void Pl_ASCIIHexDecoder::flush() { - if (this->pos == 0) - { + if (this->pos == 0) { QTC::TC("libtests", "Pl_ASCIIHexDecoder no-op flush"); return; } int b[2]; - for (int i = 0; i < 2; ++i) - { - if (this->inbuf[i] >= 'A') - { + for (int i = 0; i < 2; ++i) { + if (this->inbuf[i] >= 'A') { b[i] = this->inbuf[i] - 'A' + 10; - } - else - { + } else { b[i] = this->inbuf[i] - '0'; } } unsigned char ch = static_cast((b[0] << 4) + b[1]); - QTC::TC("libtests", "Pl_ASCIIHexDecoder partial flush", - (this->pos == 2) ? 0 : 1); + QTC::TC( + "libtests", + "Pl_ASCIIHexDecoder partial flush", + (this->pos == 2) ? 0 : 1); // Reset before calling getNext()->write in case that throws an // exception. this->pos = 0; diff --git a/libqpdf/Pl_Buffer.cc b/libqpdf/Pl_Buffer.cc index b38edc98..dba91e0f 100644 --- a/libqpdf/Pl_Buffer.cc +++ b/libqpdf/Pl_Buffer.cc @@ -1,10 +1,10 @@ #include -#include #include #include -#include +#include #include +#include Pl_Buffer::Members::Members() : ready(true), @@ -29,28 +29,24 @@ Pl_Buffer::~Pl_Buffer() void Pl_Buffer::write(unsigned char* buf, size_t len) { - if (this->m->data.get() == 0) - { + if (this->m->data.get() == 0) { this->m->data = make_pointer_holder(len); } size_t cur_size = this->m->data->getSize(); size_t left = cur_size - this->m->total_size; - if (left < len) - { + if (left < len) { size_t new_size = std::max(this->m->total_size + len, 2 * cur_size); auto b = make_pointer_holder(new_size); memcpy(b->getBuffer(), this->m->data->getBuffer(), this->m->total_size); this->m->data = b; } - if (len) - { + if (len) { memcpy(this->m->data->getBuffer() + this->m->total_size, buf, len); this->m->total_size += len; } this->m->ready = false; - if (getNext(true)) - { + if (getNext(true)) { getNext()->write(buf, len); } } @@ -59,8 +55,7 @@ void Pl_Buffer::finish() { this->m->ready = true; - if (getNext(true)) - { + if (getNext(true)) { getNext()->finish(); } } @@ -68,14 +63,12 @@ Pl_Buffer::finish() Buffer* Pl_Buffer::getBuffer() { - if (! this->m->ready) - { + if (!this->m->ready) { throw std::logic_error("Pl_Buffer::getBuffer() called when not ready"); } Buffer* b = new Buffer(this->m->total_size); - if (this->m->total_size > 0) - { + if (this->m->total_size > 0) { unsigned char* p = b->getBuffer(); memcpy(p, this->m->data->getBuffer(), this->m->total_size); } @@ -90,22 +83,18 @@ Pl_Buffer::getBufferSharedPointer() } void -Pl_Buffer::getMallocBuffer(unsigned char **buf, size_t* len) +Pl_Buffer::getMallocBuffer(unsigned char** buf, size_t* len) { - if (! this->m->ready) - { + if (!this->m->ready) { throw std::logic_error( "Pl_Buffer::getMallocBuffer() called when not ready"); } *len = this->m->total_size; - if (this->m->total_size > 0) - { + if (this->m->total_size > 0) { *buf = reinterpret_cast(malloc(this->m->total_size)); memcpy(*buf, this->m->data->getBuffer(), this->m->total_size); - } - else - { + } else { *buf = nullptr; } this->m = PointerHolder(new Members()); diff --git a/libqpdf/Pl_Concatenate.cc b/libqpdf/Pl_Concatenate.cc index 7ad8e546..7b227b0e 100644 --- a/libqpdf/Pl_Concatenate.cc +++ b/libqpdf/Pl_Concatenate.cc @@ -33,4 +33,3 @@ Pl_Concatenate::manualFinish() { getNext()->finish(); } - diff --git a/libqpdf/Pl_Count.cc b/libqpdf/Pl_Count.cc index 65fd9e3f..067f7cdb 100644 --- a/libqpdf/Pl_Count.cc +++ b/libqpdf/Pl_Count.cc @@ -25,8 +25,7 @@ Pl_Count::~Pl_Count() void Pl_Count::write(unsigned char* buf, size_t len) { - if (len) - { + if (len) { this->m->count += QIntC::to_offset(len); this->m->last_char = buf[len - 1]; getNext()->write(buf, len); diff --git a/libqpdf/Pl_DCT.cc b/libqpdf/Pl_DCT.cc index 5b42b827..30747dd3 100644 --- a/libqpdf/Pl_DCT.cc +++ b/libqpdf/Pl_DCT.cc @@ -1,14 +1,14 @@ #include -#include -#include #include +#include +#include +#include #include #include #include #include -#include #if BITS_IN_JSAMPLE != 8 # error "qpdf does not support libjpeg built with BITS_IN_JSAMPLE != 8" @@ -32,13 +32,14 @@ error_handler(j_common_ptr cinfo) longjmp(jerr->jmpbuf, 1); } -Pl_DCT::Members::Members(action_e action, - char const* buf_description, - JDIMENSION image_width, - JDIMENSION image_height, - int components, - J_COLOR_SPACE color_space, - CompressConfig* config_callback) : +Pl_DCT::Members::Members( + action_e action, + char const* buf_description, + JDIMENSION image_width, + JDIMENSION image_height, + int components, + J_COLOR_SPACE color_space, + CompressConfig* config_callback) : action(action), buf(buf_description), image_width(image_width), @@ -59,15 +60,23 @@ Pl_DCT::Pl_DCT(char const* identifier, Pipeline* next) : { } -Pl_DCT::Pl_DCT(char const* identifier, Pipeline* next, - JDIMENSION image_width, - JDIMENSION image_height, - int components, - J_COLOR_SPACE color_space, - CompressConfig* config_callback) : +Pl_DCT::Pl_DCT( + char const* identifier, + Pipeline* next, + JDIMENSION image_width, + JDIMENSION image_height, + int components, + J_COLOR_SPACE color_space, + CompressConfig* config_callback) : Pipeline(identifier, next), - m(new Members(a_compress, "DCT uncompressed image", - image_width, image_height, components, color_space, config_callback)) + m(new Members( + a_compress, + "DCT uncompressed image", + image_width, + image_height, + components, + color_space, + config_callback)) { } @@ -90,8 +99,7 @@ Pl_DCT::finish() // and decompress causes a memory leak with setjmp/longjmp. Just // use a pointer and delete it. Buffer* b = this->m->buf.getBuffer(); - if (b->getSize() == 0) - { + if (b->getSize() == 0) { // Special case: empty data will never succeed and probably // means we're calling finish a second time from an exception // handler. @@ -111,44 +119,32 @@ Pl_DCT::finish() bool error = false; // The jpeg library is a "C" library, so we use setjmp and longjmp // for exception handling. - if (setjmp(jerr.jmpbuf) == 0) - { - try - { - if (this->m->action == a_compress) - { + if (setjmp(jerr.jmpbuf) == 0) { + try { + if (this->m->action == a_compress) { compress(reinterpret_cast(&cinfo_compress), b); - } - else - { + } else { decompress(reinterpret_cast(&cinfo_decompress), b); } - } - catch (std::exception& e) - { + } catch (std::exception& e) { // Convert an exception back to a longjmp so we can ensure // that the right cleanup happens. This will get converted // back to an exception. jerr.msg = e.what(); longjmp(jerr.jmpbuf, 1); } - } - else - { + } else { error = true; } delete b; - if (this->m->action == a_compress) - { + if (this->m->action == a_compress) { jpeg_destroy_compress(&cinfo_compress); } - if (this->m->action == a_decompress) - { + if (this->m->action == a_decompress) { jpeg_destroy_decompress(&cinfo_decompress); } - if (error) - { + if (error) { throw std::runtime_error(jerr.msg); } } @@ -170,8 +166,7 @@ static boolean empty_pipeline_output_buffer(j_compress_ptr cinfo) { QTC::TC("libtests", "Pl_DCT empty_pipeline_output_buffer"); - dct_pipeline_dest* dest = - reinterpret_cast(cinfo->dest); + dct_pipeline_dest* dest = reinterpret_cast(cinfo->dest); dest->next->write(dest->buffer, dest->size); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = dest->size; @@ -182,22 +177,20 @@ static void term_pipeline_destination(j_compress_ptr cinfo) { QTC::TC("libtests", "Pl_DCT term_pipeline_destination"); - dct_pipeline_dest* dest = - reinterpret_cast(cinfo->dest); + dct_pipeline_dest* dest = reinterpret_cast(cinfo->dest); dest->next->write(dest->buffer, dest->size - dest->pub.free_in_buffer); } static void -jpeg_pipeline_dest(j_compress_ptr cinfo, - unsigned char* outbuffer, size_t size, - Pipeline* next) +jpeg_pipeline_dest( + j_compress_ptr cinfo, unsigned char* outbuffer, size_t size, Pipeline* next) { - cinfo->dest = static_cast( - (*cinfo->mem->alloc_small)(reinterpret_cast(cinfo), - JPOOL_PERMANENT, - sizeof(dct_pipeline_dest))); - dct_pipeline_dest* dest = - reinterpret_cast(cinfo->dest); + cinfo->dest = + static_cast((*cinfo->mem->alloc_small)( + reinterpret_cast(cinfo), + JPOOL_PERMANENT, + sizeof(dct_pipeline_dest))); + dct_pipeline_dest* dest = reinterpret_cast(cinfo->dest); dest->pub.init_destination = init_pipeline_destination; dest->pub.empty_output_buffer = empty_pipeline_output_buffer; dest->pub.term_destination = term_pipeline_destination; @@ -224,20 +217,15 @@ fill_buffer_input_buffer(j_decompress_ptr) static void skip_buffer_input_data(j_decompress_ptr cinfo, long num_bytes) { - if (num_bytes < 0) - { - throw std::runtime_error( - "reading jpeg: jpeg library requested" - " skipping a negative number of bytes"); + if (num_bytes < 0) { + throw std::runtime_error("reading jpeg: jpeg library requested" + " skipping a negative number of bytes"); } size_t to_skip = QIntC::to_size(num_bytes); - if ((to_skip > 0) && (to_skip <= cinfo->src->bytes_in_buffer)) - { + if ((to_skip > 0) && (to_skip <= cinfo->src->bytes_in_buffer)) { cinfo->src->next_input_byte += to_skip; cinfo->src->bytes_in_buffer -= to_skip; - } - else if (to_skip != 0) - { + } else if (to_skip != 0) { cinfo->src->next_input_byte += cinfo->src->bytes_in_buffer; cinfo->src->bytes_in_buffer = 0; } @@ -251,10 +239,10 @@ term_buffer_source(j_decompress_ptr) static void jpeg_buffer_src(j_decompress_ptr cinfo, Buffer* buffer) { - cinfo->src = reinterpret_cast( - (*cinfo->mem->alloc_small)(reinterpret_cast(cinfo), - JPOOL_PERMANENT, - sizeof(jpeg_source_mgr))); + cinfo->src = reinterpret_cast((*cinfo->mem->alloc_small)( + reinterpret_cast(cinfo), + JPOOL_PERMANENT, + sizeof(jpeg_source_mgr))); jpeg_source_mgr* src = cinfo->src; src->init_source = init_buffer_source; @@ -272,15 +260,17 @@ Pl_DCT::compress(void* cinfo_p, Buffer* b) struct jpeg_compress_struct* cinfo = reinterpret_cast(cinfo_p); -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wold-style-cast" +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wold-style-cast" #endif jpeg_create_compress(cinfo); -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic pop +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic pop #endif static int const BUF_SIZE = 65536; auto outbuffer_ph = std::make_unique(BUF_SIZE); @@ -292,33 +282,29 @@ Pl_DCT::compress(void* cinfo_p, Buffer* b) cinfo->input_components = this->m->components; cinfo->in_color_space = this->m->color_space; jpeg_set_defaults(cinfo); - if (this->m->config_callback) - { + if (this->m->config_callback) { this->m->config_callback->apply(cinfo); } jpeg_start_compress(cinfo, TRUE); - unsigned int width = cinfo->image_width * - QIntC::to_uint(cinfo->input_components); - size_t expected_size = - QIntC::to_size(cinfo->image_height) * + unsigned int width = + cinfo->image_width * QIntC::to_uint(cinfo->input_components); + size_t expected_size = QIntC::to_size(cinfo->image_height) * QIntC::to_size(cinfo->image_width) * QIntC::to_size(cinfo->input_components); - if (b->getSize() != expected_size) - { + if (b->getSize() != expected_size) { throw std::runtime_error( "Pl_DCT: image buffer size = " + - QUtil::uint_to_string(b->getSize()) + "; expected size = " + - QUtil::uint_to_string(expected_size)); + QUtil::uint_to_string(b->getSize()) + + "; expected size = " + QUtil::uint_to_string(expected_size)); } JSAMPROW row_pointer[1]; unsigned char* buffer = b->getBuffer(); - while (cinfo->next_scanline < cinfo->image_height) - { + while (cinfo->next_scanline < cinfo->image_height) { // We already verified that the buffer is big enough. row_pointer[0] = &buffer[cinfo->next_scanline * width]; - (void) jpeg_write_scanlines(cinfo, row_pointer, 1); + (void)jpeg_write_scanlines(cinfo, row_pointer, 1); } jpeg_finish_compress(cinfo); this->getNext()->finish(); @@ -330,33 +316,35 @@ Pl_DCT::decompress(void* cinfo_p, Buffer* b) struct jpeg_decompress_struct* cinfo = reinterpret_cast(cinfo_p); -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wold-style-cast" +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wold-style-cast" #endif jpeg_create_decompress(cinfo); -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic pop +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic pop #endif jpeg_buffer_src(cinfo, b); - (void) jpeg_read_header(cinfo, TRUE); - (void) jpeg_calc_output_dimensions(cinfo); + (void)jpeg_read_header(cinfo, TRUE); + (void)jpeg_calc_output_dimensions(cinfo); - unsigned int width = cinfo->output_width * - QIntC::to_uint(cinfo->output_components); - JSAMPARRAY buffer = (*cinfo->mem->alloc_sarray) - (reinterpret_cast(cinfo), JPOOL_IMAGE, width, 1); + unsigned int width = + cinfo->output_width * QIntC::to_uint(cinfo->output_components); + JSAMPARRAY buffer = (*cinfo->mem->alloc_sarray)( + reinterpret_cast(cinfo), JPOOL_IMAGE, width, 1); - (void) jpeg_start_decompress(cinfo); - while (cinfo->output_scanline < cinfo->output_height) - { - (void) jpeg_read_scanlines(cinfo, buffer, 1); - this->getNext()->write(reinterpret_cast(buffer[0]), - width * sizeof(buffer[0][0])); + (void)jpeg_start_decompress(cinfo); + while (cinfo->output_scanline < cinfo->output_height) { + (void)jpeg_read_scanlines(cinfo, buffer, 1); + this->getNext()->write( + reinterpret_cast(buffer[0]), + width * sizeof(buffer[0][0])); } - (void) jpeg_finish_decompress(cinfo); + (void)jpeg_finish_decompress(cinfo); this->getNext()->finish(); } diff --git a/libqpdf/Pl_Flate.cc b/libqpdf/Pl_Flate.cc index e32c4544..b8bdc185 100644 --- a/libqpdf/Pl_Flate.cc +++ b/libqpdf/Pl_Flate.cc @@ -1,16 +1,15 @@ #include -#include -#include #include +#include +#include -#include #include +#include int Pl_Flate::compression_level = Z_DEFAULT_COMPRESSION; -Pl_Flate::Members::Members(size_t out_bufsize, - action_e action) : +Pl_Flate::Members::Members(size_t out_bufsize, action_e action) : out_bufsize(out_bufsize), action(action), initialized(false), @@ -24,11 +23,9 @@ Pl_Flate::Members::Members(size_t out_bufsize, // Windows environment. this->zdata = new z_stream; - if (out_bufsize > UINT_MAX) - { - throw std::runtime_error( - "Pl_Flate: zlib doesn't support buffer" - " sizes larger than unsigned int"); + if (out_bufsize > UINT_MAX) { + throw std::runtime_error("Pl_Flate: zlib doesn't support buffer" + " sizes larger than unsigned int"); } z_stream& zstream = *(static_cast(this->zdata)); @@ -43,15 +40,11 @@ Pl_Flate::Members::Members(size_t out_bufsize, Pl_Flate::Members::~Members() { - if (this->initialized) - { + if (this->initialized) { z_stream& zstream = *(static_cast(this->zdata)); - if (action == a_deflate) - { + if (action == a_deflate) { deflateEnd(&zstream); - } - else - { + } else { inflateEnd(&zstream); } } @@ -60,8 +53,11 @@ Pl_Flate::Members::~Members() this->zdata = 0; } -Pl_Flate::Pl_Flate(char const* identifier, Pipeline* next, - action_e action, unsigned int out_bufsize_int) : +Pl_Flate::Pl_Flate( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int out_bufsize_int) : Pipeline(identifier, next), m(new Members(QIntC::to_size(out_bufsize_int), action)) { @@ -80,8 +76,7 @@ Pl_Flate::setWarnCallback(std::function callback) void Pl_Flate::warn(char const* msg, int code) { - if (this->m->callback != nullptr) - { + if (this->m->callback != nullptr) { this->m->callback(msg, code); } } @@ -89,8 +84,7 @@ Pl_Flate::warn(char const* msg, int code) void Pl_Flate::write(unsigned char* data, size_t len) { - if (this->m->outbuf.get() == 0) - { + if (this->m->outbuf.get() == 0) { throw std::logic_error( this->identifier + ": Pl_Flate: write() called after finish() called"); @@ -101,11 +95,12 @@ Pl_Flate::write(unsigned char* data, size_t len) static size_t const max_bytes = 1 << 30; size_t bytes_left = len; unsigned char* buf = data; - while (bytes_left > 0) - { + while (bytes_left > 0) { size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); - handleData(buf, bytes, - (this->m->action == a_inflate ? Z_SYNC_FLUSH : Z_NO_FLUSH)); + handleData( + buf, + bytes, + (this->m->action == a_inflate ? Z_SYNC_FLUSH : Z_NO_FLUSH)); bytes_left -= bytes; buf += bytes; } @@ -114,38 +109,34 @@ Pl_Flate::write(unsigned char* data, size_t len) void Pl_Flate::handleData(unsigned char* data, size_t len, int flush) { - if (len > UINT_MAX) - { - throw std::runtime_error( - "Pl_Flate: zlib doesn't support data" - " blocks larger than int"); + if (len > UINT_MAX) { + throw std::runtime_error("Pl_Flate: zlib doesn't support data" + " blocks larger than int"); } z_stream& zstream = *(static_cast(this->m->zdata)); zstream.next_in = data; zstream.avail_in = QIntC::to_uint(len); - if (! this->m->initialized) - { + if (!this->m->initialized) { int err = Z_OK; // deflateInit and inflateInit are macros that use old-style // casts. -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wold-style-cast" +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wold-style-cast" #endif - if (this->m->action == a_deflate) - { + if (this->m->action == a_deflate) { err = deflateInit(&zstream, compression_level); - } - else - { + } else { err = inflateInit(&zstream); } -#if ((defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ - defined(__clang__)) -# pragma GCC diagnostic pop +#if ( \ + (defined(__GNUC__) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406) || \ + defined(__clang__)) +# pragma GCC diagnostic pop #endif checkError("Init", err); @@ -155,27 +146,21 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) int err = Z_OK; bool done = false; - while (! done) - { - if (this->m->action == a_deflate) - { + while (!done) { + if (this->m->action == a_deflate) { err = deflate(&zstream, flush); - } - else - { + } else { err = inflate(&zstream, flush); } if ((this->m->action == a_inflate) && (err != Z_OK) && zstream.msg && - (strcmp(zstream.msg, "incorrect data check") == 0)) - { + (strcmp(zstream.msg, "incorrect data check") == 0)) { // Other PDF readers ignore this specific error. Combining // this with Z_SYNC_FLUSH enables qpdf to handle some // broken zlib streams without losing data. err = Z_STREAM_END; } - switch (err) - { - case Z_BUF_ERROR: + switch (err) { + case Z_BUF_ERROR: // Probably shouldn't be able to happen, but possible as a // boundary condition: if the last call to inflate exactly // filled the output buffer, it's possible that the next @@ -185,20 +170,17 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) // to know about this, because it indicates incorrect // compression, so call a callback if provided. this->warn( - "input stream is complete but output may still be valid", - err); + "input stream is complete but output may still be valid", err); done = true; break; - case Z_STREAM_END: + case Z_STREAM_END: done = true; // fall through - case Z_OK: + case Z_OK: { - if ((zstream.avail_in == 0) && - (zstream.avail_out > 0)) - { + if ((zstream.avail_in == 0) && (zstream.avail_out > 0)) { // There is nothing left to read, and there was // sufficient buffer space to write everything we // needed, so we're done for now. @@ -206,8 +188,7 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) } uLong ready = QIntC::to_ulong(this->m->out_bufsize - zstream.avail_out); - if (ready > 0) - { + if (ready > 0) { this->getNext()->write(this->m->outbuf.get(), ready); zstream.next_out = this->m->outbuf.get(); zstream.avail_out = QIntC::to_uint(this->m->out_bufsize); @@ -215,7 +196,7 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) } break; - default: + default: this->checkError("data", err); break; } @@ -225,23 +206,17 @@ Pl_Flate::handleData(unsigned char* data, size_t len, int flush) void Pl_Flate::finish() { - try - { - if (this->m->outbuf.get()) - { - if (this->m->initialized) - { + try { + if (this->m->outbuf.get()) { + if (this->m->initialized) { z_stream& zstream = *(static_cast(this->m->zdata)); unsigned char buf[1]; buf[0] = '\0'; handleData(buf, 0, Z_FINISH); int err = Z_OK; - if (this->m->action == a_deflate) - { + if (this->m->action == a_deflate) { err = deflateEnd(&zstream); - } - else - { + } else { err = inflateEnd(&zstream); } this->m->initialized = false; @@ -250,15 +225,10 @@ Pl_Flate::finish() this->m->outbuf = 0; } - } - catch (std::exception& e) - { - try - { + } catch (std::exception& e) { + try { this->getNext()->finish(); - } - catch (...) - { + } catch (...) { // ignore secondary exception } throw std::runtime_error(e.what()); @@ -276,46 +246,41 @@ void Pl_Flate::checkError(char const* prefix, int error_code) { z_stream& zstream = *(static_cast(this->m->zdata)); - if (error_code != Z_OK) - { + if (error_code != Z_OK) { char const* action_str = (this->m->action == a_deflate ? "deflate" : "inflate"); std::string msg = this->identifier + ": " + action_str + ": " + prefix + ": "; - if (zstream.msg) - { + if (zstream.msg) { msg += zstream.msg; - } - else - { - switch (error_code) - { - case Z_ERRNO: + } else { + switch (error_code) { + case Z_ERRNO: msg += "zlib system error"; break; - case Z_STREAM_ERROR: + case Z_STREAM_ERROR: msg += "zlib stream error"; break; - case Z_DATA_ERROR: + case Z_DATA_ERROR: msg += "zlib data error"; break; - case Z_MEM_ERROR: + case Z_MEM_ERROR: msg += "zlib memory error"; break; - case Z_BUF_ERROR: + case Z_BUF_ERROR: msg += "zlib buffer error"; break; - case Z_VERSION_ERROR: + case Z_VERSION_ERROR: msg += "zlib version error"; break; - default: + default: msg += std::string("zlib unknown error (") + QUtil::int_to_string(error_code) + ")"; break; diff --git a/libqpdf/Pl_LZWDecoder.cc b/libqpdf/Pl_LZWDecoder.cc index bace3854..34ed1bd7 100644 --- a/libqpdf/Pl_LZWDecoder.cc +++ b/libqpdf/Pl_LZWDecoder.cc @@ -1,14 +1,14 @@ #include +#include #include #include -#include +#include #include #include -#include -Pl_LZWDecoder::Pl_LZWDecoder(char const* identifier, Pipeline* next, - bool early_code_change) : +Pl_LZWDecoder::Pl_LZWDecoder( + char const* identifier, Pipeline* next, bool early_code_change) : Pipeline(identifier, next), code_size(9), next(0), @@ -29,16 +29,13 @@ Pl_LZWDecoder::~Pl_LZWDecoder() void Pl_LZWDecoder::write(unsigned char* bytes, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { this->buf[next++] = bytes[i]; - if (this->next == 3) - { + if (this->next == 3) { this->next = 0; } this->bits_available += 8; - if (this->bits_available >= this->code_size) - { + if (this->bits_available >= this->code_size) { sendNextCode(); } } @@ -60,8 +57,7 @@ Pl_LZWDecoder::sendNextCode() unsigned int bits_from_high = 8 - this->bit_pos; unsigned int bits_from_med = this->code_size - bits_from_high; unsigned int bits_from_low = 0; - if (bits_from_med > 8) - { + if (bits_from_med > 8) { bits_from_low = bits_from_med - 8; bits_from_med = 8; } @@ -71,20 +67,16 @@ Pl_LZWDecoder::sendNextCode() unsigned int code = 0; code += (this->buf[high] & high_mask) << bits_from_med; code += ((this->buf[med] & med_mask) >> (8 - bits_from_med)); - if (bits_from_low) - { + if (bits_from_low) { code <<= bits_from_low; code += ((this->buf[low] & low_mask) >> (8 - bits_from_low)); this->byte_pos = low; this->bit_pos = bits_from_low; - } - else - { + } else { this->byte_pos = med; this->bit_pos = bits_from_med; } - if (this->bit_pos == 8) - { + if (this->bit_pos == 8) { this->bit_pos = 0; ++this->byte_pos; this->byte_pos %= 3; @@ -98,23 +90,17 @@ unsigned char Pl_LZWDecoder::getFirstChar(unsigned int code) { unsigned char result = '\0'; - if (code < 256) - { + if (code < 256) { result = static_cast(code); - } - else if (code > 257) - { + } else if (code > 257) { unsigned int idx = code - 258; - if (idx >= table.size()) - { + if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::getFirstChar: table overflow"); } Buffer& b = table.at(idx); result = b.getBuffer()[0]; - } - else - { + } else { throw std::runtime_error( "Pl_LZWDecoder::getFirstChar called with invalid code (" + QUtil::int_to_string(code) + ")"); @@ -129,26 +115,20 @@ Pl_LZWDecoder::addToTable(unsigned char next) unsigned char const* last_data = 0; unsigned char tmp[1]; - if (this->last_code < 256) - { + if (this->last_code < 256) { tmp[0] = static_cast(this->last_code); last_data = tmp; last_size = 1; - } - else if (this->last_code > 257) - { + } else if (this->last_code > 257) { unsigned int idx = this->last_code - 258; - if (idx >= table.size()) - { + if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::addToTable: table overflow"); } Buffer& b = table.at(idx); last_data = b.getBuffer(); last_size = QIntC::to_uint(b.getSize()); - } - else - { + } else { throw std::runtime_error( "Pl_LZWDecoder::addToTable called with invalid code (" + QUtil::int_to_string(this->last_code) + ")"); @@ -164,84 +144,61 @@ Pl_LZWDecoder::addToTable(unsigned char next) void Pl_LZWDecoder::handleCode(unsigned int code) { - if (this->eod) - { + if (this->eod) { return; } - if (code == 256) - { - if (! this->table.empty()) - { + if (code == 256) { + if (!this->table.empty()) { QTC::TC("libtests", "Pl_LZWDecoder intermediate reset"); } this->table.clear(); this->code_size = 9; - } - else if (code == 257) - { + } else if (code == 257) { this->eod = true; - } - else - { - if (this->last_code != 256) - { + } else { + if (this->last_code != 256) { // Add to the table from last time. New table entry would // be what we read last plus the first character of what // we're reading now. unsigned char next = '\0'; unsigned int table_size = QIntC::to_uint(table.size()); - if (code < 256) - { + if (code < 256) { // just read < 256; last time's next was code next = static_cast(code); - } - else if (code > 257) - { + } else if (code > 257) { size_t idx = code - 258; - if (idx > table_size) - { + if (idx > table_size) { throw std::runtime_error("LZWDecoder: bad code received"); - } - else if (idx == table_size) - { + } else if (idx == table_size) { // The encoder would have just created this entry, // so the first character of this entry would have // been the same as the first character of the // last entry. QTC::TC("libtests", "Pl_LZWDecoder last was table size"); next = getFirstChar(this->last_code); - } - else - { + } else { next = getFirstChar(code); } } unsigned int new_idx = 258 + table_size; - if (new_idx == 4096) - { + if (new_idx == 4096) { throw std::runtime_error("LZWDecoder: table full"); } addToTable(next); unsigned int change_idx = new_idx + code_change_delta; - if ((change_idx == 511) || - (change_idx == 1023) || - (change_idx == 2047)) - { + if ((change_idx == 511) || (change_idx == 1023) || + (change_idx == 2047)) { ++this->code_size; } } - if (code < 256) - { + if (code < 256) { unsigned char ch = static_cast(code); getNext()->write(&ch, 1); - } - else - { + } else { unsigned int idx = code - 258; - if (idx >= table.size()) - { + if (idx >= table.size()) { throw std::runtime_error( "Pl_LZWDecoder::handleCode: table overflow"); } diff --git a/libqpdf/Pl_MD5.cc b/libqpdf/Pl_MD5.cc index 9bffa2a6..95e0a8d6 100644 --- a/libqpdf/Pl_MD5.cc +++ b/libqpdf/Pl_MD5.cc @@ -17,10 +17,8 @@ Pl_MD5::~Pl_MD5() void Pl_MD5::write(unsigned char* buf, size_t len) { - if (this->enabled) - { - if (! this->in_progress) - { + if (this->enabled) { + if (!this->in_progress) { this->md5.reset(); this->in_progress = true; } @@ -30,8 +28,7 @@ Pl_MD5::write(unsigned char* buf, size_t len) static size_t const max_bytes = 1 << 30; size_t bytes_left = len; unsigned char* data = buf; - while (bytes_left > 0) - { + while (bytes_left > 0) { size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); this->md5.encodeDataIncrementally( reinterpret_cast(data), bytes); @@ -47,8 +44,7 @@ void Pl_MD5::finish() { this->getNext()->finish(); - if (! this->persist_across_finish) - { + if (!this->persist_across_finish) { this->in_progress = false; } } @@ -68,10 +64,8 @@ Pl_MD5::persistAcrossFinish(bool persist) std::string Pl_MD5::getHexDigest() { - if (! this->enabled) - { - throw std::logic_error( - "digest requested for a disabled MD5 Pipeline"); + if (!this->enabled) { + throw std::logic_error("digest requested for a disabled MD5 Pipeline"); } this->in_progress = false; return this->md5.unparse(); diff --git a/libqpdf/Pl_PNGFilter.cc b/libqpdf/Pl_PNGFilter.cc index 1dca43bb..14754fd1 100644 --- a/libqpdf/Pl_PNGFilter.cc +++ b/libqpdf/Pl_PNGFilter.cc @@ -3,19 +3,23 @@ #include #include +#include #include #include -#include -static int abs_diff(int a, int b) +static int +abs_diff(int a, int b) { return a > b ? a - b : b - a; } -Pl_PNGFilter::Pl_PNGFilter(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, - unsigned int samples_per_pixel, - unsigned int bits_per_sample) : +Pl_PNGFilter::Pl_PNGFilter( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int columns, + unsigned int samples_per_pixel, + unsigned int bits_per_sample) : Pipeline(identifier, next), action(action), cur_row(0), @@ -24,17 +28,13 @@ Pl_PNGFilter::Pl_PNGFilter(char const* identifier, Pipeline* next, buf2(0), pos(0) { - if (samples_per_pixel < 1) - { + if (samples_per_pixel < 1) { throw std::runtime_error( "PNGFilter created with invalid samples_per_pixel"); } - if (! ((bits_per_sample == 1) || - (bits_per_sample == 2) || - (bits_per_sample == 4) || - (bits_per_sample == 8) || - (bits_per_sample == 16))) - { + if (!((bits_per_sample == 1) || (bits_per_sample == 2) || + (bits_per_sample == 4) || (bits_per_sample == 8) || + (bits_per_sample == 16))) { throw std::runtime_error( "PNGFilter created with invalid bits_per_sample not" " 1, 2, 4, 8, or 16"); @@ -42,25 +42,23 @@ Pl_PNGFilter::Pl_PNGFilter(char const* identifier, Pipeline* next, this->bytes_per_pixel = ((bits_per_sample * samples_per_pixel) + 7) / 8; unsigned long long bpr = ((columns * bits_per_sample * samples_per_pixel) + 7) / 8; - if ((bpr == 0) || (bpr > (UINT_MAX - 1))) - { + if ((bpr == 0) || (bpr > (UINT_MAX - 1))) { throw std::runtime_error( "PNGFilter created with invalid columns value"); } this->bytes_per_row = bpr & UINT_MAX; - this->buf1 = make_array_pointer_holder( - this->bytes_per_row + 1); - this->buf2 = make_array_pointer_holder( - this->bytes_per_row + 1); + this->buf1 = + make_array_pointer_holder(this->bytes_per_row + 1); + this->buf2 = + make_array_pointer_holder(this->bytes_per_row + 1); memset(this->buf1.get(), 0, this->bytes_per_row + 1); memset(this->buf2.get(), 0, this->bytes_per_row + 1); this->cur_row = this->buf1.get(); this->prev_row = this->buf2.get(); // number of bytes per incoming row - this->incoming = (action == a_encode ? - this->bytes_per_row : - this->bytes_per_row + 1); + this->incoming = + (action == a_encode ? this->bytes_per_row : this->bytes_per_row + 1); } Pl_PNGFilter::~Pl_PNGFilter() @@ -72,8 +70,7 @@ Pl_PNGFilter::write(unsigned char* data, size_t len) { size_t left = this->incoming - this->pos; size_t offset = 0; - while (len >= left) - { + while (len >= left) { // finish off current row memcpy(this->cur_row + this->pos, data + offset, left); offset += left; @@ -89,8 +86,7 @@ Pl_PNGFilter::write(unsigned char* data, size_t len) left = this->incoming; this->pos = 0; } - if (len) - { + if (len) { memcpy(this->cur_row + this->pos, data + offset, len); } this->pos += len; @@ -99,12 +95,9 @@ Pl_PNGFilter::write(unsigned char* data, size_t len) void Pl_PNGFilter::processRow() { - if (this->action == a_encode) - { + if (this->action == a_encode) { encodeRow(); - } - else - { + } else { decodeRow(); } } @@ -113,25 +106,23 @@ void Pl_PNGFilter::decodeRow() { int filter = this->cur_row[0]; - if (this->prev_row) - { - switch (filter) - { - case 0: + if (this->prev_row) { + switch (filter) { + case 0: break; - case 1: + case 1: this->decodeSub(); break; - case 2: + case 2: this->decodeUp(); break; - case 3: + case 3: this->decodeAverage(); break; - case 4: + case 4: this->decodePaeth(); break; - default: + default: // ignore break; } @@ -147,12 +138,10 @@ Pl_PNGFilter::decodeSub() unsigned char* buffer = this->cur_row + 1; unsigned int bpp = this->bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { + for (unsigned int i = 0; i < this->bytes_per_row; ++i) { unsigned char left = 0; - if (i >= bpp) - { + if (i >= bpp) { left = buffer[i - bpp]; } @@ -167,8 +156,7 @@ Pl_PNGFilter::decodeUp() unsigned char* buffer = this->cur_row + 1; unsigned char* above_buffer = this->prev_row + 1; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { + for (unsigned int i = 0; i < this->bytes_per_row; ++i) { unsigned char up = above_buffer[i]; buffer[i] = static_cast(buffer[i] + up); } @@ -182,18 +170,16 @@ Pl_PNGFilter::decodeAverage() unsigned char* above_buffer = this->prev_row + 1; unsigned int bpp = this->bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { + for (unsigned int i = 0; i < this->bytes_per_row; ++i) { int left = 0; int up = 0; - if (i >= bpp) - { + if (i >= bpp) { left = buffer[i - bpp]; } up = above_buffer[i]; - buffer[i] = static_cast(buffer[i] + (left+up) / 2); + buffer[i] = static_cast(buffer[i] + (left + up) / 2); } } @@ -205,21 +191,18 @@ Pl_PNGFilter::decodePaeth() unsigned char* above_buffer = this->prev_row + 1; unsigned int bpp = this->bytes_per_pixel; - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { + for (unsigned int i = 0; i < this->bytes_per_row; ++i) { int left = 0; int up = above_buffer[i]; int upper_left = 0; - if (i >= bpp) - { + if (i >= bpp) { left = buffer[i - bpp]; upper_left = above_buffer[i - bpp]; } buffer[i] = static_cast( - buffer[i] + - this->PaethPredictor(left, up, upper_left)); + buffer[i] + this->PaethPredictor(left, up, upper_left)); } } @@ -231,12 +214,10 @@ Pl_PNGFilter::PaethPredictor(int a, int b, int c) int pb = abs_diff(p, b); int pc = abs_diff(p, c); - if (pa <= pb && pa <= pc) - { + if (pa <= pb && pa <= pc) { return a; } - if (pb <= pc) - { + if (pb <= pc) { return b; } return c; @@ -248,17 +229,13 @@ Pl_PNGFilter::encodeRow() // For now, hard-code to using UP filter. unsigned char ch = 2; getNext()->write(&ch, 1); - if (this->prev_row) - { - for (unsigned int i = 0; i < this->bytes_per_row; ++i) - { + if (this->prev_row) { + for (unsigned int i = 0; i < this->bytes_per_row; ++i) { ch = static_cast( this->cur_row[i] - this->prev_row[i]); getNext()->write(&ch, 1); } - } - else - { + } else { getNext()->write(this->cur_row, this->bytes_per_row); } } @@ -266,8 +243,7 @@ Pl_PNGFilter::encodeRow() void Pl_PNGFilter::finish() { - if (this->pos) - { + if (this->pos) { // write partial row processRow(); } diff --git a/libqpdf/Pl_QPDFTokenizer.cc b/libqpdf/Pl_QPDFTokenizer.cc index 0fc7144c..632c2f1d 100644 --- a/libqpdf/Pl_QPDFTokenizer.cc +++ b/libqpdf/Pl_QPDFTokenizer.cc @@ -1,8 +1,8 @@ #include +#include #include #include -#include #include #include @@ -16,9 +16,10 @@ Pl_QPDFTokenizer::Members::~Members() { } -Pl_QPDFTokenizer::Pl_QPDFTokenizer(char const* identifier, - QPDFObjectHandle::TokenFilter* filter, - Pipeline* next) : +Pl_QPDFTokenizer::Pl_QPDFTokenizer( + char const* identifier, + QPDFObjectHandle::TokenFilter* filter, + Pipeline* next) : Pipeline(identifier, next), m(new Members) { @@ -43,39 +44,31 @@ void Pl_QPDFTokenizer::finish() { this->m->buf.finish(); - auto input = PointerHolder( - new BufferInputSource("tokenizer data", - this->m->buf.getBuffer(), true)); - - while (true) - { + auto input = PointerHolder(new BufferInputSource( + "tokenizer data", this->m->buf.getBuffer(), true)); + + while (true) { QPDFTokenizer::Token token = this->m->tokenizer.readToken( - input, "offset " + QUtil::int_to_string(input->tell()), - true); + input, "offset " + QUtil::int_to_string(input->tell()), true); this->m->filter->handleToken(token); - if (token.getType() == QPDFTokenizer::tt_eof) - { + if (token.getType() == QPDFTokenizer::tt_eof) { break; - } - else if ((token.getType() == QPDFTokenizer::tt_word) && - (token.getValue() == "ID")) - { + } else if ( + (token.getType() == QPDFTokenizer::tt_word) && + (token.getValue() == "ID")) { // Read the space after the ID. char ch = ' '; input->read(&ch, 1); - this->m->filter->handleToken( - QPDFTokenizer::Token( - QPDFTokenizer::tt_space, std::string(1, ch))); + this->m->filter->handleToken(QPDFTokenizer::Token( + QPDFTokenizer::tt_space, std::string(1, ch))); QTC::TC("qpdf", "Pl_QPDFTokenizer found ID"); this->m->tokenizer.expectInlineImage(input); } } this->m->filter->handleEOF(); - QPDFObjectHandle::TokenFilter::PipelineAccessor::setPipeline( - m->filter, 0); + QPDFObjectHandle::TokenFilter::PipelineAccessor::setPipeline(m->filter, 0); Pipeline* next = this->getNext(true); - if (next) - { + if (next) { next->finish(); } } diff --git a/libqpdf/Pl_RC4.cc b/libqpdf/Pl_RC4.cc index aa4c089e..17da3f53 100644 --- a/libqpdf/Pl_RC4.cc +++ b/libqpdf/Pl_RC4.cc @@ -2,9 +2,12 @@ #include -Pl_RC4::Pl_RC4(char const* identifier, Pipeline* next, - unsigned char const* key_data, int key_len, - size_t out_bufsize) : +Pl_RC4::Pl_RC4( + char const* identifier, + Pipeline* next, + unsigned char const* key_data, + int key_len, + size_t out_bufsize) : Pipeline(identifier, next), out_bufsize(out_bufsize), rc4(key_data, key_len) @@ -19,8 +22,7 @@ Pl_RC4::~Pl_RC4() void Pl_RC4::write(unsigned char* data, size_t len) { - if (this->outbuf.get() == 0) - { + if (this->outbuf.get() == 0) { throw std::logic_error( this->identifier + ": Pl_RC4: write() called after finish() called"); @@ -29,8 +31,7 @@ Pl_RC4::write(unsigned char* data, size_t len) size_t bytes_left = len; unsigned char* p = data; - while (bytes_left > 0) - { + while (bytes_left > 0) { size_t bytes = (bytes_left < this->out_bufsize ? bytes_left : out_bufsize); bytes_left -= bytes; diff --git a/libqpdf/Pl_RunLength.cc b/libqpdf/Pl_RunLength.cc index ed3b7576..b92e2756 100644 --- a/libqpdf/Pl_RunLength.cc +++ b/libqpdf/Pl_RunLength.cc @@ -1,7 +1,7 @@ #include -#include #include +#include Pl_RunLength::Members::Members(action_e action) : action(action), @@ -14,8 +14,8 @@ Pl_RunLength::Members::~Members() { } -Pl_RunLength::Pl_RunLength(char const* identifier, Pipeline* next, - action_e action) : +Pl_RunLength::Pl_RunLength( + char const* identifier, Pipeline* next, action_e action) : Pipeline(identifier, next), m(new Members(action)) { @@ -28,12 +28,9 @@ Pl_RunLength::~Pl_RunLength() void Pl_RunLength::write(unsigned char* data, size_t len) { - if (this->m->action == a_encode) - { + if (this->m->action == a_encode) { encode(data, len); - } - else - { + } else { decode(data, len); } } @@ -41,22 +38,20 @@ Pl_RunLength::write(unsigned char* data, size_t len) void Pl_RunLength::encode(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { - if ((this->m->state == st_top) != (this->m->length <= 1)) - { + for (size_t i = 0; i < len; ++i) { + if ((this->m->state == st_top) != (this->m->length <= 1)) { throw std::logic_error( "Pl_RunLength::encode: state/length inconsistency"); } unsigned char ch = data[i]; if ((this->m->length > 0) && ((this->m->state == st_copying) || (this->m->length < 128)) && - (ch == this->m->buf[this->m->length-1])) - { - QTC::TC("libtests", "Pl_RunLength: switch to run", - (this->m->length == 128) ? 0 : 1); - if (this->m->state == st_copying) - { + (ch == this->m->buf[this->m->length - 1])) { + QTC::TC( + "libtests", + "Pl_RunLength: switch to run", + (this->m->length == 128) ? 0 : 1); + if (this->m->state == st_copying) { --this->m->length; flush_encode(); this->m->buf[0] = ch; @@ -65,15 +60,10 @@ Pl_RunLength::encode(unsigned char* data, size_t len) this->m->state = st_run; this->m->buf[this->m->length] = ch; ++this->m->length; - } - else - { - if ((this->m->length == 128) || (this->m->state == st_run)) - { + } else { + if ((this->m->length == 128) || (this->m->state == st_run)) { flush_encode(); - } - else if (this->m->length > 0) - { + } else if (this->m->length > 0) { this->m->state = st_copying; } this->m->buf[this->m->length] = ch; @@ -85,41 +75,33 @@ Pl_RunLength::encode(unsigned char* data, size_t len) void Pl_RunLength::decode(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { unsigned char ch = data[i]; - switch (this->m->state) - { - case st_top: - if (ch < 128) - { + switch (this->m->state) { + case st_top: + if (ch < 128) { // length represents remaining number of bytes to copy this->m->length = 1U + ch; this->m->state = st_copying; - } - else if (ch > 128) - { + } else if (ch > 128) { // length represents number of copies of next byte this->m->length = 257U - ch; this->m->state = st_run; - } - else // ch == 128 + } else // ch == 128 { // EOD; stay in this state } break; - case st_copying: + case st_copying: this->getNext()->write(&ch, 1); - if (--this->m->length == 0) - { + if (--this->m->length == 0) { this->m->state = st_top; } break; - case st_run: - for (unsigned int j = 0; j < this->m->length; ++j) - { + case st_run: + for (unsigned int j = 0; j < this->m->length; ++j) { this->getNext()->write(&ch, 1); } this->m->state = st_top; @@ -131,30 +113,26 @@ Pl_RunLength::decode(unsigned char* data, size_t len) void Pl_RunLength::flush_encode() { - if (this->m->length == 128) - { - QTC::TC("libtests", "Pl_RunLength flush full buffer", - (this->m->state == st_copying ? 0 : - this->m->state == st_run ? 1 : - -1)); + if (this->m->length == 128) { + QTC::TC( + "libtests", + "Pl_RunLength flush full buffer", + (this->m->state == st_copying ? 0 + : this->m->state == st_run ? 1 + : -1)); } - if (this->m->length == 0) - { + if (this->m->length == 0) { QTC::TC("libtests", "Pl_RunLength flush empty buffer"); } - if (this->m->state == st_run) - { - if ((this->m->length < 2) || (this->m->length > 128)) - { + if (this->m->state == st_run) { + if ((this->m->length < 2) || (this->m->length > 128)) { throw std::logic_error( "Pl_RunLength: invalid length in flush_encode for run"); } unsigned char ch = static_cast(257 - this->m->length); this->getNext()->write(&ch, 1); this->getNext()->write(&this->m->buf[0], 1); - } - else if (this->m->length > 0) - { + } else if (this->m->length > 0) { unsigned char ch = static_cast(this->m->length - 1); this->getNext()->write(&ch, 1); this->getNext()->write(this->m->buf, this->m->length); @@ -170,8 +148,7 @@ Pl_RunLength::finish() // data, which means the stream was terminated early, but we will // just ignore this case since this is the only sensible thing to // do. - if (this->m->action == a_encode) - { + if (this->m->action == a_encode) { flush_encode(); unsigned char ch = 128; this->getNext()->write(&ch, 1); diff --git a/libqpdf/Pl_SHA2.cc b/libqpdf/Pl_SHA2.cc index 8844eb16..d41e6a78 100644 --- a/libqpdf/Pl_SHA2.cc +++ b/libqpdf/Pl_SHA2.cc @@ -1,17 +1,16 @@ #include -#include -#include #include -#include #include +#include +#include +#include Pl_SHA2::Pl_SHA2(int bits, Pipeline* next) : Pipeline("sha2", next), in_progress(false) { - if (bits) - { + if (bits) { resetBits(bits); } } @@ -23,8 +22,7 @@ Pl_SHA2::~Pl_SHA2() void Pl_SHA2::write(unsigned char* buf, size_t len) { - if (! this->in_progress) - { + if (!this->in_progress) { this->in_progress = true; } @@ -33,16 +31,14 @@ Pl_SHA2::write(unsigned char* buf, size_t len) static size_t const max_bytes = 1 << 30; size_t bytes_left = len; unsigned char* data = buf; - while (bytes_left > 0) - { + while (bytes_left > 0) { size_t bytes = (bytes_left >= max_bytes ? max_bytes : bytes_left); this->crypto->SHA2_update(data, bytes); bytes_left -= bytes; data += bytes; } - if (this->getNext(true)) - { + if (this->getNext(true)) { this->getNext()->write(buf, len); } } @@ -50,8 +46,7 @@ Pl_SHA2::write(unsigned char* buf, size_t len) void Pl_SHA2::finish() { - if (this->getNext(true)) - { + if (this->getNext(true)) { this->getNext()->finish(); } this->crypto->SHA2_finalize(); @@ -61,8 +56,7 @@ Pl_SHA2::finish() void Pl_SHA2::resetBits(int bits) { - if (this->in_progress) - { + if (this->in_progress) { throw std::logic_error( "bit reset requested for in-progress SHA2 Pipeline"); } @@ -73,8 +67,7 @@ Pl_SHA2::resetBits(int bits) std::string Pl_SHA2::getRawDigest() { - if (this->in_progress) - { + if (this->in_progress) { throw std::logic_error( "digest requested for in-progress SHA2 Pipeline"); } @@ -84,8 +77,7 @@ Pl_SHA2::getRawDigest() std::string Pl_SHA2::getHexDigest() { - if (this->in_progress) - { + if (this->in_progress) { throw std::logic_error( "digest requested for in-progress SHA2 Pipeline"); } diff --git a/libqpdf/Pl_StdioFile.cc b/libqpdf/Pl_StdioFile.cc index e4b96a9e..4f30ae22 100644 --- a/libqpdf/Pl_StdioFile.cc +++ b/libqpdf/Pl_StdioFile.cc @@ -1,10 +1,10 @@ -#include // include first for large file support +#include // include first for large file support #include #include -#include #include +#include Pl_StdioFile::Members::Members(FILE* f) : file(f) @@ -29,16 +29,12 @@ void Pl_StdioFile::write(unsigned char* buf, size_t len) { size_t so_far = 0; - while (len > 0) - { + while (len > 0) { so_far = fwrite(buf, 1, len, this->m->file); - if (so_far == 0) - { + if (so_far == 0) { QUtil::throw_system_error( this->identifier + ": Pl_StdioFile::write"); - } - else - { + } else { buf += so_far; len -= so_far; } @@ -48,11 +44,8 @@ Pl_StdioFile::write(unsigned char* buf, size_t len) void Pl_StdioFile::finish() { - if ((fflush(this->m->file) == -1) && - (errno == EBADF)) - { + if ((fflush(this->m->file) == -1) && (errno == EBADF)) { throw std::logic_error( - this->identifier + - ": Pl_StdioFile::finish: stream already closed"); + this->identifier + ": Pl_StdioFile::finish: stream already closed"); } } diff --git a/libqpdf/Pl_TIFFPredictor.cc b/libqpdf/Pl_TIFFPredictor.cc index 7f12a4a1..628e075b 100644 --- a/libqpdf/Pl_TIFFPredictor.cc +++ b/libqpdf/Pl_TIFFPredictor.cc @@ -1,19 +1,22 @@ #include -#include #include #include +#include #include -#include -#include -#include #include +#include +#include +#include -Pl_TIFFPredictor::Pl_TIFFPredictor(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, - unsigned int samples_per_pixel, - unsigned int bits_per_sample) : +Pl_TIFFPredictor::Pl_TIFFPredictor( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int columns, + unsigned int samples_per_pixel, + unsigned int bits_per_sample) : Pipeline(identifier, next), action(action), columns(columns), @@ -21,27 +24,24 @@ Pl_TIFFPredictor::Pl_TIFFPredictor(char const* identifier, Pipeline* next, bits_per_sample(bits_per_sample), pos(0) { - if (samples_per_pixel < 1) - { + if (samples_per_pixel < 1) { throw std::runtime_error( "TIFFPredictor created with invalid samples_per_pixel"); } if ((bits_per_sample < 1) || - (bits_per_sample > (8 * (sizeof(unsigned long long))))) - { + (bits_per_sample > (8 * (sizeof(unsigned long long))))) { throw std::runtime_error( "TIFFPredictor created with invalid bits_per_sample"); } unsigned long long bpr = ((columns * bits_per_sample * samples_per_pixel) + 7) / 8; - if ((bpr == 0) || (bpr > (UINT_MAX - 1))) - { + if ((bpr == 0) || (bpr > (UINT_MAX - 1))) { throw std::runtime_error( "TIFFPredictor created with invalid columns value"); } this->bytes_per_row = bpr & UINT_MAX; - this->cur_row = make_array_pointer_holder( - this->bytes_per_row); + this->cur_row = + make_array_pointer_holder(this->bytes_per_row); memset(this->cur_row.get(), 0, this->bytes_per_row); } @@ -54,8 +54,7 @@ Pl_TIFFPredictor::write(unsigned char* data, size_t len) { size_t left = this->bytes_per_row - this->pos; size_t offset = 0; - while (len >= left) - { + while (len >= left) { // finish off current row memcpy(this->cur_row.get() + this->pos, data + offset, left); offset += left; @@ -68,8 +67,7 @@ Pl_TIFFPredictor::write(unsigned char* data, size_t len) left = this->bytes_per_row; this->pos = 0; } - if (len) - { + if (len) { memcpy(this->cur_row.get() + this->pos, data + offset, len); } this->pos += len; @@ -78,30 +76,26 @@ Pl_TIFFPredictor::write(unsigned char* data, size_t len) void Pl_TIFFPredictor::processRow() { - QTC::TC("libtests", "Pl_TIFFPredictor processRow", - (action == a_decode ? 0 : 1)); + QTC::TC( + "libtests", + "Pl_TIFFPredictor processRow", + (action == a_decode ? 0 : 1)); BitWriter bw(this->getNext()); BitStream in(this->cur_row.get(), this->bytes_per_row); std::vector prev; - for (unsigned int i = 0; i < this->samples_per_pixel; ++i) - { + for (unsigned int i = 0; i < this->samples_per_pixel; ++i) { long long sample = in.getBitsSigned(this->bits_per_sample); bw.writeBitsSigned(sample, this->bits_per_sample); prev.push_back(sample); } - for (unsigned int col = 1; col < this->columns; ++col) - { - for (unsigned int i = 0; i < this->samples_per_pixel; ++i) - { + for (unsigned int col = 1; col < this->columns; ++col) { + for (unsigned int i = 0; i < this->samples_per_pixel; ++i) { long long sample = in.getBitsSigned(this->bits_per_sample); long long new_sample = sample; - if (action == a_encode) - { + if (action == a_encode) { new_sample -= prev[i]; prev[i] = sample; - } - else - { + } else { new_sample += prev[i]; prev[i] = new_sample; } @@ -114,8 +108,7 @@ Pl_TIFFPredictor::processRow() void Pl_TIFFPredictor::finish() { - if (this->pos) - { + if (this->pos) { // write partial row processRow(); } diff --git a/libqpdf/QPDF.cc b/libqpdf/QPDF.cc index 2337f43d..d56121b8 100644 --- a/libqpdf/QPDF.cc +++ b/libqpdf/QPDF.cc @@ -1,93 +1,100 @@ -#include // include first for large file support +#include // include first for large file support #include -#include -#include -#include #include +#include #include +#include +#include +#include #include #include #include -#include -#include +#include -#include -#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include #include -#include -#include -#include #include +#include +#include +#include // This must be a fixed value. This API returns a const reference to // it, and the C API relies on its being static as well. std::string const QPDF::qpdf_version(QPDF_VERSION); -static char const* EMPTY_PDF = - "%PDF-1.3\n" - "1 0 obj\n" - "<< /Type /Catalog /Pages 2 0 R >>\n" - "endobj\n" - "2 0 obj\n" - "<< /Type /Pages /Kids [] /Count 0 >>\n" - "endobj\n" - "xref\n" - "0 3\n" - "0000000000 65535 f \n" - "0000000009 00000 n \n" - "0000000058 00000 n \n" - "trailer << /Size 3 /Root 1 0 R >>\n" - "startxref\n" - "110\n" - "%%EOF\n"; +static char const* EMPTY_PDF = "%PDF-1.3\n" + "1 0 obj\n" + "<< /Type /Catalog /Pages 2 0 R >>\n" + "endobj\n" + "2 0 obj\n" + "<< /Type /Pages /Kids [] /Count 0 >>\n" + "endobj\n" + "xref\n" + "0 3\n" + "0000000000 65535 f \n" + "0000000009 00000 n \n" + "0000000058 00000 n \n" + "trailer << /Size 3 /Root 1 0 R >>\n" + "startxref\n" + "110\n" + "%%EOF\n"; class InvalidInputSource: public InputSource { public: virtual ~InvalidInputSource() = default; - virtual qpdf_offset_t findAndSkipNextEOL() override + virtual qpdf_offset_t + findAndSkipNextEOL() override { throwException(); return 0; } - virtual std::string const& getName() const override + virtual std::string const& + getName() const override { static std::string name("closed input source"); return name; } - virtual qpdf_offset_t tell() override + virtual qpdf_offset_t + tell() override { throwException(); return 0; } - virtual void seek(qpdf_offset_t offset, int whence) override + virtual void + seek(qpdf_offset_t offset, int whence) override { throwException(); } - virtual void rewind() override + virtual void + rewind() override { throwException(); } - virtual size_t read(char* buffer, size_t length) override + virtual size_t + read(char* buffer, size_t length) override { throwException(); return 0; } - virtual void unreadCh(char ch) override + virtual void + unreadCh(char ch) override { throwException(); } private: - void throwException() + void + throwException() { throw std::logic_error( "QPDF operation attempted on a QPDF object with no input source." @@ -103,8 +110,7 @@ QPDF::ForeignStreamData::ForeignStreamData( int foreign_generation, qpdf_offset_t offset, size_t length, - QPDFObjectHandle local_dict) - : + QPDFObjectHandle local_dict) : encp(encp), file(file), foreign_objid(foreign_objid), @@ -124,28 +130,26 @@ QPDF::CopiedStreamDataProvider::CopiedStreamDataProvider( bool QPDF::CopiedStreamDataProvider::provideStreamData( - int objid, int generation, Pipeline* pipeline, - bool suppress_warnings, bool will_retry) + int objid, + int generation, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) { PointerHolder foreign_data = this->foreign_stream_data[QPDFObjGen(objid, generation)]; bool result = false; - if (foreign_data.get()) - { + if (foreign_data.get()) { result = destination_qpdf.pipeForeignStreamData( foreign_data, pipeline, suppress_warnings, will_retry); - QTC::TC("qpdf", "QPDF copy foreign with data", - result ? 0 : 1); - } - else - { + QTC::TC("qpdf", "QPDF copy foreign with data", result ? 0 : 1); + } else { QPDFObjectHandle foreign_stream = this->foreign_streams[QPDFObjGen(objid, generation)]; result = foreign_stream.pipeStreamData( - pipeline, nullptr, 0, qpdf_dl_none, - suppress_warnings, will_retry); - QTC::TC("qpdf", "QPDF copy foreign with foreign_stream", - result ? 0 : 1); + pipeline, nullptr, 0, qpdf_dl_none, suppress_warnings, will_retry); + QTC::TC( + "qpdf", "QPDF copy foreign with foreign_stream", result ? 0 : 1); } return result; } @@ -159,8 +163,7 @@ QPDF::CopiedStreamDataProvider::registerForeignStream( void QPDF::CopiedStreamDataProvider::registerForeignStream( - QPDFObjGen const& local_og, - PointerHolder foreign_stream) + QPDFObjGen const& local_og, PointerHolder foreign_stream) { this->foreign_stream_data[local_og] = foreign_stream; } @@ -258,10 +261,9 @@ QPDF::~QPDF() this->m->xref_table.clear(); for (std::map::iterator iter = this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) - { - QPDFObject::ObjAccessor::releaseResolved( - (*iter).second.object.get()); + iter != this->m->obj_cache.end(); + ++iter) { + QPDFObject::ObjAccessor::releaseResolved((*iter).second.object.get()); } } @@ -274,8 +276,8 @@ QPDF::processFile(char const* filename, char const* password) } void -QPDF::processFile(char const* description, FILE* filep, - bool close_file, char const* password) +QPDF::processFile( + char const* description, FILE* filep, bool close_file, char const* password) { FileInputSource* fi = new FileInputSource(); fi->setFile(description, filep, close_file); @@ -283,22 +285,23 @@ QPDF::processFile(char const* description, FILE* filep, } void -QPDF::processMemoryFile(char const* description, - char const* buf, size_t length, - char const* password) +QPDF::processMemoryFile( + char const* description, + char const* buf, + size_t length, + char const* password) { processInputSource( - PointerHolder( - new BufferInputSource( - description, - new Buffer(QUtil::unsigned_char_pointer(buf), length), - true)), + PointerHolder(new BufferInputSource( + description, + new Buffer(QUtil::unsigned_char_pointer(buf), length), + true)), password); } void -QPDF::processInputSource(PointerHolder source, - char const* password) +QPDF::processInputSource( + PointerHolder source, char const* password) { this->m->file = source; parse(password); @@ -325,7 +328,7 @@ QPDF::emptyPDF() void QPDF::registerStreamFilter( std::string const& filter_name, - std::function ()> factory) + std::function()> factory) { QPDF_Stream::registerStreamFilter(filter_name, factory); } @@ -372,7 +375,7 @@ QPDF::getWarnings() bool QPDF::anyWarnings() const { - return ! this->m->warnings.empty(); + return !this->m->warnings.empty(); } size_t @@ -387,8 +390,7 @@ QPDF::findHeader() qpdf_offset_t global_offset = this->m->file->tell(); std::string line = this->m->file->readLine(1024); char const* p = line.c_str(); - if (strncmp(p, "%PDF-", 5) != 0) - { + if (strncmp(p, "%PDF-", 5) != 0) { throw std::logic_error("findHeader is not looking at %PDF-"); } p += 5; @@ -398,30 +400,22 @@ QPDF::findHeader() // because a null character always short-circuits further // advancement. bool valid = QUtil::is_digit(*p); - if (valid) - { - while (QUtil::is_digit(*p)) - { + if (valid) { + while (QUtil::is_digit(*p)) { version.append(1, *p++); } - if ((*p == '.') && QUtil::is_digit(*(p+1))) - { + if ((*p == '.') && QUtil::is_digit(*(p + 1))) { version.append(1, *p++); - while (QUtil::is_digit(*p)) - { + while (QUtil::is_digit(*p)) { version.append(1, *p++); } - } - else - { + } else { valid = false; } } - if (valid) - { + if (valid) { this->m->pdf_version = version; - if (global_offset != 0) - { + if (global_offset != 0) { // Empirical evidence strongly suggests that when there is // leading material prior to the PDF header, all explicit // offsets in the file are such that 0 points to the @@ -438,11 +432,9 @@ bool QPDF::findStartxref() { QPDFTokenizer::Token t = readToken(this->m->file); - if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "startxref")) - { + if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "startxref")) { t = readToken(this->m->file); - if (t.getType() == QPDFTokenizer::tt_integer) - { + if (t.getType() == QPDFTokenizer::tt_integer) { // Position in front of offset token this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET); return true; @@ -454,18 +446,20 @@ QPDF::findStartxref() void QPDF::parse(char const* password) { - if (password) - { + if (password) { this->m->encp->provided_password = password; } // Find the header anywhere in the first 1024 bytes of the file. PatternFinder hf(*this, &QPDF::findHeader); - if (! this->m->file->findFirst("%PDF-", 0, 1024, hf)) - { + if (!this->m->file->findFirst("%PDF-", 0, 1024, hf)) { QTC::TC("qpdf", "QPDF not a pdf file"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", 0, "can't find PDF header")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "can't find PDF header")); // QPDFWriter writes files that usually require at least // version 1.2 for /FlateDecode this->m->pdf_version = "1.2"; @@ -479,44 +473,38 @@ QPDF::parse(char const* password) qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0); PatternFinder sf(*this, &QPDF::findStartxref); qpdf_offset_t xref_offset = 0; - if (this->m->file->findLast("startxref", start_offset, 0, sf)) - { - xref_offset = QUtil::string_to_ll( - readToken(this->m->file).getValue().c_str()); + if (this->m->file->findLast("startxref", start_offset, 0, sf)) { + xref_offset = + QUtil::string_to_ll(readToken(this->m->file).getValue().c_str()); } - try - { - if (xref_offset == 0) - { + try { + if (xref_offset == 0) { QTC::TC("qpdf", "QPDF can't find startxref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "can't find startxref"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "can't find startxref"); } - try - { + try { read_xref(xref_offset); - } - catch (QPDFExc&) - { + } catch (QPDFExc&) { throw; + } catch (std::exception& e) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + std::string("error reading xref: ") + e.what()); } - catch (std::exception& e) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - std::string("error reading xref: ") + e.what()); - - } - } - catch (QPDFExc& e) - { - if (this->m->attempt_recovery) - { + } catch (QPDFExc& e) { + if (this->m->attempt_recovery) { reconstruct_xref(e); QTC::TC("qpdf", "QPDF reconstructed xref table"); - } - else - { + } else { throw e; } } @@ -528,8 +516,7 @@ QPDF::parse(char const* password) void QPDF::inParse(bool v) { - if (this->m->in_parse == v) - { + if (this->m->in_parse == v) { // This happens of QPDFObjectHandle::parseInternal tries to // resolve an indirect object while it is parsing. throw std::logic_error( @@ -543,19 +530,16 @@ void QPDF::warn(QPDFExc const& e) { this->m->warnings.push_back(e); - if (! this->m->suppress_warnings) - { - *this->m->err_stream - << "WARNING: " - << this->m->warnings.back().what() << std::endl; + if (!this->m->suppress_warnings) { + *this->m->err_stream << "WARNING: " << this->m->warnings.back().what() + << std::endl; } } void QPDF::setTrailer(QPDFObjectHandle obj) { - if (this->m->trailer.isInitialized()) - { + if (this->m->trailer.isInitialized()) { return; } this->m->trailer = obj; @@ -564,8 +548,7 @@ QPDF::setTrailer(QPDFObjectHandle obj) void QPDF::reconstruct_xref(QPDFExc& e) { - if (this->m->reconstructed_xref) - { + if (this->m->reconstructed_xref) { // Avoid xref reconstruction infinite loops. This is getting // very hard to reproduce because qpdf is throwing many fewer // exceptions while parsing. Most situations are warnings now. @@ -574,26 +557,33 @@ QPDF::reconstruct_xref(QPDFExc& e) this->m->reconstructed_xref = true; - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "file is damaged")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "file is damaged")); warn(e); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "Attempting to reconstruct cross-reference table")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "Attempting to reconstruct cross-reference table")); // Delete all references to type 1 (uncompressed) objects std::set to_delete; for (std::map::iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { - if (((*iter).second).getType() == 1) - { + iter != this->m->xref_table.end(); + ++iter) { + if (((*iter).second).getType() == 1) { to_delete.insert((*iter).first); } } for (std::set::iterator iter = to_delete.begin(); - iter != to_delete.end(); ++iter) - { + iter != to_delete.end(); + ++iter) { this->m->xref_table.erase(*iter); } @@ -603,45 +593,33 @@ QPDF::reconstruct_xref(QPDFExc& e) qpdf_offset_t line_start = 0; // Don't allow very long tokens here during recovery. static size_t const MAX_LEN = 100; - while (this->m->file->tell() < eof) - { + while (this->m->file->tell() < eof) { this->m->file->findAndSkipNextEOL(); qpdf_offset_t next_line_start = this->m->file->tell(); this->m->file->seek(line_start, SEEK_SET); QPDFTokenizer::Token t1 = readToken(this->m->file, MAX_LEN); qpdf_offset_t token_start = this->m->file->tell() - toO(t1.getValue().length()); - if (token_start >= next_line_start) - { + if (token_start >= next_line_start) { // don't process yet -- wait until we get to the line // containing this token - } - else if (t1.getType() == QPDFTokenizer::tt_integer) - { - QPDFTokenizer::Token t2 = - readToken(this->m->file, MAX_LEN); - QPDFTokenizer::Token t3 = - readToken(this->m->file, MAX_LEN); + } else if (t1.getType() == QPDFTokenizer::tt_integer) { + QPDFTokenizer::Token t2 = readToken(this->m->file, MAX_LEN); + QPDFTokenizer::Token t3 = readToken(this->m->file, MAX_LEN); if ((t2.getType() == QPDFTokenizer::tt_integer) && - (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"))) - { + (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj"))) { int obj = QUtil::string_to_int(t1.getValue().c_str()); int gen = QUtil::string_to_int(t2.getValue().c_str()); insertXrefEntry(obj, 1, token_start, gen, true); } - } - else if ((! this->m->trailer.isInitialized()) && - (t1 == QPDFTokenizer::Token( - QPDFTokenizer::tt_word, "trailer"))) - { + } else if ( + (!this->m->trailer.isInitialized()) && + (t1 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer"))) { QPDFObjectHandle t = - readObject(this->m->file, "trailer", 0, 0, false); - if (! t.isDictionary()) - { + readObject(this->m->file, "trailer", 0, 0, false); + if (!t.isDictionary()) { // Oh well. It was worth a try. - } - else - { + } else { setTrailer(t); } } @@ -649,17 +627,20 @@ QPDF::reconstruct_xref(QPDFExc& e) line_start = next_line_start; } - if (! this->m->trailer.isInitialized()) - { + if (!this->m->trailer.isInitialized()) { // We could check the last encountered object to see if it was // an xref stream. If so, we could try to get the trailer // from there. This may make it possible to recover files // with bad startxref pointers even when they have object // streams. - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "unable to find trailer " - "dictionary while recovering damaged file"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "unable to find trailer " + "dictionary while recovering damaged file"); } // We could iterate through the objects looking for streams and @@ -676,8 +657,7 @@ QPDF::read_xref(qpdf_offset_t xref_offset) { std::map free_table; std::set visited; - while (xref_offset) - { + while (xref_offset) { visited.insert(xref_offset); char buf[7]; memset(buf, 0, sizeof(buf)); @@ -690,25 +670,20 @@ QPDF::read_xref(qpdf_offset_t xref_offset) // case. bool done = false; bool skipped_space = false; - while (! done) - { + while (!done) { char ch; - if (1 == this->m->file->read(&ch, 1)) - { - if (QUtil::is_space(ch)) - { + if (1 == this->m->file->read(&ch, 1)) { + if (QUtil::is_space(ch)) { skipped_space = true; - } - else - { + } else { this->m->file->unreadCh(ch); done = true; } - } - else - { - QTC::TC("qpdf", "QPDF eof skipping spaces before xref", - skipped_space ? 0 : 1); + } else { + QTC::TC( + "qpdf", + "QPDF eof skipping spaces before xref", + skipped_space ? 0 : 1); done = true; } } @@ -717,64 +692,71 @@ QPDF::read_xref(qpdf_offset_t xref_offset) // The PDF spec says xref must be followed by a line // terminator, but files exist in the wild where it is // terminated by arbitrary whitespace. - if ((strncmp(buf, "xref", 4) == 0) && - QUtil::is_space(buf[4])) - { - if (skipped_space) - { + if ((strncmp(buf, "xref", 4) == 0) && QUtil::is_space(buf[4])) { + if (skipped_space) { QTC::TC("qpdf", "QPDF xref skipped space"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", 0, - "extraneous whitespace seen before xref")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "extraneous whitespace seen before xref")); } - QTC::TC("qpdf", "QPDF xref space", - ((buf[4] == '\n') ? 0 : - (buf[4] == '\r') ? 1 : - (buf[4] == ' ') ? 2 : 9999)); + QTC::TC( + "qpdf", + "QPDF xref space", + ((buf[4] == '\n') ? 0 + : (buf[4] == '\r') ? 1 + : (buf[4] == ' ') ? 2 + : 9999)); int skip = 4; // buf is null-terminated, and QUtil::is_space('\0') is // false, so this won't overrun. - while (QUtil::is_space(buf[skip])) - { + while (QUtil::is_space(buf[skip])) { ++skip; } xref_offset = read_xrefTable(xref_offset + skip); - } - else - { + } else { xref_offset = read_xrefStream(xref_offset); } - if (visited.count(xref_offset) != 0) - { + if (visited.count(xref_offset) != 0) { QTC::TC("qpdf", "QPDF xref loop"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "loop detected following xref tables"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "loop detected following xref tables"); } } - if (! this->m->trailer.isInitialized()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "unable to find trailer while reading xref"); + if (!this->m->trailer.isInitialized()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "unable to find trailer while reading xref"); } int size = this->m->trailer.getKey("/Size").getIntValueAsInt(); int max_obj = 0; - if (! this->m->xref_table.empty()) - { + if (!this->m->xref_table.empty()) { max_obj = (*(this->m->xref_table.rbegin())).first.getObj(); } - if (! this->m->deleted_objects.empty()) - { + if (!this->m->deleted_objects.empty()) { max_obj = std::max(max_obj, *(this->m->deleted_objects.rbegin())); } - if ((size < 1) || (size - 1 != max_obj)) - { + if ((size < 1) || (size - 1 != max_obj)) { QTC::TC("qpdf", "QPDF xref size mismatch"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - std::string("reported number of objects (") + - QUtil::int_to_string(size) + - ") is not one plus the highest object number (" + - QUtil::int_to_string(max_obj) + ")")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + std::string("reported number of objects (") + + QUtil::int_to_string(size) + + ") is not one plus the highest object number (" + + QUtil::int_to_string(max_obj) + ")")); } // We no longer need the deleted_objects table, so go ahead and @@ -783,8 +765,7 @@ QPDF::read_xref(qpdf_offset_t xref_offset) } bool -QPDF::parse_xrefFirst(std::string const& line, - int& obj, int& num, int& bytes) +QPDF::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes) { // is_space and is_digit both return false on '\0', so this will // not overrun the null-terminated buffer. @@ -792,45 +773,37 @@ QPDF::parse_xrefFirst(std::string const& line, char const* start = line.c_str(); // Skip zero or more spaces - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; } // Require digit - if (! QUtil::is_digit(*p)) - { + if (!QUtil::is_digit(*p)) { return false; } // Gather digits std::string obj_str; - while (QUtil::is_digit(*p)) - { + while (QUtil::is_digit(*p)) { obj_str.append(1, *p++); } // Require space - if (! QUtil::is_space(*p)) - { + if (!QUtil::is_space(*p)) { return false; } // Skip spaces - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; } // Require digit - if (! QUtil::is_digit(*p)) - { + if (!QUtil::is_digit(*p)) { return false; } // Gather digits std::string num_str; - while (QUtil::is_digit(*p)) - { + while (QUtil::is_digit(*p)) { num_str.append(1, *p++); } // Skip any space including line terminators - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; } bytes = toI(p - start); @@ -840,8 +813,8 @@ QPDF::parse_xrefFirst(std::string const& line, } bool -QPDF::parse_xrefEntry(std::string const& line, - qpdf_offset_t& f1, int& f2, char& type) +QPDF::parse_xrefEntry( + std::string const& line, qpdf_offset_t& f1, int& f2, char& type) { // is_space and is_digit both return false on '\0', so this will // not overrun the null-terminated buffer. @@ -849,84 +822,70 @@ QPDF::parse_xrefEntry(std::string const& line, // Skip zero or more spaces. There aren't supposed to be any. bool invalid = false; - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; QTC::TC("qpdf", "QPDF ignore first space in xref entry"); invalid = true; } // Require digit - if (! QUtil::is_digit(*p)) - { + if (!QUtil::is_digit(*p)) { return false; } // Gather digits std::string f1_str; - while (QUtil::is_digit(*p)) - { + while (QUtil::is_digit(*p)) { f1_str.append(1, *p++); } // Require space - if (! QUtil::is_space(*p)) - { + if (!QUtil::is_space(*p)) { return false; } - if (QUtil::is_space(*(p+1))) - { + if (QUtil::is_space(*(p + 1))) { QTC::TC("qpdf", "QPDF ignore first extra space in xref entry"); invalid = true; } // Skip spaces - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; } // Require digit - if (! QUtil::is_digit(*p)) - { + if (!QUtil::is_digit(*p)) { return false; } // Gather digits std::string f2_str; - while (QUtil::is_digit(*p)) - { + while (QUtil::is_digit(*p)) { f2_str.append(1, *p++); } // Require space - if (! QUtil::is_space(*p)) - { + if (!QUtil::is_space(*p)) { return false; } - if (QUtil::is_space(*(p+1))) - { + if (QUtil::is_space(*(p + 1))) { QTC::TC("qpdf", "QPDF ignore second extra space in xref entry"); invalid = true; } // Skip spaces - while (QUtil::is_space(*p)) - { + while (QUtil::is_space(*p)) { ++p; } - if ((*p == 'f') || (*p == 'n')) - { + if ((*p == 'f') || (*p == 'n')) { type = *p; - } - else - { + } else { return false; } - if ((f1_str.length() != 10) || (f2_str.length() != 5)) - { + if ((f1_str.length() != 10) || (f2_str.length() != 5)) { QTC::TC("qpdf", "QPDF ignore length error xref entry"); invalid = true; } - if (invalid) - { - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref table", - this->m->file->getLastOffset(), - "accepting invalid xref table entry")); + if (invalid) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref table", + this->m->file->getLastOffset(), + "accepting invalid xref table entry")); } f1 = QUtil::string_to_ll(f1_str.c_str()); @@ -942,8 +901,7 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset) this->m->file->seek(xref_offset, SEEK_SET); bool done = false; - while (! done) - { + while (!done) { char linebuf[51]; memset(linebuf, 0, sizeof(linebuf)); this->m->file->read(linebuf, sizeof(linebuf) - 1); @@ -951,18 +909,18 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset) int obj = 0; int num = 0; int bytes = 0; - if (! parse_xrefFirst(line, obj, num, bytes)) - { + if (!parse_xrefFirst(line, obj, num, bytes)) { QTC::TC("qpdf", "QPDF invalid xref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref table", this->m->file->getLastOffset(), - "xref syntax invalid"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref table", + this->m->file->getLastOffset(), + "xref syntax invalid"); } this->m->file->seek(this->m->file->getLastOffset() + bytes, SEEK_SET); - for (qpdf_offset_t i = obj; i - num < obj; ++i) - { - if (i == 0) - { + for (qpdf_offset_t i = obj; i - num < obj; ++i) { + if (i == 0) { // This is needed by checkLinearization() this->m->first_xref_item_offset = this->m->file->tell(); } @@ -971,34 +929,28 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset) qpdf_offset_t f1 = 0; int f2 = 0; char type = '\0'; - if (! parse_xrefEntry(xref_entry, f1, f2, type)) - { + if (!parse_xrefEntry(xref_entry, f1, f2, type)) { QTC::TC("qpdf", "QPDF invalid xref entry"); throw QPDFExc( - qpdf_e_damaged_pdf, this->m->file->getName(), - "xref table", this->m->file->getLastOffset(), - "invalid xref entry (obj=" + - QUtil::int_to_string(i) + ")"); + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref table", + this->m->file->getLastOffset(), + "invalid xref entry (obj=" + QUtil::int_to_string(i) + ")"); } - if (type == 'f') - { + if (type == 'f') { // Save deleted items until after we've checked the // XRefStm, if any. deleted_items.push_back(QPDFObjGen(toI(i), f2)); - } - else - { + } else { insertXrefEntry(toI(i), 1, f1, f2); } } qpdf_offset_t pos = this->m->file->tell(); QPDFTokenizer::Token t = readToken(this->m->file); - if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer")) - { + if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "trailer")) { done = true; - } - else - { + } else { this->m->file->seek(pos, SEEK_SET); } } @@ -1006,83 +958,83 @@ QPDF::read_xrefTable(qpdf_offset_t xref_offset) // Set offset to previous xref table if any QPDFObjectHandle cur_trailer = readObject(this->m->file, "trailer", 0, 0, false); - if (! cur_trailer.isDictionary()) - { + if (!cur_trailer.isDictionary()) { QTC::TC("qpdf", "QPDF missing trailer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), - "expected trailer dictionary"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + this->m->file->getLastOffset(), + "expected trailer dictionary"); } - if (! this->m->trailer.isInitialized()) - { + if (!this->m->trailer.isInitialized()) { setTrailer(cur_trailer); - if (! this->m->trailer.hasKey("/Size")) - { + if (!this->m->trailer.hasKey("/Size")) { QTC::TC("qpdf", "QPDF trailer lacks size"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "trailer dictionary lacks /Size key"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "trailer", + this->m->file->getLastOffset(), + "trailer dictionary lacks /Size key"); } - if (! this->m->trailer.getKey("/Size").isInteger()) - { + if (!this->m->trailer.getKey("/Size").isInteger()) { QTC::TC("qpdf", "QPDF trailer size not integer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "/Size key in trailer dictionary is not " - "an integer"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "trailer", + this->m->file->getLastOffset(), + "/Size key in trailer dictionary is not " + "an integer"); } } - if (cur_trailer.hasKey("/XRefStm")) - { - if (this->m->ignore_xref_streams) - { + if (cur_trailer.hasKey("/XRefStm")) { + if (this->m->ignore_xref_streams) { QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); - } - else - { - if (cur_trailer.getKey("/XRefStm").isInteger()) - { + } else { + if (cur_trailer.getKey("/XRefStm").isInteger()) { // Read the xref stream but disregard any return value // -- we'll use our trailer's /Prev key instead of the // xref stream's. - (void) read_xrefStream( + (void)read_xrefStream( cur_trailer.getKey("/XRefStm").getIntValue()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "invalid /XRefStm"); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "invalid /XRefStm"); } } } // Handle any deleted items now that we've read the /XRefStm. for (std::vector::iterator iter = deleted_items.begin(); - iter != deleted_items.end(); ++iter) - { + iter != deleted_items.end(); + ++iter) { QPDFObjGen& og = *iter; insertXrefEntry(og.getObj(), 0, 0, og.getGen()); } - if (cur_trailer.hasKey("/Prev")) - { - if (! cur_trailer.getKey("/Prev").isInteger()) - { + if (cur_trailer.hasKey("/Prev")) { + if (!cur_trailer.getKey("/Prev").isInteger()) { QTC::TC("qpdf", "QPDF trailer prev not integer"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "/Prev key in trailer dictionary is not " - "an integer"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "trailer", + this->m->file->getLastOffset(), + "/Prev key in trailer dictionary is not " + "an integer"); } QTC::TC("qpdf", "QPDF prev key in trailer dictionary"); xref_offset = cur_trailer.getKey("/Prev").getIntValue(); - } - else - { + } else { xref_offset = 0; } @@ -1093,33 +1045,31 @@ qpdf_offset_t QPDF::read_xrefStream(qpdf_offset_t xref_offset) { bool found = false; - if (! this->m->ignore_xref_streams) - { + if (!this->m->ignore_xref_streams) { int xobj; int xgen; QPDFObjectHandle xref_obj; - try - { + try { xref_obj = readObjectAtOffset( false, xref_offset, "xref stream", -1, 0, xobj, xgen); - } - catch (QPDFExc&) - { + } catch (QPDFExc&) { // ignore -- report error below } - if (xref_obj.isStreamOfType("/XRef")) - { + if (xref_obj.isStreamOfType("/XRef")) { QTC::TC("qpdf", "QPDF found xref stream"); found = true; xref_offset = processXRefStream(xref_offset, xref_obj); } } - if (! found) - { + if (!found) { QTC::TC("qpdf", "QPDF can't find xref"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", xref_offset, "xref not found"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + xref_offset, + "xref not found"); } return xref_offset; @@ -1131,76 +1081,76 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) QPDFObjectHandle dict = xref_obj.getDict(); QPDFObjectHandle W_obj = dict.getKey("/W"); QPDFObjectHandle Index_obj = dict.getKey("/Index"); - if (! (W_obj.isArray() && - (W_obj.getArrayNItems() >= 3) && - W_obj.getArrayItem(0).isInteger() && - W_obj.getArrayItem(1).isInteger() && - W_obj.getArrayItem(2).isInteger() && - dict.getKey("/Size").isInteger() && - (Index_obj.isArray() || Index_obj.isNull()))) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream does not have" - " proper /W and /Index keys"); + if (!(W_obj.isArray() && (W_obj.getArrayNItems() >= 3) && + W_obj.getArrayItem(0).isInteger() && + W_obj.getArrayItem(1).isInteger() && + W_obj.getArrayItem(2).isInteger() && + dict.getKey("/Size").isInteger() && + (Index_obj.isArray() || Index_obj.isNull()))) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream does not have" + " proper /W and /Index keys"); } int W[3]; size_t entry_size = 0; int max_bytes = sizeof(qpdf_offset_t); - for (int i = 0; i < 3; ++i) - { + for (int i = 0; i < 3; ++i) { W[i] = W_obj.getArrayItem(i).getIntValueAsInt(); - if (W[i] > max_bytes) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /W contains" - " impossibly large values"); + if (W[i] > max_bytes) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream's /W contains" + " impossibly large values"); } entry_size += toS(W[i]); } - if (entry_size == 0) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /W indicates" - " entry size of 0"); + if (entry_size == 0) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream's /W indicates" + " entry size of 0"); } unsigned long long max_num_entries = static_cast(-1) / entry_size; std::vector indx; - if (Index_obj.isArray()) - { + if (Index_obj.isArray()) { int n_index = Index_obj.getArrayNItems(); - if ((n_index % 2) || (n_index < 2)) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /Index has an" - " invalid number of values"); + if ((n_index % 2) || (n_index < 2)) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream's /Index has an" + " invalid number of values"); } - for (int i = 0; i < n_index; ++i) - { - if (Index_obj.getArrayItem(i).isInteger()) - { + for (int i = 0; i < n_index; ++i) { + if (Index_obj.getArrayItem(i).isInteger()) { indx.push_back(Index_obj.getArrayItem(i).getIntValue()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream's /Index's item " + - QUtil::int_to_string(i) + - " is not an integer"); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream's /Index's item " + + QUtil::int_to_string(i) + " is not an integer"); } } - QTC::TC("qpdf", "QPDF xref /Index is array", - n_index == 2 ? 0 : 1); - } - else - { + QTC::TC("qpdf", "QPDF xref /Index is array", n_index == 2 ? 0 : 1); + } else { QTC::TC("qpdf", "QPDF xref /Index is null"); long long size = dict.getKey("/Size").getIntValue(); indx.push_back(0); @@ -1208,17 +1158,18 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) } size_t num_entries = 0; - for (size_t i = 1; i < indx.size(); i += 2) - { - if (indx.at(i) > QIntC::to_longlong(max_num_entries - num_entries)) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream claims to contain" - " too many entries: " + - QUtil::int_to_string(indx.at(i)) + " " + - QUtil::uint_to_string(max_num_entries) + " " + - QUtil::uint_to_string(num_entries)); + for (size_t i = 1; i < indx.size(); i += 2) { + if (indx.at(i) > QIntC::to_longlong(max_num_entries - num_entries)) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream claims to contain" + " too many entries: " + + QUtil::int_to_string(indx.at(i)) + " " + + QUtil::uint_to_string(max_num_entries) + " " + + QUtil::uint_to_string(num_entries)); } num_entries += toS(indx.at(i)); } @@ -1230,19 +1181,19 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) PointerHolder bp = xref_obj.getStreamData(qpdf_dl_specialized); size_t actual_size = bp->getSize(); - if (expected_size != actual_size) - { - QPDFExc x(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", xref_offset, - "Cross-reference stream data has the wrong size;" - " expected = " + QUtil::uint_to_string(expected_size) + - "; actual = " + QUtil::uint_to_string(actual_size)); - if (expected_size > actual_size) - { + if (expected_size != actual_size) { + QPDFExc x( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + xref_offset, + "Cross-reference stream data has the wrong size;" + " expected = " + + QUtil::uint_to_string(expected_size) + + "; actual = " + QUtil::uint_to_string(actual_size)); + if (expected_size > actual_size) { throw x; - } - else - { + } else { warn(x); } } @@ -1256,22 +1207,18 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) // not overflow any buffers here. We know that entry_size * // num_entries is equal to the size of the buffer. unsigned char const* data = bp->getBuffer(); - for (size_t i = 0; i < num_entries; ++i) - { + for (size_t i = 0; i < num_entries; ++i) { // Read this entry unsigned char const* entry = data + (entry_size * i); qpdf_offset_t fields[3]; unsigned char const* p = entry; - for (int j = 0; j < 3; ++j) - { + for (int j = 0; j < 3; ++j) { fields[j] = 0; - if ((j == 0) && (W[0] == 0)) - { + if ((j == 0) && (W[0] == 0)) { QTC::TC("qpdf", "QPDF default for xref stream field 0"); fields[0] = 1; } - for (int k = 0; k < W[j]; ++k) - { + for (int k = 0; k < W[j]; ++k) { fields[j] <<= 8; fields[j] += toI(*p++); } @@ -1283,8 +1230,7 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) // number appears as the third field. int obj = toI(indx.at(cur_chunk)); if ((obj < 0) || - ((std::numeric_limits::max() - obj) < chunk_count)) - { + ((std::numeric_limits::max() - obj) < chunk_count)) { std::ostringstream msg; msg.imbue(std::locale::classic()); msg << "adding " << chunk_count << " to " << obj @@ -1294,59 +1240,49 @@ QPDF::processXRefStream(qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj) } obj += chunk_count; ++chunk_count; - if (chunk_count >= indx.at(cur_chunk + 1)) - { + if (chunk_count >= indx.at(cur_chunk + 1)) { cur_chunk += 2; chunk_count = 0; } - if (saw_first_compressed_object) - { - if (fields[0] != 2) - { + if (saw_first_compressed_object) { + if (fields[0] != 2) { this->m->uncompressed_after_compressed = true; } - } - else if (fields[0] == 2) - { + } else if (fields[0] == 2) { saw_first_compressed_object = true; } - if (obj == 0) - { + if (obj == 0) { // This is needed by checkLinearization() this->m->first_xref_item_offset = xref_offset; } - if (fields[0] == 0) - { + if (fields[0] == 0) { // Ignore fields[2], which we don't care about in this // case. This works around the issue of some PDF files // that put invalid values, like -1, here for deleted // objects. fields[2] = 0; } - insertXrefEntry(obj, toI(fields[0]), - fields[1], toI(fields[2])); + insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2])); } - if (! this->m->trailer.isInitialized()) - { + if (!this->m->trailer.isInitialized()) { setTrailer(dict); } - if (dict.hasKey("/Prev")) - { - if (! dict.getKey("/Prev").isInteger()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", this->m->file->getLastOffset(), - "/Prev key in xref stream dictionary is not " - "an integer"); + if (dict.hasKey("/Prev")) { + if (!dict.getKey("/Prev").isInteger()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + this->m->file->getLastOffset(), + "/Prev key in xref stream dictionary is not " + "an integer"); } QTC::TC("qpdf", "QPDF prev key in xref stream dictionary"); xref_offset = dict.getKey("/Prev").getIntValue(); - } - else - { + } else { xref_offset = 0; } @@ -1370,47 +1306,43 @@ QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2, bool overwrite) { // private scope int gen = (f0 == 2 ? 0 : f2); QPDFObjGen og(obj, gen); - if (this->m->xref_table.count(og)) - { - if (overwrite) - { + if (this->m->xref_table.count(og)) { + if (overwrite) { QTC::TC("qpdf", "QPDF xref overwrite object"); this->m->xref_table.erase(og); - } - else - { + } else { QTC::TC("qpdf", "QPDF xref reused object"); return; } } - if (this->m->deleted_objects.count(obj)) - { + if (this->m->deleted_objects.count(obj)) { QTC::TC("qpdf", "QPDF xref deleted object"); return; } } - switch (f0) - { - case 0: + switch (f0) { + case 0: this->m->deleted_objects.insert(obj); break; - case 1: + case 1: // f2 is generation QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0)); this->m->xref_table[QPDFObjGen(obj, f2)] = QPDFXRefEntry(f0, f1, f2); break; - case 2: + case 2: this->m->xref_table[QPDFObjGen(obj, 0)] = QPDFXRefEntry(f0, f1, f2); break; - default: - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "xref stream", this->m->file->getLastOffset(), - "unknown xref stream entry type " + - QUtil::int_to_string(f0)); + default: + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "xref stream", + this->m->file->getLastOffset(), + "unknown xref stream entry type " + QUtil::int_to_string(f0)); break; } } @@ -1420,26 +1352,24 @@ QPDF::showXRefTable() { for (std::map::iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { + iter != this->m->xref_table.end(); + ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; *this->m->out_stream << og.getObj() << "/" << og.getGen() << ": "; - switch (entry.getType()) - { - case 1: - *this->m->out_stream - << "uncompressed; offset = " << entry.getOffset(); + switch (entry.getType()) { + case 1: + *this->m->out_stream << "uncompressed; offset = " + << entry.getOffset(); break; - case 2: + case 2: *this->m->out_stream - << "compressed; stream = " - << entry.getObjStreamNumber() + << "compressed; stream = " << entry.getObjStreamNumber() << ", index = " << entry.getObjStreamIndex(); break; - default: + default: throw std::logic_error("unknown cross-reference table type while" " showing xref_table"); break; @@ -1451,8 +1381,7 @@ QPDF::showXRefTable() void QPDF::fixDanglingReferences(bool force) { - if (this->m->fixed_dangling_refs && (! force)) - { + if (this->m->fixed_dangling_refs && (!force)) { return; } this->m->fixed_dangling_refs = true; @@ -1462,14 +1391,14 @@ QPDF::fixDanglingReferences(bool force) std::set to_process; for (std::map::iterator iter = this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) - { + iter != this->m->obj_cache.end(); + ++iter) { to_process.insert((*iter).first); } for (std::map::iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { + iter != this->m->xref_table.end(); + ++iter) { to_process.insert((*iter).first); } @@ -1477,16 +1406,13 @@ QPDF::fixDanglingReferences(bool force) std::list queue; queue.push_back(this->m->trailer); for (std::set::iterator iter = to_process.begin(); - iter != to_process.end(); ++iter) - { + iter != to_process.end(); + ++iter) { QPDFObjectHandle obj = QPDFObjectHandle::Factory::newIndirect( this, (*iter).getObj(), (*iter).getGen()); - if (obj.isDictionary() || obj.isArray()) - { + if (obj.isDictionary() || obj.isArray()) { queue.push_back(obj); - } - else if (obj.isStream()) - { + } else if (obj.isStream()) { queue.push_back(obj.getDict()); } } @@ -1494,47 +1420,37 @@ QPDF::fixDanglingReferences(bool force) // Process the queue by recursively resolving all object // references. We don't need to do loop detection because we don't // traverse known indirect objects when processing the queue. - while (! queue.empty()) - { + while (!queue.empty()) { QPDFObjectHandle obj = queue.front(); queue.pop_front(); std::list to_check; - if (obj.isDictionary()) - { + if (obj.isDictionary()) { std::map members = obj.getDictAsMap(); for (std::map::iterator iter = members.begin(); - iter != members.end(); ++iter) - { + iter != members.end(); + ++iter) { to_check.push_back((*iter).second); } - } - else if (obj.isArray()) - { - QPDF_Array* arr = - dynamic_cast( - QPDFObjectHandle::ObjAccessor::getObject(obj).get()); + } else if (obj.isArray()) { + QPDF_Array* arr = dynamic_cast( + QPDFObjectHandle::ObjAccessor::getObject(obj).get()); arr->addExplicitElementsToList(to_check); } for (std::list::iterator iter = to_check.begin(); - iter != to_check.end(); ++iter) - { + iter != to_check.end(); + ++iter) { QPDFObjectHandle sub = *iter; - if (sub.isIndirect()) - { - if (sub.getOwningQPDF() == this) - { + if (sub.isIndirect()) { + if (sub.getOwningQPDF() == this) { QPDFObjGen og(sub.getObjGen()); - if (this->m->obj_cache.count(og) == 0) - { + if (this->m->obj_cache.count(og) == 0) { QTC::TC("qpdf", "QPDF detected dangling ref"); queue.push_back(sub); } } - } - else - { + } else { queue.push_back(sub); } } @@ -1550,8 +1466,7 @@ QPDF::getObjectCount() // will also be in obj_cache. fixDanglingReferences(); QPDFObjGen og(0, 0); - if (! this->m->obj_cache.empty()) - { + if (!this->m->obj_cache.empty()) { og = (*(this->m->obj_cache.rbegin())).first; } return toS(og.getObj()); @@ -1566,31 +1481,27 @@ QPDF::getAllObjects() std::vector result; for (std::map::iterator iter = this->m->obj_cache.begin(); - iter != this->m->obj_cache.end(); ++iter) - { - + iter != this->m->obj_cache.end(); + ++iter) { QPDFObjGen const& og = (*iter).first; result.push_back(QPDFObjectHandle::Factory::newIndirect( - this, og.getObj(), og.getGen())); + this, og.getObj(), og.getGen())); } return result; } void -QPDF::setLastObjectDescription(std::string const& description, - int objid, int generation) +QPDF::setLastObjectDescription( + std::string const& description, int objid, int generation) { this->m->last_object_description.clear(); - if (! description.empty()) - { + if (!description.empty()) { this->m->last_object_description += description; - if (objid > 0) - { + if (objid > 0) { this->m->last_object_description += ": "; } } - if (objid > 0) - { + if (objid > 0) { this->m->last_object_description += "object " + QUtil::int_to_string(objid) + " " + QUtil::int_to_string(generation); @@ -1598,9 +1509,12 @@ QPDF::setLastObjectDescription(std::string const& description, } QPDFObjectHandle -QPDF::readObject(PointerHolder input, - std::string const& description, - int objid, int generation, bool in_object_stream) +QPDF::readObject( + PointerHolder input, + std::string const& description, + int objid, + int generation, + bool in_object_stream) { setLastObjectDescription(description, objid, generation); qpdf_offset_t offset = input->tell(); @@ -1608,32 +1522,33 @@ QPDF::readObject(PointerHolder input, bool empty = false; PointerHolder decrypter_ph; StringDecrypter* decrypter = 0; - if (this->m->encp->encrypted && (! in_object_stream)) - { - decrypter_ph = make_pointer_holder( - this, objid, generation); + if (this->m->encp->encrypted && (!in_object_stream)) { + decrypter_ph = + make_pointer_holder(this, objid, generation); decrypter = decrypter_ph.get(); } QPDFObjectHandle object = QPDFObjectHandle::parse( - input, this->m->last_object_description, - this->m->tokenizer, empty, decrypter, this); - if (empty) - { + input, + this->m->last_object_description, + this->m->tokenizer, + empty, + decrypter, + this); + if (empty) { // Nothing in the PDF spec appears to allow empty objects, but // they have been encountered in actual PDF files and Adobe // Reader appears to ignore them. - warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, - input->getLastOffset(), - "empty object treated as null")); - } - else if (object.isDictionary() && (! in_object_stream)) - { + warn(QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->getLastOffset(), + "empty object treated as null")); + } else if (object.isDictionary() && (!in_object_stream)) { // check for stream qpdf_offset_t cur_offset = input->tell(); if (readToken(input) == - QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream")) - { + QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream")) { // The PDF specification states that the word "stream" // should be followed by either a carriage return and // a newline or by a newline alone. It specifically @@ -1647,33 +1562,23 @@ QPDF::readObject(PointerHolder input, // extraneous whitespace between the stream keyword and // the newline. bool done = false; - while (! done) - { + while (!done) { done = true; char ch; - if (input->read(&ch, 1) == 0) - { + if (input->read(&ch, 1) == 0) { // A premature EOF here will result in some // other problem that will get reported at // another time. - } - else if (ch == '\n') - { + } else if (ch == '\n') { // ready to read stream data QTC::TC("qpdf", "QPDF stream with NL only"); - } - else if (ch == '\r') - { + } else if (ch == '\r') { // Read another character - if (input->read(&ch, 1) != 0) - { - if (ch == '\n') - { + if (input->read(&ch, 1) != 0) { + if (ch == '\n') { // Ready to read stream data QTC::TC("qpdf", "QPDF stream with CRNL"); - } - else - { + } else { // Treat the \r by itself as the // whitespace after endstream and // start reading stream data in spite @@ -1681,35 +1586,33 @@ QPDF::readObject(PointerHolder input, QTC::TC("qpdf", "QPDF stream with CR only"); input->unreadCh(ch); warn(QPDFExc( - qpdf_e_damaged_pdf, - input->getName(), - this->m->last_object_description, - input->tell(), - "stream keyword followed" - " by carriage return only")); + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->tell(), + "stream keyword followed" + " by carriage return only")); } } - } - else if (QUtil::is_space(ch)) - { + } else if (QUtil::is_space(ch)) { warn(QPDFExc( - qpdf_e_damaged_pdf, - input->getName(), - this->m->last_object_description, - input->tell(), - "stream keyword followed by" - " extraneous whitespace")); + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->tell(), + "stream keyword followed by" + " extraneous whitespace")); done = false; - } - else - { + } else { QTC::TC("qpdf", "QPDF stream without newline"); input->unreadCh(ch); - warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, - input->tell(), - "stream keyword not followed" - " by proper line terminator")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->tell(), + "stream keyword not followed" + " by proper line terminator")); } } @@ -1719,62 +1622,59 @@ QPDF::readObject(PointerHolder input, qpdf_offset_t stream_offset = input->tell(); size_t length = 0; - try - { + try { std::map dict = object.getDictAsMap(); - if (dict.count("/Length") == 0) - { + if (dict.count("/Length") == 0) { QTC::TC("qpdf", "QPDF stream without length"); - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, offset, - "stream dictionary lacks /Length key"); + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + offset, + "stream dictionary lacks /Length key"); } QPDFObjectHandle length_obj = dict["/Length"]; - if (! length_obj.isInteger()) - { + if (!length_obj.isInteger()) { QTC::TC("qpdf", "QPDF stream length not integer"); - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, offset, - "/Length key in stream dictionary is not " - "an integer"); + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + offset, + "/Length key in stream dictionary is not " + "an integer"); } length = toS(length_obj.getUIntValue()); // Seek in two steps to avoid potential integer overflow input->seek(stream_offset, SEEK_SET); input->seek(toO(length), SEEK_CUR); - if (! (readToken(input) == - QPDFTokenizer::Token( - QPDFTokenizer::tt_word, "endstream"))) - { + if (!(readToken(input) == + QPDFTokenizer::Token( + QPDFTokenizer::tt_word, "endstream"))) { QTC::TC("qpdf", "QPDF missing endstream"); - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, - input->getLastOffset(), - "expected endstream"); + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->getLastOffset(), + "expected endstream"); } - } - catch (QPDFExc& e) - { - if (this->m->attempt_recovery) - { + } catch (QPDFExc& e) { + if (this->m->attempt_recovery) { warn(e); length = recoverStreamLength( input, objid, generation, stream_offset); - } - else - { + } else { throw e; } } object = QPDFObjectHandle::Factory::newStream( this, objid, generation, object, stream_offset, length); - } - else - { + } else { input->seek(cur_offset, SEEK_SET); } } @@ -1791,9 +1691,7 @@ QPDF::findEndstream() // Find endstream or endobj. Position the input at that token. QPDFTokenizer::Token t = readToken(this->m->file, 20); if ((t.getType() == QPDFTokenizer::tt_word) && - ((t.getValue() == "endobj") || - (t.getValue() == "endstream"))) - { + ((t.getValue() == "endobj") || (t.getValue() == "endstream"))) { this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET); return true; } @@ -1801,80 +1699,78 @@ QPDF::findEndstream() } size_t -QPDF::recoverStreamLength(PointerHolder input, - int objid, int generation, - qpdf_offset_t stream_offset) +QPDF::recoverStreamLength( + PointerHolder input, + int objid, + int generation, + qpdf_offset_t stream_offset) { // Try to reconstruct stream length by looking for // endstream or endobj - warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, stream_offset, - "attempting to recover stream length")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + stream_offset, + "attempting to recover stream length")); PatternFinder ef(*this, &QPDF::findEndstream); size_t length = 0; - if (this->m->file->findFirst("end", stream_offset, 0, ef)) - { + if (this->m->file->findFirst("end", stream_offset, 0, ef)) { length = toS(this->m->file->tell() - stream_offset); // Reread endstream but, if it was endobj, don't skip that. QPDFTokenizer::Token t = readToken(this->m->file); - if (t.getValue() == "endobj") - { + if (t.getValue() == "endobj") { this->m->file->seek(this->m->file->getLastOffset(), SEEK_SET); } } - if (length) - { + if (length) { qpdf_offset_t this_obj_offset = 0; QPDFObjGen this_obj(0, 0); // Make sure this is inside this object for (std::map::iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { + iter != this->m->xref_table.end(); + ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 1) - { + if (entry.getType() == 1) { qpdf_offset_t obj_offset = entry.getOffset(); if ((obj_offset > stream_offset) && ((this_obj_offset == 0) || - (this_obj_offset > obj_offset))) - { + (this_obj_offset > obj_offset))) { this_obj_offset = obj_offset; this_obj = og; } } } - if (this_obj_offset && - (this_obj.getObj() == objid) && - (this_obj.getGen() == generation)) - { + if (this_obj_offset && (this_obj.getObj() == objid) && + (this_obj.getGen() == generation)) { // Well, we found endstream\nendobj within the space // allowed for this object, so we're probably in good // shape. - } - else - { + } else { QTC::TC("qpdf", "QPDF found wrong endstream in recovery"); } } - if (length == 0) - { - warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, stream_offset, - "unable to recover stream data;" - " treating stream as empty")); - } - else - { - warn(QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, stream_offset, - "recovered stream length: " + - QUtil::uint_to_string(length))); + if (length == 0) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + stream_offset, + "unable to recover stream data;" + " treating stream as empty")); + } else { + warn(QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + stream_offset, + "recovered stream length: " + QUtil::uint_to_string(length))); } QTC::TC("qpdf", "QPDF recovered stream length"); @@ -1889,13 +1785,16 @@ QPDF::readToken(PointerHolder input, size_t max_len) } QPDFObjectHandle -QPDF::readObjectAtOffset(bool try_recovery, - qpdf_offset_t offset, std::string const& description, - int exp_objid, int exp_generation, - int& objid, int& generation) +QPDF::readObjectAtOffset( + bool try_recovery, + qpdf_offset_t offset, + std::string const& description, + int exp_objid, + int exp_generation, + int& objid, + int& generation) { - if (! this->m->attempt_recovery) - { + if (!this->m->attempt_recovery) { try_recovery = false; } setLastObjectDescription(description, exp_objid, exp_generation); @@ -1905,12 +1804,14 @@ QPDF::readObjectAtOffset(bool try_recovery, // store deleted objects in the xref table as "0000000000 00000 // n", which is not correct, but it won't hurt anything for to // ignore these. - if (offset == 0) - { + if (offset == 0) { QTC::TC("qpdf", "QPDF bogus 0 offset", 0); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, 0, - "object has offset 0")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + 0, + "object has offset 0")); return QPDFObjectHandle::newNull(); } @@ -1928,103 +1829,101 @@ QPDF::readObjectAtOffset(bool try_recovery, QTC::TC("qpdf", "QPDF check generation", genok ? 1 : 0); QTC::TC("qpdf", "QPDF check obj", objok ? 1 : 0); - try - { - if (! (objidok && genok && objok)) - { + try { + if (!(objidok && genok && objok)) { QTC::TC("qpdf", "QPDF expected n n obj"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, offset, - "expected n n obj"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + offset, + "expected n n obj"); } objid = QUtil::string_to_int(tobjid.getValue().c_str()); generation = QUtil::string_to_int(tgen.getValue().c_str()); - if (objid == 0) - { + if (objid == 0) { QTC::TC("qpdf", "QPDF object id 0"); - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, offset, - "object with ID 0"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + offset, + "object with ID 0"); } if ((exp_objid >= 0) && - (! ((objid == exp_objid) && (generation == exp_generation)))) - { + (!((objid == exp_objid) && (generation == exp_generation)))) { QTC::TC("qpdf", "QPDF err wrong objid/generation"); - QPDFExc e(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, offset, - std::string("expected ") + - QUtil::int_to_string(exp_objid) + " " + - QUtil::int_to_string(exp_generation) + " obj"); - if (try_recovery) - { + QPDFExc e( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + offset, + std::string("expected ") + QUtil::int_to_string(exp_objid) + + " " + QUtil::int_to_string(exp_generation) + " obj"); + if (try_recovery) { // Will be retried below throw e; - } - else - { + } else { // We can try reading the object anyway even if the ID // doesn't match. warn(e); } } - } - catch (QPDFExc& e) - { - if ((exp_objid >= 0) && try_recovery) - { + } catch (QPDFExc& e) { + if ((exp_objid >= 0) && try_recovery) { // Try again after reconstructing xref table reconstruct_xref(e); QPDFObjGen og(exp_objid, exp_generation); if (this->m->xref_table.count(og) && - (this->m->xref_table[og].getType() == 1)) - { + (this->m->xref_table[og].getType() == 1)) { qpdf_offset_t new_offset = this->m->xref_table[og].getOffset(); QPDFObjectHandle result = readObjectAtOffset( - false, new_offset, description, - exp_objid, exp_generation, objid, generation); + false, + new_offset, + description, + exp_objid, + exp_generation, + objid, + generation); QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset"); return result; - } - else - { + } else { QTC::TC("qpdf", "QPDF object gone after xref reconstruction"); warn(QPDFExc( - qpdf_e_damaged_pdf, this->m->file->getName(), - "", 0, - std::string( - "object " + - QUtil::int_to_string(exp_objid) + - " " + - QUtil::int_to_string(exp_generation) + - " not found in file after regenerating" - " cross reference table"))); + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + std::string( + "object " + QUtil::int_to_string(exp_objid) + " " + + QUtil::int_to_string(exp_generation) + + " not found in file after regenerating" + " cross reference table"))); return QPDFObjectHandle::newNull(); } - } - else - { + } else { throw e; } } - QPDFObjectHandle oh = readObject( - this->m->file, description, objid, generation, false); + QPDFObjectHandle oh = + readObject(this->m->file, description, objid, generation, false); - if (! (readToken(this->m->file) == - QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))) - { + if (!(readToken(this->m->file) == + QPDFTokenizer::Token(QPDFTokenizer::tt_word, "endobj"))) { QTC::TC("qpdf", "QPDF err expected endobj"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "expected endobj")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "expected endobj")); } QPDFObjGen og(objid, generation); - if (! this->m->obj_cache.count(og)) - { + if (!this->m->obj_cache.count(og)) { // Store the object in the cache here so it gets cached // whether we first know the offset or whether we first know // the object ID and generation (in which we case we would get @@ -2038,30 +1937,28 @@ QPDF::readObjectAtOffset(bool try_recovery, qpdf_offset_t end_before_space = this->m->file->tell(); // skip over spaces - while (true) - { + while (true) { char ch; - if (this->m->file->read(&ch, 1)) - { - if (! isspace(static_cast(ch))) - { + if (this->m->file->read(&ch, 1)) { + if (!isspace(static_cast(ch))) { this->m->file->seek(-1, SEEK_CUR); break; } - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->tell(), - "EOF after endobj"); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->tell(), + "EOF after endobj"); } } qpdf_offset_t end_after_space = this->m->file->tell(); - this->m->obj_cache[og] = - ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), - end_before_space, end_after_space); + this->m->obj_cache[og] = ObjCache( + QPDFObjectHandle::ObjAccessor::getObject(oh), + end_before_space, + end_after_space); } return oh; @@ -2079,13 +1976,11 @@ QPDF::objectChanged(QPDFObjGen const& og, PointerHolder& oph) // already in cache. It is important for functions that do this to // set ever_replaced_objects = true. - if (! this->m->ever_replaced_objects) - { + if (!this->m->ever_replaced_objects) { return false; } auto c = this->m->obj_cache.find(og); - if (c == this->m->obj_cache.end()) - { + if (c == this->m->obj_cache.end()) { return true; } return (c->second.object.get() != oph.get()); @@ -2098,68 +1993,71 @@ QPDF::resolve(int objid, int generation) // to insert things into the object cache that don't actually // exist in the file. QPDFObjGen og(objid, generation); - if (this->m->resolving.count(og)) - { + if (this->m->resolving.count(og)) { // This can happen if an object references itself directly or // indirectly in some key that has to be resolved during // object parsing, such as stream length. QTC::TC("qpdf", "QPDF recursion loop in resolve"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), - "loop detected resolving object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation))); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + this->m->file->getLastOffset(), + "loop detected resolving object " + QUtil::int_to_string(objid) + + " " + QUtil::int_to_string(generation))); return PointerHolder(new QPDF_Null); } ResolveRecorder rr(this, og); - if ((! this->m->obj_cache.count(og)) && this->m->xref_table.count(og)) - { + if ((!this->m->obj_cache.count(og)) && this->m->xref_table.count(og)) { QPDFXRefEntry const& entry = this->m->xref_table[og]; - try - { - switch (entry.getType()) - { - case 1: + try { + switch (entry.getType()) { + case 1: { qpdf_offset_t offset = entry.getOffset(); // Object stored in cache by readObjectAtOffset int aobjid; int ageneration; - QPDFObjectHandle oh = - readObjectAtOffset(true, offset, "", objid, generation, - aobjid, ageneration); + QPDFObjectHandle oh = readObjectAtOffset( + true, + offset, + "", + objid, + generation, + aobjid, + ageneration); } break; - case 2: + case 2: resolveObjectsInStream(entry.getObjStreamNumber()); break; - default: - throw QPDFExc(qpdf_e_damaged_pdf, - this->m->file->getName(), "", 0, - "object " + - QUtil::int_to_string(objid) + "/" + - QUtil::int_to_string(generation) + - " has unexpected xref entry type"); + default: + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "object " + QUtil::int_to_string(objid) + "/" + + QUtil::int_to_string(generation) + + " has unexpected xref entry type"); } - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { warn(e); - } - catch (std::exception& e) - { - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), "", 0, - "object " + - QUtil::int_to_string(objid) + "/" + - QUtil::int_to_string(generation) + - ": error reading object: " + e.what())); + } catch (std::exception& e) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + 0, + "object " + QUtil::int_to_string(objid) + "/" + + QUtil::int_to_string(generation) + + ": error reading object: " + e.what())); } } - if (this->m->obj_cache.count(og) == 0) - { + if (this->m->obj_cache.count(og) == 0) { // PDF spec says unknown objects resolve to the null object. QTC::TC("qpdf", "QPDF resolve failure to null"); QPDFObjectHandle oh = QPDFObjectHandle::newNull(); @@ -2168,12 +2066,11 @@ QPDF::resolve(int objid, int generation) } PointerHolder result(this->m->obj_cache[og].object); - if (! result->hasDescription()) - { + if (!result->hasDescription()) { result->setDescription( this, "object " + QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation)); + QUtil::int_to_string(generation)); } return result; } @@ -2181,21 +2078,20 @@ QPDF::resolve(int objid, int generation) void QPDF::resolveObjectsInStream(int obj_stream_number) { - if (this->m->resolved_object_streams.count(obj_stream_number)) - { + if (this->m->resolved_object_streams.count(obj_stream_number)) { return; } this->m->resolved_object_streams.insert(obj_stream_number); // Force resolution of object stream QPDFObjectHandle obj_stream = getObjectByID(obj_stream_number, 0); - if (! obj_stream.isStream()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "supposed object stream " + - QUtil::int_to_string(obj_stream_number) + - " is not a stream"); + if (!obj_stream.isStream()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "supposed object stream " + + QUtil::int_to_string(obj_stream_number) + " is not a stream"); } // For linearization data in the object, use the data from the @@ -2207,26 +2103,25 @@ QPDF::resolveObjectsInStream(int obj_stream_number) this->m->obj_cache[stream_og].end_after_space; QPDFObjectHandle dict = obj_stream.getDict(); - if (! dict.isDictionaryOfType("/ObjStm")) - { + if (!dict.isDictionaryOfType("/ObjStm")) { QTC::TC("qpdf", "QPDF ERR object stream with wrong type"); - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "supposed object stream " + - QUtil::int_to_string(obj_stream_number) + - " has wrong type")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "supposed object stream " + + QUtil::int_to_string(obj_stream_number) + " has wrong type")); } - if (! (dict.getKey("/N").isInteger() && - dict.getKey("/First").isInteger())) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "object stream " + - QUtil::int_to_string(obj_stream_number) + - " has incorrect keys"); + if (!(dict.getKey("/N").isInteger() && dict.getKey("/First").isInteger())) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "object stream " + QUtil::int_to_string(obj_stream_number) + + " has incorrect keys"); } int n = dict.getKey("/N").getIntValueAsInt(); @@ -2235,23 +2130,22 @@ QPDF::resolveObjectsInStream(int obj_stream_number) std::map offsets; PointerHolder bp = obj_stream.getStreamData(qpdf_dl_specialized); - auto input = PointerHolder( - new BufferInputSource( - this->m->file->getName() + - " object stream " + QUtil::int_to_string(obj_stream_number), - bp.get())); + auto input = PointerHolder(new BufferInputSource( + this->m->file->getName() + " object stream " + + QUtil::int_to_string(obj_stream_number), + bp.get())); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { QPDFTokenizer::Token tnum = readToken(input); QPDFTokenizer::Token toffset = readToken(input); - if (! ((tnum.getType() == QPDFTokenizer::tt_integer) && - (toffset.getType() == QPDFTokenizer::tt_integer))) - { - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - this->m->last_object_description, - input->getLastOffset(), - "expected integer in object stream header"); + if (!((tnum.getType() == QPDFTokenizer::tt_integer) && + (toffset.getType() == QPDFTokenizer::tt_integer))) { + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + this->m->last_object_description, + input->getLastOffset(), + "expected integer in object stream header"); } int num = QUtil::string_to_int(tnum.getValue().c_str()); @@ -2265,23 +2159,21 @@ QPDF::resolveObjectsInStream(int obj_stream_number) // objects appended to the file, so it is necessary to recheck the // xref table and only cache what would actually be resolved here. for (std::map::iterator iter = offsets.begin(); - iter != offsets.end(); ++iter) - { + iter != offsets.end(); + ++iter) { int obj = (*iter).first; QPDFObjGen og(obj, 0); QPDFXRefEntry const& entry = this->m->xref_table[og]; if ((entry.getType() == 2) && - (entry.getObjStreamNumber() == obj_stream_number)) - { + (entry.getObjStreamNumber() == obj_stream_number)) { int offset = (*iter).second; input->seek(offset, SEEK_SET); QPDFObjectHandle oh = readObject(input, "", obj, 0, true); - this->m->obj_cache[og] = - ObjCache(QPDFObjectHandle::ObjAccessor::getObject(oh), - end_before_space, end_after_space); - } - else - { + this->m->obj_cache[og] = ObjCache( + QPDFObjectHandle::ObjAccessor::getObject(oh), + end_before_space, + end_after_space); + } else { QTC::TC("qpdf", "QPDF not caching overridden objstm object"); } } @@ -2291,8 +2183,7 @@ QPDFObjectHandle QPDF::makeIndirectObject(QPDFObjectHandle oh) { int max_objid = toI(getObjectCount()); - if (max_objid == std::numeric_limits::max()) - { + if (max_objid == std::numeric_limits::max()) { throw std::range_error( "max object id is too high to create new objects"); } @@ -2324,8 +2215,7 @@ QPDF::replaceObject(QPDFObjGen const& og, QPDFObjectHandle oh) void QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh) { - if (oh.isIndirect()) - { + if (oh.isIndirect()) { QTC::TC("qpdf", "QPDF replaceObject called with indirect object"); throw std::logic_error( "QPDF::replaceObject called with indirect object handle"); @@ -2342,8 +2232,7 @@ QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh) } void -QPDF::replaceReserved(QPDFObjectHandle reserved, - QPDFObjectHandle replacement) +QPDF::replaceReserved(QPDFObjectHandle reserved, QPDFObjectHandle replacement) { QTC::TC("qpdf", "QPDF replaceReserved"); reserved.assertReserved(); @@ -2397,23 +2286,20 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) // Note that we explicitly allow use of copyForeignObject on page // objects. It is a documented use case to copy pages this way if // the intention is to not update the pages tree. - if (! foreign.isIndirect()) - { + if (!foreign.isIndirect()) { QTC::TC("qpdf", "QPDF copyForeign direct"); throw std::logic_error( "QPDF::copyForeign called with direct object handle"); } QPDF* other = foreign.getOwningQPDF(); - if (other == this) - { + if (other == this) { QTC::TC("qpdf", "QPDF copyForeign not foreign"); throw std::logic_error( "QPDF::copyForeign called with object from this QPDF"); } ObjCopier& obj_copier = this->m->object_copiers[other->m->unique_id]; - if (! obj_copier.visiting.empty()) - { + if (!obj_copier.visiting.empty()) { throw std::logic_error("obj_copier.visiting is not empty" " at the beginning of copyForeignObject"); } @@ -2426,8 +2312,7 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) // stream. reserveObjects(foreign, obj_copier, true); - if (! obj_copier.visiting.empty()) - { + if (!obj_copier.visiting.empty()) { throw std::logic_error("obj_copier.visiting is not empty" " after reserving objects"); } @@ -2435,13 +2320,12 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) // Copy any new objects and replace the reservations. for (std::vector::iterator iter = obj_copier.to_copy.begin(); - iter != obj_copier.to_copy.end(); ++iter) - { + iter != obj_copier.to_copy.end(); + ++iter) { QPDFObjectHandle& to_copy = *iter; QPDFObjectHandle copy = replaceForeignIndirectObjects(to_copy, obj_copier, true); - if (! to_copy.isStream()) - { + if (!to_copy.isStream()) { QPDFObjGen og(to_copy.getObjGen()); replaceReserved(obj_copier.object_map[og], copy); } @@ -2452,38 +2336,31 @@ QPDF::copyForeignObject(QPDFObjectHandle foreign) } void -QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, - bool top) +QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top) { - if (foreign.isReserved()) - { + if (foreign.isReserved()) { throw std::logic_error( "QPDF: attempting to copy a foreign reserved object"); } - if (foreign.isPagesObject()) - { + if (foreign.isPagesObject()) { QTC::TC("qpdf", "QPDF not copying pages object"); return; } - if ((! top) && foreign.isPageObject()) - { + if ((!top) && foreign.isPageObject()) { QTC::TC("qpdf", "QPDF not crossing page boundary"); return; } - if (foreign.isIndirect()) - { + if (foreign.isIndirect()) { QPDFObjGen foreign_og(foreign.getObjGen()); - if (obj_copier.visiting.find(foreign_og) != obj_copier.visiting.end()) - { + if (obj_copier.visiting.find(foreign_og) != obj_copier.visiting.end()) { QTC::TC("qpdf", "QPDF loop reserving objects"); return; } if (obj_copier.object_map.find(foreign_og) != - obj_copier.object_map.end()) - { + obj_copier.object_map.end()) { QTC::TC("qpdf", "QPDF already reserved object"); return; } @@ -2491,49 +2368,38 @@ QPDF::reserveObjects(QPDFObjectHandle foreign, ObjCopier& obj_copier, obj_copier.visiting.insert(foreign_og); std::map::iterator mapping = obj_copier.object_map.find(foreign_og); - if (mapping == obj_copier.object_map.end()) - { + if (mapping == obj_copier.object_map.end()) { obj_copier.to_copy.push_back(foreign); QPDFObjectHandle reservation; - if (foreign.isStream()) - { + if (foreign.isStream()) { reservation = QPDFObjectHandle::newStream(this); - } - else - { + } else { reservation = QPDFObjectHandle::newReserved(this); } obj_copier.object_map[foreign_og] = reservation; } } - if (foreign.isArray()) - { + if (foreign.isArray()) { QTC::TC("qpdf", "QPDF reserve array"); int n = foreign.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { reserveObjects(foreign.getArrayItem(i), obj_copier, false); } - } - else if (foreign.isDictionary()) - { + } else if (foreign.isDictionary()) { QTC::TC("qpdf", "QPDF reserve dictionary"); std::set keys = foreign.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { reserveObjects(foreign.getKey(*iter), obj_copier, false); } - } - else if (foreign.isStream()) - { + } else if (foreign.isStream()) { QTC::TC("qpdf", "QPDF reserve stream"); reserveObjects(foreign.getDict(), obj_copier, false); } - if (foreign.isIndirect()) - { + if (foreign.isIndirect()) { QPDFObjGen foreign_og(foreign.getObjGen()); obj_copier.visiting.erase(foreign_og); } @@ -2544,52 +2410,40 @@ QPDF::replaceForeignIndirectObjects( QPDFObjectHandle foreign, ObjCopier& obj_copier, bool top) { QPDFObjectHandle result; - if ((! top) && foreign.isIndirect()) - { + if ((!top) && foreign.isIndirect()) { QTC::TC("qpdf", "QPDF replace indirect"); QPDFObjGen foreign_og(foreign.getObjGen()); std::map::iterator mapping = obj_copier.object_map.find(foreign_og); - if (mapping == obj_copier.object_map.end()) - { + if (mapping == obj_copier.object_map.end()) { // This case would occur if this is a reference to a Page // or Pages object that we didn't traverse into. QTC::TC("qpdf", "QPDF replace foreign indirect with null"); result = QPDFObjectHandle::newNull(); - } - else - { + } else { result = obj_copier.object_map[foreign_og]; } - } - else if (foreign.isArray()) - { + } else if (foreign.isArray()) { QTC::TC("qpdf", "QPDF replace array"); result = QPDFObjectHandle::newArray(); int n = foreign.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - result.appendItem( - replaceForeignIndirectObjects( - foreign.getArrayItem(i), obj_copier, false)); + for (int i = 0; i < n; ++i) { + result.appendItem(replaceForeignIndirectObjects( + foreign.getArrayItem(i), obj_copier, false)); } - } - else if (foreign.isDictionary()) - { + } else if (foreign.isDictionary()) { QTC::TC("qpdf", "QPDF replace dictionary"); result = QPDFObjectHandle::newDictionary(); std::set keys = foreign.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { result.replaceKey( *iter, replaceForeignIndirectObjects( foreign.getKey(*iter), obj_copier, false)); } - } - else if (foreign.isStream()) - { + } else if (foreign.isStream()) { QTC::TC("qpdf", "QPDF replace stream"); QPDFObjGen foreign_og(foreign.getObjGen()); result = obj_copier.object_map[foreign_og]; @@ -2598,24 +2452,21 @@ QPDF::replaceForeignIndirectObjects( QPDFObjectHandle old_dict = foreign.getDict(); std::set keys = old_dict.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { dict.replaceKey( *iter, replaceForeignIndirectObjects( old_dict.getKey(*iter), obj_copier, false)); } copyStreamData(result, foreign); - } - else - { + } else { foreign.assertScalar(); result = foreign; result.makeDirect(); } - if (top && (! result.isStream()) && result.isIndirect()) - { + if (top && (!result.isStream()) && result.isIndirect()) { throw std::logic_error("replacement for foreign object is indirect"); } @@ -2631,8 +2482,7 @@ QPDF::copyStreamData(QPDFObjectHandle result, QPDFObjectHandle foreign) QPDFObjectHandle dict = result.getDict(); QPDFObjectHandle old_dict = foreign.getDict(); - if (this->m->copied_stream_data_provider == 0) - { + if (this->m->copied_stream_data_provider == 0) { this->m->copied_stream_data_provider = new CopiedStreamDataProvider(*this); this->m->copied_streams = @@ -2643,70 +2493,60 @@ QPDF::copyStreamData(QPDFObjectHandle result, QPDFObjectHandle foreign) // Copy information from the foreign stream so we can pipe its // data later without keeping the original QPDF object around. QPDF* foreign_stream_qpdf = foreign.getOwningQPDF(); - if (! foreign_stream_qpdf) - { + if (!foreign_stream_qpdf) { throw std::logic_error("unable to retrieve owning qpdf" " from foreign stream"); } - QPDF_Stream* stream = - dynamic_cast( - QPDFObjectHandle::ObjAccessor::getObject( - foreign).get()); - if (! stream) - { + QPDF_Stream* stream = dynamic_cast( + QPDFObjectHandle::ObjAccessor::getObject(foreign).get()); + if (!stream) { throw std::logic_error("unable to retrieve underlying" " stream object from foreign stream"); } - PointerHolder stream_buffer = - stream->getStreamDataBuffer(); + PointerHolder stream_buffer = stream->getStreamDataBuffer(); if ((foreign_stream_qpdf->m->immediate_copy_from) && - (stream_buffer.get() == 0)) - { + (stream_buffer.get() == 0)) { // Pull the stream data into a buffer before attempting // the copy operation. Do it on the source stream so that // if the source stream is copied multiple times, we don't // have to keep duplicating the memory. QTC::TC("qpdf", "QPDF immediate copy stream data"); - foreign.replaceStreamData(foreign.getRawStreamData(), - old_dict.getKey("/Filter"), - old_dict.getKey("/DecodeParms")); + foreign.replaceStreamData( + foreign.getRawStreamData(), + old_dict.getKey("/Filter"), + old_dict.getKey("/DecodeParms")); stream_buffer = stream->getStreamDataBuffer(); } PointerHolder stream_provider = stream->getStreamDataProvider(); - if (stream_buffer.get()) - { + if (stream_buffer.get()) { QTC::TC("qpdf", "QPDF copy foreign stream with buffer"); - result.replaceStreamData(stream_buffer, - dict.getKey("/Filter"), - dict.getKey("/DecodeParms")); - } - else if (stream_provider.get()) - { + result.replaceStreamData( + stream_buffer, dict.getKey("/Filter"), dict.getKey("/DecodeParms")); + } else if (stream_provider.get()) { // In this case, the remote stream's QPDF must stay in scope. QTC::TC("qpdf", "QPDF copy foreign stream with provider"); this->m->copied_stream_data_provider->registerForeignStream( local_og, foreign); - result.replaceStreamData(this->m->copied_streams, - dict.getKey("/Filter"), - dict.getKey("/DecodeParms")); - } - else - { - auto foreign_stream_data = - make_pointer_holder( - foreign_stream_qpdf->m->encp, - foreign_stream_qpdf->m->file, - foreign.getObjectID(), - foreign.getGeneration(), - stream->getOffset(), - stream->getLength(), - dict); + result.replaceStreamData( + this->m->copied_streams, + dict.getKey("/Filter"), + dict.getKey("/DecodeParms")); + } else { + auto foreign_stream_data = make_pointer_holder( + foreign_stream_qpdf->m->encp, + foreign_stream_qpdf->m->file, + foreign.getObjectID(), + foreign.getGeneration(), + stream->getOffset(), + stream->getLength(), + dict); this->m->copied_stream_data_provider->registerForeignStream( local_og, foreign_stream_data); - result.replaceStreamData(this->m->copied_streams, - dict.getKey("/Filter"), - dict.getKey("/DecodeParms")); + result.replaceStreamData( + this->m->copied_streams, + dict.getKey("/Filter"), + dict.getKey("/DecodeParms")); } } @@ -2752,8 +2592,7 @@ QPDF::getVersionAsPDFVersion() std::regex v("^[[:space:]]*([0-9]+)\\.([0-9]+)"); std::smatch m; - if (std::regex_search(this->m->pdf_version, m, v)) - { + if (std::regex_search(this->m->pdf_version, m, v)) { major = QUtil::string_to_int(m[1].str().c_str()); minor = QUtil::string_to_int(m[2].str().c_str()); } @@ -2772,17 +2611,13 @@ QPDF::getExtensionLevel() { int result = 0; QPDFObjectHandle obj = getRoot(); - if (obj.hasKey("/Extensions")) - { + if (obj.hasKey("/Extensions")) { obj = obj.getKey("/Extensions"); - if (obj.isDictionary() && obj.hasKey("/ADBE")) - { + if (obj.isDictionary() && obj.hasKey("/ADBE")) { obj = obj.getKey("/ADBE"); - if (obj.isDictionary() && obj.hasKey("/ExtensionLevel")) - { + if (obj.isDictionary() && obj.hasKey("/ExtensionLevel")) { obj = obj.getKey("/ExtensionLevel"); - if (obj.isInteger()) - { + if (obj.isInteger()) { result = obj.getIntValueAsInt(); } } @@ -2801,11 +2636,13 @@ QPDFObjectHandle QPDF::getRoot() { QPDFObjectHandle root = this->m->trailer.getKey("/Root"); - if (! root.isDictionary()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), - "unable to find /Root dictionary"); + if (!root.isDictionary()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + this->m->file->getLastOffset(), + "unable to find /Root dictionary"); } return root; } @@ -2813,8 +2650,7 @@ QPDF::getRoot() std::map QPDF::getXRefTable() { - if (! this->m->parsed) - { + if (!this->m->parsed) { throw std::logic_error("QPDF::getXRefTable called before parsing."); } @@ -2826,12 +2662,11 @@ QPDF::getObjectStreamData(std::map& omap) { for (std::map::iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { + iter != this->m->xref_table.end(); + ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 2) - { + if (entry.getType() == 2) { omap[og.getObj()] = entry.getObjStreamNumber(); } } @@ -2850,76 +2685,59 @@ QPDF::getCompressibleObjGens() // orphaned items. // Exclude encryption dictionary, if any - QPDFObjectHandle encryption_dict = - this->m->trailer.getKey("/Encrypt"); + QPDFObjectHandle encryption_dict = this->m->trailer.getKey("/Encrypt"); QPDFObjGen encryption_dict_og = encryption_dict.getObjGen(); std::set visited; std::list queue; queue.push_front(this->m->trailer); std::vector result; - while (! queue.empty()) - { + while (!queue.empty()) { QPDFObjectHandle obj = queue.front(); queue.pop_front(); - if (obj.isIndirect()) - { + if (obj.isIndirect()) { QPDFObjGen og = obj.getObjGen(); - if (visited.count(og)) - { + if (visited.count(og)) { QTC::TC("qpdf", "QPDF loop detected traversing objects"); continue; } - if (og == encryption_dict_og) - { + if (og == encryption_dict_og) { QTC::TC("qpdf", "QPDF exclude encryption dictionary"); - } - else if (! (obj.isStream() || - (obj.isDictionaryOfType("/Sig") && - obj.hasKey("/ByteRange") && - obj.hasKey("/Contents")))) - { + } else if (!(obj.isStream() || + (obj.isDictionaryOfType("/Sig") && + obj.hasKey("/ByteRange") && + obj.hasKey("/Contents")))) { result.push_back(og); } visited.insert(og); } - if (obj.isStream()) - { + if (obj.isStream()) { QPDFObjectHandle dict = obj.getDict(); std::set keys = dict.getKeys(); for (std::set::reverse_iterator iter = keys.rbegin(); - iter != keys.rend(); ++iter) - { + iter != keys.rend(); + ++iter) { std::string const& key = *iter; QPDFObjectHandle value = dict.getKey(key); - if (key == "/Length") - { + if (key == "/Length") { // omit stream lengths - if (value.isIndirect()) - { + if (value.isIndirect()) { QTC::TC("qpdf", "QPDF exclude indirect length"); } - } - else - { + } else { queue.push_front(value); } } - } - else if (obj.isDictionary()) - { + } else if (obj.isDictionary()) { std::set keys = obj.getKeys(); for (std::set::reverse_iterator iter = keys.rbegin(); - iter != keys.rend(); ++iter) - { + iter != keys.rend(); + ++iter) { queue.push_front(obj.getKey(*iter)); } - } - else if (obj.isArray()) - { + } else if (obj.isArray()) { int n = obj.getArrayNItems(); - for (int i = 1; i <= n; ++i) - { + for (int i = 1; i <= n; ++i) { queue.push_front(obj.getArrayItem(n - i)); } } @@ -2929,83 +2747,82 @@ QPDF::getCompressibleObjGens() } bool -QPDF::pipeStreamData(PointerHolder encp, - PointerHolder file, - QPDF& qpdf_for_warning, - int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle stream_dict, - Pipeline* pipeline, - bool suppress_warnings, - bool will_retry) +QPDF::pipeStreamData( + PointerHolder encp, + PointerHolder file, + QPDF& qpdf_for_warning, + int objid, + int generation, + qpdf_offset_t offset, + size_t length, + QPDFObjectHandle stream_dict, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) { std::vector> to_delete; - if (encp->encrypted) - { - decryptStream(encp, file, qpdf_for_warning, - pipeline, objid, generation, - stream_dict, to_delete); + if (encp->encrypted) { + decryptStream( + encp, + file, + qpdf_for_warning, + pipeline, + objid, + generation, + stream_dict, + to_delete); } bool success = false; - try - { + try { file->seek(offset, SEEK_SET); char buf[10240]; - while (length > 0) - { + while (length > 0) { size_t to_read = (sizeof(buf) < length ? sizeof(buf) : length); size_t len = file->read(buf, to_read); - if (len == 0) - { - throw QPDFExc(qpdf_e_damaged_pdf, - file->getName(), - "", - file->getLastOffset(), - "unexpected EOF reading stream data"); + if (len == 0) { + throw QPDFExc( + qpdf_e_damaged_pdf, + file->getName(), + "", + file->getLastOffset(), + "unexpected EOF reading stream data"); } length -= len; pipeline->write(QUtil::unsigned_char_pointer(buf), len); } pipeline->finish(); success = true; - } - catch (QPDFExc& e) - { - if (! suppress_warnings) - { + } catch (QPDFExc& e) { + if (!suppress_warnings) { qpdf_for_warning.warn(e); } - } - catch (std::exception& e) - { - if (! suppress_warnings) - { + } catch (std::exception& e) { + if (!suppress_warnings) { QTC::TC("qpdf", "QPDF decoding error warning"); - qpdf_for_warning.warn( - QPDFExc(qpdf_e_damaged_pdf, file->getName(), - "", file->getLastOffset(), - "error decoding stream data for object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation) + ": " + e.what())); - if (will_retry) - { - qpdf_for_warning.warn( - QPDFExc(qpdf_e_damaged_pdf, file->getName(), - "", file->getLastOffset(), - "stream will be re-processed without" - " filtering to avoid data loss")); + qpdf_for_warning.warn(QPDFExc( + qpdf_e_damaged_pdf, + file->getName(), + "", + file->getLastOffset(), + "error decoding stream data for object " + + QUtil::int_to_string(objid) + " " + + QUtil::int_to_string(generation) + ": " + e.what())); + if (will_retry) { + qpdf_for_warning.warn(QPDFExc( + qpdf_e_damaged_pdf, + file->getName(), + "", + file->getLastOffset(), + "stream will be re-processed without" + " filtering to avoid data loss")); } } } - if (! success) - { - try - { + if (!success) { + try { pipeline->finish(); - } - catch (std::exception&) - { + } catch (std::exception&) { // ignore } } @@ -3013,36 +2830,52 @@ QPDF::pipeStreamData(PointerHolder encp, } bool -QPDF::pipeStreamData(int objid, int generation, - qpdf_offset_t offset, size_t length, - QPDFObjectHandle stream_dict, - Pipeline* pipeline, - bool suppress_warnings, - bool will_retry) +QPDF::pipeStreamData( + int objid, + int generation, + qpdf_offset_t offset, + size_t length, + QPDFObjectHandle stream_dict, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) { return pipeStreamData( - this->m->encp, this->m->file, *this, - objid, generation, offset, length, - stream_dict, pipeline, - suppress_warnings, will_retry); + this->m->encp, + this->m->file, + *this, + objid, + generation, + offset, + length, + stream_dict, + pipeline, + suppress_warnings, + will_retry); } bool QPDF::pipeForeignStreamData( PointerHolder foreign, Pipeline* pipeline, - bool suppress_warnings, bool will_retry) + bool suppress_warnings, + bool will_retry) { - if (foreign->encp->encrypted) - { + if (foreign->encp->encrypted) { QTC::TC("qpdf", "QPDF pipe foreign encrypted stream"); } return pipeStreamData( - foreign->encp, foreign->file, *this, - foreign->foreign_objid, foreign->foreign_generation, - foreign->offset, foreign->length, - foreign->local_dict, pipeline, - suppress_warnings, will_retry); + foreign->encp, + foreign->file, + *this, + foreign->foreign_objid, + foreign->foreign_generation, + foreign->offset, + foreign->length, + foreign->local_dict, + pipeline, + suppress_warnings, + will_retry); } void @@ -3051,6 +2884,10 @@ QPDF::stopOnError(std::string const& message) // Throw a generic exception when we lack context for something // more specific. New code should not use this. This method exists // to improve somewhat from calling assert in very old code. - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "", this->m->file->getLastOffset(), message); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "", + this->m->file->getLastOffset(), + message); } diff --git a/libqpdf/QPDFAcroFormDocumentHelper.cc b/libqpdf/QPDFAcroFormDocumentHelper.cc index 4e05c46a..96f6d395 100644 --- a/libqpdf/QPDFAcroFormDocumentHelper.cc +++ b/libqpdf/QPDFAcroFormDocumentHelper.cc @@ -1,10 +1,10 @@ #include -#include -#include -#include #include +#include +#include #include +#include QPDFAcroFormDocumentHelper::Members::~Members() { @@ -43,10 +43,9 @@ QPDFObjectHandle QPDFAcroFormDocumentHelper::getOrCreateAcroForm() { auto acroform = this->qpdf.getRoot().getKey("/AcroForm"); - if (! acroform.isDictionary()) - { - acroform = this->qpdf.makeIndirectObject( - QPDFObjectHandle::newDictionary()); + if (!acroform.isDictionary()) { + acroform = + this->qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()); this->qpdf.getRoot().replaceKey("/AcroForm", acroform); } return acroform; @@ -57,8 +56,7 @@ QPDFAcroFormDocumentHelper::addFormField(QPDFFormFieldObjectHelper ff) { auto acroform = getOrCreateAcroForm(); auto fields = acroform.getKey("/Fields"); - if (! fields.isArray()) - { + if (!fields.isArray()) { fields = QPDFObjectHandle::newArray(); acroform.replaceKey("/Fields", fields); } @@ -77,28 +75,23 @@ QPDFAcroFormDocumentHelper::addAndRenameFormFields( std::list queue; queue.insert(queue.begin(), fields.begin(), fields.end()); std::set seen; - while (! queue.empty()) - { + while (!queue.empty()) { QPDFObjectHandle obj = queue.front(); queue.pop_front(); auto og = obj.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { // loop continue; } seen.insert(og); auto kids = obj.getKey("/Kids"); - if (kids.isArray()) - { - for (auto kid: kids.aitems()) - { + if (kids.isArray()) { + for (auto kid : kids.aitems()) { queue.push_back(kid); } } - if (obj.hasKey("/T")) - { + if (obj.hasKey("/T")) { // Find something we can append to the partial name that // makes the fully qualified name unique. When we find // something, reuse the same suffix for all fields in this @@ -109,13 +102,11 @@ QPDFAcroFormDocumentHelper::addAndRenameFormFields( // qualified name. std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName(); - if (renames.count(old_name) == 0) - { + if (renames.count(old_name) == 0) { std::string new_name = old_name; int suffix = 0; std::string append; - while (! getFieldsWithQualifiedName(new_name).empty()) - { + while (!getFieldsWithQualifiedName(new_name).empty()) { ++suffix; append = "+" + QUtil::int_to_string(suffix); new_name = old_name + append; @@ -123,17 +114,16 @@ QPDFAcroFormDocumentHelper::addAndRenameFormFields( renames[old_name] = append; } std::string append = renames[old_name]; - if (! append.empty()) - { + if (!append.empty()) { obj.replaceKey( - "/T", QPDFObjectHandle::newUnicodeString( + "/T", + QPDFObjectHandle::newUnicodeString( obj.getKey("/T").getUTF8Value() + append)); } } } - for (auto i: fields) - { + for (auto i : fields) { addFormField(i); } } @@ -143,34 +133,27 @@ QPDFAcroFormDocumentHelper::removeFormFields( std::set const& to_remove) { auto acroform = this->qpdf.getRoot().getKey("/AcroForm"); - if (! acroform.isDictionary()) - { + if (!acroform.isDictionary()) { return; } auto fields = acroform.getKey("/Fields"); - if (! fields.isArray()) - { + if (!fields.isArray()) { return; } - for (auto const& og: to_remove) - { + for (auto const& og : to_remove) { auto annotations = this->m->field_to_annotations.find(og); - if (annotations != this->m->field_to_annotations.end()) - { - for (auto aoh: annotations->second) - { + if (annotations != this->m->field_to_annotations.end()) { + for (auto aoh : annotations->second) { this->m->annotation_to_field.erase( aoh.getObjectHandle().getObjGen()); } this->m->field_to_annotations.erase(og); } auto name = this->m->field_to_name.find(og); - if (name != this->m->field_to_name.end()) - { + if (name != this->m->field_to_name.end()) { this->m->name_to_fields[name->second].erase(og); - if (this->m->name_to_fields[name->second].empty()) - { + if (this->m->name_to_fields[name->second].empty()) { this->m->name_to_fields.erase(name->second); } this->m->field_to_name.erase(og); @@ -178,15 +161,11 @@ QPDFAcroFormDocumentHelper::removeFormFields( } int i = 0; - while (i < fields.getArrayNItems()) - { + while (i < fields.getArrayNItems()) { auto field = fields.getArrayItem(i); - if (to_remove.count(field.getObjGen())) - { + if (to_remove.count(field.getObjGen())) { fields.eraseItem(i); - } - else - { + } else { ++i; } } @@ -207,26 +186,23 @@ QPDFAcroFormDocumentHelper::getFormFields() { analyze(); std::vector result; - for (std::map >::iterator iter = - this->m->field_to_annotations.begin(); - iter != this->m->field_to_annotations.end(); ++iter) - { + for (std::map>::iterator + iter = this->m->field_to_annotations.begin(); + iter != this->m->field_to_annotations.end(); + ++iter) { result.push_back(this->qpdf.getObjectByObjGen((*iter).first)); } return result; } std::set -QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName( - std::string const& name) +QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName(std::string const& name) { analyze(); // Keep from creating an empty entry std::set result; auto iter = this->m->name_to_fields.find(name); - if (iter != this->m->name_to_fields.end()) - { + if (iter != this->m->name_to_fields.end()) { result = iter->second; } return result; @@ -238,8 +214,7 @@ QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h) analyze(); std::vector result; QPDFObjGen og(h.getObjectHandle().getObjGen()); - if (this->m->field_to_annotations.count(og)) - { + if (this->m->field_to_annotations.count(og)) { result = this->m->field_to_annotations[og]; } return result; @@ -258,16 +233,13 @@ QPDFAcroFormDocumentHelper::getFormFieldsForPage(QPDFPageObjectHelper ph) std::set added; std::vector result; auto widget_annotations = getWidgetAnnotationsForPage(ph); - for (auto annot: widget_annotations) - { + for (auto annot : widget_annotations) { auto field = getFieldForAnnotation(annot); field = field.getTopLevelField(); auto og = field.getObjectHandle().getObjGen(); - if (! added.count(og)) - { + if (!added.count(og)) { added.insert(og); - if (field.getObjectHandle().isDictionary()) - { + if (field.getObjectHandle().isDictionary()) { result.push_back(field); } } @@ -280,14 +252,12 @@ QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h) { QPDFObjectHandle oh = h.getObjectHandle(); QPDFFormFieldObjectHelper result(QPDFObjectHandle::newNull()); - if (! oh.isDictionaryOfType("", "/Widget")) - { + if (!oh.isDictionaryOfType("", "/Widget")) { return result; } analyze(); QPDFObjGen og(oh.getObjGen()); - if (this->m->annotation_to_field.count(og)) - { + if (this->m->annotation_to_field.count(og)) { result = this->m->annotation_to_field[og]; } return result; @@ -296,19 +266,16 @@ QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h) void QPDFAcroFormDocumentHelper::analyze() { - if (this->m->cache_valid) - { + if (this->m->cache_valid) { return; } this->m->cache_valid = true; QPDFObjectHandle acroform = this->qpdf.getRoot().getKey("/AcroForm"); - if (! (acroform.isDictionary() && acroform.hasKey("/Fields"))) - { + if (!(acroform.isDictionary() && acroform.hasKey("/Fields"))) { return; } QPDFObjectHandle fields = acroform.getKey("/Fields"); - if (! fields.isArray()) - { + if (!fields.isArray()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper fields not array"); acroform.warnIfPossible( "/Fields key of /AcroForm dictionary is not an array; ignoring"); @@ -321,8 +288,7 @@ QPDFAcroFormDocumentHelper::analyze() std::set visited; int nfields = fields.getArrayNItems(); QPDFObjectHandle null(QPDFObjectHandle::newNull()); - for (int i = 0; i < nfields; ++i) - { + for (int i = 0; i < nfields; ++i) { traverseField(fields.getArrayItem(i), null, 0, visited); } @@ -338,19 +304,18 @@ QPDFAcroFormDocumentHelper::analyze() QPDFPageDocumentHelper dh(this->qpdf); std::vector pages = dh.getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper ph(*iter); std::vector annots = getWidgetAnnotationsForPage(ph); for (std::vector::iterator i2 = annots.begin(); - i2 != annots.end(); ++i2) - { + i2 != annots.end(); + ++i2) { QPDFObjectHandle annot((*i2).getObjectHandle()); QPDFObjGen og(annot.getObjGen()); - if (this->m->annotation_to_field.count(og) == 0) - { + if (this->m->annotation_to_field.count(og) == 0) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper orphaned widget"); // This is not supposed to happen, but it's easy // enough for us to handle this case. Treat the @@ -373,25 +338,24 @@ QPDFAcroFormDocumentHelper::analyze() void QPDFAcroFormDocumentHelper::traverseField( - QPDFObjectHandle field, QPDFObjectHandle parent, int depth, + QPDFObjectHandle field, + QPDFObjectHandle parent, + int depth, std::set& visited) { - if (depth > 100) - { + if (depth > 100) { // Arbitrarily cut off recursion at a fixed depth to avoid // specially crafted files that could cause stack overflow. return; } - if (! field.isIndirect()) - { + if (!field.isIndirect()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper direct field"); field.warnIfPossible( "encountered a direct object as a field or annotation while" " traversing /AcroForm; ignoring field or annotation"); return; } - if (! field.isDictionary()) - { + if (!field.isDictionary()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper non-dictionary field"); field.warnIfPossible( "encountered a non-dictionary as a field or annotation while" @@ -399,8 +363,7 @@ QPDFAcroFormDocumentHelper::traverseField( return; } QPDFObjGen og(field.getObjGen()); - if (visited.count(og) != 0) - { + if (visited.count(og) != 0) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper loop"); field.warnIfPossible("loop detected while traversing /AcroForm"); return; @@ -418,51 +381,42 @@ QPDFAcroFormDocumentHelper::traverseField( bool is_annotation = false; bool is_field = (0 == depth); QPDFObjectHandle kids = field.getKey("/Kids"); - if (kids.isArray()) - { + if (kids.isArray()) { is_field = true; int nkids = kids.getArrayNItems(); - for (int k = 0; k < nkids; ++k) - { + for (int k = 0; k < nkids; ++k) { traverseField(kids.getArrayItem(k), field, 1 + depth, visited); } - } - else - { - if (field.hasKey("/Parent")) - { + } else { + if (field.hasKey("/Parent")) { is_field = true; } - if (field.hasKey("/Subtype") || - field.hasKey("/Rect") || - field.hasKey("/AP")) - { + if (field.hasKey("/Subtype") || field.hasKey("/Rect") || + field.hasKey("/AP")) { is_annotation = true; } } - QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", - (depth == 0) ? 0 : 1); - QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", - (is_field ? 0 : 1)); + QTC::TC( + "qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1); + QTC::TC( + "qpdf", + "QPDFAcroFormDocumentHelper annotation found", + (is_field ? 0 : 1)); - if (is_annotation) - { + if (is_annotation) { QPDFObjectHandle our_field = (is_field ? field : parent); this->m->field_to_annotations[our_field.getObjGen()].push_back( QPDFAnnotationObjectHelper(field)); - this->m->annotation_to_field[og] = - QPDFFormFieldObjectHelper(our_field); + this->m->annotation_to_field[og] = QPDFFormFieldObjectHelper(our_field); } - if (is_field && (field.hasKey("/T"))) - { + if (is_field && (field.hasKey("/T"))) { QPDFFormFieldObjectHelper foh(field); auto f_og = field.getObjGen(); std::string name = foh.getFullyQualifiedName(); auto old = this->m->field_to_name.find(f_og); - if (old != this->m->field_to_name.end()) - { + if (old != this->m->field_to_name.end()) { // We might be updating after a name change, so remove any // old information std::string old_name = old->second; @@ -479,8 +433,7 @@ QPDFAcroFormDocumentHelper::getNeedAppearances() bool result = false; QPDFObjectHandle acroform = this->qpdf.getRoot().getKey("/AcroForm"); if (acroform.isDictionary() && - acroform.getKey("/NeedAppearances").isBool()) - { + acroform.getKey("/NeedAppearances").isBool()) { result = acroform.getKey("/NeedAppearances").getBoolValue(); } return result; @@ -490,20 +443,16 @@ void QPDFAcroFormDocumentHelper::setNeedAppearances(bool val) { QPDFObjectHandle acroform = this->qpdf.getRoot().getKey("/AcroForm"); - if (! acroform.isDictionary()) - { + if (!acroform.isDictionary()) { this->qpdf.getRoot().warnIfPossible( "ignoring call to QPDFAcroFormDocumentHelper::setNeedAppearances" " on a file that lacks an /AcroForm dictionary"); return; } - if (val) - { - acroform.replaceKey("/NeedAppearances", - QPDFObjectHandle::newBool(true)); - } - else - { + if (val) { + acroform.replaceKey( + "/NeedAppearances", QPDFObjectHandle::newBool(true)); + } else { acroform.removeKey("/NeedAppearances"); } } @@ -511,41 +460,34 @@ QPDFAcroFormDocumentHelper::setNeedAppearances(bool val) void QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded() { - if (! getNeedAppearances()) - { + if (!getNeedAppearances()) { return; } QPDFPageDocumentHelper pdh(this->qpdf); std::vector pages = pdh.getAllPages(); - for (std::vector::iterator page_iter = - pages.begin(); - page_iter != pages.end(); ++page_iter) - { + for (std::vector::iterator page_iter = pages.begin(); + page_iter != pages.end(); + ++page_iter) { std::vector annotations = getWidgetAnnotationsForPage(*page_iter); for (std::vector::iterator annot_iter = annotations.begin(); - annot_iter != annotations.end(); ++annot_iter) - { + annot_iter != annotations.end(); + ++annot_iter) { QPDFAnnotationObjectHelper& aoh = *annot_iter; - QPDFFormFieldObjectHelper ffh = - getFieldForAnnotation(aoh); - if (ffh.getFieldType() == "/Btn") - { + QPDFFormFieldObjectHelper ffh = getFieldForAnnotation(aoh); + if (ffh.getFieldType() == "/Btn") { // Rather than generating appearances for button // fields, rely on what's already there. Just make // sure /AS is consistent with /V, which we can do by // resetting the value of the field back to itself. // This code is referenced in a comment in // QPDFFormFieldObjectHelper::generateAppearance. - if (ffh.isRadioButton() || ffh.isCheckbox()) - { + if (ffh.isRadioButton() || ffh.isCheckbox()) { ffh.setV(ffh.getValue()); } - } - else - { + } else { ffh.generateAppearance(aoh); } } @@ -556,8 +498,10 @@ QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded() void QPDFAcroFormDocumentHelper::adjustInheritedFields( QPDFObjectHandle obj, - bool override_da, std::string const& from_default_da, - bool override_q, int from_default_q) + bool override_da, + std::string const& from_default_da, + bool override_q, + int from_default_q) { // Override /Q or /DA if needed. If this object has a field type, // directly or inherited, it is a field and not just an @@ -572,42 +516,32 @@ QPDFAcroFormDocumentHelper::adjustInheritedFields( auto has_explicit = [](QPDFFormFieldObjectHelper& field, std::string const& key) { - if (field.getObjectHandle().hasKey(key)) - { + if (field.getObjectHandle().hasKey(key)) { return true; } auto oh = field.getInheritableFieldValue(key); - if (! oh.isNull()) - { + if (!oh.isNull()) { return true; } return false; }; - if (override_da || override_q) - { + if (override_da || override_q) { QPDFFormFieldObjectHelper cur_field(obj); - if (override_da && (! has_explicit(cur_field, "/DA"))) - { + if (override_da && (!has_explicit(cur_field, "/DA"))) { std::string da = cur_field.getDefaultAppearance(); - if (da != from_default_da) - { + if (da != from_default_da) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper override da"); obj.replaceKey( - "/DA", - QPDFObjectHandle::newUnicodeString( - from_default_da)); + "/DA", QPDFObjectHandle::newUnicodeString(from_default_da)); } } - if (override_q && (! has_explicit(cur_field, "/Q"))) - { + if (override_q && (!has_explicit(cur_field, "/Q"))) { int q = cur_field.getQuadding(); - if (q != from_default_q) - { + if (q != from_default_q) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper override q"); obj.replaceKey( - "/Q", - QPDFObjectHandle::newInteger(from_default_q)); + "/Q", QPDFObjectHandle::newInteger(from_default_q)); } } } @@ -617,12 +551,9 @@ class ResourceReplacer: public QPDFObjectHandle::TokenFilter { public: ResourceReplacer( - std::map> const& dr_map, - std::map>> const& rnames); + std::map> const& dr_map, + std::map>> const& + rnames); virtual ~ResourceReplacer() = default; virtual void handleToken(QPDFTokenizer::Token const&) override; @@ -632,11 +563,9 @@ class ResourceReplacer: public QPDFObjectHandle::TokenFilter }; ResourceReplacer::ResourceReplacer( - std::map> const& dr_map, - std::map>> const& rnames) - : + std::map> const& dr_map, + std::map>> const& + rnames) : offset(0) { // We have: @@ -646,26 +575,21 @@ ResourceReplacer::ResourceReplacer( // We want: // * to_replace[key][offset] = new_key - for (auto const& rn_iter: rnames) - { + for (auto const& rn_iter : rnames) { std::string const& rtype = rn_iter.first; auto dr_map_rtype = dr_map.find(rtype); - if (dr_map_rtype == dr_map.end()) - { + if (dr_map_rtype == dr_map.end()) { continue; } auto const& key_offsets = rn_iter.second; - for (auto const& ko_iter: key_offsets) - { + for (auto const& ko_iter : key_offsets) { std::string const& old_key = ko_iter.first; auto dr_map_rtype_old = dr_map_rtype->second.find(old_key); - if (dr_map_rtype_old == dr_map_rtype->second.end()) - { + if (dr_map_rtype_old == dr_map_rtype->second.end()) { continue; } auto const& offsets = ko_iter.second; - for (auto const& o_iter: offsets) - { + for (auto const& o_iter : offsets) { to_replace[old_key][o_iter] = dr_map_rtype_old->second; } } @@ -676,21 +600,17 @@ void ResourceReplacer::handleToken(QPDFTokenizer::Token const& token) { bool wrote = false; - if (token.getType() == QPDFTokenizer::tt_name) - { + if (token.getType() == QPDFTokenizer::tt_name) { std::string name = QPDFObjectHandle::newName(token.getValue()).getName(); - if (to_replace.count(name) && - to_replace[name].count(offset)) - { + if (to_replace.count(name) && to_replace[name].count(offset)) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token"); write(to_replace[name][offset]); wrote = true; } } this->offset += token.getRawValue().length(); - if (! wrote) - { + if (!wrote) { writeToken(token); } } @@ -698,8 +618,7 @@ ResourceReplacer::handleToken(QPDFTokenizer::Token const& token) void QPDFAcroFormDocumentHelper::adjustDefaultAppearances( QPDFObjectHandle obj, - std::map> const& dr_map) + std::map> const& dr_map) { // This method is called on a field that has been copied from // another file but whose /DA still refers to resources in the @@ -733,8 +652,7 @@ QPDFAcroFormDocumentHelper::adjustDefaultAppearances( // done in adjustInheritedFields. auto DA = obj.getKey("/DA"); - if (! DA.isString()) - { + if (!DA.isString()) { return; } @@ -743,19 +661,15 @@ QPDFAcroFormDocumentHelper::adjustDefaultAppearances( // then filter it. We don't attach the stream to anything, so it // will get discarded. ResourceFinder rf; - auto da_stream = QPDFObjectHandle::newStream( - &this->qpdf, DA.getUTF8Value()); - try - { + auto da_stream = + QPDFObjectHandle::newStream(&this->qpdf, DA.getUTF8Value()); + try { auto nwarnings = this->qpdf.numWarnings(); da_stream.parseAsContents(&rf); - if (this->qpdf.numWarnings() > nwarnings) - { + if (this->qpdf.numWarnings() > nwarnings) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper /DA parse error"); } - } - catch (std::exception& e) - { + } catch (std::exception& e) { // No way to reproduce in test suite right now since error // conditions are converted to warnings. obj.warnIfPossible( @@ -795,8 +709,7 @@ QPDFAcroFormDocumentHelper::adjustAppearanceStream( // Make sure this stream has its own private resource dictionary. bool was_indirect = resources.isIndirect(); resources = resources.shallowCopy(); - if (was_indirect) - { + if (was_indirect) { resources = this->qpdf.makeIndirectObject(resources); } dict.replaceKey("/Resources", resources); @@ -805,29 +718,23 @@ QPDFAcroFormDocumentHelper::adjustAppearanceStream( // this to resolve conflicts that may already be in the resource // dictionary. auto merge_with = QPDFObjectHandle::newDictionary(); - for (auto const& top_key: dr_map) - { - merge_with.replaceKey( - top_key.first, QPDFObjectHandle::newDictionary()); + for (auto const& top_key : dr_map) { + merge_with.replaceKey(top_key.first, QPDFObjectHandle::newDictionary()); } resources.mergeResources(merge_with); // Rename any keys in the resource dictionary that we // remapped. - for (auto const& i1: dr_map) - { + for (auto const& i1 : dr_map) { std::string const& top_key = i1.first; auto subdict = resources.getKey(top_key); - if (! subdict.isDictionary()) - { + if (!subdict.isDictionary()) { continue; } - for (auto const& i2: i1.second) - { + for (auto const& i2 : i1.second) { std::string const& old_key = i2.first; std::string const& new_key = i2.second; auto existing_new = subdict.getKey(new_key); - if (! existing_new.isNull()) - { + if (!existing_new.isNull()) { // The resource dictionary already has a key in it // matching what we remapped an old key to, so we'll // have to move it out of the way. Stick it in @@ -838,8 +745,7 @@ QPDFAcroFormDocumentHelper::adjustAppearanceStream( merge_with.getKey(top_key).replaceKey(new_key, existing_new); } auto existing_old = subdict.getKey(old_key); - if (! existing_old.isNull()) - { + if (!existing_old.isNull()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper ap rename"); subdict.replaceKey(new_key, existing_old); subdict.removeKey(old_key); @@ -851,31 +757,24 @@ QPDFAcroFormDocumentHelper::adjustAppearanceStream( // the stream contents. resources.mergeResources(merge_with, &dr_map); // Remove empty subdictionaries - for (auto iter: resources.ditems()) - { - if (iter.second.isDictionary() && - (iter.second.getKeys().size() == 0)) - { + for (auto iter : resources.ditems()) { + if (iter.second.isDictionary() && (iter.second.getKeys().size() == 0)) { resources.removeKey(iter.first); } } // Now attach a token filter to replace the actual resources. ResourceFinder rf; - try - { + try { auto nwarnings = this->qpdf.numWarnings(); stream.parseAsContents(&rf); - if (this->qpdf.numWarnings() > nwarnings) - { + if (this->qpdf.numWarnings() > nwarnings) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper AP parse error"); } auto rr = new ResourceReplacer(dr_map, rf.getNamesByResourceType()); auto tf = PointerHolder(rr); stream.addTokenFilter(tf); - } - catch (std::exception& e) - { + } catch (std::exception& e) { // No way to reproduce in test suite right now since error // conditions are converted to warnings. stream.warnIfPossible( @@ -894,14 +793,11 @@ QPDFAcroFormDocumentHelper::transformAnnotations( QPDFAcroFormDocumentHelper* from_afdh) { PointerHolder afdhph; - if (! from_qpdf) - { + if (!from_qpdf) { // Assume these are from the same QPDF. from_qpdf = &this->qpdf; from_afdh = this; - } - else if ((from_qpdf != &this->qpdf) && (! from_afdh)) - { + } else if ((from_qpdf != &this->qpdf) && (!from_afdh)) { afdhph = make_pointer_holder(*from_qpdf); from_afdh = afdhph.get(); } @@ -926,47 +822,36 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // If we copy any form fields, we will need to merge the source // document's /DR into this document's /DR. QPDFObjectHandle from_dr = QPDFObjectHandle::newNull(); - if (foreign) - { + if (foreign) { std::string default_da; int default_q = 0; - if (acroform.isDictionary()) - { - if (acroform.getKey("/DA").isString()) - { + if (acroform.isDictionary()) { + if (acroform.getKey("/DA").isString()) { default_da = acroform.getKey("/DA").getUTF8Value(); } - if (acroform.getKey("/Q").isInteger()) - { + if (acroform.getKey("/Q").isInteger()) { default_q = acroform.getKey("/Q").getIntValueAsInt(); } } - if (from_acroform.isDictionary()) - { - if (from_acroform.getKey("/DR").isDictionary()) - { + if (from_acroform.isDictionary()) { + if (from_acroform.getKey("/DR").isDictionary()) { from_dr = from_acroform.getKey("/DR"); - if (! from_dr.isIndirect()) - { + if (!from_dr.isIndirect()) { from_dr = from_qpdf->makeIndirectObject(from_dr); } from_dr = this->qpdf.copyForeignObject(from_dr); } - if (from_acroform.getKey("/DA").isString()) - { + if (from_acroform.getKey("/DA").isString()) { from_default_da = from_acroform.getKey("/DA").getUTF8Value(); } - if (from_acroform.getKey("/Q").isInteger()) - { + if (from_acroform.getKey("/Q").isInteger()) { from_default_q = from_acroform.getKey("/Q").getIntValueAsInt(); } } - if (from_default_da != default_da) - { + if (from_default_da != default_da) { override_da = true; } - if (from_default_q != default_q) - { + if (from_default_q != default_q) { override_q = true; } } @@ -978,23 +863,19 @@ QPDFAcroFormDocumentHelper::transformAnnotations( bool initialized_dr_map = false; QPDFObjectHandle dr = QPDFObjectHandle::newNull(); auto init_dr_map = [&]() { - if (! initialized_dr_map) - { + if (!initialized_dr_map) { initialized_dr_map = true; // Ensure that we have a /DR that is an indirect // dictionary object. - if (! acroform.isDictionary()) - { + if (!acroform.isDictionary()) { acroform = getOrCreateAcroForm(); } dr = acroform.getKey("/DR"); - if (! dr.isDictionary()) - { + if (!dr.isDictionary()) { dr = QPDFObjectHandle::newDictionary(); } dr.makeResourcesIndirect(this->qpdf); - if (! dr.isIndirect()) - { + if (!dr.isIndirect()) { dr = this->qpdf.makeIndirectObject(dr); acroform.replaceKey("/DR", dr); } @@ -1006,8 +887,7 @@ QPDFAcroFormDocumentHelper::transformAnnotations( from_dr.makeResourcesIndirect(this->qpdf); dr.mergeResources(from_dr, &dr_map); - if (from_afdh->getNeedAppearances()) - { + if (from_afdh->getNeedAppearances()) { setNeedAppearances(true); } } @@ -1018,13 +898,10 @@ QPDFAcroFormDocumentHelper::transformAnnotations( std::map orig_to_copy; auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) { auto og = to_copy.getObjGen(); - if (orig_to_copy.count(og)) - { + if (orig_to_copy.count(og)) { to_copy = orig_to_copy[og]; return false; - } - else - { + } else { to_copy = this->qpdf.makeIndirectObject(to_copy.shallowCopy()); orig_to_copy[og] = to_copy; return true; @@ -1034,10 +911,8 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // Now do the actual copies. std::set added_new_fields; - for (auto annot: old_annots.aitems()) - { - if (annot.isStream()) - { + for (auto annot : old_annots.aitems()) { + if (annot.isStream()) { annot.warnIfPossible("ignoring annotation that's a stream"); continue; } @@ -1081,25 +956,18 @@ QPDFAcroFormDocumentHelper::transformAnnotations( QPDFObjectHandle top_field; bool have_field = false; bool have_parent = false; - if (ffield_oh.isStream()) - { + if (ffield_oh.isStream()) { ffield_oh.warnIfPossible("ignoring form field that's a stream"); - } - else if ((! ffield_oh.isNull()) && (! ffield_oh.isIndirect())) - { + } else if ((!ffield_oh.isNull()) && (!ffield_oh.isIndirect())) { ffield_oh.warnIfPossible("ignoring form field not indirect"); - } - else if (! ffield_oh.isNull()) - { + } else if (!ffield_oh.isNull()) { // A field and its associated annotation can be the same // object. This matters because we don't want to clone the // annotation and field separately in this case. have_field = true; // Find the top-level field. It may be the field itself. - top_field = ffield.getTopLevelField( - &have_parent).getObjectHandle(); - if (foreign) - { + top_field = ffield.getTopLevelField(&have_parent).getObjectHandle(); + if (foreign) { // copyForeignObject returns the same value if called // multiple times with the same field. Create/retrieve // the local copy of the original field. This pulls @@ -1112,9 +980,7 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // top_field and ffield_oh are known to be indirect. top_field = this->qpdf.copyForeignObject(top_field); ffield_oh = this->qpdf.copyForeignObject(ffield_oh); - } - else - { + } else { // We don't need to add top_field to old_fields if // it's foreign because the new copy of the foreign // field won't be referenced anywhere. It's just the @@ -1126,62 +992,53 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // Traverse the field, copying kids, and preserving // integrity. std::list queue; - if (maybe_copy_object(top_field)) - { + if (maybe_copy_object(top_field)) { queue.push_back(top_field); } std::set seen; - while (! queue.empty()) - { + while (!queue.empty()) { QPDFObjectHandle obj = queue.front(); queue.pop_front(); auto orig_og = obj.getObjGen(); - if (seen.count(orig_og)) - { + if (seen.count(orig_og)) { // loop break; } seen.insert(orig_og); auto parent = obj.getKey("/Parent"); - if (parent.isIndirect()) - { + if (parent.isIndirect()) { auto parent_og = parent.getObjGen(); - if (orig_to_copy.count(parent_og)) - { + if (orig_to_copy.count(parent_og)) { obj.replaceKey("/Parent", orig_to_copy[parent_og]); - } - else - { + } else { parent.warnIfPossible( "while traversing field " + - obj.getObjGen().unparse() + - ", found parent (" + parent_og.unparse() + + obj.getObjGen().unparse() + ", found parent (" + + parent_og.unparse() + ") that had not been seen, indicating likely" " invalid field structure"); } } auto kids = obj.getKey("/Kids"); - if (kids.isArray()) - { - for (int i = 0; i < kids.getArrayNItems(); ++i) - { + if (kids.isArray()) { + for (int i = 0; i < kids.getArrayNItems(); ++i) { auto kid = kids.getArrayItem(i); - if (maybe_copy_object(kid)) - { + if (maybe_copy_object(kid)) { kids.setArrayItem(i, kid); queue.push_back(kid); } } } - if (override_da || override_q) - { + if (override_da || override_q) { adjustInheritedFields( - obj, override_da, from_default_da, - override_q, from_default_q); + obj, + override_da, + from_default_da, + override_q, + from_default_q); } - if (foreign) - { + if (foreign) { // Lazily initialize our /DR and the conflict map. init_dr_map(); // The spec doesn't say anything about /DR on the @@ -1195,14 +1052,12 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // the mac Preview application, and several of the // free readers on Linux all ignore /DR at the // field level. - if (obj.hasKey("/DR")) - { + if (obj.hasKey("/DR")) { obj.replaceKey("/DR", dr); } } if (foreign && obj.getKey("/DA").isString() && - (! dr_map.empty())) - { + (!dr_map.empty())) { adjustDefaultAppearances(obj, dr_map); } } @@ -1212,17 +1067,18 @@ QPDFAcroFormDocumentHelper::transformAnnotations( ffield = QPDFFormFieldObjectHelper(ffield_oh); } - QTC::TC("qpdf", "QPDFAcroFormDocumentHelper copy annotation", - (have_field ? 1 : 0) | (foreign ? 2 : 0)); - if (have_field) - { - QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field with parent", - (have_parent ? 1 : 0) | (foreign ? 2 : 0)); + QTC::TC( + "qpdf", + "QPDFAcroFormDocumentHelper copy annotation", + (have_field ? 1 : 0) | (foreign ? 2 : 0)); + if (have_field) { + QTC::TC( + "qpdf", + "QPDFAcroFormDocumentHelper field with parent", + (have_parent ? 1 : 0) | (foreign ? 2 : 0)); } - if (foreign) - { - if (! annot.isIndirect()) - { + if (foreign) { + if (!annot.isIndirect()) { annot = from_qpdf->makeIndirectObject(annot); } annot = this->qpdf.copyForeignObject(annot); @@ -1230,8 +1086,7 @@ QPDFAcroFormDocumentHelper::transformAnnotations( maybe_copy_object(annot); // Now we have copies, so we can safely mutate. - if (have_field && ! added_new_fields.count(top_field.getObjGen())) - { + if (have_field && !added_new_fields.count(top_field.getObjGen())) { new_fields.push_back(top_field); added_new_fields.insert(top_field.getObjGen()); } @@ -1247,24 +1102,16 @@ QPDFAcroFormDocumentHelper::transformAnnotations( dict.replaceKey(key, new_stream); return new_stream; }; - if (apdict.isDictionary()) - { - for (auto& ap: apdict.ditems()) - { - if (ap.second.isStream()) - { + if (apdict.isDictionary()) { + for (auto& ap : apdict.ditems()) { + if (ap.second.isStream()) { streams.push_back( replace_stream(apdict, ap.first, ap.second)); - } - else if (ap.second.isDictionary()) - { - for (auto& ap2: ap.second.ditems()) - { - if (ap2.second.isStream()) - { - streams.push_back( - replace_stream( - ap.second, ap2.first, ap2.second)); + } else if (ap.second.isDictionary()) { + for (auto& ap2 : ap.second.ditems()) { + if (ap2.second.isStream()) { + streams.push_back(replace_stream( + ap.second, ap2.first, ap2.second)); } } } @@ -1273,33 +1120,28 @@ QPDFAcroFormDocumentHelper::transformAnnotations( // Now we can safely mutate the annotation and its appearance // streams. - for (auto& stream: streams) - { + for (auto& stream : streams) { auto dict = stream.getDict(); auto omatrix = dict.getKey("/Matrix"); QPDFMatrix apcm; - if (omatrix.isArray()) - { + if (omatrix.isArray()) { QTC::TC("qpdf", "QPDFAcroFormDocumentHelper modify ap matrix"); auto m1 = omatrix.getArrayAsMatrix(); apcm = QPDFMatrix(m1); } apcm.concat(cm); auto new_matrix = QPDFObjectHandle::newFromMatrix(apcm); - if (omatrix.isArray() || (apcm != QPDFMatrix())) - { + if (omatrix.isArray() || (apcm != QPDFMatrix())) { dict.replaceKey("/Matrix", new_matrix); } auto resources = dict.getKey("/Resources"); - if ((! dr_map.empty()) && resources.isDictionary()) - { + if ((!dr_map.empty()) && resources.isDictionary()) { adjustAppearanceStream(stream, dr_map); } } - auto rect = cm.transformRectangle( - annot.getKey("/Rect").getArrayAsRectangle()); - annot.replaceKey( - "/Rect", QPDFObjectHandle::newFromRectangle(rect)); + auto rect = + cm.transformRectangle(annot.getKey("/Rect").getArrayAsRectangle()); + annot.replaceKey("/Rect", QPDFObjectHandle::newFromRectangle(rect)); } } @@ -1309,10 +1151,13 @@ QPDFAcroFormDocumentHelper::copyFieldsFromForeignPage( QPDFAcroFormDocumentHelper& foreign_afdh, std::vector* copied_fields) { - this->qpdf.warn( - QPDFExc(qpdf_e_unsupported, "", "", 0, - "Non-working version of copyFieldsFromForeignPage" - " from qpdf 10.2 called; application requires updating")); + this->qpdf.warn(QPDFExc( + qpdf_e_unsupported, + "", + "", + 0, + "Non-working version of copyFieldsFromForeignPage" + " from qpdf 10.2 called; application requires updating")); } void @@ -1323,24 +1168,26 @@ QPDFAcroFormDocumentHelper::fixCopiedAnnotations( std::set* added_fields) { auto old_annots = from_page.getKey("/Annots"); - if ((! old_annots.isArray()) || (old_annots.getArrayNItems() == 0)) - { + if ((!old_annots.isArray()) || (old_annots.getArrayNItems() == 0)) { return; } std::vector new_annots; std::vector new_fields; std::set old_fields; - transformAnnotations(old_annots, new_annots, new_fields, old_fields, - QPDFMatrix(), &(from_afdh.getQPDF()), - &from_afdh); + transformAnnotations( + old_annots, + new_annots, + new_fields, + old_fields, + QPDFMatrix(), + &(from_afdh.getQPDF()), + &from_afdh); to_page.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots)); addAndRenameFormFields(new_fields); - if (added_fields) - { - for (auto f: new_fields) - { + if (added_fields) { + for (auto f : new_fields) { added_fields->insert(f.getObjGen()); } } diff --git a/libqpdf/QPDFAnnotationObjectHelper.cc b/libqpdf/QPDFAnnotationObjectHelper.cc index 2a47cd3e..37ef7502 100644 --- a/libqpdf/QPDFAnnotationObjectHelper.cc +++ b/libqpdf/QPDFAnnotationObjectHelper.cc @@ -1,10 +1,10 @@ #include -#include -#include -#include #include +#include #include +#include +#include QPDFAnnotationObjectHelper::Members::~Members() { @@ -40,8 +40,7 @@ QPDFAnnotationObjectHelper::getAppearanceDictionary() std::string QPDFAnnotationObjectHelper::getAppearanceState() { - if (this->oh.getKey("/AS").isName()) - { + if (this->oh.getKey("/AS").isName()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AS present"); return this->oh.getKey("/AS").getName(); } @@ -58,25 +57,20 @@ QPDFAnnotationObjectHelper::getFlags() QPDFObjectHandle QPDFAnnotationObjectHelper::getAppearanceStream( - std::string const& which, - std::string const& state) + std::string const& which, std::string const& state) { QPDFObjectHandle ap = getAppearanceDictionary(); std::string desired_state = state.empty() ? getAppearanceState() : state; - if (ap.isDictionary()) - { + if (ap.isDictionary()) { QPDFObjectHandle ap_sub = ap.getKey(which); - if (ap_sub.isStream() && desired_state.empty()) - { + if (ap_sub.isStream() && desired_state.empty()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP stream"); return ap_sub; } - if (ap_sub.isDictionary() && (! desired_state.empty())) - { + if (ap_sub.isDictionary() && (!desired_state.empty())) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP dictionary"); QPDFObjectHandle ap_sub_val = ap_sub.getKey(desired_state); - if (ap_sub_val.isStream()) - { + if (ap_sub_val.isStream()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper AP sub stream"); return ap_sub_val; } @@ -88,11 +82,12 @@ QPDFAnnotationObjectHelper::getAppearanceStream( std::string QPDFAnnotationObjectHelper::getPageContentForAppearance( - std::string const& name, int rotate, - int required_flags, int forbidden_flags) + std::string const& name, + int rotate, + int required_flags, + int forbidden_flags) { - if (! getAppearanceStream("/N").isStream()) - { + if (!getAppearanceStream("/N").isStream()) { return ""; } @@ -181,35 +176,28 @@ QPDFAnnotationObjectHelper::getPageContentForAppearance( QPDFObjectHandle matrix_obj = as.getKey("/Matrix"); int flags = getFlags(); - if (flags & forbidden_flags) - { + if (flags & forbidden_flags) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper forbidden flags"); return ""; } - if ((flags & required_flags) != required_flags) - { + if ((flags & required_flags) != required_flags) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper missing required flags"); return ""; } - if (! (bbox_obj.isRectangle() && rect_obj.isRectangle())) - { + if (!(bbox_obj.isRectangle() && rect_obj.isRectangle())) { return ""; } QPDFMatrix matrix; - if (matrix_obj.isMatrix()) - { + if (matrix_obj.isMatrix()) { QTC::TC("qpdf", "QPDFAnnotationObjectHelper explicit matrix"); matrix = QPDFMatrix(matrix_obj.getArrayAsMatrix()); - } - else - { + } else { QTC::TC("qpdf", "QPDFAnnotationObjectHelper default matrix"); } QPDFObjectHandle::Rectangle rect = rect_obj.getArrayAsRectangle(); bool do_rotate = (rotate && (flags & an_no_rotate)); - if (do_rotate) - { + if (do_rotate) { // If the the annotation flags include the NoRotate bit and // the page is rotated, we have to rotate the annotation about // its upper left corner by the same amount in the opposite @@ -224,33 +212,23 @@ QPDFAnnotationObjectHelper::getPageContentForAppearance( matrix = mr; double rect_w = rect.urx - rect.llx; double rect_h = rect.ury - rect.lly; - switch (rotate) - { - case 90: + switch (rotate) { + case 90: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 90"); rect = QPDFObjectHandle::Rectangle( - rect.llx, - rect.ury, - rect.llx + rect_h, - rect.ury + rect_w); + rect.llx, rect.ury, rect.llx + rect_h, rect.ury + rect_w); break; - case 180: + case 180: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 180"); rect = QPDFObjectHandle::Rectangle( - rect.llx - rect_w, - rect.ury, - rect.llx, - rect.ury + rect_h); + rect.llx - rect_w, rect.ury, rect.llx, rect.ury + rect_h); break; - case 270: + case 270: QTC::TC("qpdf", "QPDFAnnotationObjectHelper rotate 270"); rect = QPDFObjectHandle::Rectangle( - rect.llx - rect_h, - rect.ury - rect_w, - rect.llx, - rect.ury); + rect.llx - rect_h, rect.ury - rect_w, rect.llx, rect.ury); break; - default: + default: // ignore break; } @@ -259,26 +237,21 @@ QPDFAnnotationObjectHelper::getPageContentForAppearance( // Transform bounding box by matrix to get T QPDFObjectHandle::Rectangle bbox = bbox_obj.getArrayAsRectangle(); QPDFObjectHandle::Rectangle T = matrix.transformRectangle(bbox); - if ((T.urx == T.llx) || (T.ury == T.lly)) - { + if ((T.urx == T.llx) || (T.ury == T.lly)) { // avoid division by zero return ""; } // Compute a matrix to transform the appearance box to the rectangle QPDFMatrix AA; AA.translate(rect.llx, rect.lly); - AA.scale((rect.urx - rect.llx) / (T.urx - T.llx), - (rect.ury - rect.lly) / (T.ury - T.lly)); + AA.scale( + (rect.urx - rect.llx) / (T.urx - T.llx), + (rect.ury - rect.lly) / (T.ury - T.lly)); AA.translate(-T.llx, -T.lly); - if (do_rotate) - { + if (do_rotate) { AA.rotatex90(rotate); } as.replaceKey("/Subtype", QPDFObjectHandle::newName("/Form")); - return ( - "q\n" + - AA.unparse() + " cm\n" + - name + " Do\n" + - "Q\n"); + return ("q\n" + AA.unparse() + " cm\n" + name + " Do\n" + "Q\n"); } diff --git a/libqpdf/QPDFArgParser.cc b/libqpdf/QPDFArgParser.cc index 05e7a50e..207946b8 100644 --- a/libqpdf/QPDFArgParser.cc +++ b/libqpdf/QPDFArgParser.cc @@ -1,12 +1,12 @@ #include -#include #include -#include #include -#include -#include +#include +#include #include +#include +#include QPDFArgParser::Members::Members( int argc, char const* const argv[], char const* progname_env) : @@ -24,8 +24,8 @@ QPDFArgParser::Members::Members( whoami = QUtil::getWhoami(tmp.get()); } -QPDFArgParser::QPDFArgParser(int argc, char const* const argv[], - char const* progname_env) : +QPDFArgParser::QPDFArgParser( + int argc, char const* const argv[], char const* progname_env) : m(new Members(argc, argv, progname_env)) { selectHelpOptionTable(); @@ -35,10 +35,9 @@ QPDFArgParser::QPDFArgParser(int argc, char const* const argv[], "help", bindParam(&QPDFArgParser::argHelp, this), false, help_choices); addInvalidChoiceHandler( "help", bindParam(&QPDFArgParser::invalidHelpArg, this)); - addBare("completion-bash", - bindBare(&QPDFArgParser::argCompletionBash, this)); - addBare("completion-zsh", - bindBare(&QPDFArgParser::argCompletionZsh, this)); + addBare( + "completion-bash", bindBare(&QPDFArgParser::argCompletionBash, this)); + addBare("completion-zsh", bindBare(&QPDFArgParser::argCompletionZsh, this)); selectMainOptionTable(); } @@ -60,8 +59,7 @@ void QPDFArgParser::selectOptionTable(std::string const& name) { auto t = this->m->option_tables.find(name); - if (t == this->m->option_tables.end()) - { + if (t == this->m->option_tables.end()) { QTC::TC("libtests", "QPDFArgParser select unregistered table"); throw std::logic_error( "QPDFArgParser: selecting unregistered option table " + name); @@ -72,15 +70,13 @@ QPDFArgParser::selectOptionTable(std::string const& name) void QPDFArgParser::registerOptionTable( - std::string const& name, - bare_arg_handler_t end_handler) + std::string const& name, bare_arg_handler_t end_handler) { - if (0 != this->m->option_tables.count(name)) - { + if (0 != this->m->option_tables.count(name)) { QTC::TC("libtests", "QPDFArgParser register registered table"); throw std::logic_error( - "QPDFArgParser: registering already registered option table " - + name); + "QPDFArgParser: registering already registered option table " + + name); } this->m->option_tables[name]; selectOptionTable(name); @@ -90,13 +86,11 @@ QPDFArgParser::registerOptionTable( QPDFArgParser::OptionEntry& QPDFArgParser::registerArg(std::string const& arg) { - if (0 != this->m->option_table->count(arg)) - { + if (0 != this->m->option_table->count(arg)) { QTC::TC("libtests", "QPDFArgParser duplicate handler"); throw std::logic_error( - "QPDFArgParser: adding a duplicate handler for option " + - arg + " in " + this->m->option_table_name + - " option table"); + "QPDFArgParser: adding a duplicate handler for option " + arg + + " in " + this->m->option_table_name + " option table"); } return ((*this->m->option_table)[arg]); } @@ -109,8 +103,7 @@ QPDFArgParser::addPositional(param_arg_handler_t handler) } void -QPDFArgParser::addBare( - std::string const& arg, bare_arg_handler_t handler) +QPDFArgParser::addBare(std::string const& arg, bare_arg_handler_t handler) { OptionEntry& oe = registerArg(arg); oe.parameter_needed = false; @@ -148,8 +141,7 @@ QPDFArgParser::addChoices( OptionEntry& oe = registerArg(arg); oe.parameter_needed = required; oe.param_arg_handler = handler; - for (char const** i = choices; *i; ++i) - { + for (char const** i = choices; *i; ++i) { oe.choices.insert(*i); } } @@ -159,8 +151,7 @@ QPDFArgParser::addInvalidChoiceHandler( std::string const& arg, param_arg_handler_t handler) { auto i = this->m->option_table->find(arg); - if (i == this->m->option_table->end()) - { + if (i == this->m->option_table->end()) { QTC::TC("libtests", "QPDFArgParser invalid choice handler to unknown"); throw std::logic_error( "QPDFArgParser: attempt to add invalid choice handler" @@ -201,35 +192,29 @@ QPDFArgParser::completionCommon(bool zsh) std::string executable; std::string appdir; std::string appimage; - if (QUtil::get_env(this->m->progname_env.c_str(), &executable)) - { + if (QUtil::get_env(this->m->progname_env.c_str(), &executable)) { progname = executable; - } - else if (QUtil::get_env("APPDIR", &appdir) && - QUtil::get_env("APPIMAGE", &appimage)) - { + } else if ( + QUtil::get_env("APPDIR", &appdir) && + QUtil::get_env("APPIMAGE", &appimage)) { // Detect if we're in an AppImage and adjust if ((appdir.length() < strlen(this->m->argv[0])) && - (strncmp(appdir.c_str(), this->m->argv[0], appdir.length()) == 0)) - { + (strncmp(appdir.c_str(), this->m->argv[0], appdir.length()) == 0)) { progname = appimage; } } - if (zsh) - { + if (zsh) { std::cout << "autoload -U +X bashcompinit && bashcompinit && "; } std::cout << "complete -o bashdefault -o default"; - if (! zsh) - { + if (!zsh) { std::cout << " -o nospace"; } std::cout << " -C " << progname << " " << this->m->whoami << std::endl; // Put output before error so calling from zsh works properly std::string path = progname; size_t slash = path.find('/'); - if ((slash != 0) && (slash != std::string::npos)) - { + if ((slash != 0) && (slash != std::string::npos)) { std::cerr << "WARNING: " << this->m->whoami << " completion enabled" << " using relative path to executable" << std::endl; } @@ -257,8 +242,7 @@ QPDFArgParser::argHelp(std::string const& p) void QPDFArgParser::invalidHelpArg(std::string const& p) { - usage(std::string("unknown help option") + - (p.empty() ? "" : (" " + p))); + usage(std::string("unknown help option") + (p.empty() ? "" : (" " + p))); } void @@ -268,35 +252,27 @@ QPDFArgParser::handleArgFileArguments() // that argv itself as well as all its contents are automatically // deleted by using shared pointers to back the pointers in argv. this->m->new_argv.push_back(QUtil::make_shared_cstr(this->m->argv[0])); - for (int i = 1; i < this->m->argc; ++i) - { + for (int i = 1; i < this->m->argc; ++i) { char const* argfile = 0; - if ((strlen(this->m->argv[i]) > 1) && (this->m->argv[i][0] == '@')) - { + if ((strlen(this->m->argv[i]) > 1) && (this->m->argv[i][0] == '@')) { argfile = 1 + this->m->argv[i]; - if (strcmp(argfile, "-") != 0) - { - if (! QUtil::file_can_be_opened(argfile)) - { + if (strcmp(argfile, "-") != 0) { + if (!QUtil::file_can_be_opened(argfile)) { // The file's not there; treating as regular option argfile = nullptr; } } } - if (argfile) - { + if (argfile) { readArgsFromFile(1 + this->m->argv[i]); - } - else - { + } else { this->m->new_argv.push_back( QUtil::make_shared_cstr(this->m->argv[i])); } } - this->m->argv_ph = QUtil::make_shared_array( - 1 + this->m->new_argv.size()); - for (size_t i = 0; i < this->m->new_argv.size(); ++i) - { + this->m->argv_ph = + QUtil::make_shared_array(1 + this->m->new_argv.size()); + for (size_t i = 0; i < this->m->new_argv.size(); ++i) { this->m->argv_ph.get()[i] = this->m->new_argv.at(i).get(); } this->m->argc = QIntC::to_int(this->m->new_argv.size()); @@ -319,88 +295,64 @@ QPDFArgParser::handleBashArguments() enum { st_top, st_squote, st_dquote } state = st_top; std::string arg; for (std::string::iterator iter = this->m->bash_line.begin(); - iter != this->m->bash_line.end(); ++iter) - { + iter != this->m->bash_line.end(); + ++iter) { char ch = (*iter); - if (last_was_backslash) - { + if (last_was_backslash) { arg.append(1, ch); last_was_backslash = false; - } - else if (ch == '\\') - { + } else if (ch == '\\') { last_was_backslash = true; - } - else - { + } else { bool append = false; - switch (state) - { - case st_top: - if (QUtil::is_space(ch)) - { - if (! arg.empty()) - { + switch (state) { + case st_top: + if (QUtil::is_space(ch)) { + if (!arg.empty()) { this->m->bash_argv.push_back( QUtil::make_shared_cstr(arg)); arg.clear(); } - } - else if (ch == '"') - { + } else if (ch == '"') { state = st_dquote; - } - else if (ch == '\'') - { + } else if (ch == '\'') { state = st_squote; - } - else - { + } else { append = true; } break; - case st_squote: - if (ch == '\'') - { + case st_squote: + if (ch == '\'') { state = st_top; - } - else - { + } else { append = true; } break; - case st_dquote: - if (ch == '"') - { + case st_dquote: + if (ch == '"') { state = st_top; - } - else - { + } else { append = true; } break; } - if (append) - { + if (append) { arg.append(1, ch); } } } - if (this->m->bash_argv.empty()) - { + if (this->m->bash_argv.empty()) { // This can't happen if properly invoked by bash, but ensure // we have a valid argv[0] regardless. - this->m->bash_argv.push_back( - QUtil::make_shared_cstr(this->m->argv[0])); + this->m->bash_argv.push_back(QUtil::make_shared_cstr(this->m->argv[0])); } // Explicitly discard any non-space-terminated word. The "current // word" is handled specially. - this->m->bash_argv_ph = QUtil::make_shared_array( - 1 + this->m->bash_argv.size()); - for (size_t i = 0; i < this->m->bash_argv.size(); ++i) - { + this->m->bash_argv_ph = + QUtil::make_shared_array(1 + this->m->bash_argv.size()); + for (size_t i = 0; i < this->m->bash_argv.size(); ++i) { this->m->bash_argv_ph.get()[i] = this->m->bash_argv.at(i).get(); } this->m->argc = QIntC::to_int(this->m->bash_argv.size()); @@ -411,8 +363,7 @@ QPDFArgParser::handleBashArguments() void QPDFArgParser::usage(std::string const& message) { - if (this->m->bash_completion) - { + if (this->m->bash_completion) { // This will cause bash to fall back to regular file completion. exit(0); } @@ -423,18 +374,14 @@ void QPDFArgParser::readArgsFromFile(std::string const& filename) { std::list lines; - if (filename == "-") - { + if (filename == "-") { QTC::TC("libtests", "QPDFArgParser read args from stdin"); lines = QUtil::read_lines_from_file(std::cin); - } - else - { + } else { QTC::TC("libtests", "QPDFArgParser read args from file"); lines = QUtil::read_lines_from_file(filename.c_str()); } - for (auto const& line: lines) - { + for (auto const& line : lines) { this->m->new_argv.push_back(QUtil::make_shared_cstr(line)); } } @@ -452,17 +399,14 @@ QPDFArgParser::checkCompletion() // set together under ordinary circumstances. bool got_line = QUtil::get_env("COMP_LINE", &this->m->bash_line); bool got_point = QUtil::get_env("COMP_POINT", &bash_point_env); - if (got_line || got_point) - { + if (got_line || got_point) { size_t p = QUtil::string_to_uint(bash_point_env.c_str()); - if (p < this->m->bash_line.length()) - { + if (p < this->m->bash_line.length()) { // Truncate the line. We ignore everything at or after the // cursor for completion purposes. this->m->bash_line = this->m->bash_line.substr(0, p); } - if (p > this->m->bash_line.length()) - { + if (p > this->m->bash_line.length()) { p = this->m->bash_line.length(); } // Set bash_cur and bash_prev based on bash_line rather than @@ -475,52 +419,42 @@ QPDFArgParser::checkCompletion() // for the first separator. bash_cur is everything after the // last separator, possibly empty. char sep(0); - while (p > 0) - { + while (p > 0) { --p; char ch = this->m->bash_line.at(p); - if ((ch == ' ') || (ch == '=') || (ch == ':')) - { + if ((ch == ' ') || (ch == '=') || (ch == ':')) { sep = ch; break; } } - if (1+p <= this->m->bash_line.length()) - { - this->m->bash_cur = this->m->bash_line.substr( - 1+p, std::string::npos); + if (1 + p <= this->m->bash_line.length()) { + this->m->bash_cur = + this->m->bash_line.substr(1 + p, std::string::npos); } - if ((sep == ':') || (sep == '=')) - { + if ((sep == ':') || (sep == '=')) { // Bash sets prev to the non-space separator if any. // Actually, if there are multiple separators in a row, // they are all included in prev, but that detail is not // important to us and not worth coding. this->m->bash_prev = this->m->bash_line.substr(p, 1); - } - else - { + } else { // Go back to the last separator and set prev based on // that. size_t p1 = p; - while (p1 > 0) - { + while (p1 > 0) { --p1; char ch = this->m->bash_line.at(p1); - if ((ch == ' ') || (ch == ':') || (ch == '=')) - { + if ((ch == ' ') || (ch == ':') || (ch == '=')) { this->m->bash_prev = this->m->bash_line.substr(p1 + 1, p - p1 - 1); break; } } } - if (this->m->bash_prev.empty()) - { + if (this->m->bash_prev.empty()) { this->m->bash_prev = this->m->bash_line.substr(0, p); } - if (this->m->argc == 1) - { + if (this->m->argc == 1) { // This is probably zsh using bashcompinit. There are a // few differences in the expected output. this->m->zsh_completion = true; @@ -536,10 +470,8 @@ QPDFArgParser::parseArgs() selectMainOptionTable(); checkCompletion(); handleArgFileArguments(); - for (this->m->cur_arg = 1; - this->m->cur_arg < this->m->argc; - ++this->m->cur_arg) - { + for (this->m->cur_arg = 1; this->m->cur_arg < this->m->argc; + ++this->m->cur_arg) { bool help_option = false; bool end_option = false; auto oep = this->m->option_table->end(); @@ -548,29 +480,22 @@ QPDFArgParser::parseArgs() bool have_parameter = false; std::string o_arg(arg); std::string arg_s(arg); - if (strcmp(arg, "--") == 0) - { + if (strcmp(arg, "--") == 0) { // Special case for -- option, which is used to break out // of subparsers. oep = this->m->option_table->find("--"); end_option = true; - if (oep == this->m->option_table->end()) - { + if (oep == this->m->option_table->end()) { // This is registered automatically, so this can't happen. throw std::logic_error( "QPDFArgParser: -- handler not registered"); } - } - else if ((arg[0] == '-') && (strcmp(arg, "-") != 0)) - { + } else if ((arg[0] == '-') && (strcmp(arg, "-") != 0)) { ++arg; - if (arg[0] == '-') - { + if (arg[0] == '-') { // Be lax about -arg vs --arg ++arg; - } - else - { + } else { QTC::TC("libtests", "QPDFArgParser single dash"); } @@ -581,21 +506,18 @@ QPDFArgParser::parseArgs() // sense to have an empty option. arg_s = arg; size_t equal_pos = std::string::npos; - if (arg_s.length() > 0) - { + if (arg_s.length() > 0) { equal_pos = arg_s.find('=', 1); } - if (equal_pos != std::string::npos) - { + if (equal_pos != std::string::npos) { have_parameter = true; parameter = arg_s.substr(equal_pos + 1); arg_s = arg_s.substr(0, equal_pos); } - if ((! this->m->bash_completion) && - (this->m->argc == 2) && (this->m->cur_arg == 1) && - this->m->help_option_table.count(arg_s)) - { + if ((!this->m->bash_completion) && (this->m->argc == 2) && + (this->m->cur_arg == 1) && + this->m->help_option_table.count(arg_s)) { // Handle help option, which is only valid as the sole // option. QTC::TC("libtests", "QPDFArgParser help option"); @@ -603,13 +525,10 @@ QPDFArgParser::parseArgs() help_option = true; } - if (! (help_option || arg_s.empty() || (arg_s.at(0) == '-'))) - { + if (!(help_option || arg_s.empty() || (arg_s.at(0) == '-'))) { oep = this->m->option_table->find(arg_s); } - } - else - { + } else { // The empty string maps to the positional argument // handler. QTC::TC("libtests", "QPDFArgParser positional"); @@ -617,12 +536,10 @@ QPDFArgParser::parseArgs() parameter = arg; } - if (oep == this->m->option_table->end()) - { + if (oep == this->m->option_table->end()) { QTC::TC("libtests", "QPDFArgParser unrecognized"); std::string message = "unrecognized argument " + o_arg; - if (this->m->option_table != &this->m->main_option_table) - { + if (this->m->option_table != &this->m->main_option_table) { message += " (" + this->m->option_table_name + " options must be terminated with --)"; } @@ -630,70 +547,52 @@ QPDFArgParser::parseArgs() } OptionEntry& oe = oep->second; - if ((oe.parameter_needed && (! have_parameter)) || - ((! oe.choices.empty() && have_parameter && - (0 == oe.choices.count(parameter))))) - { + if ((oe.parameter_needed && (!have_parameter)) || + ((!oe.choices.empty() && have_parameter && + (0 == oe.choices.count(parameter))))) { std::string message = "--" + arg_s + " must be given as --" + arg_s + "="; - if (oe.invalid_choice_handler) - { + if (oe.invalid_choice_handler) { oe.invalid_choice_handler(parameter); // Method should call usage() or exit. Just in case it // doesn't... message += "option"; - } - else if (! oe.choices.empty()) - { + } else if (!oe.choices.empty()) { QTC::TC("libtests", "QPDFArgParser required choices"); message += "{"; - for (std::set::iterator iter = - oe.choices.begin(); - iter != oe.choices.end(); ++iter) - { - if (iter != oe.choices.begin()) - { + for (std::set::iterator iter = oe.choices.begin(); + iter != oe.choices.end(); + ++iter) { + if (iter != oe.choices.begin()) { message += ","; } message += *iter; } message += "}"; - } - else if (! oe.parameter_name.empty()) - { + } else if (!oe.parameter_name.empty()) { QTC::TC("libtests", "QPDFArgParser required parameter"); message += oe.parameter_name; - } - else - { + } else { // should not be possible message += "option"; } usage(message); } - if (oe.bare_arg_handler) - { + if (oe.bare_arg_handler) { oe.bare_arg_handler(); - } - else if (oe.param_arg_handler) - { + } else if (oe.param_arg_handler) { oe.param_arg_handler(parameter); } - if (help_option) - { + if (help_option) { exit(0); } - if (end_option) - { + if (end_option) { selectMainOptionTable(); } } - if (this->m->bash_completion) - { + if (this->m->bash_completion) { handleCompletion(); - } - else - { + } else { doFinalChecks(); } } @@ -707,29 +606,27 @@ QPDFArgParser::getProgname() void QPDFArgParser::doFinalChecks() { - if (this->m->option_table != &(this->m->main_option_table)) - { + if (this->m->option_table != &(this->m->main_option_table)) { QTC::TC("libtests", "QPDFArgParser missing --"); - usage("missing -- at end of " + this->m->option_table_name + - " options"); + usage( + "missing -- at end of " + this->m->option_table_name + " options"); } - if (this->m->final_check_handler != nullptr) - { + if (this->m->final_check_handler != nullptr) { this->m->final_check_handler(); } } void -QPDFArgParser::addChoicesToCompletions(option_table_t& option_table, - std::string const& option, - std::string const& extra_prefix) +QPDFArgParser::addChoicesToCompletions( + option_table_t& option_table, + std::string const& option, + std::string const& extra_prefix) { - if (option_table.count(option) != 0) - { + if (option_table.count(option) != 0) { OptionEntry& oe = option_table[option]; for (std::set::iterator iter = oe.choices.begin(); - iter != oe.choices.end(); ++iter) - { + iter != oe.choices.end(); + ++iter) { QTC::TC("libtests", "QPDFArgParser complete choices"); this->m->completions.insert(extra_prefix + *iter); } @@ -739,44 +636,37 @@ QPDFArgParser::addChoicesToCompletions(option_table_t& option_table, void QPDFArgParser::addOptionsToCompletions(option_table_t& option_table) { - for (auto& iter: option_table) - { + for (auto& iter : option_table) { std::string const& arg = iter.first; - if (arg == "--") - { + if (arg == "--") { continue; } OptionEntry& oe = iter.second; std::string base = "--" + arg; - if (oe.param_arg_handler) - { - if (this->m->zsh_completion) - { + if (oe.param_arg_handler) { + if (this->m->zsh_completion) { // zsh doesn't treat = as a word separator, so add all // the options so we don't get a space after the =. addChoicesToCompletions(option_table, arg, base + "="); } this->m->completions.insert(base + "="); } - if (! oe.parameter_needed) - { + if (!oe.parameter_needed) { this->m->completions.insert(base); } } } void -QPDFArgParser::insertCompletions(option_table_t& option_table, - std::string const& choice_option, - std::string const& extra_prefix) +QPDFArgParser::insertCompletions( + option_table_t& option_table, + std::string const& choice_option, + std::string const& extra_prefix) { - if (! choice_option.empty()) - { + if (!choice_option.empty()) { addChoicesToCompletions(option_table, choice_option, extra_prefix); - } - else if ((! this->m->bash_cur.empty()) && - (this->m->bash_cur.at(0) == '-')) - { + } else if ( + (!this->m->bash_cur.empty()) && (this->m->bash_cur.at(0) == '-')) { addOptionsToCompletions(option_table); } } @@ -785,51 +675,39 @@ void QPDFArgParser::handleCompletion() { std::string extra_prefix; - if (this->m->completions.empty()) - { + if (this->m->completions.empty()) { // Detect --option=... Bash treats the = as a word separator. std::string choice_option; if (this->m->bash_cur.empty() && (this->m->bash_prev.length() > 2) && (this->m->bash_prev.at(0) == '-') && (this->m->bash_prev.at(1) == '-') && - (this->m->bash_line.at(this->m->bash_line.length() - 1) == '=')) - { + (this->m->bash_line.at(this->m->bash_line.length() - 1) == '=')) { choice_option = this->m->bash_prev.substr(2, std::string::npos); - } - else if ((this->m->bash_prev == "=") && - (this->m->bash_line.length() > - (this->m->bash_cur.length() + 1))) - { + } else if ( + (this->m->bash_prev == "=") && + (this->m->bash_line.length() > (this->m->bash_cur.length() + 1))) { // We're sitting at --option=x. Find previous option. - size_t end_mark = this->m->bash_line.length() - - this->m->bash_cur.length() - 1; + size_t end_mark = + this->m->bash_line.length() - this->m->bash_cur.length() - 1; char before_cur = this->m->bash_line.at(end_mark); - if (before_cur == '=') - { + if (before_cur == '=') { size_t space = this->m->bash_line.find_last_of(' ', end_mark); - if (space != std::string::npos) - { - std::string candidate = - this->m->bash_line.substr( - space + 1, end_mark - space - 1); - if ((candidate.length() > 2) && - (candidate.at(0) == '-') && - (candidate.at(1) == '-')) - { - choice_option = - candidate.substr(2, std::string::npos); + if (space != std::string::npos) { + std::string candidate = this->m->bash_line.substr( + space + 1, end_mark - space - 1); + if ((candidate.length() > 2) && (candidate.at(0) == '-') && + (candidate.at(1) == '-')) { + choice_option = candidate.substr(2, std::string::npos); } } } } - if (this->m->zsh_completion && (! choice_option.empty())) - { + if (this->m->zsh_completion && (!choice_option.empty())) { // zsh wants --option=choice rather than just choice extra_prefix = "--" + choice_option + "="; } insertCompletions(*this->m->option_table, choice_option, extra_prefix); - if (this->m->argc == 1) - { + if (this->m->argc == 1) { // Help options are valid only by themselves. insertCompletions( this->m->help_option_table, choice_option, extra_prefix); @@ -837,11 +715,9 @@ QPDFArgParser::handleCompletion() } std::string prefix = extra_prefix + this->m->bash_cur; for (std::set::iterator iter = this->m->completions.begin(); - iter != this->m->completions.end(); ++iter) - { - if (prefix.empty() || - ((*iter).substr(0, prefix.length()) == prefix)) - { + iter != this->m->completions.end(); + ++iter) { + if (prefix.empty() || ((*iter).substr(0, prefix.length()) == prefix)) { std::cout << *iter << std::endl; } } @@ -855,24 +731,22 @@ QPDFArgParser::addHelpFooter(std::string const& text) } void -QPDFArgParser::addHelpTopic(std::string const& topic, - std::string const& short_text, - std::string const& long_text) +QPDFArgParser::addHelpTopic( + std::string const& topic, + std::string const& short_text, + std::string const& long_text) { - if (topic == "all") - { + if (topic == "all") { QTC::TC("libtests", "QPDFArgParser add reserved help topic"); throw std::logic_error( "QPDFArgParser: can't register reserved help topic " + topic); } - if (! ((topic.length() > 0) && (topic.at(0) != '-'))) - { + if (!((topic.length() > 0) && (topic.at(0) != '-'))) { QTC::TC("libtests", "QPDFArgParser bad topic for help"); throw std::logic_error( "QPDFArgParser: help topics must not start with -"); } - if (this->m->help_topics.count(topic)) - { + if (this->m->help_topics.count(topic)) { QTC::TC("libtests", "QPDFArgParser add existing topic"); throw std::logic_error( "QPDFArgParser: topic " + topic + " has already been added"); @@ -883,28 +757,25 @@ QPDFArgParser::addHelpTopic(std::string const& topic, } void -QPDFArgParser::addOptionHelp(std::string const& option_name, - std::string const& topic, - std::string const& short_text, - std::string const& long_text) +QPDFArgParser::addOptionHelp( + std::string const& option_name, + std::string const& topic, + std::string const& short_text, + std::string const& long_text) { - if (! ((option_name.length() > 2) && - (option_name.at(0) == '-') && - (option_name.at(1) == '-'))) - { + if (!((option_name.length() > 2) && (option_name.at(0) == '-') && + (option_name.at(1) == '-'))) { QTC::TC("libtests", "QPDFArgParser bad option for help"); throw std::logic_error( "QPDFArgParser: options for help must start with --"); } - if (this->m->option_help.count(option_name)) - { + if (this->m->option_help.count(option_name)) { QTC::TC("libtests", "QPDFArgParser duplicate option help"); throw std::logic_error( "QPDFArgParser: option " + option_name + " already has help"); } auto ht = this->m->help_topics.find(topic); - if (ht == this->m->help_topics.end()) - { + if (ht == this->m->help_topics.end()) { QTC::TC("libtests", "QPDFArgParser add to unknown topic"); throw std::logic_error( "QPDFArgParser: unable to add option " + option_name + @@ -918,16 +789,15 @@ QPDFArgParser::addOptionHelp(std::string const& option_name, void QPDFArgParser::getTopHelp(std::ostringstream& msg) { - msg << "Run \"" << this->m->whoami - << " --help=topic\" for help on a topic." << std::endl + msg << "Run \"" << this->m->whoami << " --help=topic\" for help on a topic." + << std::endl << "Run \"" << this->m->whoami << " --help=--option\" for help on an option." << std::endl << "Run \"" << this->m->whoami << " --help=all\" to see all available help." << std::endl << std::endl << "Topics:" << std::endl; - for (auto const& i: this->m->help_topics) - { + for (auto const& i : this->m->help_topics) { msg << " " << i.first << ": " << i.second.short_text << std::endl; } } @@ -937,13 +807,11 @@ QPDFArgParser::getAllHelp(std::ostringstream& msg) { getTopHelp(msg); auto show = [this, &msg](std::map& topics) { - for (auto const& i: topics) - { + for (auto const& i : topics) { auto const& topic = i.first; msg << std::endl - << "== " << topic - << " (" << i.second.short_text << ") ==" - << std::endl + << "== " << topic << " (" << i.second.short_text + << ") ==" << std::endl << std::endl; getTopicHelp(topic, i.second, msg); } @@ -954,25 +822,19 @@ QPDFArgParser::getAllHelp(std::ostringstream& msg) } void -QPDFArgParser::getTopicHelp(std::string const& name, - HelpTopic const& ht, - std::ostringstream& msg) +QPDFArgParser::getTopicHelp( + std::string const& name, HelpTopic const& ht, std::ostringstream& msg) { - if (ht.long_text.empty()) - { + if (ht.long_text.empty()) { msg << ht.short_text << std::endl; - } - else - { + } else { msg << ht.long_text; } - if (! ht.options.empty()) - { + if (!ht.options.empty()) { msg << std::endl << "Related options:" << std::endl; - for (auto const& i: ht.options) - { - msg << " " << i << ": " - << this->m->option_help[i].short_text << std::endl; + for (auto const& i : ht.options) { + msg << " " << i << ": " << this->m->option_help[i].short_text + << std::endl; } } } @@ -981,26 +843,16 @@ std::string QPDFArgParser::getHelp(std::string const& arg) { std::ostringstream msg; - if (arg.empty()) - { + if (arg.empty()) { getTopHelp(msg); - } - else - { - if (arg == "all") - { + } else { + if (arg == "all") { getAllHelp(msg); - } - else if (this->m->option_help.count(arg)) - { + } else if (this->m->option_help.count(arg)) { getTopicHelp(arg, this->m->option_help[arg], msg); - } - else if (this->m->help_topics.count(arg)) - { + } else if (this->m->help_topics.count(arg)) { getTopicHelp(arg, this->m->help_topics[arg], msg); - } - else - { + } else { // should not be possible getTopHelp(msg); } diff --git a/libqpdf/QPDFCryptoProvider.cc b/libqpdf/QPDFCryptoProvider.cc index 705f403d..6d147d4d 100644 --- a/libqpdf/QPDFCryptoProvider.cc +++ b/libqpdf/QPDFCryptoProvider.cc @@ -1,7 +1,7 @@ #include -#include #include +#include #include #ifdef USE_CRYPTO_NATIVE @@ -18,8 +18,7 @@ std::shared_ptr QPDFCryptoProvider::getImpl() { QPDFCryptoProvider& p = getInstance(); - if (p.m->default_provider.empty()) - { + if (p.m->default_provider.empty()) { throw std::logic_error( "QPDFCryptoProvider::getImpl called with no default provider."); } @@ -32,7 +31,7 @@ QPDFCryptoProvider::getImpl(std::string const& name) return getInstance().getImpl_internal(name); } -template +template void QPDFCryptoProvider::registerImpl(std::string const& name) { @@ -58,8 +57,7 @@ QPDFCryptoProvider::QPDFCryptoProvider() : registerImpl_internal("openssl"); #endif std::string default_crypto; - if (! QUtil::get_env("QPDF_CRYPTO_PROVIDER", &default_crypto)) - { + if (!QUtil::get_env("QPDF_CRYPTO_PROVIDER", &default_crypto)) { default_crypto = DEFAULT_CRYPTO; } setDefaultProvider_internal(default_crypto); @@ -76,28 +74,25 @@ std::shared_ptr QPDFCryptoProvider::getImpl_internal(std::string const& name) const { auto iter = this->m->providers.find(name); - if (iter == this->m->providers.end()) - { + if (iter == this->m->providers.end()) { throw std::logic_error( - "QPDFCryptoProvider requested unknown implementation \"" + - name + "\""); + "QPDFCryptoProvider requested unknown implementation \"" + name + + "\""); } return this->m->providers[name](); } -template +template void QPDFCryptoProvider::registerImpl_internal(std::string const& name) { this->m->providers[name] = std::make_shared; - } void QPDFCryptoProvider::setDefaultProvider_internal(std::string const& name) { - if (! this->m->providers.count(name)) - { + if (!this->m->providers.count(name)) { throw std::logic_error( "QPDFCryptoProvider: request to set default" " provider to unknown implementation \"" + @@ -111,8 +106,7 @@ QPDFCryptoProvider::getRegisteredImpls() { std::set result; QPDFCryptoProvider& p = getInstance(); - for (auto const& iter: p.m->providers) - { + for (auto const& iter : p.m->providers) { result.insert(iter.first); } return result; diff --git a/libqpdf/QPDFCrypto_gnutls.cc b/libqpdf/QPDFCrypto_gnutls.cc index 8c05f314..86e92c40 100644 --- a/libqpdf/QPDFCrypto_gnutls.cc +++ b/libqpdf/QPDFCrypto_gnutls.cc @@ -18,12 +18,10 @@ QPDFCrypto_gnutls::QPDFCrypto_gnutls() : QPDFCrypto_gnutls::~QPDFCrypto_gnutls() { - if (this->hash_ctx) - { + if (this->hash_ctx) { gnutls_hash_deinit(this->hash_ctx, digest); } - if (cipher_ctx) - { + if (cipher_ctx) { gnutls_cipher_deinit(this->cipher_ctx); } this->aes_key_data = nullptr; @@ -33,9 +31,8 @@ QPDFCrypto_gnutls::~QPDFCrypto_gnutls() void QPDFCrypto_gnutls::provideRandomData(unsigned char* data, size_t len) { - int code = gnutls_rnd (GNUTLS_RND_KEY, data, len); - if (code < 0) - { + int code = gnutls_rnd(GNUTLS_RND_KEY, data, len); + if (code < 0) { throw std::runtime_error( std::string("gnutls: random number generation error: ") + std::string(gnutls_strerror(code))); @@ -47,8 +44,7 @@ QPDFCrypto_gnutls::MD5_init() { MD5_finalize(); int code = gnutls_hash_init(&this->hash_ctx, GNUTLS_DIG_MD5); - if (code < 0) - { + if (code < 0) { this->hash_ctx = nullptr; throw std::runtime_error( std::string("gnutls: MD5 error: ") + @@ -65,8 +61,7 @@ QPDFCrypto_gnutls::MD5_update(unsigned char const* data, size_t len) void QPDFCrypto_gnutls::MD5_finalize() { - if (this->hash_ctx) - { + if (this->hash_ctx) { gnutls_hash_deinit(this->hash_ctx, this->digest); this->hash_ctx = nullptr; } @@ -82,10 +77,9 @@ void QPDFCrypto_gnutls::RC4_init(unsigned char const* key_data, int key_len) { RC4_finalize(); - if (key_len == -1) - { - key_len = QIntC::to_int( - strlen(reinterpret_cast(key_data))); + if (key_len == -1) { + key_len = + QIntC::to_int(strlen(reinterpret_cast(key_data))); } gnutls_datum_t key; key.data = const_cast(key_data); @@ -93,8 +87,7 @@ QPDFCrypto_gnutls::RC4_init(unsigned char const* key_data, int key_len) int code = gnutls_cipher_init( &this->cipher_ctx, GNUTLS_CIPHER_ARCFOUR_128, &key, nullptr); - if (code < 0) - { + if (code < 0) { this->cipher_ctx = nullptr; throw std::runtime_error( std::string("gnutls: RC4 error: ") + @@ -103,11 +96,10 @@ QPDFCrypto_gnutls::RC4_init(unsigned char const* key_data, int key_len) } void -QPDFCrypto_gnutls::RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data) +QPDFCrypto_gnutls::RC4_process( + unsigned char* in_data, size_t len, unsigned char* out_data) { - if (nullptr == out_data) - { + if (nullptr == out_data) { out_data = in_data; } gnutls_cipher_encrypt2(this->cipher_ctx, in_data, len, out_data, len); @@ -116,8 +108,7 @@ QPDFCrypto_gnutls::RC4_process(unsigned char* in_data, size_t len, void QPDFCrypto_gnutls::RC4_finalize() { - if (this->cipher_ctx) - { + if (this->cipher_ctx) { gnutls_cipher_deinit(this->cipher_ctx); this->cipher_ctx = nullptr; } @@ -128,25 +119,23 @@ QPDFCrypto_gnutls::SHA2_init(int bits) { SHA2_finalize(); gnutls_digest_algorithm_t alg = GNUTLS_DIG_UNKNOWN; - switch (bits) - { - case 256: + switch (bits) { + case 256: alg = GNUTLS_DIG_SHA256; break; - case 384: + case 384: alg = GNUTLS_DIG_SHA384; break; - case 512: + case 512: alg = GNUTLS_DIG_SHA512; break; - default: + default: badBits(); break; } this->sha2_bits = bits; int code = gnutls_hash_init(&this->hash_ctx, alg); - if (code < 0) - { + if (code < 0) { this->hash_ctx = nullptr; throw std::runtime_error( std::string("gnutls: SHA") + QUtil::int_to_string(bits) + @@ -163,8 +152,7 @@ QPDFCrypto_gnutls::SHA2_update(unsigned char const* data, size_t len) void QPDFCrypto_gnutls::SHA2_finalize() { - if (this->hash_ctx) - { + if (this->hash_ctx) { gnutls_hash_deinit(this->hash_ctx, this->digest); this->hash_ctx = nullptr; } @@ -174,18 +162,17 @@ std::string QPDFCrypto_gnutls::SHA2_digest() { std::string result; - switch (this->sha2_bits) - { - case 256: + switch (this->sha2_bits) { + case 256: result = std::string(reinterpret_cast(this->digest), 32); break; - case 384: + case 384: result = std::string(reinterpret_cast(this->digest), 48); break; - case 512: + case 512: result = std::string(reinterpret_cast(this->digest), 64); break; - default: + default: badBits(); break; } @@ -194,14 +181,16 @@ QPDFCrypto_gnutls::SHA2_digest() void QPDFCrypto_gnutls::rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block) + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block) { rijndael_finalize(); this->encrypt = encrypt; this->cbc_mode = cbc_mode; - if (! cbc_mode) - { + if (!cbc_mode) { // Save the key so we can re-initialize. this->aes_key_data = key_data; this->aes_key_len = key_len; @@ -213,18 +202,17 @@ QPDFCrypto_gnutls::rijndael_init( cipher_key.data = const_cast(key_data); - switch(key_len) - { - case 16: + switch (key_len) { + case 16: alg = GNUTLS_CIPHER_AES_128_CBC; break; - case 32: + case 32: alg = GNUTLS_CIPHER_AES_256_CBC; break; - case 24: + case 24: alg = GNUTLS_CIPHER_AES_192_CBC; break; - default: + default: alg = GNUTLS_CIPHER_AES_128_CBC; break; } @@ -235,8 +223,7 @@ QPDFCrypto_gnutls::rijndael_init( iv.size = rijndael_buf_size; int code = gnutls_cipher_init(&this->cipher_ctx, alg, &cipher_key, &iv); - if (code < 0) - { + if (code < 0) { this->cipher_ctx = nullptr; throw std::runtime_error( std::string("gnutls: AES error: ") + @@ -245,39 +232,45 @@ QPDFCrypto_gnutls::rijndael_init( } void -QPDFCrypto_gnutls::rijndael_process(unsigned char* in_data, - unsigned char* out_data) +QPDFCrypto_gnutls::rijndael_process( + unsigned char* in_data, unsigned char* out_data) { - if (this->encrypt) - { - gnutls_cipher_encrypt2(this->cipher_ctx, - in_data, rijndael_buf_size, - out_data, rijndael_buf_size); - } - else - { - gnutls_cipher_decrypt2(this->cipher_ctx, - in_data, rijndael_buf_size, - out_data, rijndael_buf_size); + if (this->encrypt) { + gnutls_cipher_encrypt2( + this->cipher_ctx, + in_data, + rijndael_buf_size, + out_data, + rijndael_buf_size); + } else { + gnutls_cipher_decrypt2( + this->cipher_ctx, + in_data, + rijndael_buf_size, + out_data, + rijndael_buf_size); } // Gnutls doesn't support AES in ECB (non-CBC) mode, but the // result is the same as if you just reset the cbc block to all // zeroes each time. We jump through a few hoops here to make this // work. - if (! this->cbc_mode) - { - static unsigned char zeroes[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - rijndael_init(this->encrypt, this->aes_key_data, this->aes_key_len, - false, zeroes); + if (!this->cbc_mode) { + static unsigned char zeroes[16] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + rijndael_init( + this->encrypt, + this->aes_key_data, + this->aes_key_len, + false, + zeroes); } } void QPDFCrypto_gnutls::rijndael_finalize() { - if (this->cipher_ctx) - { + if (this->cipher_ctx) { gnutls_cipher_deinit(this->cipher_ctx); this->cipher_ctx = nullptr; } diff --git a/libqpdf/QPDFCrypto_native.cc b/libqpdf/QPDFCrypto_native.cc index 22340648..5255ba30 100644 --- a/libqpdf/QPDFCrypto_native.cc +++ b/libqpdf/QPDFCrypto_native.cc @@ -7,7 +7,8 @@ #endif #include -static RandomDataProvider* getRandomProvider() +static RandomDataProvider* +getRandomProvider() { #ifdef USE_INSECURE_RANDOM static RandomDataProvider* insecure_random_data_provider = @@ -18,13 +19,12 @@ static RandomDataProvider* getRandomProvider() static RandomDataProvider* secure_random_data_provider = SecureRandomDataProvider::getInstance(); - static RandomDataProvider* provider = ( - secure_random_data_provider ? secure_random_data_provider - : insecure_random_data_provider ? insecure_random_data_provider - : 0); + static RandomDataProvider* provider = + (secure_random_data_provider ? secure_random_data_provider + : insecure_random_data_provider ? insecure_random_data_provider + : 0); - if (provider == 0) - { + if (provider == 0) { throw std::logic_error("QPDFCrypto_native has no random data provider"); } @@ -68,8 +68,8 @@ QPDFCrypto_native::RC4_init(unsigned char const* key_data, int key_len) } void -QPDFCrypto_native::RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data) +QPDFCrypto_native::RC4_process( + unsigned char* in_data, size_t len, unsigned char* out_data) { this->rc4->process(in_data, len, out_data); } @@ -105,8 +105,11 @@ QPDFCrypto_native::SHA2_digest() void QPDFCrypto_native::rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block) + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block) { this->aes_pdf = std::make_shared( @@ -114,8 +117,8 @@ QPDFCrypto_native::rijndael_init( } void -QPDFCrypto_native::rijndael_process(unsigned char* in_data, - unsigned char* out_data) +QPDFCrypto_native::rijndael_process( + unsigned char* in_data, unsigned char* out_data) { this->aes_pdf->update(in_data, out_data); } diff --git a/libqpdf/QPDFCrypto_openssl.cc b/libqpdf/QPDFCrypto_openssl.cc index 427ce5bb..a281bf79 100644 --- a/libqpdf/QPDFCrypto_openssl.cc +++ b/libqpdf/QPDFCrypto_openssl.cc @@ -28,8 +28,7 @@ bad_bits(int bits) static void check_openssl(int status) { - if (status != 1) - { + if (status != 1) { // OpenSSL creates a "queue" of errors; copy the first (innermost) // error to the exception message. char buf[256] = ""; @@ -50,21 +49,18 @@ QPDFCrypto_openssl::QPDFCrypto_openssl() : { #ifndef QPDF_OPENSSL_1 libctx = OSSL_LIB_CTX_new(); - if (libctx == nullptr) - { + if (libctx == nullptr) { throw std::runtime_error("unable to create openssl library context"); return; } legacy = OSSL_PROVIDER_load(libctx, "legacy"); - if (legacy == nullptr) - { + if (legacy == nullptr) { OSSL_LIB_CTX_free(libctx); throw std::runtime_error("unable to load openssl legacy provider"); return; } rc4 = EVP_CIPHER_fetch(libctx, "RC4", nullptr); - if (rc4 == nullptr) - { + if (rc4 == nullptr) { OSSL_PROVIDER_unload(legacy); OSSL_LIB_CTX_free(libctx); throw std::runtime_error("unable to load openssl rc4 algorithm"); @@ -106,18 +102,17 @@ void QPDFCrypto_openssl::SHA2_init(int bits) { const EVP_MD* md = EVP_sha512(); - switch (bits) - { - case 256: + switch (bits) { + case 256: md = EVP_sha256(); break; - case 384: + case 384: md = EVP_sha384(); break; - case 512: + case 512: md = EVP_sha512(); break; - default: + default: bad_bits(bits); return; } @@ -146,8 +141,7 @@ QPDFCrypto_openssl::MD5_finalize() #else auto md = EVP_MD_CTX_get0_md(md_ctx); #endif - if (md) - { + if (md) { check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr)); } } @@ -160,9 +154,8 @@ QPDFCrypto_openssl::SHA2_finalize() #else auto md = EVP_MD_CTX_get0_md(md_ctx); #endif - if (md) - { - check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr)); + if (md) { + check_openssl(EVP_DigestFinal(md_ctx, md_out + 0, nullptr)); } } @@ -182,10 +175,9 @@ void QPDFCrypto_openssl::RC4_init(unsigned char const* key_data, int key_len) { check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx)); - if (key_len == -1) - { - key_len = QIntC::to_int( - strlen(reinterpret_cast(key_data))); + if (key_len == -1) { + key_len = + QIntC::to_int(strlen(reinterpret_cast(key_data))); } check_openssl( EVP_EncryptInit_ex(cipher_ctx, rc4, nullptr, nullptr, nullptr)); @@ -196,27 +188,28 @@ QPDFCrypto_openssl::RC4_init(unsigned char const* key_data, int key_len) void QPDFCrypto_openssl::rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block) + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block) { const EVP_CIPHER* cipher = nullptr; - switch (key_len) - { - case 32: + switch (key_len) { + case 32: cipher = cbc_mode ? EVP_aes_256_cbc() : EVP_aes_256_ecb(); break; - case 24: + case 24: cipher = cbc_mode ? EVP_aes_192_cbc() : EVP_aes_192_ecb(); break; - default: + default: cipher = cbc_mode ? EVP_aes_128_cbc() : EVP_aes_128_ecb(); break; } check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx)); - check_openssl( - EVP_CipherInit_ex(cipher_ctx, cipher, nullptr, - key_data, cbc_block, encrypt)); + check_openssl(EVP_CipherInit_ex( + cipher_ctx, cipher, nullptr, key_data, cbc_block, encrypt)); check_openssl(EVP_CIPHER_CTX_set_padding(cipher_ctx, 0)); } @@ -224,8 +217,7 @@ void QPDFCrypto_openssl::RC4_process( unsigned char* in_data, size_t len, unsigned char* out_data) { - if (nullptr == out_data) - { + if (nullptr == out_data) { out_data = in_data; } int out_len = static_cast(len); @@ -244,8 +236,7 @@ QPDFCrypto_openssl::rijndael_process( void QPDFCrypto_openssl::RC4_finalize() { - if (EVP_CIPHER_CTX_cipher(cipher_ctx)) - { + if (EVP_CIPHER_CTX_cipher(cipher_ctx)) { check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx)); } } @@ -253,8 +244,7 @@ QPDFCrypto_openssl::RC4_finalize() void QPDFCrypto_openssl::rijndael_finalize() { - if (EVP_CIPHER_CTX_cipher(cipher_ctx)) - { + if (EVP_CIPHER_CTX_cipher(cipher_ctx)) { check_openssl(EVP_CIPHER_CTX_reset(cipher_ctx)); } } diff --git a/libqpdf/QPDFEFStreamObjectHelper.cc b/libqpdf/QPDFEFStreamObjectHelper.cc index ef44c1c1..de11e30f 100644 --- a/libqpdf/QPDFEFStreamObjectHelper.cc +++ b/libqpdf/QPDFEFStreamObjectHelper.cc @@ -1,13 +1,12 @@ #include +#include +#include +#include #include #include -#include -#include -#include -QPDFEFStreamObjectHelper::QPDFEFStreamObjectHelper( - QPDFObjectHandle oh) : +QPDFEFStreamObjectHelper::QPDFEFStreamObjectHelper(QPDFObjectHandle oh) : QPDFObjectHelper(oh), m(new Members()) { @@ -21,8 +20,7 @@ QPDFObjectHandle QPDFEFStreamObjectHelper::getParam(std::string const& pkey) { auto params = this->oh.getDict().getKey("/Params"); - if (params.isDictionary()) - { + if (params.isDictionary()) { return params.getKey(pkey); } return QPDFObjectHandle::newNull(); @@ -33,8 +31,7 @@ QPDFEFStreamObjectHelper::setParam( std::string const& pkey, QPDFObjectHandle const& pval) { auto params = this->oh.getDict().getKey("/Params"); - if (! params.isDictionary()) - { + if (!params.isDictionary()) { params = QPDFObjectHandle::newDictionary(); this->oh.getDict().replaceKey("/Params", params); } @@ -45,8 +42,7 @@ std::string QPDFEFStreamObjectHelper::getCreationDate() { auto val = getParam("/CreationDate"); - if (val.isString()) - { + if (val.isString()) { return val.getUTF8Value(); } return ""; @@ -56,8 +52,7 @@ std::string QPDFEFStreamObjectHelper::getModDate() { auto val = getParam("/ModDate"); - if (val.isString()) - { + if (val.isString()) { return val.getUTF8Value(); } return ""; @@ -67,8 +62,7 @@ size_t QPDFEFStreamObjectHelper::getSize() { auto val = getParam("/Size"); - if (val.isInteger()) - { + if (val.isInteger()) { return QIntC::to_size(val.getUIntValueAsUInt()); } return 0; @@ -78,11 +72,9 @@ std::string QPDFEFStreamObjectHelper::getSubtype() { auto val = this->oh.getDict().getKey("/Subtype"); - if (val.isName()) - { + if (val.isName()) { auto n = val.getName(); - if (n.length() > 1) - { + if (n.length() > 1) { return n.substr(1); } } @@ -93,23 +85,20 @@ std::string QPDFEFStreamObjectHelper::getChecksum() { auto val = getParam("/CheckSum"); - if (val.isString()) - { + if (val.isString()) { return val.getStringValue(); } return ""; } QPDFEFStreamObjectHelper -QPDFEFStreamObjectHelper::createEFStream( - QPDF& qpdf, PointerHolder data) +QPDFEFStreamObjectHelper::createEFStream(QPDF& qpdf, PointerHolder data) { return newFromStream(QPDFObjectHandle::newStream(&qpdf, data)); } QPDFEFStreamObjectHelper -QPDFEFStreamObjectHelper::createEFStream( - QPDF& qpdf, std::string const& data) +QPDFEFStreamObjectHelper::createEFStream(QPDF& qpdf, std::string const& data) { return newFromStream(QPDFObjectHandle::newStream(&qpdf, data)); } @@ -119,9 +108,8 @@ QPDFEFStreamObjectHelper::createEFStream( QPDF& qpdf, std::function provider) { auto stream = QPDFObjectHandle::newStream(&qpdf); - stream.replaceStreamData(provider, - QPDFObjectHandle::newNull(), - QPDFObjectHandle::newNull()); + stream.replaceStreamData( + provider, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); return newFromStream(stream); } @@ -156,18 +144,15 @@ QPDFEFStreamObjectHelper::newFromStream(QPDFObjectHandle stream) Pl_Discard discard; Pl_MD5 md5("EF md5", &discard); Pl_Count count("EF size", &md5); - if (! stream.pipeStreamData(&count, nullptr, 0, qpdf_dl_all)) - { + if (!stream.pipeStreamData(&count, nullptr, 0, qpdf_dl_all)) { stream.warnIfPossible( "unable to get stream data for new embedded file stream"); - } - else - { + } else { result.setParam( "/Size", QPDFObjectHandle::newInteger(count.getCount())); result.setParam( - "/CheckSum", QPDFObjectHandle::newString( - QUtil::hex_decode(md5.getHexDigest()))); + "/CheckSum", + QPDFObjectHandle::newString(QUtil::hex_decode(md5.getHexDigest()))); } return result; } diff --git a/libqpdf/QPDFEmbeddedFileDocumentHelper.cc b/libqpdf/QPDFEmbeddedFileDocumentHelper.cc index 6348529d..4e2bd3cd 100644 --- a/libqpdf/QPDFEmbeddedFileDocumentHelper.cc +++ b/libqpdf/QPDFEmbeddedFileDocumentHelper.cc @@ -37,11 +37,9 @@ QPDFEmbeddedFileDocumentHelper::QPDFEmbeddedFileDocumentHelper(QPDF& qpdf) : { auto root = qpdf.getRoot(); auto names = root.getKey("/Names"); - if (names.isDictionary()) - { + if (names.isDictionary()) { auto embedded_files = names.getKey("/EmbeddedFiles"); - if (embedded_files.isDictionary()) - { + if (embedded_files.isDictionary()) { this->m->embedded_files = std::make_shared( embedded_files, qpdf); @@ -62,20 +60,17 @@ QPDFEmbeddedFileDocumentHelper::hasEmbeddedFiles() const void QPDFEmbeddedFileDocumentHelper::initEmbeddedFiles() { - if (hasEmbeddedFiles()) - { + if (hasEmbeddedFiles()) { return; } auto root = qpdf.getRoot(); auto names = root.getKey("/Names"); - if (! names.isDictionary()) - { + if (!names.isDictionary()) { names = QPDFObjectHandle::newDictionary(); root.replaceKey("/Names", names); } auto embedded_files = names.getKey("/EmbeddedFiles"); - if (! embedded_files.isDictionary()) - { + if (!embedded_files.isDictionary()) { auto nth = QPDFNameTreeObjectHelper::newEmpty(this->qpdf); names.replaceKey("/EmbeddedFiles", nth.getObjectHandle()); this->m->embedded_files = @@ -87,11 +82,9 @@ std::shared_ptr QPDFEmbeddedFileDocumentHelper::getEmbeddedFile(std::string const& name) { std::shared_ptr result; - if (this->m->embedded_files) - { + if (this->m->embedded_files) { auto i = this->m->embedded_files->find(name); - if (i != this->m->embedded_files->end()) - { + if (i != this->m->embedded_files->end()) { result = std::make_shared(i->second); } } @@ -101,14 +94,11 @@ QPDFEmbeddedFileDocumentHelper::getEmbeddedFile(std::string const& name) std::map> QPDFEmbeddedFileDocumentHelper::getEmbeddedFiles() { - std::map> result; - if (this->m->embedded_files) - { - for (auto const& i: *(this->m->embedded_files)) - { - result[i.first] = std::make_shared( - i.second); + std::map> result; + if (this->m->embedded_files) { + for (auto const& i : *(this->m->embedded_files)) { + result[i.first] = + std::make_shared(i.second); } } return result; @@ -119,26 +109,22 @@ QPDFEmbeddedFileDocumentHelper::replaceEmbeddedFile( std::string const& name, QPDFFileSpecObjectHelper const& fs) { initEmbeddedFiles(); - this->m->embedded_files->insert( - name, fs.getObjectHandle()); + this->m->embedded_files->insert(name, fs.getObjectHandle()); } bool QPDFEmbeddedFileDocumentHelper::removeEmbeddedFile(std::string const& name) { - if (! hasEmbeddedFiles()) - { + if (!hasEmbeddedFiles()) { return false; } auto iter = this->m->embedded_files->find(name); - if (iter == this->m->embedded_files->end()) - { + if (iter == this->m->embedded_files->end()) { return false; } auto oh = iter->second; iter.remove(); - if (oh.isIndirect()) - { + if (oh.isIndirect()) { this->qpdf.replaceObject(oh.getObjGen(), QPDFObjectHandle::newNull()); } diff --git a/libqpdf/QPDFExc.cc b/libqpdf/QPDFExc.cc index df8ceaff..6c270c82 100644 --- a/libqpdf/QPDFExc.cc +++ b/libqpdf/QPDFExc.cc @@ -2,11 +2,12 @@ #include -QPDFExc::QPDFExc(qpdf_error_code_e error_code, - std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message) : +QPDFExc::QPDFExc( + qpdf_error_code_e error_code, + std::string const& filename, + std::string const& object, + qpdf_offset_t offset, + std::string const& message) : std::runtime_error(createWhat(filename, object, offset, message)), error_code(error_code), filename(filename), @@ -17,41 +18,34 @@ QPDFExc::QPDFExc(qpdf_error_code_e error_code, } std::string -QPDFExc::createWhat(std::string const& filename, - std::string const& object, - qpdf_offset_t offset, - std::string const& message) +QPDFExc::createWhat( + std::string const& filename, + std::string const& object, + qpdf_offset_t offset, + std::string const& message) { std::string result; - if (! filename.empty()) - { + if (!filename.empty()) { result += filename; } - if (! (object.empty() && offset == 0)) - { - if (! filename.empty()) - { + if (!(object.empty() && offset == 0)) { + if (!filename.empty()) { result += " ("; } - if (! object.empty()) - { + if (!object.empty()) { result += object; - if (offset > 0) - { + if (offset > 0) { result += ", "; } } - if (offset > 0) - { + if (offset > 0) { result += "offset " + QUtil::int_to_string(offset); } - if (! filename.empty()) - { + if (!filename.empty()) { result += ")"; } } - if (! result.empty()) - { + if (!result.empty()) { result += ": "; } result += message; diff --git a/libqpdf/QPDFFileSpecObjectHelper.cc b/libqpdf/QPDFFileSpecObjectHelper.cc index 43be4699..7f7932e3 100644 --- a/libqpdf/QPDFFileSpecObjectHelper.cc +++ b/libqpdf/QPDFFileSpecObjectHelper.cc @@ -1,23 +1,20 @@ #include -#include #include +#include #include -#include #include +#include -QPDFFileSpecObjectHelper::QPDFFileSpecObjectHelper( - QPDFObjectHandle oh) : +QPDFFileSpecObjectHelper::QPDFFileSpecObjectHelper(QPDFObjectHandle oh) : QPDFObjectHelper(oh) { - if (! oh.isDictionary()) - { + if (!oh.isDictionary()) { oh.warnIfPossible("Embedded file object is not a dictionary"); return; } - if (! oh.isDictionaryOfType("/Filespec")) - { + if (!oh.isDictionaryOfType("/Filespec")) { oh.warnIfPossible("Embedded file object's type is not /Filespec"); } } @@ -34,8 +31,7 @@ QPDFFileSpecObjectHelper::getDescription() { std::string result; auto desc = this->oh.getKey("/Desc"); - if (desc.isString()) - { + if (desc.isString()) { result = desc.getUTF8Value(); } return result; @@ -44,11 +40,9 @@ QPDFFileSpecObjectHelper::getDescription() std::string QPDFFileSpecObjectHelper::getFilename() { - for (auto const& i: name_keys) - { + for (auto const& i : name_keys) { auto k = this->oh.getKey(i); - if (k.isString()) - { + if (k.isString()) { return k.getUTF8Value(); } } @@ -59,11 +53,9 @@ std::map QPDFFileSpecObjectHelper::getFilenames() { std::map result; - for (auto const& i: name_keys) - { + for (auto const& i : name_keys) { auto k = this->oh.getKey(i); - if (k.isString()) - { + if (k.isString()) { result[i] = k.getUTF8Value(); } } @@ -74,19 +66,15 @@ QPDFObjectHandle QPDFFileSpecObjectHelper::getEmbeddedFileStream(std::string const& key) { auto ef = this->oh.getKey("/EF"); - if (! ef.isDictionary()) - { + if (!ef.isDictionary()) { return QPDFObjectHandle::newNull(); } - if (! key.empty()) - { + if (!key.empty()) { return ef.getKey(key); } - for (auto const& i: name_keys) - { + for (auto const& i : name_keys) { auto k = ef.getKey(i); - if (k.isStream()) - { + if (k.isStream()) { return k; } } @@ -101,22 +89,18 @@ QPDFFileSpecObjectHelper::getEmbeddedFileStreams() QPDFFileSpecObjectHelper QPDFFileSpecObjectHelper::createFileSpec( - QPDF& qpdf, - std::string const& filename, - std::string const& fullpath) + QPDF& qpdf, std::string const& filename, std::string const& fullpath) { return createFileSpec( - qpdf, filename, + qpdf, + filename, QPDFEFStreamObjectHelper::createEFStream( - qpdf, - QUtil::file_provider(fullpath))); + qpdf, QUtil::file_provider(fullpath))); } QPDFFileSpecObjectHelper QPDFFileSpecObjectHelper::createFileSpec( - QPDF& qpdf, - std::string const& filename, - QPDFEFStreamObjectHelper efsoh) + QPDF& qpdf, std::string const& filename, QPDFEFStreamObjectHelper efsoh) { auto oh = qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()); oh.replaceKey("/Type", QPDFObjectHandle::newName("/Filespec")); @@ -138,18 +122,14 @@ QPDFFileSpecObjectHelper::setDescription(std::string const& desc) QPDFFileSpecObjectHelper& QPDFFileSpecObjectHelper::setFilename( - std::string const& unicode_name, - std::string const& compat_name) + std::string const& unicode_name, std::string const& compat_name) { auto uf = QPDFObjectHandle::newUnicodeString(unicode_name); this->oh.replaceKey("/UF", uf); - if (compat_name.empty()) - { + if (compat_name.empty()) { QTC::TC("qpdf", "QPDFFileSpecObjectHelper empty compat_name"); this->oh.replaceKey("/F", uf); - } - else - { + } else { QTC::TC("qpdf", "QPDFFileSpecObjectHelper non-empty compat_name"); this->oh.replaceKey("/F", QPDFObjectHandle::newString(compat_name)); } diff --git a/libqpdf/QPDFFormFieldObjectHelper.cc b/libqpdf/QPDFFormFieldObjectHelper.cc index 7124826c..664e66fc 100644 --- a/libqpdf/QPDFFormFieldObjectHelper.cc +++ b/libqpdf/QPDFFormFieldObjectHelper.cc @@ -1,11 +1,11 @@ #include -#include -#include -#include -#include #include #include +#include +#include +#include +#include #include QPDFFormFieldObjectHelper::Members::~Members() @@ -46,16 +46,13 @@ QPDFFormFieldObjectHelper::getTopLevelField(bool* is_different) auto top_field = this->oh; std::set seen; while (top_field.isDictionary() && - (! top_field.getKey("/Parent").isNull())) - { + (!top_field.getKey("/Parent").isNull())) { top_field = top_field.getKey("/Parent"); - if (is_different) - { + if (is_different) { *is_different = true; } auto og = top_field.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { break; } seen.insert(og); @@ -69,13 +66,11 @@ QPDFFormFieldObjectHelper::getFieldFromAcroForm(std::string const& name) QPDFObjectHandle result = QPDFObjectHandle::newNull(); // Fields are supposed to be indirect, so this should work. QPDF* q = this->oh.getOwningQPDF(); - if (! q) - { + if (!q) { return result; } auto acroform = q->getRoot().getKey("/AcroForm"); - if (! acroform.isDictionary()) - { + if (!acroform.isDictionary()) { return result; } return acroform.getKey(name); @@ -85,24 +80,21 @@ QPDFObjectHandle QPDFFormFieldObjectHelper::getInheritableFieldValue(std::string const& name) { QPDFObjectHandle node = this->oh; - if (! node.isDictionary()) - { + if (!node.isDictionary()) { return QPDFObjectHandle::newNull(); } QPDFObjectHandle result(node.getKey(name)); std::set seen; - while (result.isNull() && node.hasKey("/Parent")) - { + while (result.isNull() && node.hasKey("/Parent")) { seen.insert(node.getObjGen()); node = node.getKey("/Parent"); - if (seen.count(node.getObjGen())) - { + if (seen.count(node.getObjGen())) { break; } result = node.getKey(name); - if (! result.isNull()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper non-trivial inheritance"); + if (!result.isNull()) { + QTC::TC( + "qpdf", "QPDFFormFieldObjectHelper non-trivial inheritance"); } } return result; @@ -114,8 +106,7 @@ QPDFFormFieldObjectHelper::getInheritableFieldValueAsString( { QPDFObjectHandle fv = getInheritableFieldValue(name); std::string result; - if (fv.isString()) - { + if (fv.isString()) { result = fv.getUTF8Value(); } return result; @@ -127,8 +118,7 @@ QPDFFormFieldObjectHelper::getInheritableFieldValueAsName( { QPDFObjectHandle fv = getInheritableFieldValue(name); std::string result; - if (fv.isName()) - { + if (fv.isName()) { result = fv.getName(); } return result; @@ -146,13 +136,12 @@ QPDFFormFieldObjectHelper::getFullyQualifiedName() std::string result; QPDFObjectHandle node = this->oh; std::set seen; - while ((! node.isNull()) && (seen.count(node.getObjGen()) == 0)) - { - if (node.getKey("/T").isString()) - { - if (! result.empty()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper non-trivial qualified name"); + while ((!node.isNull()) && (seen.count(node.getObjGen()) == 0)) { + if (node.getKey("/T").isString()) { + if (!result.empty()) { + QTC::TC( + "qpdf", + "QPDFFormFieldObjectHelper non-trivial qualified name"); result = "." + result; } result = node.getKey("/T").getUTF8Value() + result; @@ -167,8 +156,7 @@ std::string QPDFFormFieldObjectHelper::getPartialName() { std::string result; - if (this->oh.getKey("/T").isString()) - { + if (this->oh.getKey("/T").isString()) { result = this->oh.getKey("/T").getUTF8Value(); } return result; @@ -177,8 +165,7 @@ QPDFFormFieldObjectHelper::getPartialName() std::string QPDFFormFieldObjectHelper::getAlternativeName() { - if (this->oh.getKey("/TU").isString()) - { + if (this->oh.getKey("/TU").isString()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper TU present"); return this->oh.getKey("/TU").getUTF8Value(); } @@ -189,8 +176,7 @@ QPDFFormFieldObjectHelper::getAlternativeName() std::string QPDFFormFieldObjectHelper::getMappingName() { - if (this->oh.getKey("/TM").isString()) - { + if (this->oh.getKey("/TM").isString()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper TM present"); return this->oh.getKey("/TM").getUTF8Value(); } @@ -233,16 +219,16 @@ QPDFFormFieldObjectHelper::getDefaultAppearance() { auto value = getInheritableFieldValue("/DA"); bool looked_in_acroform = false; - if (! value.isString()) - { + if (!value.isString()) { value = getFieldFromAcroForm("/DA"); looked_in_acroform = true; } std::string result; - if (value.isString()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper DA present", - looked_in_acroform ? 0 : 1); + if (value.isString()) { + QTC::TC( + "qpdf", + "QPDFFormFieldObjectHelper DA present", + looked_in_acroform ? 0 : 1); result = value.getUTF8Value(); } return result; @@ -253,16 +239,16 @@ QPDFFormFieldObjectHelper::getQuadding() { QPDFObjectHandle fv = getInheritableFieldValue("/Q"); bool looked_in_acroform = false; - if (! fv.isInteger()) - { + if (!fv.isInteger()) { fv = getFieldFromAcroForm("/Q"); looked_in_acroform = true; } int result = 0; - if (fv.isInteger()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper Q present", - looked_in_acroform ? 0 : 1); + if (fv.isInteger()) { + QTC::TC( + "qpdf", + "QPDFFormFieldObjectHelper Q present", + looked_in_acroform ? 0 : 1); result = QIntC::to_int(fv.getIntValue()); } return result; @@ -284,22 +270,25 @@ QPDFFormFieldObjectHelper::isText() bool QPDFFormFieldObjectHelper::isCheckbox() { - return ((getFieldType() == "/Btn") && - ((getFlags() & (ff_btn_radio | ff_btn_pushbutton)) == 0)); + return ( + (getFieldType() == "/Btn") && + ((getFlags() & (ff_btn_radio | ff_btn_pushbutton)) == 0)); } bool QPDFFormFieldObjectHelper::isRadioButton() { - return ((getFieldType() == "/Btn") && - ((getFlags() & ff_btn_radio) == ff_btn_radio)); + return ( + (getFieldType() == "/Btn") && + ((getFlags() & ff_btn_radio) == ff_btn_radio)); } bool QPDFFormFieldObjectHelper::isPushbutton() { - return ((getFieldType() == "/Btn") && - ((getFlags() & ff_btn_pushbutton) == ff_btn_pushbutton)); + return ( + (getFieldType() == "/Btn") && + ((getFlags() & ff_btn_pushbutton) == ff_btn_pushbutton)); } bool @@ -312,19 +301,15 @@ std::vector QPDFFormFieldObjectHelper::getChoices() { std::vector result; - if (! isChoice()) - { + if (!isChoice()) { return result; } QPDFObjectHandle opt = getInheritableFieldValue("/Opt"); - if (opt.isArray()) - { + if (opt.isArray()) { int n = opt.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { QPDFObjectHandle item = opt.getArrayItem(i); - if (item.isString()) - { + if (item.isString()) { result.push_back(item.getUTF8Value()); } } @@ -347,64 +332,46 @@ QPDFFormFieldObjectHelper::setFieldAttribute( } void -QPDFFormFieldObjectHelper::setV( - QPDFObjectHandle value, bool need_appearances) +QPDFFormFieldObjectHelper::setV(QPDFObjectHandle value, bool need_appearances) { - if (getFieldType() == "/Btn") - { - if (isCheckbox()) - { + if (getFieldType() == "/Btn") { + if (isCheckbox()) { bool okay = false; - if (value.isName()) - { + if (value.isName()) { std::string name = value.getName(); - if ((name == "/Yes") || (name == "/Off")) - { + if ((name == "/Yes") || (name == "/Off")) { okay = true; setCheckBoxValue((name == "/Yes")); } } - if (! okay) - { + if (!okay) { this->oh.warnIfPossible( "ignoring attempt to set a checkbox field to a" " value of other than /Yes or /Off"); } - } - else if (isRadioButton()) - { - if (value.isName()) - { + } else if (isRadioButton()) { + if (value.isName()) { setRadioButtonValue(value); - } - else - { + } else { this->oh.warnIfPossible( "ignoring attempt to set a radio button field to" " an object that is not a name"); } - } - else if (isPushbutton()) - { + } else if (isPushbutton()) { this->oh.warnIfPossible( "ignoring attempt set the value of a pushbutton field"); } return; } - if (value.isString()) - { + if (value.isString()) { setFieldAttribute( "/V", QPDFObjectHandle::newUnicodeString(value.getUTF8Value())); - } - else - { + } else { setFieldAttribute("/V", value); } - if (need_appearances) - { + if (need_appearances) { QPDF* qpdf = this->oh.getOwningQPDF(); - if (! qpdf) - { + if (!qpdf) { throw std::logic_error( "QPDFFormFieldObjectHelper::setV called with" " need_appearances = true on an object that is" @@ -418,8 +385,7 @@ void QPDFFormFieldObjectHelper::setV( std::string const& utf8_value, bool need_appearances) { - setV(QPDFObjectHandle::newUnicodeString(utf8_value), - need_appearances); + setV(QPDFObjectHandle::newUnicodeString(utf8_value), need_appearances); } void @@ -438,74 +404,62 @@ QPDFFormFieldObjectHelper::setRadioButtonValue(QPDFObjectHandle name) // Note that we never turn on /NeedAppearances when setting a // radio button field. QPDFObjectHandle parent = this->oh.getKey("/Parent"); - if (parent.isDictionary() && parent.getKey("/Parent").isNull()) - { + if (parent.isDictionary() && parent.getKey("/Parent").isNull()) { QPDFFormFieldObjectHelper ph(parent); - if (ph.isRadioButton()) - { + if (ph.isRadioButton()) { // This is most likely one of the individual buttons. Try // calling on the parent. - QTC::TC("qpdf", "QPDFFormFieldObjectHelper set parent radio button"); + QTC::TC( + "qpdf", "QPDFFormFieldObjectHelper set parent radio button"); ph.setRadioButtonValue(name); return; } } QPDFObjectHandle kids = this->oh.getKey("/Kids"); - if (! (isRadioButton() && parent.isNull() && kids.isArray())) - { + if (!(isRadioButton() && parent.isNull() && kids.isArray())) { this->oh.warnIfPossible("don't know how to set the value" " of this field as a radio button"); return; } setFieldAttribute("/V", name); int nkids = kids.getArrayNItems(); - for (int i = 0; i < nkids; ++i) - { + for (int i = 0; i < nkids; ++i) { QPDFObjectHandle kid = kids.getArrayItem(i); QPDFObjectHandle AP = kid.getKey("/AP"); QPDFObjectHandle annot; - if (AP.isNull()) - { + if (AP.isNull()) { // The widget may be below. If there is more than one, // just find the first one. QPDFObjectHandle grandkids = kid.getKey("/Kids"); - if (grandkids.isArray()) - { + if (grandkids.isArray()) { int ngrandkids = grandkids.getArrayNItems(); - for (int j = 0; j < ngrandkids; ++j) - { + for (int j = 0; j < ngrandkids; ++j) { QPDFObjectHandle grandkid = grandkids.getArrayItem(j); AP = grandkid.getKey("/AP"); - if (! AP.isNull()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper radio button grandkid"); + if (!AP.isNull()) { + QTC::TC( + "qpdf", + "QPDFFormFieldObjectHelper radio button grandkid"); annot = grandkid; break; } } } - } - else - { + } else { annot = kid; } - if (! annot.isInitialized()) - { + if (!annot.isInitialized()) { QTC::TC("qpdf", "QPDFObjectHandle broken radio button"); this->oh.warnIfPossible( "unable to set the value of this radio button"); continue; } - if (AP.isDictionary() && - AP.getKey("/N").isDictionary() && - AP.getKey("/N").hasKey(name.getName())) - { + if (AP.isDictionary() && AP.getKey("/N").isDictionary() && + AP.getKey("/N").hasKey(name.getName())) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper turn on radio button"); annot.replaceKey("/AS", name); - } - else - { + } else { QTC::TC("qpdf", "QPDFFormFieldObjectHelper turn off radio button"); annot.replaceKey("/AS", QPDFObjectHandle::newName("/Off")); } @@ -516,41 +470,34 @@ void QPDFFormFieldObjectHelper::setCheckBoxValue(bool value) { // Set /AS to /Yes or /Off in addition to setting /V. - QPDFObjectHandle name = - QPDFObjectHandle::newName(value ? "/Yes" : "/Off"); + QPDFObjectHandle name = QPDFObjectHandle::newName(value ? "/Yes" : "/Off"); setFieldAttribute("/V", name); QPDFObjectHandle AP = this->oh.getKey("/AP"); QPDFObjectHandle annot; - if (AP.isNull()) - { + if (AP.isNull()) { // The widget may be below. If there is more than one, just // find the first one. QPDFObjectHandle kids = this->oh.getKey("/Kids"); - if (kids.isArray()) - { + if (kids.isArray()) { int nkids = kids.getArrayNItems(); - for (int i = 0; i < nkids; ++i) - { + for (int i = 0; i < nkids; ++i) { QPDFObjectHandle kid = kids.getArrayItem(i); AP = kid.getKey("/AP"); - if (! AP.isNull()) - { - QTC::TC("qpdf", "QPDFFormFieldObjectHelper checkbox kid widget"); + if (!AP.isNull()) { + QTC::TC( + "qpdf", + "QPDFFormFieldObjectHelper checkbox kid widget"); annot = kid; break; } } } - } - else - { + } else { annot = this->oh; } - if (! annot.isInitialized()) - { + if (!annot.isInitialized()) { QTC::TC("qpdf", "QPDFObjectHandle broken checkbox"); - this->oh.warnIfPossible( - "unable to set the value of this checkbox"); + this->oh.warnIfPossible("unable to set the value of this checkbox"); return; } QTC::TC("qpdf", "QPDFFormFieldObjectHelper set checkbox AS"); @@ -564,8 +511,7 @@ QPDFFormFieldObjectHelper::generateAppearance(QPDFAnnotationObjectHelper& aoh) // Ignore field types we don't know how to generate appearances // for. Button fields don't really need them -- see code in // QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded. - if ((ft == "/Tx") || (ft == "/Ch")) - { + if ((ft == "/Tx") || (ft == "/Ch")) { generateTextAppearance(aoh); } } @@ -573,9 +519,12 @@ QPDFFormFieldObjectHelper::generateAppearance(QPDFAnnotationObjectHelper& aoh) class ValueSetter: public QPDFObjectHandle::TokenFilter { public: - ValueSetter(std::string const& DA, std::string const& V, - std::vector const& opt, double tf, - QPDFObjectHandle::Rectangle const& bbox); + ValueSetter( + std::string const& DA, + std::string const& V, + std::vector const& opt, + double tf, + QPDFObjectHandle::Rectangle const& bbox); virtual ~ValueSetter() { } @@ -593,9 +542,12 @@ class ValueSetter: public QPDFObjectHandle::TokenFilter bool replaced; }; -ValueSetter::ValueSetter(std::string const& DA, std::string const& V, - std::vector const& opt, double tf, - QPDFObjectHandle::Rectangle const& bbox) : +ValueSetter::ValueSetter( + std::string const& DA, + std::string const& V, + std::vector const& opt, + double tf, + QPDFObjectHandle::Rectangle const& bbox) : DA(DA), V(V), opt(opt), @@ -612,42 +564,35 @@ ValueSetter::handleToken(QPDFTokenizer::Token const& token) QPDFTokenizer::token_type_e ttype = token.getType(); std::string value = token.getValue(); bool do_replace = false; - switch (state) - { - case st_top: - writeToken(token); - if ((ttype == QPDFTokenizer::tt_word) && (value == "BMC")) - { - state = st_bmc; - } - break; - - case st_bmc: - if ((ttype == QPDFTokenizer::tt_space) || - (ttype == QPDFTokenizer::tt_comment)) - { - writeToken(token); + switch (state) { + case st_top: + writeToken(token); + if ((ttype == QPDFTokenizer::tt_word) && (value == "BMC")) { + state = st_bmc; } - else - { + break; + + case st_bmc: + if ((ttype == QPDFTokenizer::tt_space) || + (ttype == QPDFTokenizer::tt_comment)) { + writeToken(token); + } else { state = st_emc; } // fall through to emc - case st_emc: - if ((ttype == QPDFTokenizer::tt_word) && (value == "EMC")) - { + case st_emc: + if ((ttype == QPDFTokenizer::tt_word) && (value == "EMC")) { do_replace = true; state = st_end; } break; - case st_end: + case st_end: writeToken(token); break; } - if (do_replace) - { + if (do_replace) { writeAppearance(); } } @@ -655,8 +600,7 @@ ValueSetter::handleToken(QPDFTokenizer::Token const& token) void ValueSetter::handleEOF() { - if (! this->replaced) - { + if (!this->replaced) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper replaced BMC at EOF"); write("/Tx BMC\n"); writeAppearance(); @@ -683,42 +627,33 @@ ValueSetter::writeAppearance() size_t highlight_idx = 0; std::vector lines; - if (opt.empty() || (max_rows < 2)) - { + if (opt.empty() || (max_rows < 2)) { lines.push_back(V); - } - else - { + } else { // Figure out what rows to write size_t nopt = opt.size(); size_t found_idx = 0; bool found = false; - for (found_idx = 0; found_idx < nopt; ++found_idx) - { - if (opt.at(found_idx) == V) - { + for (found_idx = 0; found_idx < nopt; ++found_idx) { + if (opt.at(found_idx) == V) { found = true; break; } } - if (found) - { + if (found) { // Try to make the found item the second one, but // adjust for under/overflow. int wanted_first = QIntC::to_int(found_idx) - 1; int wanted_last = QIntC::to_int(found_idx + max_rows) - 2; QTC::TC("qpdf", "QPDFFormFieldObjectHelper list found"); - while (wanted_first < 0) - { + while (wanted_first < 0) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper list first too low"); ++wanted_first; ++wanted_last; } - while (wanted_last >= QIntC::to_int(nopt)) - { + while (wanted_last >= QIntC::to_int(nopt)) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper list last too high"); - if (wanted_first > 0) - { + if (wanted_first > 0) { --wanted_first; } --wanted_last; @@ -726,20 +661,17 @@ ValueSetter::writeAppearance() highlight = true; highlight_idx = found_idx - QIntC::to_size(wanted_first); for (size_t i = QIntC::to_size(wanted_first); - i <= QIntC::to_size(wanted_last); ++i) - { + i <= QIntC::to_size(wanted_last); + ++i) { lines.push_back(opt.at(i)); } - } - else - { + } else { QTC::TC("qpdf", "QPDFFormFieldObjectHelper list not found"); // include our value and the first n-1 rows highlight_idx = 0; highlight = true; lines.push_back(V); - for (size_t i = 0; ((i < nopt) && (i < (max_rows - 1))); ++i) - { + for (size_t i = 0; ((i < nopt) && (i < (max_rows - 1))); ++i) { lines.push_back(opt.at(i)); } } @@ -747,36 +679,31 @@ ValueSetter::writeAppearance() // Write the lines centered vertically, highlighting if needed size_t nlines = lines.size(); - double dy = bbox.ury - ((bbox.ury - bbox.lly - - (static_cast(nlines) * tfh)) / 2.0); - if (highlight) - { - write("q\n0.85 0.85 0.85 rg\n" + - QUtil::double_to_string(bbox.llx) + " " + - QUtil::double_to_string( - bbox.lly + dy - - (tfh * (static_cast(highlight_idx + 1)))) + " " + - QUtil::double_to_string(bbox.urx - bbox.llx) + " " + - QUtil::double_to_string(tfh) + - " re f\nQ\n"); + double dy = bbox.ury - + ((bbox.ury - bbox.lly - (static_cast(nlines) * tfh)) / 2.0); + if (highlight) { + write( + "q\n0.85 0.85 0.85 rg\n" + QUtil::double_to_string(bbox.llx) + " " + + QUtil::double_to_string( + bbox.lly + dy - + (tfh * (static_cast(highlight_idx + 1)))) + + " " + QUtil::double_to_string(bbox.urx - bbox.llx) + " " + + QUtil::double_to_string(tfh) + " re f\nQ\n"); } dy -= tf; write("q\nBT\n" + DA + "\n"); - for (size_t i = 0; i < nlines; ++i) - { + for (size_t i = 0; i < nlines; ++i) { // We could adjust Tm to translate to the beginning the first // line, set TL to tfh, and use T* for each subsequent line, // but doing this would require extracting any Tm from DA, // which doesn't seem really worth the effort. - if (i == 0) - { - write(QUtil::double_to_string(bbox.llx + static_cast(dx)) + - " " + - QUtil::double_to_string(bbox.lly + static_cast(dy)) + - " Td\n"); - } - else - { + if (i == 0) { + write( + QUtil::double_to_string(bbox.llx + static_cast(dx)) + + " " + + QUtil::double_to_string(bbox.lly + static_cast(dy)) + + " Td\n"); + } else { write("0 " + QUtil::double_to_string(-tfh) + " Td\n"); } write(QPDFObjectHandle::newString(lines.at(i)).unparse() + " Tj\n"); @@ -820,23 +747,20 @@ TfFinder::handleToken(QPDFTokenizer::Token const& token) QPDFTokenizer::token_type_e ttype = token.getType(); std::string value = token.getValue(); DA.push_back(token.getRawValue()); - switch (ttype) - { - case QPDFTokenizer::tt_integer: - case QPDFTokenizer::tt_real: + switch (ttype) { + case QPDFTokenizer::tt_integer: + case QPDFTokenizer::tt_real: last_num = strtod(value.c_str(), 0); last_num_idx = QIntC::to_int(DA.size() - 1); break; - case QPDFTokenizer::tt_name: + case QPDFTokenizer::tt_name: last_name = value; break; - case QPDFTokenizer::tt_word: - if (value == "Tf") - { - if ((last_num > 1.0) && (last_num < 1000.0)) - { + case QPDFTokenizer::tt_word: + if (value == "Tf") { + if ((last_num > 1.0) && (last_num < 1000.0)) { // These ranges are arbitrary but keep us from doing // insane things or suffering from over/underflow tf = last_num; @@ -846,7 +770,7 @@ TfFinder::handleToken(QPDFTokenizer::Token const& token) } break; - default: + default: break; } } @@ -862,14 +786,11 @@ TfFinder::getDA() { std::string result; size_t n = this->DA.size(); - for (size_t i = 0; i < n; ++i) - { + for (size_t i = 0; i < n; ++i) { std::string cur = this->DA.at(i); - if (QIntC::to_int(i) == tf_idx) - { + if (QIntC::to_int(i) == tf_idx) { double delta = strtod(cur.c_str(), 0) - this->tf; - if ((delta > 0.001) || (delta < -0.001)) - { + if ((delta > 0.001) || (delta < -0.001)) { // tf doesn't match the font size passed to Tf, so // substitute. QTC::TC("qpdf", "QPDFFormFieldObjectHelper fallback Tf"); @@ -892,10 +813,8 @@ QPDFFormFieldObjectHelper::getFontFromResource( QPDFObjectHandle resources, std::string const& name) { QPDFObjectHandle result; - if (resources.isDictionary() && - resources.getKey("/Font").isDictionary() && - resources.getKey("/Font").hasKey(name)) - { + if (resources.isDictionary() && resources.getKey("/Font").isDictionary() && + resources.getKey("/Font").hasKey(name)) { result = resources.getKey("/Font").getKey(name); } return result; @@ -906,8 +825,7 @@ QPDFFormFieldObjectHelper::generateTextAppearance( QPDFAnnotationObjectHelper& aoh) { QPDFObjectHandle AS = aoh.getAppearanceStream("/N"); - if (AS.isNull()) - { + if (AS.isNull()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper create AS from scratch"); QPDFObjectHandle::Rectangle rect = aoh.getRect(); QPDFObjectHandle::Rectangle bbox( @@ -920,8 +838,7 @@ QPDFFormFieldObjectHelper::generateTextAppearance( this->oh.getOwningQPDF(), "/Tx BMC\nEMC\n"); AS.replaceDict(dict); QPDFObjectHandle AP = aoh.getAppearanceDictionary(); - if (AP.isNull()) - { + if (AP.isNull()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper create AP from scratch"); aoh.getObjectHandle().replaceKey( "/AP", QPDFObjectHandle::newDictionary()); @@ -929,15 +846,13 @@ QPDFFormFieldObjectHelper::generateTextAppearance( } AP.replaceKey("/N", AS); } - if (! AS.isStream()) - { + if (!AS.isStream()) { aoh.getObjectHandle().warnIfPossible( "unable to get normal appearance stream for update"); return; } QPDFObjectHandle bbox_obj = AS.getDict().getKey("/BBox"); - if (! bbox_obj.isRectangle()) - { + if (!bbox_obj.isRectangle()) { aoh.getObjectHandle().warnIfPossible( "unable to get appearance stream bounding box"); return; @@ -946,8 +861,7 @@ QPDFFormFieldObjectHelper::generateTextAppearance( std::string DA = getDefaultAppearance(); std::string V = getValueAsString(); std::vector opt; - if (isChoice() && ((getFlags() & ff_ch_combo) == 0)) - { + if (isChoice() && ((getFlags() & ff_ch_combo) == 0)) { opt = getChoices(); } @@ -960,23 +874,19 @@ QPDFFormFieldObjectHelper::generateTextAppearance( std::string (*encoder)(std::string const&, char) = &QUtil::utf8_to_ascii; std::string font_name = tff.getFontName(); - if (! font_name.empty()) - { + if (!font_name.empty()) { // See if the font is encoded with something we know about. QPDFObjectHandle resources = AS.getDict().getKey("/Resources"); QPDFObjectHandle font = getFontFromResource(resources, font_name); bool found_font_in_dr = false; - if (! font.isInitialized()) - { + if (!font.isInitialized()) { QPDFObjectHandle dr = getDefaultResources(); font = getFontFromResource(dr, font_name); found_font_in_dr = (font.isInitialized() && font.isDictionary()); } - if (found_font_in_dr && resources.isDictionary()) - { + if (found_font_in_dr && resources.isDictionary()) { QTC::TC("qpdf", "QPDFFormFieldObjectHelper get font from /DR"); - if (resources.isIndirect()) - { + if (resources.isIndirect()) { resources = resources.getOwningQPDF()->makeIndirectObject( resources.shallowCopy()); AS.getDict().replaceKey("/Resources", resources); @@ -986,30 +896,23 @@ QPDFFormFieldObjectHelper::generateTextAppearance( resources.getKey("/Font").replaceKey(font_name, font); } - if (font.isInitialized() && - font.isDictionary() && - font.getKey("/Encoding").isName()) - { + if (font.isInitialized() && font.isDictionary() && + font.getKey("/Encoding").isName()) { std::string encoding = font.getKey("/Encoding").getName(); - if (encoding == "/WinAnsiEncoding") - { + if (encoding == "/WinAnsiEncoding") { QTC::TC("qpdf", "QPDFFormFieldObjectHelper WinAnsi"); encoder = &QUtil::utf8_to_win_ansi; - } - else if (encoding == "/MacRomanEncoding") - { + } else if (encoding == "/MacRomanEncoding") { encoder = &QUtil::utf8_to_mac_roman; } } } V = (*encoder)(V, '?'); - for (size_t i = 0; i < opt.size(); ++i) - { + for (size_t i = 0; i < opt.size(); ++i) { opt.at(i) = (*encoder)(opt.at(i), '?'); } - AS.addTokenFilter( - PointerHolder( - new ValueSetter(DA, V, opt, tf, bbox))); + AS.addTokenFilter(PointerHolder( + new ValueSetter(DA, V, opt, tf, bbox))); } diff --git a/libqpdf/QPDFJob.cc b/libqpdf/QPDFJob.cc index 1d0811ef..cfef7b8a 100644 --- a/libqpdf/QPDFJob.cc +++ b/libqpdf/QPDFJob.cc @@ -8,30 +8,30 @@ #include #include -#include -#include #include #include -#include -#include -#include #include +#include +#include #include +#include +#include +#include +#include #include -#include -#include -#include -#include #include -#include -#include -#include +#include #include #include -#include +#include +#include +#include +#include +#include +#include +#include #include -#include #include // JOB_SCHEMA_DATA @@ -40,18 +40,19 @@ namespace class ImageOptimizer: public QPDFObjectHandle::StreamDataProvider { public: - ImageOptimizer(QPDFJob& o, - size_t oi_min_width, - size_t oi_min_height, - size_t oi_min_area, - QPDFObjectHandle& image); + ImageOptimizer( + QPDFJob& o, + size_t oi_min_width, + size_t oi_min_height, + size_t oi_min_area, + QPDFObjectHandle& image); virtual ~ImageOptimizer() { } - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); - std::shared_ptr makePipeline( - std::string const& description, Pipeline* next); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); + std::shared_ptr + makePipeline(std::string const& description, Pipeline* next); bool evaluate(std::string const& description); private: @@ -65,15 +66,23 @@ namespace class DiscardContents: public QPDFObjectHandle::ParserCallbacks { public: - virtual ~DiscardContents() {} - virtual void handleObject(QPDFObjectHandle) {} - virtual void handleEOF() {} + virtual ~DiscardContents() + { + } + virtual void + handleObject(QPDFObjectHandle) + { + } + virtual void + handleEOF() + { + } }; struct QPDFPageData { - QPDFPageData(std::string const& filename, - QPDF* qpdf, std::string const& range); + QPDFPageData( + std::string const& filename, QPDF* qpdf, std::string const& range); QPDFPageData(QPDFPageData const& other, int page); std::string filename; @@ -85,9 +94,10 @@ namespace class ProgressReporter: public QPDFWriter::ProgressReporter { public: - ProgressReporter(std::ostream& cout, - std::string const& prefix, - char const* filename) : + ProgressReporter( + std::ostream& cout, + std::string const& prefix, + char const* filename) : cout(cout), prefix(prefix), filename(filename) @@ -98,18 +108,20 @@ namespace } virtual void reportProgress(int); + private: std::ostream& cout; std::string prefix; std::string filename; }; -} +} // namespace -ImageOptimizer::ImageOptimizer(QPDFJob& o, - size_t oi_min_width, - size_t oi_min_height, - size_t oi_min_area, - QPDFObjectHandle& image) : +ImageOptimizer::ImageOptimizer( + QPDFJob& o, + size_t oi_min_width, + size_t oi_min_height, + size_t oi_min_area, + QPDFObjectHandle& image) : o(o), oi_min_width(oi_min_width), oi_min_height(oi_min_height), @@ -126,10 +138,8 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) QPDFObjectHandle w_obj = dict.getKey("/Width"); QPDFObjectHandle h_obj = dict.getKey("/Height"); QPDFObjectHandle colorspace_obj = dict.getKey("/ColorSpace"); - if (! (w_obj.isNumber() && h_obj.isNumber())) - { - if (! description.empty()) - { + if (!(w_obj.isNumber() && h_obj.isNumber())) { + if (!description.empty()) { o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description << ": not optimizing because image dictionary" @@ -139,11 +149,9 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) return result; } QPDFObjectHandle components_obj = dict.getKey("/BitsPerComponent"); - if (! (components_obj.isInteger() && (components_obj.getIntValue() == 8))) - { + if (!(components_obj.isInteger() && (components_obj.getIntValue() == 8))) { QTC::TC("qpdf", "QPDFJob image optimize bits per component"); - if (! description.empty()) - { + if (!description.empty()) { o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description << ": not optimizing because image has other than" @@ -155,48 +163,33 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) // Files have been seen in the wild whose width and height are // floating point, which is goofy, but we can deal with it. JDIMENSION w = 0; - if (w_obj.isInteger()) - { + if (w_obj.isInteger()) { w = w_obj.getUIntValueAsUInt(); - } - else - { + } else { w = static_cast(w_obj.getNumericValue()); } JDIMENSION h = 0; - if (h_obj.isInteger()) - { + if (h_obj.isInteger()) { h = h_obj.getUIntValueAsUInt(); - } - else - { + } else { h = static_cast(h_obj.getNumericValue()); } - std::string colorspace = (colorspace_obj.isName() ? - colorspace_obj.getName() : - std::string()); + std::string colorspace = + (colorspace_obj.isName() ? colorspace_obj.getName() : std::string()); int components = 0; J_COLOR_SPACE cs = JCS_UNKNOWN; - if (colorspace == "/DeviceRGB") - { + if (colorspace == "/DeviceRGB") { components = 3; cs = JCS_RGB; - } - else if (colorspace == "/DeviceGray") - { + } else if (colorspace == "/DeviceGray") { components = 1; cs = JCS_GRAYSCALE; - } - else if (colorspace == "/DeviceCMYK") - { + } else if (colorspace == "/DeviceCMYK") { components = 4; cs = JCS_CMYK; - } - else - { + } else { QTC::TC("qpdf", "QPDFJob image optimize colorspace"); - if (! description.empty()) - { + if (!description.empty()) { o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description << ": not optimizing because qpdf can't optimize" @@ -207,11 +200,9 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) } if (((this->oi_min_width > 0) && (w <= this->oi_min_width)) || ((this->oi_min_height > 0) && (h <= this->oi_min_height)) || - ((this->oi_min_area > 0) && ((w * h) <= this->oi_min_area))) - { + ((this->oi_min_area > 0) && ((w * h) <= this->oi_min_area))) { QTC::TC("qpdf", "QPDFJob image optimize too small"); - if (! description.empty()) - { + if (!description.empty()) { o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description << ": not optimizing because image" @@ -229,32 +220,27 @@ ImageOptimizer::makePipeline(std::string const& description, Pipeline* next) bool ImageOptimizer::evaluate(std::string const& description) { - if (! image.pipeStreamData(0, 0, qpdf_dl_specialized, true)) - { + if (!image.pipeStreamData(0, 0, qpdf_dl_specialized, true)) { QTC::TC("qpdf", "QPDFJob image optimize no pipeline"); o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description << ": not optimizing because unable to decode data" - << " or data already uses DCT" - << std::endl; + << " or data already uses DCT" << std::endl; }); return false; } Pl_Discard d; Pl_Count c("count", &d); std::shared_ptr p = makePipeline(description, &c); - if (p.get() == nullptr) - { + if (p.get() == nullptr) { // message issued by makePipeline return false; } - if (! image.pipeStreamData(p.get(), 0, qpdf_dl_specialized)) - { + if (!image.pipeStreamData(p.get(), 0, qpdf_dl_specialized)) { return false; } long long orig_length = image.getDict().getKey("/Length").getIntValue(); - if (c.getCount() >= orig_length) - { + if (c.getCount() >= orig_length) { QTC::TC("qpdf", "QPDFJob image optimize no shrink"); o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description @@ -265,9 +251,8 @@ ImageOptimizer::evaluate(std::string const& description) } o.doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << description - << ": optimizing image reduces size from " - << orig_length << " to " << c.getCount() - << std::endl; + << ": optimizing image reduces size from " << orig_length << " to " + << c.getCount() << std::endl; }); return true; } @@ -276,45 +261,38 @@ void ImageOptimizer::provideStreamData(int, int, Pipeline* pipeline) { std::shared_ptr p = makePipeline("", pipeline); - if (p.get() == nullptr) - { + if (p.get() == nullptr) { // Should not be possible image.warnIfPossible("unable to create pipeline after previous" " success; image data will be lost"); pipeline->finish(); return; } - image.pipeStreamData(p.get(), 0, qpdf_dl_specialized, - false, false); + image.pipeStreamData(p.get(), 0, qpdf_dl_specialized, false, false); } -QPDFJob::PageSpec::PageSpec(std::string const& filename, - char const* password, - std::string const& range) : +QPDFJob::PageSpec::PageSpec( + std::string const& filename, + char const* password, + std::string const& range) : filename(filename), range(range) { - if (password) - { + if (password) { this->password = QUtil::make_shared_cstr(password); } } -QPDFPageData::QPDFPageData(std::string const& filename, - QPDF* qpdf, - std::string const& range) : +QPDFPageData::QPDFPageData( + std::string const& filename, QPDF* qpdf, std::string const& range) : filename(filename), qpdf(qpdf), orig_pages(qpdf->getAllPages()) { - try - { - this->selected_pages = - QUtil::parse_numrange(range.c_str(), - QIntC::to_int(this->orig_pages.size())); - } - catch (std::runtime_error& e) - { + try { + this->selected_pages = QUtil::parse_numrange( + range.c_str(), QIntC::to_int(this->orig_pages.size())); + } catch (std::runtime_error& e) { throw std::runtime_error( "parsing numeric range for " + filename + ": " + e.what()); } @@ -331,8 +309,8 @@ QPDFPageData::QPDFPageData(QPDFPageData const& other, int page) : void ProgressReporter::reportProgress(int percentage) { - this->cout << prefix << ": " << filename << ": write progress: " - << percentage << "%" << std::endl; + this->cout << prefix << ": " << filename + << ": write progress: " << percentage << "%" << std::endl; } // These default values are duplicated in help and docs. @@ -452,7 +430,6 @@ QPDFJob::QPDFJob() : { } - void QPDFJob::usage(std::string const& msg) { @@ -476,8 +453,7 @@ void QPDFJob::doIfVerbose( std::function fn) { - if (this->m->verbose && (this->m->cout != nullptr)) - { + if (this->m->verbose && (this->m->cout != nullptr)) { fn(*(this->m->cout), this->m->message_prefix); } } @@ -501,61 +477,44 @@ QPDFJob::parseRotationParameter(std::string const& parameter) std::string range; size_t colon = parameter.find(':'); int relative = 0; - if (colon != std::string::npos) - { - if (colon > 0) - { + if (colon != std::string::npos) { + if (colon > 0) { angle_str = parameter.substr(0, colon); } - if (colon + 1 < parameter.length()) - { + if (colon + 1 < parameter.length()) { range = parameter.substr(colon + 1); } - } - else - { + } else { angle_str = parameter; } - if (angle_str.length() > 0) - { + if (angle_str.length() > 0) { char first = angle_str.at(0); - if ((first == '+') || (first == '-')) - { + if ((first == '+') || (first == '-')) { relative = ((first == '+') ? 1 : -1); angle_str = angle_str.substr(1); - } - else if (! QUtil::is_digit(angle_str.at(0))) - { + } else if (!QUtil::is_digit(angle_str.at(0))) { angle_str = ""; } } - if (range.empty()) - { + if (range.empty()) { range = "1-z"; } bool range_valid = false; - try - { + try { QUtil::parse_numrange(range.c_str(), 0); range_valid = true; - } - catch (std::runtime_error const&) - { + } catch (std::runtime_error const&) { // ignore } if (range_valid && - ((angle_str == "0") ||(angle_str == "90") || - (angle_str == "180") || (angle_str == "270"))) - { + ((angle_str == "0") || (angle_str == "90") || (angle_str == "180") || + (angle_str == "270"))) { int angle = QUtil::string_to_int(angle_str.c_str()); - if (relative == -1) - { + if (relative == -1) { angle = -angle; } m->rotations[range] = RotationSpec(angle, (relative != 0)); - } - else - { + } else { usage("invalid parameter to rotate: " + parameter); } } @@ -563,12 +522,9 @@ QPDFJob::parseRotationParameter(std::string const& parameter) std::vector QPDFJob::parseNumrange(char const* range, int max) { - try - { + try { return QUtil::parse_numrange(range, max); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { usage(e.what()); } return std::vector(); @@ -579,79 +535,58 @@ QPDFJob::run() { checkConfiguration(); std::shared_ptr pdf_ph; - try - { + try { pdf_ph = processFile(m->infilename.get(), m->password.get(), true); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { if ((e.getErrorCode() == qpdf_e_password) && - (m->check_is_encrypted || m->check_requires_password)) - { + (m->check_is_encrypted || m->check_requires_password)) { // Allow --is-encrypted and --requires-password to // work when an incorrect password is supplied. this->m->encryption_status = - qpdf_es_encrypted | - qpdf_es_password_incorrect; + qpdf_es_encrypted | qpdf_es_password_incorrect; return; } throw e; } QPDF& pdf = *pdf_ph; - if (pdf.isEncrypted()) - { + if (pdf.isEncrypted()) { this->m->encryption_status = qpdf_es_encrypted; } - if (m->check_is_encrypted || m->check_requires_password) - { + if (m->check_is_encrypted || m->check_requires_password) { return; } bool other_warnings = false; std::vector> page_heap; - if (! m->page_specs.empty()) - { + if (!m->page_specs.empty()) { handlePageSpecs(pdf, other_warnings, page_heap); } - if (! m->rotations.empty()) - { + if (!m->rotations.empty()) { handleRotations(pdf); } handleUnderOverlay(pdf); handleTransformations(pdf); - if (! createsOutput()) - { + if (!createsOutput()) { doInspection(pdf); - } - else if (m->split_pages) - { + } else if (m->split_pages) { doSplitPages(pdf, other_warnings); - } - else - { + } else { writeOutfile(pdf); } - if (! pdf.getWarnings().empty()) - { + if (!pdf.getWarnings().empty()) { this->m->warnings = true; } - if (this->m->warnings && (! this->m->suppress_warnings)) - { - if (createsOutput()) - { + if (this->m->warnings && (!this->m->suppress_warnings)) { + if (createsOutput()) { (*this->m->cerr) << this->m->message_prefix << ": operation succeeded with warnings;" - << " resulting file may have some problems" - << std::endl; - } - else - { + << " resulting file may have some problems" << std::endl; + } else { (*this->m->cerr) << this->m->message_prefix - << ": operation succeeded with warnings" - << std::endl; + << ": operation succeeded with warnings" << std::endl; } } } @@ -671,43 +606,30 @@ QPDFJob::createsOutput() const int QPDFJob::getExitCode() const { - if (this->m->check_is_encrypted) - { - if (this->m->encryption_status & qpdf_es_encrypted) - { + if (this->m->check_is_encrypted) { + if (this->m->encryption_status & qpdf_es_encrypted) { QTC::TC("qpdf", "QPDFJob check encrypted encrypted"); return 0; - } - else - { + } else { QTC::TC("qpdf", "QPDFJob check encrypted not encrypted"); return EXIT_IS_NOT_ENCRYPTED; } - } - else if (this->m->check_requires_password) - { - if (this->m->encryption_status & qpdf_es_encrypted) - { - if (this->m->encryption_status & qpdf_es_password_incorrect) - { + } else if (this->m->check_requires_password) { + if (this->m->encryption_status & qpdf_es_encrypted) { + if (this->m->encryption_status & qpdf_es_password_incorrect) { QTC::TC("qpdf", "QPDFJob check password password incorrect"); return 0; - } - else - { + } else { QTC::TC("qpdf", "QPDFJob check password password correct"); return EXIT_CORRECT_PASSWORD; } - } - else - { + } else { QTC::TC("qpdf", "QPDFJob check password not encrypted"); return EXIT_IS_NOT_ENCRYPTED; } } - if (this->m->warnings && (! this->m->warnings_exit_zero)) - { + if (this->m->warnings && (!this->m->warnings_exit_zero)) { return EXIT_WARNING; } return 0; @@ -716,43 +638,31 @@ QPDFJob::getExitCode() const void QPDFJob::checkConfiguration() { - if (m->replace_input) - { - if (m->outfilename) - { + if (m->replace_input) { + if (m->outfilename) { usage("--replace-input may not be used when" " an output file is specified"); - } - else if (m->split_pages) - { + } else if (m->split_pages) { usage("--split-pages may not be used with --replace-input"); } } - if (m->infilename == 0) - { + if (m->infilename == 0) { usage("an input file name is required"); - } - else if (m->require_outfile && - (m->outfilename == 0) && (! m->replace_input)) - { + } else if ( + m->require_outfile && (m->outfilename == 0) && (!m->replace_input)) { usage("an output file name is required; use - for standard output"); - } - else if ((! m->require_outfile) && - ((m->outfilename != 0) || m->replace_input)) - { + } else if ( + (!m->require_outfile) && ((m->outfilename != 0) || m->replace_input)) { usage("no output file may be given for this option"); } - if (m->check_requires_password && m->check_is_encrypted) - { + if (m->check_requires_password && m->check_is_encrypted) { usage("--requires-password and --is-encrypted may not be given" " together"); } - if (m->encrypt && (! m->allow_insecure) && - (m->owner_password.empty() && - (! m->user_password.empty()) && - (m->keylen == 256))) - { + if (m->encrypt && (!m->allow_insecure) && + (m->owner_password.empty() && (!m->user_password.empty()) && + (m->keylen == 256))) { // Note that empty owner passwords for R < 5 are copied from // the user password, so this lack of security is not an issue // for those files. Also we are consider only the ability to @@ -767,28 +677,23 @@ QPDFJob::checkConfiguration() } if (m->require_outfile && m->outfilename && - (strcmp(m->outfilename.get(), "-") == 0)) - { - if (m->split_pages) - { + (strcmp(m->outfilename.get(), "-") == 0)) { + if (m->split_pages) { usage("--split-pages may not be used when" " writing to standard output"); } - if (this->m->verbose) - { + if (this->m->verbose) { usage("--verbose may not be used when" " writing to standard output"); } - if (m->progress) - { + if (m->progress) { usage("--progress may not be used when" " writing to standard output"); } } - if ((! m->split_pages) && - QUtil::same_file(m->infilename.get(), m->outfilename.get())) - { + if ((!m->split_pages) && + QUtil::same_file(m->infilename.get(), m->outfilename.get())) { QTC::TC("qpdf", "QPDFJob same file error"); usage("input file and output file are the same;" " use --replace-input to intentionally" @@ -805,47 +710,44 @@ QPDFJob::getEncryptionStatus() void QPDFJob::setQPDFOptions(QPDF& pdf) { - if (m->ignore_xref_streams) - { + if (m->ignore_xref_streams) { pdf.setIgnoreXRefStreams(true); } - if (m->suppress_recovery) - { + if (m->suppress_recovery) { pdf.setAttemptRecovery(false); } - if (m->password_is_hex_key) - { + if (m->password_is_hex_key) { pdf.setPasswordIsHexKey(true); } - if (m->suppress_warnings) - { + if (m->suppress_warnings) { pdf.setSuppressWarnings(true); } } -static std::string show_bool(bool v) +static std::string +show_bool(bool v) { return v ? "allowed" : "not allowed"; } -static std::string show_encryption_method(QPDF::encryption_method_e method) +static std::string +show_encryption_method(QPDF::encryption_method_e method) { std::string result = "unknown"; - switch (method) - { - case QPDF::e_none: + switch (method) { + case QPDF::e_none: result = "none"; break; - case QPDF::e_unknown: + case QPDF::e_unknown: result = "unknown"; break; - case QPDF::e_rc4: + case QPDF::e_rc4: result = "RC4"; break; - case QPDF::e_aes: + case QPDF::e_aes: result = "AESv2"; break; - case QPDF::e_aesv3: + case QPDF::e_aesv3: result = "AESv3"; break; // no default so gcc will warn for missing case @@ -864,51 +766,43 @@ QPDFJob::showEncryption(QPDF& pdf) QPDF::encryption_method_e string_method = QPDF::e_unknown; QPDF::encryption_method_e file_method = QPDF::e_unknown; auto& cout = *this->m->cout; - if (! pdf.isEncrypted(R, P, V, - stream_method, string_method, file_method)) - { + if (!pdf.isEncrypted(R, P, V, stream_method, string_method, file_method)) { cout << "File is not encrypted" << std::endl; - } - else - { + } else { cout << "R = " << R << std::endl; cout << "P = " << P << std::endl; std::string user_password = pdf.getTrimmedUserPassword(); std::string encryption_key = pdf.getEncryptionKey(); cout << "User password = " << user_password << std::endl; - if (m->show_encryption_key) - { - cout << "Encryption key = " - << QUtil::hex_encode(encryption_key) << std::endl; + if (m->show_encryption_key) { + cout << "Encryption key = " << QUtil::hex_encode(encryption_key) + << std::endl; } - if (pdf.ownerPasswordMatched()) - { + if (pdf.ownerPasswordMatched()) { cout << "Supplied password is owner password" << std::endl; } - if (pdf.userPasswordMatched()) - { + if (pdf.userPasswordMatched()) { cout << "Supplied password is user password" << std::endl; } cout << "extract for accessibility: " << show_bool(pdf.allowAccessibility()) << std::endl - << "extract for any purpose: " - << show_bool(pdf.allowExtractAll()) << std::endl - << "print low resolution: " - << show_bool(pdf.allowPrintLowRes()) << std::endl - << "print high resolution: " - << show_bool(pdf.allowPrintHighRes()) << std::endl + << "extract for any purpose: " << show_bool(pdf.allowExtractAll()) + << std::endl + << "print low resolution: " << show_bool(pdf.allowPrintLowRes()) + << std::endl + << "print high resolution: " << show_bool(pdf.allowPrintHighRes()) + << std::endl << "modify document assembly: " << show_bool(pdf.allowModifyAssembly()) << std::endl - << "modify forms: " - << show_bool(pdf.allowModifyForm()) << std::endl - << "modify annotations: " - << show_bool(pdf.allowModifyAnnotation()) << std::endl - << "modify other: " - << show_bool(pdf.allowModifyOther()) << std::endl - << "modify anything: " - << show_bool(pdf.allowModifyAll()) << std::endl; - if (V >= 4) - { + << "modify forms: " << show_bool(pdf.allowModifyForm()) + << std::endl + << "modify annotations: " << show_bool(pdf.allowModifyAnnotation()) + << std::endl + << "modify other: " << show_bool(pdf.allowModifyOther()) + << std::endl + << "modify anything: " << show_bool(pdf.allowModifyAll()) + << std::endl; + if (V >= 4) { cout << "stream encryption method: " << show_encryption_method(stream_method) << std::endl << "string encryption method: " @@ -930,29 +824,23 @@ QPDFJob::doCheck(QPDF& pdf) bool warnings = false; auto& cout = *this->m->cout; cout << "checking " << m->infilename << std::endl; - try - { + try { int extension_level = pdf.getExtensionLevel(); cout << "PDF Version: " << pdf.getPDFVersion(); - if (extension_level > 0) - { + if (extension_level > 0) { cout << " extension level " << pdf.getExtensionLevel(); } cout << std::endl; showEncryption(pdf); - if (pdf.isLinearized()) - { + if (pdf.isLinearized()) { cout << "File is linearized\n"; // any errors or warnings are reported by // checkLinearization(). We treat all issues reported here // as warnings. - if (! pdf.checkLinearization()) - { + if (!pdf.checkLinearization()) { warnings = true; } - } - else - { + } else { cout << "File is not linearized\n"; } @@ -970,47 +858,33 @@ QPDFJob::doCheck(QPDF& pdf) std::vector pages = dh.getAllPages(); DiscardContents discard_contents; int pageno = 0; - for (std::vector::iterator iter = - pages.begin(); - iter != pages.end(); ++iter) - { + for (std::vector::iterator iter = pages.begin(); + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); ++pageno; - try - { + try { page.parseContents(&discard_contents); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { okay = false; - *(this->m->cerr) - << "ERROR: page " << pageno << ": " - << e.what() << std::endl; + *(this->m->cerr) << "ERROR: page " << pageno << ": " << e.what() + << std::endl; } } - } - catch (std::exception& e) - { + } catch (std::exception& e) { (*this->m->cerr) << "ERROR: " << e.what() << std::endl; okay = false; } - if (! okay) - { + if (!okay) { throw std::runtime_error("errors detected"); } - if ((! pdf.getWarnings().empty()) || warnings) - { + if ((!pdf.getWarnings().empty()) || warnings) { this->m->warnings = true; - } - else - { - *(this->m->cout) - << "No syntax or stream encoding errors" - << " found; the file may still contain" - << std::endl - << "errors that qpdf cannot detect" - << std::endl; + } else { + *(this->m->cout) << "No syntax or stream encoding errors" + << " found; the file may still contain" << std::endl + << "errors that qpdf cannot detect" << std::endl; } } @@ -1018,29 +892,20 @@ void QPDFJob::doShowObj(QPDF& pdf) { QPDFObjectHandle obj; - if (m->show_trailer) - { + if (m->show_trailer) { obj = pdf.getTrailer(); - } - else - { + } else { obj = pdf.getObjectByID(m->show_obj, m->show_gen); } bool error = false; - if (obj.isStream()) - { - if (m->show_raw_stream_data || m->show_filtered_stream_data) - { + if (obj.isStream()) { + if (m->show_raw_stream_data || m->show_filtered_stream_data) { bool filter = m->show_filtered_stream_data; - if (filter && - (! obj.pipeStreamData(0, 0, qpdf_dl_all))) - { + if (filter && (!obj.pipeStreamData(0, 0, qpdf_dl_all))) { QTC::TC("qpdf", "QPDFJob unable to filter"); obj.warnIfPossible("unable to filter stream data"); error = true; - } - else - { + } else { QUtil::binary_stdout(); Pl_StdioFile out("stdout", stdout); obj.pipeStreamData( @@ -1048,20 +913,14 @@ QPDFJob::doShowObj(QPDF& pdf) (filter && m->normalize) ? qpdf_ef_normalize : 0, filter ? qpdf_dl_all : qpdf_dl_none); } + } else { + *(this->m->cout) << "Object is stream. Dictionary:" << std::endl + << obj.getDict().unparseResolved() << std::endl; } - else - { - *(this->m->cout) - << "Object is stream. Dictionary:" << std::endl - << obj.getDict().unparseResolved() << std::endl; - } - } - else - { + } else { *(this->m->cout) << obj.unparseResolved() << std::endl; } - if (error) - { + if (error) { throw std::runtime_error( "unable to get object " + obj.getObjGen().unparse()); } @@ -1075,43 +934,33 @@ QPDFJob::doShowPages(QPDF& pdf) int pageno = 0; auto& cout = *this->m->cout; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& ph(*iter); QPDFObjectHandle page = ph.getObjectHandle(); ++pageno; - cout << "page " << pageno << ": " - << page.getObjectID() << " " + cout << "page " << pageno << ": " << page.getObjectID() << " " << page.getGeneration() << " R" << std::endl; - if (m->show_page_images) - { + if (m->show_page_images) { std::map images = ph.getImages(); - if (! images.empty()) - { + if (!images.empty()) { cout << " images:" << std::endl; - for (auto const& iter2: images) - { + for (auto const& iter2 : images) { std::string const& name = iter2.first; QPDFObjectHandle image = iter2.second; QPDFObjectHandle dict = image.getDict(); - int width = - dict.getKey("/Width").getIntValueAsInt(); - int height = - dict.getKey("/Height").getIntValueAsInt(); - cout << " " << name << ": " - << image.unparse() - << ", " << width << " x " << height - << std::endl; + int width = dict.getKey("/Width").getIntValueAsInt(); + int height = dict.getKey("/Height").getIntValueAsInt(); + cout << " " << name << ": " << image.unparse() << ", " + << width << " x " << height << std::endl; } } } cout << " content:" << std::endl; - std::vector content = - ph.getPageContents(); - for (auto& iter2: content) - { + std::vector content = ph.getPageContents(); + for (auto& iter2 : content) { cout << " " << iter2.unparse() << std::endl; } } @@ -1121,44 +970,35 @@ void QPDFJob::doListAttachments(QPDF& pdf) { QPDFEmbeddedFileDocumentHelper efdh(pdf); - if (efdh.hasEmbeddedFiles()) - { - for (auto const& i: efdh.getEmbeddedFiles()) - { + if (efdh.hasEmbeddedFiles()) { + for (auto const& i : efdh.getEmbeddedFiles()) { std::string const& key = i.first; auto efoh = i.second; *(this->m->cout) - << key << " -> " - << efoh->getEmbeddedFileStream().getObjGen() + << key << " -> " << efoh->getEmbeddedFileStream().getObjGen() << std::endl; doIfVerbose([&](std::ostream& cout, std::string const& prefix) { auto desc = efoh->getDescription(); - if (! desc.empty()) - { + if (!desc.empty()) { cout << " description: " << desc << std::endl; } cout << " preferred name: " << efoh->getFilename() << std::endl; cout << " all names:" << std::endl; - for (auto const& i2: efoh->getFilenames()) - { + for (auto const& i2 : efoh->getFilenames()) { cout << " " << i2.first << " -> " << i2.second << std::endl; } cout << " all data streams:" << std::endl; - for (auto i2: efoh->getEmbeddedFileStreams().ditems()) - { + for (auto i2 : efoh->getEmbeddedFileStreams().ditems()) { cout << " " << i2.first << " -> " - << i2.second.getObjGen() - << std::endl; + << i2.second.getObjGen() << std::endl; } }); } - } - else - { - *(this->m->cout) - << m->infilename << " has no embedded files" << std::endl; + } else { + *(this->m->cout) << m->infilename << " has no embedded files" + << std::endl; } } @@ -1167,8 +1007,7 @@ QPDFJob::doShowAttachment(QPDF& pdf) { QPDFEmbeddedFileDocumentHelper efdh(pdf); auto fs = efdh.getEmbeddedFile(m->attachment_to_show); - if (! fs) - { + if (!fs) { throw std::runtime_error( "attachment " + m->attachment_to_show + " not found"); } @@ -1179,20 +1018,16 @@ QPDFJob::doShowAttachment(QPDF& pdf) } void -QPDFJob::parse_object_id(std::string const& objspec, - bool& trailer, int& obj, int& gen) +QPDFJob::parse_object_id( + std::string const& objspec, bool& trailer, int& obj, int& gen) { - if (objspec == "trailer") - { + if (objspec == "trailer") { trailer = true; - } - else - { + } else { trailer = false; obj = QUtil::string_to_int(objspec.c_str()); size_t comma = objspec.find(','); - if ((comma != std::string::npos) && (comma + 1 < objspec.length())) - { + if ((comma != std::string::npos) && (comma + 1 < objspec.length())) { gen = QUtil::string_to_int( objspec.substr(1 + comma, std::string::npos).c_str()); } @@ -1203,14 +1038,12 @@ std::set QPDFJob::getWantedJSONObjects() { std::set wanted_og; - for (auto const& iter: m->json_objects) - { + for (auto const& iter : m->json_objects) { bool trailer; int obj = 0; int gen = 0; parse_object_id(iter, trailer, obj, gen); - if (obj) - { + if (obj) { wanted_og.insert(QPDFObjGen(obj, gen)); } } @@ -1226,17 +1059,15 @@ QPDFJob::doJSONObjects(QPDF& pdf, JSON& j) bool all_objects = m->json_objects.empty(); std::set wanted_og = getWantedJSONObjects(); JSON j_objects = j.addDictionaryMember("objects", JSON::makeDictionary()); - if (all_objects || m->json_objects.count("trailer")) - { + if (all_objects || m->json_objects.count("trailer")) { j_objects.addDictionaryMember( "trailer", pdf.getTrailer().getJSON(true)); } std::vector objects = pdf.getAllObjects(); for (std::vector::iterator iter = objects.begin(); - iter != objects.end(); ++iter) - { - if (all_objects || wanted_og.count((*iter).getObjGen())) - { + iter != objects.end(); + ++iter) { + if (all_objects || wanted_og.count((*iter).getObjGen())) { j_objects.addDictionaryMember( (*iter).unparse(), (*iter).getJSON(true)); } @@ -1250,29 +1081,24 @@ QPDFJob::doJSONObjectinfo(QPDF& pdf, JSON& j) // stuff like calling pushInheritedAttributesToPage. bool all_objects = m->json_objects.empty(); std::set wanted_og = getWantedJSONObjects(); - JSON j_objectinfo = j.addDictionaryMember( - "objectinfo", JSON::makeDictionary()); - for (auto& obj: pdf.getAllObjects()) - { - if (all_objects || wanted_og.count(obj.getObjGen())) - { + JSON j_objectinfo = + j.addDictionaryMember("objectinfo", JSON::makeDictionary()); + for (auto& obj : pdf.getAllObjects()) { + if (all_objects || wanted_og.count(obj.getObjGen())) { auto j_details = j_objectinfo.addDictionaryMember( obj.unparse(), JSON::makeDictionary()); - auto j_stream = j_details.addDictionaryMember( - "stream", JSON::makeDictionary()); + auto j_stream = + j_details.addDictionaryMember("stream", JSON::makeDictionary()); bool is_stream = obj.isStream(); - j_stream.addDictionaryMember( - "is", JSON::makeBool(is_stream)); + j_stream.addDictionaryMember("is", JSON::makeBool(is_stream)); j_stream.addDictionaryMember( "length", - (is_stream - ? obj.getDict().getKey("/Length").getJSON(true) - : JSON::makeNull())); + (is_stream ? obj.getDict().getKey("/Length").getJSON(true) + : JSON::makeNull())); j_stream.addDictionaryMember( "filter", - (is_stream - ? obj.getDict().getKey("/Filter").getJSON(true) - : JSON::makeNull())); + (is_stream ? obj.getDict().getKey("/Filter").getJSON(true) + : JSON::makeNull())); } } } @@ -1288,20 +1114,17 @@ QPDFJob::doJSONPages(QPDF& pdf, JSON& j) std::vector pages = pdh.getAllPages(); int pageno = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter, ++pageno) - { + iter != pages.end(); + ++iter, ++pageno) { JSON j_page = j_pages.addArrayElement(JSON::makeDictionary()); QPDFPageObjectHelper& ph(*iter); QPDFObjectHandle page = ph.getObjectHandle(); j_page.addDictionaryMember("object", page.getJSON()); - JSON j_images = j_page.addDictionaryMember( - "images", JSON::makeArray()); + JSON j_images = j_page.addDictionaryMember("images", JSON::makeArray()); std::map images = ph.getImages(); - for (auto const& iter2: images) - { + for (auto const& iter2 : images) { JSON j_image = j_images.addArrayElement(JSON::makeDictionary()); - j_image.addDictionaryMember( - "name", JSON::makeString(iter2.first)); + j_image.addDictionaryMember("name", JSON::makeString(iter2.first)); QPDFObjectHandle image = iter2.second; QPDFObjectHandle dict = image.getDict(); j_image.addDictionaryMember("object", image.getJSON()); @@ -1314,19 +1137,14 @@ QPDFJob::doJSONPages(QPDF& pdf, JSON& j) j_image.addDictionaryMember( "bitspercomponent", dict.getKey("/BitsPerComponent").getJSON()); QPDFObjectHandle filters = dict.getKey("/Filter").wrapInArray(); - j_image.addDictionaryMember( - "filter", filters.getJSON()); + j_image.addDictionaryMember("filter", filters.getJSON()); QPDFObjectHandle decode_parms = dict.getKey("/DecodeParms"); QPDFObjectHandle dp_array; - if (decode_parms.isArray()) - { + if (decode_parms.isArray()) { dp_array = decode_parms; - } - else - { + } else { dp_array = QPDFObjectHandle::newArray(); - for (int i = 0; i < filters.getArrayNItems(); ++i) - { + for (int i = 0; i < filters.getArrayNItems(); ++i) { dp_array.appendItem(decode_parms); } } @@ -1337,23 +1155,22 @@ QPDFJob::doJSONPages(QPDF& pdf, JSON& j) image.pipeStreamData(0, 0, m->decode_level, true))); } j_page.addDictionaryMember("images", j_images); - JSON j_contents = j_page.addDictionaryMember( - "contents", JSON::makeArray()); + JSON j_contents = + j_page.addDictionaryMember("contents", JSON::makeArray()); std::vector content = ph.getPageContents(); - for (auto& iter2: content) - { + for (auto& iter2 : content) { j_contents.addArrayElement(iter2.getJSON()); } j_page.addDictionaryMember( "label", pldh.getLabelForPage(pageno).getJSON()); - JSON j_outlines = j_page.addDictionaryMember( - "outlines", JSON::makeArray()); + JSON j_outlines = + j_page.addDictionaryMember("outlines", JSON::makeArray()); std::vector outlines = odh.getOutlinesForPage(page.getObjGen()); for (std::vector::iterator oiter = outlines.begin(); - oiter != outlines.end(); ++oiter) - { + oiter != outlines.end(); + ++oiter) { JSON j_outline = j_outlines.addArrayElement(JSON::makeDictionary()); j_outline.addDictionaryMember( "object", (*oiter).getObjectHandle().getJSON()); @@ -1373,18 +1190,16 @@ QPDFJob::doJSONPageLabels(QPDF& pdf, JSON& j) QPDFPageLabelDocumentHelper pldh(pdf); QPDFPageDocumentHelper pdh(pdf); std::vector pages = pdh.getAllPages(); - if (pldh.hasPageLabels()) - { + if (pldh.hasPageLabels()) { std::vector labels; pldh.getLabelsForPageRange( 0, QIntC::to_int(pages.size()) - 1, 0, labels); for (std::vector::iterator iter = labels.begin(); - iter != labels.end(); ++iter) - { + iter != labels.end(); + ++iter) { std::vector::iterator next = iter; ++next; - if (next == labels.end()) - { + if (next == labels.end()) { // This can't happen, so ignore it. This could only // happen if getLabelsForPageRange somehow returned an // odd number of items. @@ -1398,13 +1213,15 @@ QPDFJob::doJSONPageLabels(QPDF& pdf, JSON& j) } } -static void add_outlines_to_json( - std::vector outlines, JSON& j, +static void +add_outlines_to_json( + std::vector outlines, + JSON& j, std::map& page_numbers) { for (std::vector::iterator iter = outlines.begin(); - iter != outlines.end(); ++iter) - { + iter != outlines.end(); + ++iter) { QPDFOutlineObjectHelper& ol = *iter; JSON jo = j.addArrayElement(JSON::makeDictionary()); jo.addDictionaryMember("object", ol.getObjectHandle().getJSON()); @@ -1413,11 +1230,9 @@ static void add_outlines_to_json( jo.addDictionaryMember("open", JSON::makeBool(ol.getCount() >= 0)); QPDFObjectHandle page = ol.getDestPage(); JSON j_destpage = JSON::makeNull(); - if (page.isIndirect()) - { + if (page.isIndirect()) { QPDFObjGen og = page.getObjGen(); - if (page_numbers.count(og)) - { + if (page_numbers.count(og)) { j_destpage = JSON::makeInt(page_numbers[og]); } } @@ -1435,14 +1250,13 @@ QPDFJob::doJSONOutlines(QPDF& pdf, JSON& j) std::vector pages = dh.getAllPages(); int n = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFObjectHandle oh = (*iter).getObjectHandle(); page_numbers[oh.getObjGen()] = ++n; } - JSON j_outlines = j.addDictionaryMember( - "outlines", JSON::makeArray()); + JSON j_outlines = j.addDictionaryMember("outlines", JSON::makeArray()); QPDFOutlineDocumentHelper odh(pdf); add_outlines_to_json(odh.getTopLevelOutlines(), j_outlines, page_numbers); } @@ -1450,103 +1264,75 @@ QPDFJob::doJSONOutlines(QPDF& pdf, JSON& j) void QPDFJob::doJSONAcroform(QPDF& pdf, JSON& j) { - JSON j_acroform = j.addDictionaryMember( - "acroform", JSON::makeDictionary()); + JSON j_acroform = j.addDictionaryMember("acroform", JSON::makeDictionary()); QPDFAcroFormDocumentHelper afdh(pdf); j_acroform.addDictionaryMember( - "hasacroform", - JSON::makeBool(afdh.hasAcroForm())); + "hasacroform", JSON::makeBool(afdh.hasAcroForm())); j_acroform.addDictionaryMember( - "needappearances", - JSON::makeBool(afdh.getNeedAppearances())); - JSON j_fields = j_acroform.addDictionaryMember( - "fields", JSON::makeArray()); + "needappearances", JSON::makeBool(afdh.getNeedAppearances())); + JSON j_fields = j_acroform.addDictionaryMember("fields", JSON::makeArray()); QPDFPageDocumentHelper pdh(pdf); std::vector pages = pdh.getAllPages(); int pagepos1 = 0; - for (std::vector::iterator page_iter = - pages.begin(); - page_iter != pages.end(); ++page_iter) - { + for (std::vector::iterator page_iter = pages.begin(); + page_iter != pages.end(); + ++page_iter) { ++pagepos1; std::vector annotations = afdh.getWidgetAnnotationsForPage(*page_iter); for (std::vector::iterator annot_iter = annotations.begin(); - annot_iter != annotations.end(); ++annot_iter) - { + annot_iter != annotations.end(); + ++annot_iter) { QPDFAnnotationObjectHelper& aoh = *annot_iter; - QPDFFormFieldObjectHelper ffh = - afdh.getFieldForAnnotation(aoh); - JSON j_field = j_fields.addArrayElement( - JSON::makeDictionary()); + QPDFFormFieldObjectHelper ffh = afdh.getFieldForAnnotation(aoh); + JSON j_field = j_fields.addArrayElement(JSON::makeDictionary()); j_field.addDictionaryMember( - "object", - ffh.getObjectHandle().getJSON()); + "object", ffh.getObjectHandle().getJSON()); j_field.addDictionaryMember( - "parent", - ffh.getObjectHandle().getKey("/Parent").getJSON()); + "parent", ffh.getObjectHandle().getKey("/Parent").getJSON()); j_field.addDictionaryMember( - "pageposfrom1", - JSON::makeInt(pagepos1)); + "pageposfrom1", JSON::makeInt(pagepos1)); j_field.addDictionaryMember( - "fieldtype", - JSON::makeString(ffh.getFieldType())); + "fieldtype", JSON::makeString(ffh.getFieldType())); j_field.addDictionaryMember( - "fieldflags", - JSON::makeInt(ffh.getFlags())); + "fieldflags", JSON::makeInt(ffh.getFlags())); j_field.addDictionaryMember( - "fullname", - JSON::makeString(ffh.getFullyQualifiedName())); + "fullname", JSON::makeString(ffh.getFullyQualifiedName())); j_field.addDictionaryMember( - "partialname", - JSON::makeString(ffh.getPartialName())); + "partialname", JSON::makeString(ffh.getPartialName())); j_field.addDictionaryMember( - "alternativename", - JSON::makeString(ffh.getAlternativeName())); + "alternativename", JSON::makeString(ffh.getAlternativeName())); j_field.addDictionaryMember( - "mappingname", - JSON::makeString(ffh.getMappingName())); + "mappingname", JSON::makeString(ffh.getMappingName())); + j_field.addDictionaryMember("value", ffh.getValue().getJSON()); j_field.addDictionaryMember( - "value", - ffh.getValue().getJSON()); + "defaultvalue", ffh.getDefaultValue().getJSON()); j_field.addDictionaryMember( - "defaultvalue", - ffh.getDefaultValue().getJSON()); + "quadding", JSON::makeInt(ffh.getQuadding())); j_field.addDictionaryMember( - "quadding", - JSON::makeInt(ffh.getQuadding())); + "ischeckbox", JSON::makeBool(ffh.isCheckbox())); j_field.addDictionaryMember( - "ischeckbox", - JSON::makeBool(ffh.isCheckbox())); + "isradiobutton", JSON::makeBool(ffh.isRadioButton())); j_field.addDictionaryMember( - "isradiobutton", - JSON::makeBool(ffh.isRadioButton())); - j_field.addDictionaryMember( - "ischoice", - JSON::makeBool(ffh.isChoice())); - j_field.addDictionaryMember( - "istext", - JSON::makeBool(ffh.isText())); - JSON j_choices = j_field.addDictionaryMember( - "choices", JSON::makeArray()); + "ischoice", JSON::makeBool(ffh.isChoice())); + j_field.addDictionaryMember("istext", JSON::makeBool(ffh.isText())); + JSON j_choices = + j_field.addDictionaryMember("choices", JSON::makeArray()); std::vector choices = ffh.getChoices(); for (std::vector::iterator iter = choices.begin(); - iter != choices.end(); ++iter) - { + iter != choices.end(); + ++iter) { j_choices.addArrayElement(JSON::makeString(*iter)); } JSON j_annot = j_field.addDictionaryMember( "annotation", JSON::makeDictionary()); j_annot.addDictionaryMember( - "object", - aoh.getObjectHandle().getJSON()); + "object", aoh.getObjectHandle().getJSON()); j_annot.addDictionaryMember( - "appearancestate", - JSON::makeString(aoh.getAppearanceState())); + "appearancestate", JSON::makeString(aoh.getAppearanceState())); j_annot.addDictionaryMember( - "annotationflags", - JSON::makeInt(aoh.getFlags())); + "annotationflags", JSON::makeInt(aoh.getFlags())); } } } @@ -1560,69 +1346,54 @@ QPDFJob::doJSONEncrypt(QPDF& pdf, JSON& j) QPDF::encryption_method_e stream_method = QPDF::e_none; QPDF::encryption_method_e string_method = QPDF::e_none; QPDF::encryption_method_e file_method = QPDF::e_none; - bool is_encrypted = pdf.isEncrypted( - R, P, V, stream_method, string_method, file_method); - JSON j_encrypt = j.addDictionaryMember( - "encrypt", JSON::makeDictionary()); - j_encrypt.addDictionaryMember( - "encrypted", - JSON::makeBool(is_encrypted)); + bool is_encrypted = + pdf.isEncrypted(R, P, V, stream_method, string_method, file_method); + JSON j_encrypt = j.addDictionaryMember("encrypt", JSON::makeDictionary()); + j_encrypt.addDictionaryMember("encrypted", JSON::makeBool(is_encrypted)); j_encrypt.addDictionaryMember( "userpasswordmatched", JSON::makeBool(is_encrypted && pdf.userPasswordMatched())); j_encrypt.addDictionaryMember( "ownerpasswordmatched", JSON::makeBool(is_encrypted && pdf.ownerPasswordMatched())); - JSON j_capabilities = j_encrypt.addDictionaryMember( - "capabilities", JSON::makeDictionary()); + JSON j_capabilities = + j_encrypt.addDictionaryMember("capabilities", JSON::makeDictionary()); j_capabilities.addDictionaryMember( - "accessibility", - JSON::makeBool(pdf.allowAccessibility())); + "accessibility", JSON::makeBool(pdf.allowAccessibility())); j_capabilities.addDictionaryMember( - "extract", - JSON::makeBool(pdf.allowExtractAll())); + "extract", JSON::makeBool(pdf.allowExtractAll())); j_capabilities.addDictionaryMember( - "printlow", - JSON::makeBool(pdf.allowPrintLowRes())); + "printlow", JSON::makeBool(pdf.allowPrintLowRes())); j_capabilities.addDictionaryMember( - "printhigh", - JSON::makeBool(pdf.allowPrintHighRes())); + "printhigh", JSON::makeBool(pdf.allowPrintHighRes())); j_capabilities.addDictionaryMember( - "modifyassembly", - JSON::makeBool(pdf.allowModifyAssembly())); + "modifyassembly", JSON::makeBool(pdf.allowModifyAssembly())); j_capabilities.addDictionaryMember( - "modifyforms", - JSON::makeBool(pdf.allowModifyForm())); + "modifyforms", JSON::makeBool(pdf.allowModifyForm())); j_capabilities.addDictionaryMember( - "moddifyannotations", - JSON::makeBool(pdf.allowModifyAnnotation())); + "moddifyannotations", JSON::makeBool(pdf.allowModifyAnnotation())); j_capabilities.addDictionaryMember( - "modifyother", - JSON::makeBool(pdf.allowModifyOther())); + "modifyother", JSON::makeBool(pdf.allowModifyOther())); j_capabilities.addDictionaryMember( - "modify", - JSON::makeBool(pdf.allowModifyAll())); - JSON j_parameters = j_encrypt.addDictionaryMember( - "parameters", JSON::makeDictionary()); + "modify", JSON::makeBool(pdf.allowModifyAll())); + JSON j_parameters = + j_encrypt.addDictionaryMember("parameters", JSON::makeDictionary()); j_parameters.addDictionaryMember("R", JSON::makeInt(R)); j_parameters.addDictionaryMember("V", JSON::makeInt(V)); j_parameters.addDictionaryMember("P", JSON::makeInt(P)); int bits = 0; JSON key = JSON::makeNull(); - if (is_encrypted) - { + if (is_encrypted) { std::string encryption_key = pdf.getEncryptionKey(); bits = QIntC::to_int(encryption_key.length() * 8); - if (m->show_encryption_key) - { + if (m->show_encryption_key) { key = JSON::makeString(QUtil::hex_encode(encryption_key)); } } j_parameters.addDictionaryMember("bits", JSON::makeInt(bits)); j_parameters.addDictionaryMember("key", key); auto fix_method = [is_encrypted](QPDF::encryption_method_e& m) { - if (is_encrypted && m == QPDF::e_none) - { + if (is_encrypted && m == QPDF::e_none) { m = QPDF::e_rc4; } }; @@ -1633,13 +1404,9 @@ QPDFJob::doJSONEncrypt(QPDF& pdf, JSON& j) std::string s_string_method = show_encryption_method(string_method); std::string s_file_method = show_encryption_method(file_method); std::string s_overall_method; - if ((stream_method == string_method) && - (stream_method == file_method)) - { + if ((stream_method == string_method) && (stream_method == file_method)) { s_overall_method = s_stream_method; - } - else - { + } else { s_overall_method = "mixed"; } j_parameters.addDictionaryMember( @@ -1655,18 +1422,16 @@ QPDFJob::doJSONEncrypt(QPDF& pdf, JSON& j) void QPDFJob::doJSONAttachments(QPDF& pdf, JSON& j) { - JSON j_attachments = j.addDictionaryMember( - "attachments", JSON::makeDictionary()); + JSON j_attachments = + j.addDictionaryMember("attachments", JSON::makeDictionary()); QPDFEmbeddedFileDocumentHelper efdh(pdf); - for (auto const& iter: efdh.getEmbeddedFiles()) - { + for (auto const& iter : efdh.getEmbeddedFiles()) { std::string const& key = iter.first; auto fsoh = iter.second; - auto j_details = j_attachments.addDictionaryMember( - key, JSON::makeDictionary()); + auto j_details = + j_attachments.addDictionaryMember(key, JSON::makeDictionary()); j_details.addDictionaryMember( - "filespec", - JSON::makeString(fsoh->getObjectHandle().unparse())); + "filespec", JSON::makeString(fsoh->getObjectHandle().unparse())); j_details.addDictionaryMember( "preferredname", JSON::makeString(fsoh->getFilename())); j_details.addDictionaryMember( @@ -1696,10 +1461,10 @@ QPDFJob::json_schema(std::set* keys) // more depth in the manual. JSON schema = JSON::makeDictionary(); schema.addDictionaryMember( - "version", JSON::makeString( + "version", + JSON::makeString( "JSON format serial number; increased for non-compatible changes")); - JSON j_params = schema.addDictionaryMember( - "parameters", JSON::parse(R"({ + JSON j_params = schema.addDictionaryMember("parameters", JSON::parse(R"({ "decodelevel": "decode level used to determine stream filterability" })")); @@ -1708,17 +1473,14 @@ QPDFJob::json_schema(std::set* keys) // The list of selectable top-level keys id duplicated in the // following places: job.yml, QPDFJob::json_schema, and // QPDFJob::doJSON. - if (all_keys || keys->count("objects")) - { - schema.addDictionaryMember( - "objects", JSON::parse(R"({ + if (all_keys || keys->count("objects")) { + schema.addDictionaryMember("objects", JSON::parse(R"({ "": "json representation of object" })")); } - if (all_keys || keys->count("objectinfo")) - { - JSON objectinfo = schema.addDictionaryMember( - "objectinfo", JSON::parse(R"({ + if (all_keys || keys->count("objectinfo")) { + JSON objectinfo = + schema.addDictionaryMember("objectinfo", JSON::parse(R"({ "": { "stream": { "filter": "if stream, its filters, otherwise null", @@ -1728,8 +1490,7 @@ QPDFJob::json_schema(std::set* keys) } })")); } - if (all_keys || keys->count("pages")) - { + if (all_keys || keys->count("pages")) { JSON page = schema.addDictionaryMember("pages", JSON::parse(R"([ { "contents": [ @@ -1765,20 +1526,16 @@ QPDFJob::json_schema(std::set* keys) } ])")); } - if (all_keys || keys->count("pagelabels")) - { - JSON labels = schema.addDictionaryMember( - "pagelabels", JSON::parse(R"([ + if (all_keys || keys->count("pagelabels")) { + JSON labels = schema.addDictionaryMember("pagelabels", JSON::parse(R"([ { "index": "starting page position starting from zero", "label": "page label dictionary" } ])")); } - if (all_keys || keys->count("outlines")) - { - JSON outlines = schema.addDictionaryMember( - "outlines", JSON::parse(R"([ + if (all_keys || keys->count("outlines")) { + JSON outlines = schema.addDictionaryMember("outlines", JSON::parse(R"([ { "dest": "outline destination dictionary", "destpageposfrom1": "position of destination page in document numbered from 1; null if not known", @@ -1789,10 +1546,8 @@ QPDFJob::json_schema(std::set* keys) } ])")); } - if (all_keys || keys->count("acroform")) - { - JSON acroform = schema.addDictionaryMember( - "acroform", JSON::parse(R"({ + if (all_keys || keys->count("acroform")) { + JSON acroform = schema.addDictionaryMember("acroform", JSON::parse(R"({ "fields": [ { "alternativename": "alternative name of field -- this is the one usually shown to users", @@ -1823,10 +1578,8 @@ QPDFJob::json_schema(std::set* keys) "needappearances": "whether the form fields' appearance streams need to be regenerated" })")); } - if (all_keys || keys->count("encrypt")) - { - JSON encrypt = schema.addDictionaryMember( - "encrypt", JSON::parse(R"({ + if (all_keys || keys->count("encrypt")) { + JSON encrypt = schema.addDictionaryMember("encrypt", JSON::parse(R"({ "capabilities": { "accessibility": "allow extraction for accessibility?", "extract": "allow extraction?", @@ -1854,10 +1607,9 @@ QPDFJob::json_schema(std::set* keys) "userpasswordmatched": "whether supplied password matched user password; always false for non-encrypted files" })")); } - if (all_keys || keys->count("attachments")) - { - JSON attachments = schema.addDictionaryMember( - "attachments", JSON::parse(R"({ + if (all_keys || keys->count("attachments")) { + JSON attachments = + schema.addDictionaryMember("attachments", JSON::parse(R"({ "": { "filespec": "object containing the file spec", "preferredcontents": "most preferred embedded file stream", @@ -1883,21 +1635,19 @@ QPDFJob::doJSON(QPDF& pdf) // ignore unrecognized keys, so we only update the version of a // key disappears or if its value changes meaning. j.addDictionaryMember("version", JSON::makeInt(1)); - JSON j_params = j.addDictionaryMember( - "parameters", JSON::makeDictionary()); + JSON j_params = j.addDictionaryMember("parameters", JSON::makeDictionary()); std::string decode_level_str; - switch (m->decode_level) - { - case qpdf_dl_none: + switch (m->decode_level) { + case qpdf_dl_none: decode_level_str = "none"; break; - case qpdf_dl_generalized: + case qpdf_dl_generalized: decode_level_str = "generalized"; break; - case qpdf_dl_specialized: + case qpdf_dl_specialized: decode_level_str = "specialized"; break; - case qpdf_dl_all: + case qpdf_dl_all: decode_level_str = "all"; break; } @@ -1908,36 +1658,28 @@ QPDFJob::doJSON(QPDF& pdf) // The list of selectable top-level keys id duplicated in the // following places: job.yml, QPDFJob::json_schema, and // QPDFJob::doJSON. - if (all_keys || m->json_keys.count("objects")) - { + if (all_keys || m->json_keys.count("objects")) { doJSONObjects(pdf, j); } - if (all_keys || m->json_keys.count("objectinfo")) - { + if (all_keys || m->json_keys.count("objectinfo")) { doJSONObjectinfo(pdf, j); } - if (all_keys || m->json_keys.count("pages")) - { + if (all_keys || m->json_keys.count("pages")) { doJSONPages(pdf, j); } - if (all_keys || m->json_keys.count("pagelabels")) - { + if (all_keys || m->json_keys.count("pagelabels")) { doJSONPageLabels(pdf, j); } - if (all_keys || m->json_keys.count("outlines")) - { + if (all_keys || m->json_keys.count("outlines")) { doJSONOutlines(pdf, j); } - if (all_keys || m->json_keys.count("acroform")) - { + if (all_keys || m->json_keys.count("acroform")) { doJSONAcroform(pdf, j); } - if (all_keys || m->json_keys.count("encrypt")) - { + if (all_keys || m->json_keys.count("encrypt")) { doJSONEncrypt(pdf, j); } - if (all_keys || m->json_keys.count("attachments")) - { + if (all_keys || m->json_keys.count("attachments")) { doJSONAttachments(pdf, j); } @@ -1945,8 +1687,7 @@ QPDFJob::doJSON(QPDF& pdf) JSON schema = json_schema(&m->json_keys); std::list errors; - if (! j.checkSchema(schema, errors)) - { + if (!j.checkSchema(schema, errors)) { *(this->m->cerr) << "QPDFJob didn't create JSON that complies with its own rules.\n\ Please report this as a bug at\n\ @@ -1954,8 +1695,8 @@ Please report this as a bug at\n\ ideally with the file that caused the error and the output below. Thanks!\n\ \n"; for (std::list::iterator iter = errors.begin(); - iter != errors.end(); ++iter) - { + iter != errors.end(); + ++iter) { *(this->m->cerr) << (*iter) << std::endl; } } @@ -1966,75 +1707,56 @@ ideally with the file that caused the error and the output below. Thanks!\n\ void QPDFJob::doInspection(QPDF& pdf) { - if (m->check) - { + if (m->check) { doCheck(pdf); } - if (m->json_version) - { + if (m->json_version) { doJSON(pdf); } - if (m->show_npages) - { + if (m->show_npages) { QTC::TC("qpdf", "QPDFJob npages"); - *(this->m->cout) << pdf.getRoot().getKey("/Pages"). - getKey("/Count").getIntValue() << std::endl; + *(this->m->cout) + << pdf.getRoot().getKey("/Pages").getKey("/Count").getIntValue() + << std::endl; } - if (m->show_encryption) - { + if (m->show_encryption) { showEncryption(pdf); } - if (m->check_linearization) - { - if (! pdf.isLinearized()) - { + if (m->check_linearization) { + if (!pdf.isLinearized()) { *(this->m->cout) << m->infilename << " is not linearized" << std::endl; - } - else if (pdf.checkLinearization()) - { + } else if (pdf.checkLinearization()) { *(this->m->cout) << m->infilename << ": no linearization errors" << std::endl; - } - else - { + } else { this->m->warnings = true; } } - if (m->show_linearization) - { - if (pdf.isLinearized()) - { + if (m->show_linearization) { + if (pdf.isLinearized()) { pdf.showLinearizationData(); - } - else - { + } else { *(this->m->cout) << m->infilename << " is not linearized" << std::endl; } } - if (m->show_xref) - { + if (m->show_xref) { pdf.showXRefTable(); } - if ((m->show_obj > 0) || m->show_trailer) - { + if ((m->show_obj > 0) || m->show_trailer) { doShowObj(pdf); } - if (m->show_pages) - { + if (m->show_pages) { doShowPages(pdf); } - if (m->list_attachments) - { + if (m->list_attachments) { doListAttachments(pdf); } - if (! m->attachment_to_show.empty()) - { + if (!m->attachment_to_show.empty()) { doShowAttachment(pdf); } - if (! pdf.getWarnings().empty()) - { + if (!pdf.getWarnings().empty()) { this->m->warnings = true; } } @@ -2042,20 +1764,18 @@ QPDFJob::doInspection(QPDF& pdf) std::shared_ptr QPDFJob::doProcessOnce( std::function fn, - char const* password, bool empty, bool used_for_input) + char const* password, + bool empty, + bool used_for_input) { auto pdf = std::make_shared(); setQPDFOptions(*pdf); - if (empty) - { + if (empty) { pdf->emptyPDF(); - } - else - { + } else { fn(pdf.get(), password); } - if (used_for_input) - { + if (used_for_input) { this->m->max_input_version.updateIfGreater( pdf->getVersionAsPDFVersion()); } @@ -2065,7 +1785,9 @@ QPDFJob::doProcessOnce( std::shared_ptr QPDFJob::doProcess( std::function fn, - char const* password, bool empty, bool used_for_input) + char const* password, + bool empty, + bool used_for_input) { // If a password has been specified but doesn't work, try other // passwords that are equivalent in different character encodings. @@ -2078,10 +1800,8 @@ QPDFJob::doProcess( // good chance we'd succeed here. std::string ptemp; - if (password && (! m->password_is_hex_key)) - { - if (m->password_mode == QPDFJob::pm_hex_bytes) - { + if (password && (!m->password_is_hex_key)) { + if (m->password_mode == QPDFJob::pm_hex_bytes) { // Special case: handle --password-mode=hex-bytes for input // password as well as output password QTC::TC("qpdf", "QPDFJob input password hex-bytes"); @@ -2090,8 +1810,7 @@ QPDFJob::doProcess( } } if ((password == 0) || empty || m->password_is_hex_key || - m->suppress_password_recovery) - { + m->suppress_password_recovery) { // There is no password, or we're not doing recovery, so just // do the normal processing with the supplied password. return doProcessOnce(fn, password, empty, used_for_input); @@ -2104,8 +1823,8 @@ QPDFJob::doProcess( // Represent to char const*, as required by the QPDF class. std::vector passwords; for (std::vector::iterator iter = passwords_str.begin(); - iter != passwords_str.end(); ++iter) - { + iter != passwords_str.end(); + ++iter) { passwords.push_back((*iter).c_str()); } // We always try the supplied password first because it is the @@ -2113,8 +1832,7 @@ QPDFJob::doProcess( // is more than one option, go ahead and put the supplied password // at the end so that it's that decoding attempt whose exception // is thrown. - if (passwords.size() > 1) - { + if (passwords.size() > 1) { passwords.push_back(password); } @@ -2124,23 +1842,18 @@ QPDFJob::doProcess( // supplied password. bool warned = false; for (std::vector::iterator iter = passwords.begin(); - iter != passwords.end(); ++iter) - { - try - { + iter != passwords.end(); + ++iter) { + try { return doProcessOnce(fn, *iter, empty, used_for_input); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { std::vector::iterator next = iter; ++next; - if (next == passwords.end()) - { + if (next == passwords.end()) { throw e; } } - if (! warned) - { + if (!warned) { warned = true; doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": supplied password didn't work;" @@ -2155,12 +1868,12 @@ QPDFJob::doProcess( } std::shared_ptr -QPDFJob::processFile(char const* filename, char const* password, - bool used_for_input) +QPDFJob::processFile( + char const* filename, char const* password, bool used_for_input) { auto f1 = std::mem_fn(&QPDF::processFile); - auto fn = std::bind( - f1, std::placeholders::_1, filename, std::placeholders::_2); + auto fn = + std::bind(f1, std::placeholders::_1, filename, std::placeholders::_2); return doProcess(fn, password, strcmp(filename, "") == 0, used_for_input); } @@ -2169,16 +1882,14 @@ QPDFJob::processInputSource( PointerHolder is, char const* password, bool used_for_input) { auto f1 = std::mem_fn(&QPDF::processInputSource); - auto fn = std::bind( - f1, std::placeholders::_1, is, std::placeholders::_2); + auto fn = std::bind(f1, std::placeholders::_1, is, std::placeholders::_2); return doProcess(fn, password, false, used_for_input); } void QPDFJob::validateUnderOverlay(QPDF& pdf, UnderOverlay* uo) { - if (uo->filename.empty()) - { + if (uo->filename.empty()) { return; } QPDFPageDocumentHelper main_pdh(pdf); @@ -2186,47 +1897,39 @@ QPDFJob::validateUnderOverlay(QPDF& pdf, UnderOverlay* uo) uo->pdf = processFile(uo->filename.c_str(), uo->password.get(), true); QPDFPageDocumentHelper uo_pdh(*(uo->pdf)); int uo_npages = QIntC::to_int(uo_pdh.getAllPages().size()); - try - { + try { uo->to_pagenos = QUtil::parse_numrange(uo->to_nr.c_str(), main_npages); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { throw std::runtime_error( "parsing numeric range for " + uo->which + " \"to\" pages: " + e.what()); } - try - { - if (uo->from_nr.empty()) - { + try { + if (uo->from_nr.empty()) { QTC::TC("qpdf", "QPDFJob from_nr from repeat_nr"); uo->from_nr = uo->repeat_nr; } uo->from_pagenos = QUtil::parse_numrange(uo->from_nr.c_str(), uo_npages); - if (! uo->repeat_nr.empty()) - { + if (!uo->repeat_nr.empty()) { uo->repeat_pagenos = QUtil::parse_numrange(uo->repeat_nr.c_str(), uo_npages); } - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { throw std::runtime_error( - "parsing numeric range for " + uo->which + " file " + - uo->filename + ": " + e.what()); + "parsing numeric range for " + uo->which + " file " + uo->filename + + ": " + e.what()); } } -static QPDFAcroFormDocumentHelper* get_afdh_for_qpdf( - std::map>& afdh_map, +static QPDFAcroFormDocumentHelper* +get_afdh_for_qpdf( + std::map>& + afdh_map, QPDF* q) { auto uid = q->getUniqueId(); - if (! afdh_map.count(uid)) - { + if (!afdh_map.count(uid)) { afdh_map[uid] = std::make_shared(*q); } return afdh_map[uid].get(); @@ -2236,7 +1939,7 @@ void QPDFJob::doUnderOverlayForPage( QPDF& pdf, UnderOverlay& uo, - std::map >& pagenos, + std::map>& pagenos, size_t page_idx, std::map& fo, std::vector& pages, @@ -2244,13 +1947,12 @@ QPDFJob::doUnderOverlayForPage( bool before) { int pageno = 1 + QIntC::to_int(page_idx); - if (! pagenos.count(pageno)) - { + if (!pagenos.count(pageno)) { return; } - std::map> afdh; + std::map> + afdh; auto make_afdh = [&](QPDFPageObjectHelper& ph) { QPDF* q = ph.getObjectHandle().getOwningQPDF(); return get_afdh_for_qpdf(afdh, q); @@ -2260,25 +1962,22 @@ QPDFJob::doUnderOverlayForPage( std::string content; int min_suffix = 1; QPDFObjectHandle resources = dest_page.getAttribute("/Resources", true); - if (! resources.isDictionary()) - { + if (!resources.isDictionary()) { QTC::TC("qpdf", "QPDFJob overlay page with no resources"); resources = QPDFObjectHandle::newDictionary(); dest_page.getObjectHandle().replaceKey("/Resources", resources); } for (std::vector::iterator iter = pagenos[pageno].begin(); - iter != pagenos[pageno].end(); ++iter) - { + iter != pagenos[pageno].end(); + ++iter) { int from_pageno = *iter; doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << " " << uo.which << " " << from_pageno << std::endl; }); auto from_page = pages.at(QIntC::to_size(from_pageno - 1)); - if (0 == fo.count(from_pageno)) - { + if (0 == fo.count(from_pageno)) { fo[from_pageno] = - pdf.copyForeignObject( - from_page.getFormXObjectForPage()); + pdf.copyForeignObject(from_page.getFormXObjectForPage()); } // If the same page is overlaid or underlaid multiple times, @@ -2288,31 +1987,27 @@ QPDFJob::doUnderOverlayForPage( std::string name = resources.getUniqueResourceName("/Fx", min_suffix); QPDFMatrix cm; std::string new_content = dest_page.placeFormXObject( - fo[from_pageno], name, - dest_page.getTrimBox().getArrayAsRectangle(), cm); + fo[from_pageno], + name, + dest_page.getTrimBox().getArrayAsRectangle(), + cm); dest_page.copyAnnotations( from_page, cm, dest_afdh, make_afdh(from_page)); - if (! new_content.empty()) - { + if (!new_content.empty()) { resources.mergeResources("<< /XObject << >> >>"_qpdf); auto xobject = resources.getKey("/XObject"); - if (xobject.isDictionary()) - { + if (xobject.isDictionary()) { xobject.replaceKey(name, fo[from_pageno]); } ++min_suffix; content += new_content; } } - if (! content.empty()) - { - if (before) - { + if (!content.empty()) { + if (before) { dest_page.addPageContents( QPDFObjectHandle::newStream(&pdf, content), true); - } - else - { + } else { dest_page.addPageContents( QPDFObjectHandle::newStream(&pdf, "q\n"), true); dest_page.addPageContents( @@ -2322,21 +2017,18 @@ QPDFJob::doUnderOverlayForPage( } void -QPDFJob::getUOPagenos(QPDFJob::UnderOverlay& uo, - std::map >& pagenos) +QPDFJob::getUOPagenos( + QPDFJob::UnderOverlay& uo, std::map>& pagenos) { size_t idx = 0; size_t from_size = uo.from_pagenos.size(); size_t repeat_size = uo.repeat_pagenos.size(); for (std::vector::iterator iter = uo.to_pagenos.begin(); - iter != uo.to_pagenos.end(); ++iter, ++idx) - { - if (idx < from_size) - { + iter != uo.to_pagenos.end(); + ++iter, ++idx) { + if (idx < from_size) { pagenos[*iter].push_back(uo.from_pagenos.at(idx)); - } - else if (repeat_size) - { + } else if (repeat_size) { pagenos[*iter].push_back( uo.repeat_pagenos.at((idx - from_size) % repeat_size)); } @@ -2349,24 +2041,21 @@ QPDFJob::handleUnderOverlay(QPDF& pdf) validateUnderOverlay(pdf, &m->underlay); validateUnderOverlay(pdf, &m->overlay); if ((nullptr == m->underlay.pdf.get()) && - (nullptr == m->overlay.pdf.get())) - { + (nullptr == m->overlay.pdf.get())) { return; } - std::map > underlay_pagenos; + std::map> underlay_pagenos; getUOPagenos(m->underlay, underlay_pagenos); - std::map > overlay_pagenos; + std::map> overlay_pagenos; getUOPagenos(m->overlay, overlay_pagenos); std::map underlay_fo; std::map overlay_fo; std::vector upages; - if (m->underlay.pdf.get()) - { + if (m->underlay.pdf.get()) { upages = QPDFPageDocumentHelper(*(m->underlay.pdf)).getAllPages(); } std::vector opages; - if (m->overlay.pdf.get()) - { + if (m->overlay.pdf.get()) { opages = QPDFPageDocumentHelper(*(m->overlay.pdf)).getAllPages(); } @@ -2376,25 +2065,36 @@ QPDFJob::handleUnderOverlay(QPDF& pdf) doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": processing underlay/overlay" << std::endl; }); - for (size_t i = 0; i < main_npages; ++i) - { + for (size_t i = 0; i < main_npages; ++i) { doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << " page " << 1+i << std::endl; + cout << " page " << 1 + i << std::endl; }); - doUnderOverlayForPage(pdf, m->underlay, underlay_pagenos, i, - underlay_fo, upages, main_pages.at(i), - true); - doUnderOverlayForPage(pdf, m->overlay, overlay_pagenos, i, - overlay_fo, opages, main_pages.at(i), - false); + doUnderOverlayForPage( + pdf, + m->underlay, + underlay_pagenos, + i, + underlay_fo, + upages, + main_pages.at(i), + true); + doUnderOverlayForPage( + pdf, + m->overlay, + overlay_pagenos, + i, + overlay_fo, + opages, + main_pages.at(i), + false); } } -static void maybe_set_pagemode(QPDF& pdf, std::string const& pagemode) +static void +maybe_set_pagemode(QPDF& pdf, std::string const& pagemode) { auto root = pdf.getRoot(); - if (root.getKey("/PageMode").isNull()) - { + if (root.getKey("/PageMode").isNull()) { root.replaceKey("/PageMode", QPDFObjectHandle::newName(pagemode)); } } @@ -2405,50 +2105,40 @@ QPDFJob::addAttachments(QPDF& pdf) maybe_set_pagemode(pdf, "/UseAttachments"); QPDFEmbeddedFileDocumentHelper efdh(pdf); std::vector duplicated_keys; - for (auto const& to_add: m->attachments_to_add) - { - if ((! to_add.replace) && efdh.getEmbeddedFile(to_add.key)) - { + for (auto const& to_add : m->attachments_to_add) { + if ((!to_add.replace) && efdh.getEmbeddedFile(to_add.key)) { duplicated_keys.push_back(to_add.key); continue; } auto fs = QPDFFileSpecObjectHelper::createFileSpec( pdf, to_add.filename, to_add.path); - if (! to_add.description.empty()) - { + if (!to_add.description.empty()) { fs.setDescription(to_add.description); } auto efs = QPDFEFStreamObjectHelper(fs.getEmbeddedFileStream()); - efs.setCreationDate(to_add.creationdate) - .setModDate(to_add.moddate); - if (! to_add.mimetype.empty()) - { + efs.setCreationDate(to_add.creationdate).setModDate(to_add.moddate); + if (!to_add.mimetype.empty()) { efs.setSubtype(to_add.mimetype); } efdh.replaceEmbeddedFile(to_add.key, fs); doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << prefix << ": attached " << to_add.path - << " as " << to_add.filename - << " with key " << to_add.key << std::endl; + cout << prefix << ": attached " << to_add.path << " as " + << to_add.filename << " with key " << to_add.key << std::endl; }); } - if (! duplicated_keys.empty()) - { + if (!duplicated_keys.empty()) { std::string message; - for (auto const& k: duplicated_keys) - { - if (! message.empty()) - { + for (auto const& k : duplicated_keys) { + if (!message.empty()) { message += ", "; } message += k; } message = pdf.getFilename() + - " already has attachments with the following keys: " + - message + + " already has attachments with the following keys: " + message + "; use --replace to replace or --key to specify a different key"; throw std::runtime_error(message); } @@ -2460,58 +2150,49 @@ QPDFJob::copyAttachments(QPDF& pdf) maybe_set_pagemode(pdf, "/UseAttachments"); QPDFEmbeddedFileDocumentHelper efdh(pdf); std::vector duplicates; - for (auto const& to_copy: m->attachments_to_copy) - { + for (auto const& to_copy : m->attachments_to_copy) { doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << prefix << ": copying attachments from " - << to_copy.path << std::endl; + cout << prefix << ": copying attachments from " << to_copy.path + << std::endl; }); - auto other = processFile( - to_copy.path.c_str(), to_copy.password.c_str(), false); + auto other = + processFile(to_copy.path.c_str(), to_copy.password.c_str(), false); QPDFEmbeddedFileDocumentHelper other_efdh(*other); auto other_attachments = other_efdh.getEmbeddedFiles(); - for (auto const& iter: other_attachments) - { + for (auto const& iter : other_attachments) { std::string new_key = to_copy.prefix + iter.first; - if (efdh.getEmbeddedFile(new_key)) - { + if (efdh.getEmbeddedFile(new_key)) { duplicates.push_back( "file: " + to_copy.path + ", key: " + new_key); - } - else - { - auto new_fs_oh = pdf.copyForeignObject( - iter.second->getObjectHandle()); + } else { + auto new_fs_oh = + pdf.copyForeignObject(iter.second->getObjectHandle()); efdh.replaceEmbeddedFile( new_key, QPDFFileSpecObjectHelper(new_fs_oh)); - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { + doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << " " << iter.first << " -> " << new_key << std::endl; }); } } - if (other->anyWarnings()) - { + if (other->anyWarnings()) { this->m->warnings = true; } } - if (! duplicates.empty()) - { + if (!duplicates.empty()) { std::string message; - for (auto const& i: duplicates) - { - if (! message.empty()) - { + for (auto const& i : duplicates) { + if (!message.empty()) { message += "; "; } message += i; } message = pdf.getFilename() + " already has attachments with keys that conflict with" - " attachments from other files: " + message + + " attachments from other files: " + + message + ". Use --prefix with --copy-attachments-from" " or manually copy individual attachments."; throw std::runtime_error(message); @@ -2524,44 +2205,43 @@ QPDFJob::handleTransformations(QPDF& pdf) QPDFPageDocumentHelper dh(pdf); std::shared_ptr afdh; auto make_afdh = [&]() { - if (! afdh.get()) - { + if (!afdh.get()) { afdh = std::make_shared(pdf); } }; if (m->externalize_inline_images || - (m->optimize_images && (! m->keep_inline_images))) - { + (m->optimize_images && (!m->keep_inline_images))) { std::vector pages = dh.getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& ph(*iter); ph.externalizeInlineImages(m->ii_min_bytes); } } - if (m->optimize_images) - { + if (m->optimize_images) { int pageno = 0; std::vector pages = dh.getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { ++pageno; QPDFPageObjectHelper& ph(*iter); QPDFObjectHandle page = ph.getObjectHandle(); std::map images = ph.getImages(); - for (auto& iter2: images) - { + for (auto& iter2 : images) { std::string name = iter2.first; QPDFObjectHandle& image = iter2.second; ImageOptimizer* io = new ImageOptimizer( - *this, m->oi_min_width, m->oi_min_height, - m->oi_min_area, image); + *this, + m->oi_min_width, + m->oi_min_height, + m->oi_min_area, + image); PointerHolder sdp(io); - if (io->evaluate("image " + name + " on page " + - QUtil::int_to_string(pageno))) - { + if (io->evaluate( + "image " + name + " on page " + + QUtil::int_to_string(pageno))) { QPDFObjectHandle new_image = QPDFObjectHandle::newStream(&pdf); new_image.replaceDict(image.getDict().shallowCopy()); @@ -2569,69 +2249,55 @@ QPDFJob::handleTransformations(QPDF& pdf) sdp, QPDFObjectHandle::newName("/DCTDecode"), QPDFObjectHandle::newNull()); - ph.getAttribute("/Resources", true). - getKey("/XObject").replaceKey( - name, new_image); + ph.getAttribute("/Resources", true) + .getKey("/XObject") + .replaceKey(name, new_image); } } } } - if (m->generate_appearances) - { + if (m->generate_appearances) { make_afdh(); afdh->generateAppearancesIfNeeded(); } - if (m->flatten_annotations) - { - dh.flattenAnnotations(m->flatten_annotations_required, - m->flatten_annotations_forbidden); + if (m->flatten_annotations) { + dh.flattenAnnotations( + m->flatten_annotations_required, m->flatten_annotations_forbidden); } - if (m->coalesce_contents) - { + if (m->coalesce_contents) { std::vector pages = dh.getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { (*iter).coalesceContentStreams(); } } - if (m->flatten_rotation) - { + if (m->flatten_rotation) { make_afdh(); - for (auto& page: dh.getAllPages()) - { + for (auto& page : dh.getAllPages()) { page.flattenRotation(afdh.get()); } } - if (m->remove_page_labels) - { + if (m->remove_page_labels) { pdf.getRoot().removeKey("/PageLabels"); } - if (! m->attachments_to_remove.empty()) - { + if (!m->attachments_to_remove.empty()) { QPDFEmbeddedFileDocumentHelper efdh(pdf); - for (auto const& key: m->attachments_to_remove) - { - if (efdh.removeEmbeddedFile(key)) - { - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { - cout << prefix << - ": removed attachment " << key << std::endl; + for (auto const& key : m->attachments_to_remove) { + if (efdh.removeEmbeddedFile(key)) { + doIfVerbose([&](std::ostream& cout, std::string const& prefix) { + cout << prefix << ": removed attachment " << key + << std::endl; }); - } - else - { + } else { throw std::runtime_error("attachment " + key + " not found"); } } } - if (! m->attachments_to_add.empty()) - { + if (!m->attachments_to_add.empty()) { addAttachments(pdf); } - if (! m->attachments_to_copy.empty()) - { + if (!m->attachments_to_copy.empty()) { copyAttachments(pdf); } } @@ -2639,12 +2305,9 @@ QPDFJob::handleTransformations(QPDF& pdf) bool QPDFJob::shouldRemoveUnreferencedResources(QPDF& pdf) { - if (m->remove_unreferenced_page_resources == QPDFJob::re_no) - { + if (m->remove_unreferenced_page_resources == QPDFJob::re_no) { return false; - } - else if (m->remove_unreferenced_page_resources == QPDFJob::re_yes) - { + } else if (m->remove_unreferenced_page_resources == QPDFJob::re_yes) { return true; } @@ -2658,8 +2321,8 @@ QPDFJob::shouldRemoveUnreferencedResources(QPDF& pdf) // Return true as soon as we find any shared resources. - std::set resources_seen; // shared resources detection - std::set nodes_seen; // loop detection + std::set resources_seen; // shared resources detection + std::set nodes_seen; // loop detection doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": " << pdf.getFilename() @@ -2668,90 +2331,70 @@ QPDFJob::shouldRemoveUnreferencedResources(QPDF& pdf) std::list queue; queue.push_back(pdf.getRoot().getKey("/Pages")); - while (! queue.empty()) - { + while (!queue.empty()) { QPDFObjectHandle node = *queue.begin(); queue.pop_front(); QPDFObjGen og = node.getObjGen(); - if (nodes_seen.count(og)) - { + if (nodes_seen.count(og)) { continue; } nodes_seen.insert(og); QPDFObjectHandle dict = node.isStream() ? node.getDict() : node; QPDFObjectHandle kids = dict.getKey("/Kids"); - if (kids.isArray()) - { + if (kids.isArray()) { // This is a non-leaf node. - if (dict.hasKey("/Resources")) - { + if (dict.hasKey("/Resources")) { QTC::TC("qpdf", "QPDFJob found resources in non-leaf"); - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { + doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << " found resources in non-leaf page node " - << og.getObj() << " " << og.getGen() - << std::endl; + << og.getObj() << " " << og.getGen() << std::endl; }); return true; } int n = kids.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { queue.push_back(kids.getArrayItem(i)); } - } - else - { + } else { // This is a leaf node or a form XObject. QPDFObjectHandle resources = dict.getKey("/Resources"); - if (resources.isIndirect()) - { + if (resources.isIndirect()) { QPDFObjGen resources_og = resources.getObjGen(); - if (resources_seen.count(resources_og)) - { + if (resources_seen.count(resources_og)) { QTC::TC("qpdf", "QPDFJob found shared resources in leaf"); - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { - cout << " found shared resources in leaf node " - << og.getObj() << " " << og.getGen() - << ": " - << resources_og.getObj() << " " - << resources_og.getGen() - << std::endl; - }); + doIfVerbose( + [&](std::ostream& cout, std::string const& prefix) { + cout << " found shared resources in leaf node " + << og.getObj() << " " << og.getGen() << ": " + << resources_og.getObj() << " " + << resources_og.getGen() << std::endl; + }); return true; } resources_seen.insert(resources_og); } - QPDFObjectHandle xobject = (resources.isDictionary() ? - resources.getKey("/XObject") : - QPDFObjectHandle::newNull()); - if (xobject.isIndirect()) - { + QPDFObjectHandle xobject = + (resources.isDictionary() ? resources.getKey("/XObject") + : QPDFObjectHandle::newNull()); + if (xobject.isIndirect()) { QPDFObjGen xobject_og = xobject.getObjGen(); - if (resources_seen.count(xobject_og)) - { + if (resources_seen.count(xobject_og)) { QTC::TC("qpdf", "QPDFJob found shared xobject in leaf"); - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { - cout << " found shared xobject in leaf node " - << og.getObj() << " " << og.getGen() - << ": " - << xobject_og.getObj() << " " - << xobject_og.getGen() - << std::endl; - }); + doIfVerbose( + [&](std::ostream& cout, std::string const& prefix) { + cout << " found shared xobject in leaf node " + << og.getObj() << " " << og.getGen() << ": " + << xobject_og.getObj() << " " + << xobject_og.getGen() << std::endl; + }); return true; } resources_seen.insert(xobject_og); } - if (xobject.isDictionary()) - { - for (auto const& k: xobject.getKeys()) - { + if (xobject.isDictionary()) { + for (auto const& k : xobject.getKeys()) { QPDFObjectHandle xobj = xobject.getKey(k); - if (xobj.isFormXObject()) - { + if (xobj.isFormXObject()) { queue.push_back(xobj); } } @@ -2765,11 +2408,11 @@ QPDFJob::shouldRemoveUnreferencedResources(QPDF& pdf) return false; } -static QPDFObjectHandle added_page(QPDF& pdf, QPDFObjectHandle page) +static QPDFObjectHandle +added_page(QPDF& pdf, QPDFObjectHandle page) { QPDFObjectHandle result = page; - if (page.getOwningQPDF() != &pdf) - { + if (page.getOwningQPDF() != &pdf) { // Calling copyForeignObject on an object we already copied // will give us the already existing copy. result = pdf.copyForeignObject(page); @@ -2777,48 +2420,46 @@ static QPDFObjectHandle added_page(QPDF& pdf, QPDFObjectHandle page) return result; } -static QPDFObjectHandle added_page(QPDF& pdf, QPDFPageObjectHelper page) +static QPDFObjectHandle +added_page(QPDF& pdf, QPDFPageObjectHelper page) { return added_page(pdf, page.getObjectHandle()); } void QPDFJob::handlePageSpecs( - QPDF& pdf, bool& warnings, - std::vector>& page_heap) + QPDF& pdf, bool& warnings, std::vector>& page_heap) { // Parse all page specifications and translate them into lists of // actual pages. // Handle "." as a shortcut for the input file for (std::vector::iterator iter = m->page_specs.begin(); - iter != m->page_specs.end(); ++iter) - { + iter != m->page_specs.end(); + ++iter) { QPDFJob::PageSpec& page_spec = *iter; - if (page_spec.filename == ".") - { + if (page_spec.filename == ".") { page_spec.filename = m->infilename.get(); } } - if (! m->keep_files_open_set) - { + if (!m->keep_files_open_set) { // Count the number of distinct files to determine whether we // should keep files open or not. Rather than trying to code // some portable heuristic based on OS limits, just hard-code // this at a given number and allow users to override. std::set filenames; - for (auto& page_spec: m->page_specs) - { + for (auto& page_spec : m->page_specs) { filenames.insert(page_spec.filename); } m->keep_files_open = (filenames.size() <= m->keep_files_open_threshold); - QTC::TC("qpdf", "QPDFJob automatically set keep files open", - m->keep_files_open ? 0 : 1); + QTC::TC( + "qpdf", + "QPDFJob automatically set keep files open", + m->keep_files_open ? 0 : 1); doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": selecting --keep-open-files=" - << (m->keep_files_open ? "y" : "n") - << std::endl; + << (m->keep_files_open ? "y" : "n") << std::endl; }); } @@ -2827,13 +2468,12 @@ QPDFJob::handlePageSpecs( std::map page_spec_cfis; page_spec_qpdfs[m->infilename.get()] = &pdf; std::vector parsed_specs; - std::map > copied_pages; + std::map> copied_pages; for (std::vector::iterator iter = m->page_specs.begin(); - iter != m->page_specs.end(); ++iter) - { + iter != m->page_specs.end(); + ++iter) { QPDFJob::PageSpec& page_spec = *iter; - if (page_spec_qpdfs.count(page_spec.filename) == 0) - { + if (page_spec_qpdfs.count(page_spec.filename) == 0) { // Open the PDF file and store the QPDF object. Throw a // std::shared_ptr to the qpdf into a heap so that it // survives through copying to the output but gets cleaned up @@ -2845,38 +2485,33 @@ QPDFJob::handlePageSpecs( // to the same underlying file with the same path to // achieve the same affect. char const* password = page_spec.password.get(); - if ((! m->encryption_file.empty()) && (password == 0) && - (page_spec.filename == m->encryption_file)) - { + if ((!m->encryption_file.empty()) && (password == 0) && + (page_spec.filename == m->encryption_file)) { QTC::TC("qpdf", "QPDFJob pages encryption password"); password = m->encryption_file_password.get(); } doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << prefix << ": processing " - << page_spec.filename << std::endl; + cout << prefix << ": processing " << page_spec.filename + << std::endl; }); PointerHolder is; ClosedFileInputSource* cis = 0; - if (! m->keep_files_open) - { + if (!m->keep_files_open) { QTC::TC("qpdf", "QPDFJob keep files open n"); cis = new ClosedFileInputSource(page_spec.filename.c_str()); is = PointerHolder(cis); cis->stayOpen(true); - } - else - { + } else { QTC::TC("qpdf", "QPDFJob keep files open y"); FileInputSource* fis = new FileInputSource(); is = PointerHolder(fis); fis->setFilename(page_spec.filename.c_str()); } - std::shared_ptr qpdf_ph = processInputSource( - is, password, true); + std::shared_ptr qpdf_ph = + processInputSource(is, password, true); page_heap.push_back(qpdf_ph); page_spec_qpdfs[page_spec.filename] = qpdf_ph.get(); - if (cis) - { + if (cis) { cis->stayOpen(false); page_spec_cfis[page_spec.filename] = cis; } @@ -2884,35 +2519,31 @@ QPDFJob::handlePageSpecs( // Read original pages from the PDF, and parse the page range // associated with this occurrence of the file. - parsed_specs.push_back( - QPDFPageData(page_spec.filename, - page_spec_qpdfs[page_spec.filename], - page_spec.range)); + parsed_specs.push_back(QPDFPageData( + page_spec.filename, + page_spec_qpdfs[page_spec.filename], + page_spec.range)); } std::map remove_unreferenced; - if (m->remove_unreferenced_page_resources != QPDFJob::re_no) - { + if (m->remove_unreferenced_page_resources != QPDFJob::re_no) { for (std::map::iterator iter = page_spec_qpdfs.begin(); - iter != page_spec_qpdfs.end(); ++iter) - { + iter != page_spec_qpdfs.end(); + ++iter) { std::string const& filename = (*iter).first; ClosedFileInputSource* cis = 0; - if (page_spec_cfis.count(filename)) - { + if (page_spec_cfis.count(filename)) { cis = page_spec_cfis[filename]; cis->stayOpen(true); } QPDF& other(*((*iter).second)); auto other_uuid = other.getUniqueId(); - if (remove_unreferenced.count(other_uuid) == 0) - { + if (remove_unreferenced.count(other_uuid) == 0) { remove_unreferenced[other_uuid] = shouldRemoveUnreferencedResources(other); } - if (cis) - { + if (cis) { cis->stayOpen(false); } } @@ -2924,21 +2555,18 @@ QPDFJob::handlePageSpecs( // things in the original file, such as outlines, to continue to // work. doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << prefix - << ": removing unreferenced pages from primary input" + cout << prefix << ": removing unreferenced pages from primary input" << std::endl; }); QPDFPageDocumentHelper dh(pdf); std::vector orig_pages = dh.getAllPages(); - for (std::vector::iterator iter = - orig_pages.begin(); - iter != orig_pages.end(); ++iter) - { + for (std::vector::iterator iter = orig_pages.begin(); + iter != orig_pages.end(); + ++iter) { dh.removePage(*iter); } - if (m->collate && (parsed_specs.size() > 1)) - { + if (m->collate && (parsed_specs.size() > 1)) { // Collate the pages by selecting one page from each spec in // order. When a spec runs out of pages, stop selecting from // it. @@ -2946,21 +2574,16 @@ QPDFJob::handlePageSpecs( size_t nspecs = parsed_specs.size(); size_t cur_page = 0; bool got_pages = true; - while (got_pages) - { + while (got_pages) { got_pages = false; - for (size_t i = 0; i < nspecs; ++i) - { + for (size_t i = 0; i < nspecs; ++i) { QPDFPageData& page_data = parsed_specs.at(i); - for (size_t j = 0; j < m->collate; ++j) - { - if (cur_page + j < page_data.selected_pages.size()) - { + for (size_t j = 0; j < m->collate; ++j) { + if (cur_page + j < page_data.selected_pages.size()) { got_pages = true; - new_parsed_specs.push_back( - QPDFPageData( - page_data, - page_data.selected_pages.at(cur_page + j))); + new_parsed_specs.push_back(QPDFPageData( + page_data, + page_data.selected_pages.at(cur_page + j))); } } } @@ -2976,64 +2599,56 @@ QPDFJob::handlePageSpecs( std::vector new_labels; bool any_page_labels = false; int out_pageno = 0; - std::map> afdh_map; + std::map> + afdh_map; auto this_afdh = get_afdh_for_qpdf(afdh_map, &pdf); std::set referenced_fields; - for (std::vector::iterator iter = - parsed_specs.begin(); - iter != parsed_specs.end(); ++iter) - { + for (std::vector::iterator iter = parsed_specs.begin(); + iter != parsed_specs.end(); + ++iter) { QPDFPageData& page_data = *iter; ClosedFileInputSource* cis = 0; - if (page_spec_cfis.count(page_data.filename)) - { + if (page_spec_cfis.count(page_data.filename)) { cis = page_spec_cfis[page_data.filename]; cis->stayOpen(true); } QPDFPageLabelDocumentHelper pldh(*page_data.qpdf); auto other_afdh = get_afdh_for_qpdf(afdh_map, page_data.qpdf); - if (pldh.hasPageLabels()) - { + if (pldh.hasPageLabels()) { any_page_labels = true; } doIfVerbose([&](std::ostream& cout, std::string const& prefix) { - cout << prefix << ": adding pages from " - << page_data.filename << std::endl; + cout << prefix << ": adding pages from " << page_data.filename + << std::endl; }); for (std::vector::iterator pageno_iter = page_data.selected_pages.begin(); pageno_iter != page_data.selected_pages.end(); - ++pageno_iter, ++out_pageno) - { + ++pageno_iter, ++out_pageno) { // Pages are specified from 1 but numbered from 0 in the // vector int pageno = *pageno_iter - 1; - pldh.getLabelsForPageRange(pageno, pageno, out_pageno, - new_labels); + pldh.getLabelsForPageRange(pageno, pageno, out_pageno, new_labels); QPDFPageObjectHelper to_copy = page_data.orig_pages.at(QIntC::to_size(pageno)); QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen(); unsigned long long from_uuid = page_data.qpdf->getUniqueId(); - if (copied_pages[from_uuid].count(to_copy_og)) - { - QTC::TC("qpdf", "QPDFJob copy same page more than once", - (page_data.qpdf == &pdf) ? 0 : 1); + if (copied_pages[from_uuid].count(to_copy_og)) { + QTC::TC( + "qpdf", + "QPDFJob copy same page more than once", + (page_data.qpdf == &pdf) ? 0 : 1); to_copy = to_copy.shallowCopyPage(); - } - else - { + } else { copied_pages[from_uuid].insert(to_copy_og); - if (remove_unreferenced[from_uuid]) - { + if (remove_unreferenced[from_uuid]) { to_copy.removeUnreferencedResources(); } } dh.addPage(to_copy, false); bool first_copy_from_orig = false; bool this_file = (page_data.qpdf == &pdf); - if (this_file) - { + if (this_file) { // This is a page from the original file. Keep track // of the fact that we are using it. first_copy_from_orig = (selected_from_orig.count(pageno) == 0); @@ -3051,47 +2666,40 @@ QPDFJob::handlePageSpecs( // more than once, that page would be in conflict with the // previous copy of itself. if (other_afdh->hasAcroForm() && - ((! this_file) || (! first_copy_from_orig))) - { - if (! this_file) - { + ((!this_file) || (!first_copy_from_orig))) { + if (!this_file) { QTC::TC("qpdf", "QPDFJob copy fields not this file"); - } - else if (! first_copy_from_orig) - { + } else if (!first_copy_from_orig) { QTC::TC("qpdf", "QPDFJob copy fields non-first from orig"); } - try - { + try { this_afdh->fixCopiedAnnotations( - new_page, to_copy.getObjectHandle(), *other_afdh, + new_page, + to_copy.getObjectHandle(), + *other_afdh, &referenced_fields); - } - catch (std::exception& e) - { - pdf.warn( - QPDFExc(qpdf_e_damaged_pdf, pdf.getFilename(), - "", 0, "Exception caught while fixing copied" - " annotations. This may be a qpdf bug. " + - std::string("Exception: ") + e.what())); + } catch (std::exception& e) { + pdf.warn(QPDFExc( + qpdf_e_damaged_pdf, + pdf.getFilename(), + "", + 0, + "Exception caught while fixing copied" + " annotations. This may be a qpdf bug. " + + std::string("Exception: ") + e.what())); } } } - if (page_data.qpdf->anyWarnings()) - { + if (page_data.qpdf->anyWarnings()) { warnings = true; } - if (cis) - { + if (cis) { cis->stayOpen(false); } } - if (any_page_labels) - { - QPDFObjectHandle page_labels = - QPDFObjectHandle::newDictionary(); - page_labels.replaceKey( - "/Nums", QPDFObjectHandle::newArray(new_labels)); + if (any_page_labels) { + QPDFObjectHandle page_labels = QPDFObjectHandle::newDictionary(); + page_labels.replaceKey("/Nums", QPDFObjectHandle::newArray(new_labels)); pdf.getRoot().replaceKey("/PageLabels", page_labels); } @@ -3099,50 +2707,37 @@ QPDFJob::handlePageSpecs( // those objects from being preserved by being referred to from // other places, such as the outlines dictionary. Also make sure // we keep form fields from pages we preserved. - for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno) - { + for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno) { auto page = orig_pages.at(pageno); - if (selected_from_orig.count(QIntC::to_int(pageno))) - { - for (auto field: this_afdh->getFormFieldsForPage(page)) - { + if (selected_from_orig.count(QIntC::to_int(pageno))) { + for (auto field : this_afdh->getFormFieldsForPage(page)) { QTC::TC("qpdf", "QPDFJob pages keeping field from original"); referenced_fields.insert(field.getObjectHandle().getObjGen()); } - } - else - { + } else { pdf.replaceObject( page.getObjectHandle().getObjGen(), QPDFObjectHandle::newNull()); } } // Remove unreferenced form fields - if (this_afdh->hasAcroForm()) - { + if (this_afdh->hasAcroForm()) { auto acroform = pdf.getRoot().getKey("/AcroForm"); auto fields = acroform.getKey("/Fields"); - if (fields.isArray()) - { + if (fields.isArray()) { auto new_fields = QPDFObjectHandle::newArray(); - if (fields.isIndirect()) - { + if (fields.isIndirect()) { new_fields = pdf.makeIndirectObject(new_fields); } - for (auto const& field: fields.aitems()) - { - if (referenced_fields.count(field.getObjGen())) - { + for (auto const& field : fields.aitems()) { + if (referenced_fields.count(field.getObjGen())) { new_fields.appendItem(field); } } - if (new_fields.getArrayNItems() > 0) - { + if (new_fields.getArrayNItems() > 0) { QTC::TC("qpdf", "QPDFJob keep some fields in pages"); acroform.replaceKey("/Fields", new_fields); - } - else - { + } else { QTC::TC("qpdf", "QPDFJob no more fields in pages"); pdf.getRoot().removeKey("/AcroForm"); } @@ -3158,21 +2753,20 @@ QPDFJob::handleRotations(QPDF& pdf) int npages = QIntC::to_int(pages.size()); for (std::map::iterator iter = m->rotations.begin(); - iter != m->rotations.end(); ++iter) - { + iter != m->rotations.end(); + ++iter) { std::string const& range = (*iter).first; QPDFJob::RotationSpec const& rspec = (*iter).second; // range has been previously validated std::vector to_rotate = QUtil::parse_numrange(range.c_str(), npages); for (std::vector::iterator i2 = to_rotate.begin(); - i2 != to_rotate.end(); ++i2) - { + i2 != to_rotate.end(); + ++i2) { int pageno = *i2 - 1; - if ((pageno >= 0) && (pageno < npages)) - { - pages.at(QIntC::to_size(pageno)).rotatePage( - rspec.angle, rspec.relative); + if ((pageno >= 0) && (pageno < npages)) { + pages.at(QIntC::to_size(pageno)) + .rotatePage(rspec.angle, rspec.relative); } } } @@ -3181,44 +2775,36 @@ QPDFJob::handleRotations(QPDF& pdf) void QPDFJob::maybeFixWritePassword(int R, std::string& password) { - switch (m->password_mode) - { - case QPDFJob::pm_bytes: + switch (m->password_mode) { + case QPDFJob::pm_bytes: QTC::TC("qpdf", "QPDFJob password mode bytes"); break; - case QPDFJob::pm_hex_bytes: + case QPDFJob::pm_hex_bytes: QTC::TC("qpdf", "QPDFJob password mode hex-bytes"); password = QUtil::hex_decode(password); break; - case QPDFJob::pm_unicode: - case QPDFJob::pm_auto: + case QPDFJob::pm_unicode: + case QPDFJob::pm_auto: { bool has_8bit_chars; bool is_valid_utf8; bool is_utf16; - QUtil::analyze_encoding(password, - has_8bit_chars, - is_valid_utf8, - is_utf16); - if (! has_8bit_chars) - { + QUtil::analyze_encoding( + password, has_8bit_chars, is_valid_utf8, is_utf16); + if (!has_8bit_chars) { return; } - if (m->password_mode == QPDFJob::pm_unicode) - { - if (! is_valid_utf8) - { + if (m->password_mode == QPDFJob::pm_unicode) { + if (!is_valid_utf8) { QTC::TC("qpdf", "QPDFJob password not unicode"); throw std::runtime_error( "supplied password is not valid UTF-8"); } - if (R < 5) - { + if (R < 5) { std::string encoded; - if (! QUtil::utf8_to_pdf_doc(password, encoded)) - { + if (!QUtil::utf8_to_pdf_doc(password, encoded)) { QTC::TC("qpdf", "QPDFJob password not encodable"); throw std::runtime_error( "supplied password cannot be encoded for" @@ -3226,28 +2812,21 @@ QPDFJob::maybeFixWritePassword(int R, std::string& password) } password = encoded; } - } - else - { - if ((R < 5) && is_valid_utf8) - { + } else { + if ((R < 5) && is_valid_utf8) { std::string encoded; - if (QUtil::utf8_to_pdf_doc(password, encoded)) - { + if (QUtil::utf8_to_pdf_doc(password, encoded)) { QTC::TC("qpdf", "QPDFJob auto-encode password"); - doIfVerbose([&](std::ostream& cout, - std::string const& prefix) { - cout - << prefix - << ": automatically converting Unicode" - << " password to single-byte encoding as" - << " required for 40-bit or 128-bit" - << " encryption" << std::endl; - }); + doIfVerbose( + [&](std::ostream& cout, std::string const& prefix) { + cout << prefix + << ": automatically converting Unicode" + << " password to single-byte encoding as" + << " required for 40-bit or 128-bit" + << " encryption" << std::endl; + }); password = encoded; - } - else - { + } else { QTC::TC("qpdf", "QPDFJob bytes fallback warning"); *(this->m->cerr) << this->m->message_prefix << ": WARNING: " @@ -3260,9 +2839,7 @@ QPDFJob::maybeFixWritePassword(int R, std::string& password) << " warning and use the password anyway.)" << std::endl; } - } - else if ((R >= 5) && (! is_valid_utf8)) - { + } else if ((R >= 5) && (!is_valid_utf8)) { QTC::TC("qpdf", "QPDFJob invalid utf-8 in auto"); throw std::runtime_error( "supplied password is not a valid Unicode password," @@ -3280,49 +2857,32 @@ void QPDFJob::setEncryptionOptions(QPDF& pdf, QPDFWriter& w) { int R = 0; - if (m->keylen == 40) - { + if (m->keylen == 40) { R = 2; - } - else if (m->keylen == 128) - { - if (m->force_V4 || m->cleartext_metadata || m->use_aes) - { + } else if (m->keylen == 128) { + if (m->force_V4 || m->cleartext_metadata || m->use_aes) { R = 4; - } - else - { + } else { R = 3; } - } - else if (m->keylen == 256) - { - if (m->force_R5) - { + } else if (m->keylen == 256) { + if (m->force_R5) { R = 5; - } - else - { + } else { R = 6; } - } - else - { + } else { throw std::logic_error("bad encryption keylen"); } - if ((R > 3) && (m->r3_accessibility == false)) - { - *(this->m->cerr) - << this->m->message_prefix - << ": -accessibility=n is ignored for modern" - << " encryption formats" << std::endl; + if ((R > 3) && (m->r3_accessibility == false)) { + *(this->m->cerr) << this->m->message_prefix + << ": -accessibility=n is ignored for modern" + << " encryption formats" << std::endl; } maybeFixWritePassword(R, m->user_password); maybeFixWritePassword(R, m->owner_password); - if ((R < 4) || ((R == 4) && (! m->use_aes))) - { - if (! m->allow_weak_crypto) - { + if ((R < 4) || ((R == 4) && (!m->use_aes))) { + if (!m->allow_weak_crypto) { // Do not set warnings = true for this case as this does // not reflect a potential problem with the input file. QTC::TC("qpdf", "QPDFJob weak crypto warning"); @@ -3330,68 +2890,92 @@ QPDFJob::setEncryptionOptions(QPDF& pdf, QPDFWriter& w) << this->m->message_prefix << ": writing a file with RC4, a weak cryptographic algorithm" << std::endl - << "Please use 256-bit keys for better security." - << std::endl + << "Please use 256-bit keys for better security." << std::endl << "Pass --allow-weak-crypto to suppress this warning." << std::endl << "This will become an error in a future version of qpdf." << std::endl; } } - switch (R) - { - case 2: + switch (R) { + case 2: w.setR2EncryptionParameters( - m->user_password.c_str(), m->owner_password.c_str(), - m->r2_print, m->r2_modify, m->r2_extract, m->r2_annotate); + m->user_password.c_str(), + m->owner_password.c_str(), + m->r2_print, + m->r2_modify, + m->r2_extract, + m->r2_annotate); break; - case 3: + case 3: w.setR3EncryptionParameters( - m->user_password.c_str(), m->owner_password.c_str(), - m->r3_accessibility, m->r3_extract, - m->r3_assemble, m->r3_annotate_and_form, - m->r3_form_filling, m->r3_modify_other, + m->user_password.c_str(), + m->owner_password.c_str(), + m->r3_accessibility, + m->r3_extract, + m->r3_assemble, + m->r3_annotate_and_form, + m->r3_form_filling, + m->r3_modify_other, m->r3_print); break; - case 4: + case 4: w.setR4EncryptionParameters( - m->user_password.c_str(), m->owner_password.c_str(), - m->r3_accessibility, m->r3_extract, - m->r3_assemble, m->r3_annotate_and_form, - m->r3_form_filling, m->r3_modify_other, - m->r3_print, !m->cleartext_metadata, m->use_aes); + m->user_password.c_str(), + m->owner_password.c_str(), + m->r3_accessibility, + m->r3_extract, + m->r3_assemble, + m->r3_annotate_and_form, + m->r3_form_filling, + m->r3_modify_other, + m->r3_print, + !m->cleartext_metadata, + m->use_aes); break; - case 5: + case 5: w.setR5EncryptionParameters( - m->user_password.c_str(), m->owner_password.c_str(), - m->r3_accessibility, m->r3_extract, - m->r3_assemble, m->r3_annotate_and_form, - m->r3_form_filling, m->r3_modify_other, - m->r3_print, !m->cleartext_metadata); + m->user_password.c_str(), + m->owner_password.c_str(), + m->r3_accessibility, + m->r3_extract, + m->r3_assemble, + m->r3_annotate_and_form, + m->r3_form_filling, + m->r3_modify_other, + m->r3_print, + !m->cleartext_metadata); break; - case 6: + case 6: w.setR6EncryptionParameters( - m->user_password.c_str(), m->owner_password.c_str(), - m->r3_accessibility, m->r3_extract, - m->r3_assemble, m->r3_annotate_and_form, - m->r3_form_filling, m->r3_modify_other, - m->r3_print, !m->cleartext_metadata); + m->user_password.c_str(), + m->owner_password.c_str(), + m->r3_accessibility, + m->r3_extract, + m->r3_assemble, + m->r3_annotate_and_form, + m->r3_form_filling, + m->r3_modify_other, + m->r3_print, + !m->cleartext_metadata); break; - default: + default: throw std::logic_error("bad encryption R value"); break; } } -static void parse_version(std::string const& full_version_string, - std::string& version, int& extension_level) +static void +parse_version( + std::string const& full_version_string, + std::string& version, + int& extension_level) { auto vp = QUtil::make_unique_cstr(full_version_string); char* v = vp.get(); char* p1 = strchr(v, '.'); char* p2 = (p1 ? strchr(1 + p1, '.') : 0); - if (p2 && *(p2 + 1)) - { + if (p2 && *(p2 + 1)) { *p2++ = '\0'; extension_level = QUtil::string_to_int(p2); } @@ -3401,107 +2985,86 @@ static void parse_version(std::string const& full_version_string, void QPDFJob::setWriterOptions(QPDF& pdf, QPDFWriter& w) { - if (m->compression_level >= 0) - { + if (m->compression_level >= 0) { Pl_Flate::setCompressionLevel(m->compression_level); } - if (m->qdf_mode) - { + if (m->qdf_mode) { w.setQDFMode(true); } - if (m->preserve_unreferenced_objects) - { + if (m->preserve_unreferenced_objects) { w.setPreserveUnreferencedObjects(true); } - if (m->newline_before_endstream) - { + if (m->newline_before_endstream) { w.setNewlineBeforeEndstream(true); } - if (m->normalize_set) - { + if (m->normalize_set) { w.setContentNormalization(m->normalize); } - if (m->stream_data_set) - { + if (m->stream_data_set) { w.setStreamDataMode(m->stream_data_mode); } - if (m->compress_streams_set) - { + if (m->compress_streams_set) { w.setCompressStreams(m->compress_streams); } - if (m->recompress_flate_set) - { + if (m->recompress_flate_set) { w.setRecompressFlate(m->recompress_flate); } - if (m->decode_level_set) - { + if (m->decode_level_set) { w.setDecodeLevel(m->decode_level); } - if (m->decrypt) - { + if (m->decrypt) { w.setPreserveEncryption(false); } - if (m->deterministic_id) - { + if (m->deterministic_id) { w.setDeterministicID(true); } - if (m->static_id) - { + if (m->static_id) { w.setStaticID(true); } - if (m->static_aes_iv) - { + if (m->static_aes_iv) { w.setStaticAesIV(true); } - if (m->suppress_original_object_id) - { + if (m->suppress_original_object_id) { w.setSuppressOriginalObjectIDs(true); } - if (m->copy_encryption) - { - std::shared_ptr encryption_pdf = - processFile(m->encryption_file.c_str(), - m->encryption_file_password.get(), false); + if (m->copy_encryption) { + std::shared_ptr encryption_pdf = processFile( + m->encryption_file.c_str(), + m->encryption_file_password.get(), + false); w.copyEncryptionParameters(*encryption_pdf); } - if (m->encrypt) - { + if (m->encrypt) { setEncryptionOptions(pdf, w); } - if (m->linearize) - { + if (m->linearize) { w.setLinearization(true); } - if (! m->linearize_pass1.empty()) - { + if (!m->linearize_pass1.empty()) { w.setLinearizationPass1Filename(m->linearize_pass1); } - if (m->object_stream_set) - { + if (m->object_stream_set) { w.setObjectStreamMode(m->object_stream_mode); } w.setMinimumPDFVersion(this->m->max_input_version); - if (! m->min_version.empty()) - { + if (!m->min_version.empty()) { std::string version; int extension_level = 0; parse_version(m->min_version, version, extension_level); w.setMinimumPDFVersion(version, extension_level); } - if (! m->force_version.empty()) - { + if (!m->force_version.empty()) { std::string version; int extension_level = 0; parse_version(m->force_version, version, extension_level); w.forcePDFVersion(version, extension_level); } - if (m->progress && m->outfilename) - { + if (m->progress && m->outfilename) { w.registerProgressReporter( - PointerHolder( - new ProgressReporter( - *(this->m->cout), this->m->message_prefix, - m->outfilename.get()))); + PointerHolder(new ProgressReporter( + *(this->m->cout), + this->m->message_prefix, + m->outfilename.get()))); } } @@ -3513,29 +3076,25 @@ QPDFJob::doSplitPages(QPDF& pdf, bool& warnings) std::string after; size_t len = strlen(m->outfilename.get()); char* num_spot = strstr(const_cast(m->outfilename.get()), "%d"); - if (num_spot != 0) - { + if (num_spot != 0) { QTC::TC("qpdf", "QPDFJob split-pages %d"); - before = std::string(m->outfilename.get(), - QIntC::to_size(num_spot - m->outfilename.get())); + before = std::string( + m->outfilename.get(), + QIntC::to_size(num_spot - m->outfilename.get())); after = num_spot + 2; - } - else if ((len >= 4) && - (QUtil::str_compare_nocase( - m->outfilename.get() + len - 4, ".pdf") == 0)) - { + } else if ( + (len >= 4) && + (QUtil::str_compare_nocase(m->outfilename.get() + len - 4, ".pdf") == + 0)) { QTC::TC("qpdf", "QPDFJob split-pages .pdf"); before = std::string(m->outfilename.get(), len - 4) + "-"; after = m->outfilename.get() + len - 4; - } - else - { + } else { QTC::TC("qpdf", "QPDFJob split-pages other"); before = std::string(m->outfilename.get()) + "-"; } - if (shouldRemoveUnreferencedResources(pdf)) - { + if (shouldRemoveUnreferencedResources(pdf)) { QPDFPageDocumentHelper dh(pdf); dh.removeUnreferencedResources(); } @@ -3544,70 +3103,60 @@ QPDFJob::doSplitPages(QPDF& pdf, bool& warnings) std::vector const& pages = pdf.getAllPages(); size_t pageno_len = QUtil::uint_to_string(pages.size()).length(); size_t num_pages = pages.size(); - for (size_t i = 0; i < num_pages; i += QIntC::to_size(m->split_pages)) - { + for (size_t i = 0; i < num_pages; i += QIntC::to_size(m->split_pages)) { size_t first = i + 1; size_t last = i + QIntC::to_size(m->split_pages); - if (last > num_pages) - { + if (last > num_pages) { last = num_pages; } QPDF outpdf; outpdf.emptyPDF(); std::shared_ptr out_afdh; - if (afdh.hasAcroForm()) - { + if (afdh.hasAcroForm()) { out_afdh = std::make_shared(outpdf); } - if (m->suppress_warnings) - { + if (m->suppress_warnings) { outpdf.setSuppressWarnings(true); } - for (size_t pageno = first; pageno <= last; ++pageno) - { + for (size_t pageno = first; pageno <= last; ++pageno) { QPDFObjectHandle page = pages.at(pageno - 1); outpdf.addPage(page, false); auto new_page = added_page(outpdf, page); - if (out_afdh.get()) - { + if (out_afdh.get()) { QTC::TC("qpdf", "QPDFJob copy form fields in split_pages"); - try - { + try { out_afdh->fixCopiedAnnotations(new_page, page, afdh); - } - catch (std::exception& e) - { - pdf.warn( - QPDFExc(qpdf_e_damaged_pdf, pdf.getFilename(), - "", 0, "Exception caught while fixing copied" - " annotations. This may be a qpdf bug." + - std::string("Exception: ") + e.what())); + } catch (std::exception& e) { + pdf.warn(QPDFExc( + qpdf_e_damaged_pdf, + pdf.getFilename(), + "", + 0, + "Exception caught while fixing copied" + " annotations. This may be a qpdf bug." + + std::string("Exception: ") + e.what())); } } } - if (pldh.hasPageLabels()) - { + if (pldh.hasPageLabels()) { std::vector labels; pldh.getLabelsForPageRange( QIntC::to_longlong(first - 1), QIntC::to_longlong(last - 1), - 0, labels); - QPDFObjectHandle page_labels = - QPDFObjectHandle::newDictionary(); - page_labels.replaceKey( - "/Nums", QPDFObjectHandle::newArray(labels)); + 0, + labels); + QPDFObjectHandle page_labels = QPDFObjectHandle::newDictionary(); + page_labels.replaceKey("/Nums", QPDFObjectHandle::newArray(labels)); outpdf.getRoot().replaceKey("/PageLabels", page_labels); } std::string page_range = QUtil::uint_to_string(first, QIntC::to_int(pageno_len)); - if (m->split_pages > 1) - { - page_range += "-" + - QUtil::uint_to_string(last, QIntC::to_int(pageno_len)); + if (m->split_pages > 1) { + page_range += + "-" + QUtil::uint_to_string(last, QIntC::to_int(pageno_len)); } std::string outfile = before + page_range + after; - if (QUtil::same_file(m->infilename.get(), outfile.c_str())) - { + if (QUtil::same_file(m->infilename.get(), outfile.c_str())) { throw std::runtime_error( "split pages would overwrite input file with " + outfile); } @@ -3617,8 +3166,7 @@ QPDFJob::doSplitPages(QPDF& pdf, bool& warnings) doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": wrote file " << outfile << std::endl; }); - if (outpdf.anyWarnings()) - { + if (outpdf.anyWarnings()) { warnings = true; } } @@ -3628,8 +3176,7 @@ void QPDFJob::writeOutfile(QPDF& pdf) { std::shared_ptr temp_out; - if (m->replace_input) - { + if (m->replace_input) { // Append but don't prepend to the path to generate a // temporary name. This saves us from having to split the path // by directory and non-directory. @@ -3638,9 +3185,7 @@ QPDFJob::writeOutfile(QPDF& pdf) // m->outfilename will be restored to 0 before temp_out // goes out of scope. m->outfilename = temp_out; - } - else if (strcmp(m->outfilename.get(), "-") == 0) - { + } else if (strcmp(m->outfilename.get(), "-") == 0) { m->outfilename = 0; } { @@ -3649,50 +3194,37 @@ QPDFJob::writeOutfile(QPDF& pdf) setWriterOptions(pdf, w); w.write(); } - if (m->outfilename) - { + if (m->outfilename) { doIfVerbose([&](std::ostream& cout, std::string const& prefix) { cout << prefix << ": wrote file " << m->outfilename << std::endl; }); } - if (m->replace_input) - { + if (m->replace_input) { m->outfilename = 0; } - if (m->replace_input) - { + if (m->replace_input) { // We must close the input before we can rename files pdf.closeInputSource(); std::string backup = std::string(m->infilename.get()) + ".~qpdf-orig"; bool warnings = pdf.anyWarnings(); - if (! warnings) - { + if (!warnings) { backup.append(1, '#'); } QUtil::rename_file(m->infilename.get(), backup.c_str()); QUtil::rename_file(temp_out.get(), m->infilename.get()); - if (warnings) - { - *(this->m->cerr) - << this->m->message_prefix - << ": there are warnings; original file kept in " - << backup << std::endl; - } - else - { - try - { + if (warnings) { + *(this->m->cerr) << this->m->message_prefix + << ": there are warnings; original file kept in " + << backup << std::endl; + } else { + try { QUtil::remove_file(backup.c_str()); - } - catch (QPDFSystemError& e) - { + } catch (QPDFSystemError& e) { *(this->m->cerr) << this->m->message_prefix - << ": unable to delete original file (" - << e.what() << ");" + << ": unable to delete original file (" << e.what() << ");" << " original file left in " << backup - << ", but the input was successfully replaced" - << std::endl; + << ", but the input was successfully replaced" << std::endl; } } } diff --git a/libqpdf/QPDFJob_argv.cc b/libqpdf/QPDFJob_argv.cc index b1e3da1c..969af7db 100644 --- a/libqpdf/QPDFJob_argv.cc +++ b/libqpdf/QPDFJob_argv.cc @@ -2,32 +2,31 @@ // See "HOW TO ADD A COMMAND-LINE ARGUMENT" in README-maintainer. -#include -#include -#include #include #include +#include #include #include +#include +#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include namespace { class ArgParser { public: - ArgParser(QPDFArgParser& ap, - std::shared_ptr c_main); + ArgParser(QPDFArgParser& ap, std::shared_ptr c_main); void parseOptions(); private: -# include +#include void usage(std::string const& message); void initOptionTables(); @@ -44,10 +43,10 @@ namespace bool gave_input; bool gave_output; }; -} +} // namespace -ArgParser::ArgParser(QPDFArgParser& ap, - std::shared_ptr c_main) : +ArgParser::ArgParser( + QPDFArgParser& ap, std::shared_ptr c_main) : ap(ap), c_main(c_main), pages_password(nullptr), @@ -62,33 +61,27 @@ ArgParser::ArgParser(QPDFArgParser& ap, void ArgParser::initOptionTables() { - -# include - this->ap.addFinalCheck([this](){c_main->checkConfiguration();}); +#include + this->ap.addFinalCheck([this]() { c_main->checkConfiguration(); }); // add_help is defined in auto_job_help.hh add_help(this->ap); // Special case: ignore -- at the top level. This undocumented // behavior is for backward compatibility; it was unintentionally // the case prior to 10.6, and some users were relying on it. this->ap.selectMainOptionTable(); - this->ap.addBare("--", [](){}); + this->ap.addBare("--", []() {}); } void ArgParser::argPositional(std::string const& arg) { - if (! this->gave_input) - { + if (!this->gave_input) { c_main->inputFile(arg); this->gave_input = true; - } - else if (! this->gave_output) - { + } else if (!this->gave_output) { c_main->outputFile(arg); this->gave_output = true; - } - else - { + } else { usage("unknown argument " + arg); } } @@ -111,10 +104,10 @@ void ArgParser::argVersion() { auto whoami = this->ap.getProgname(); - std::cout - << whoami << " version " << QPDF::QPDFVersion() << std::endl - << "Run " << whoami << " --copyright to see copyright and license information." - << std::endl; + std::cout << whoami << " version " << QPDF::QPDFVersion() << std::endl + << "Run " << whoami + << " --copyright to see copyright and license information." + << std::endl; } void @@ -174,10 +167,8 @@ ArgParser::argShowCrypto() auto crypto = QPDFCryptoProvider::getRegisteredImpls(); std::string default_crypto = QPDFCryptoProvider::getDefaultProvider(); std::cout << default_crypto << std::endl; - for (auto const& iter: crypto) - { - if (iter != default_crypto) - { + for (auto const& iter : crypto) { + if (iter != default_crypto) { std::cout << iter << std::endl; } } @@ -187,8 +178,7 @@ void ArgParser::argEncrypt() { this->accumulated_args.clear(); - if (this->ap.isCompleting() && this->ap.argsLeft() == 0) - { + if (this->ap.isCompleting() && this->ap.argsLeft() == 0) { this->ap.insertCompletion("user-password"); } this->ap.selectOptionTable(O_ENCRYPTION); @@ -199,16 +189,11 @@ ArgParser::argEncPositional(std::string const& arg) { this->accumulated_args.push_back(arg); size_t n_args = this->accumulated_args.size(); - if (n_args < 3) - { - if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) - { - if (n_args == 1) - { + if (n_args < 3) { + if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) { + if (n_args == 1) { this->ap.insertCompletion("owner-password"); - } - else if (n_args == 2) - { + } else if (n_args == 2) { this->ap.insertCompletion("40"); this->ap.insertCompletion("128"); this->ap.insertCompletion("256"); @@ -220,23 +205,16 @@ ArgParser::argEncPositional(std::string const& arg) std::string owner_password = this->accumulated_args.at(1); std::string len_str = this->accumulated_args.at(2); int keylen = 0; - if (len_str == "40") - { + if (len_str == "40") { keylen = 40; this->ap.selectOptionTable(O_40_BIT_ENCRYPTION); - } - else if (len_str == "128") - { + } else if (len_str == "128") { keylen = 128; this->ap.selectOptionTable(O_128_BIT_ENCRYPTION); - } - else if (len_str == "256") - { + } else if (len_str == "256") { keylen = 256; this->ap.selectOptionTable(O_256_BIT_ENCRYPTION); - } - else - { + } else { usage("encryption key length must be 40, 128, or 256"); } this->c_enc = c_main->encrypt(keylen, user_password, owner_password); @@ -253,13 +231,11 @@ ArgParser::argPages() void ArgParser::argPagesPassword(std::string const& parameter) { - if (this->pages_password) - { + if (this->pages_password) { QTC::TC("qpdf", "QPDFJob duplicated pages password"); usage("--password already specified for this file"); } - if (this->accumulated_args.size() != 1) - { + if (this->accumulated_args.size() != 1) { QTC::TC("qpdf", "QPDFJob misplaced pages password"); usage("in --pages, --password must immediately follow a file name"); } @@ -269,15 +245,11 @@ ArgParser::argPagesPassword(std::string const& parameter) void ArgParser::argPagesPositional(std::string const& arg) { - if (arg.empty()) - { - if (this->accumulated_args.empty()) - { + if (arg.empty()) { + if (this->accumulated_args.empty()) { return; } - } - else - { + } else { this->accumulated_args.push_back(arg); } @@ -285,8 +257,7 @@ ArgParser::argPagesPositional(std::string const& arg) char const* range_p = nullptr; size_t n_args = this->accumulated_args.size(); - if (n_args >= 2) - { + if (n_args >= 2) { // will be copied before accumulated_args is cleared range_p = this->accumulated_args.at(1).c_str(); } @@ -294,41 +265,29 @@ ArgParser::argPagesPositional(std::string const& arg) // See if the user omitted the range entirely, in which case we // assume "1-z". std::string next_file; - if (range_p == nullptr) - { - if (arg.empty()) - { + if (range_p == nullptr) { + if (arg.empty()) { // The filename or password was the last argument - QTC::TC("qpdf", "QPDFJob pages range omitted at end", - this->pages_password ? 0 : 1); - } - else - { + QTC::TC( + "qpdf", + "QPDFJob pages range omitted at end", + this->pages_password ? 0 : 1); + } else { // We need to accumulate some more arguments return; } - } - else - { - try - { + } else { + try { QUtil::parse_numrange(range_p, 0); - } - catch (std::runtime_error& e1) - { + } catch (std::runtime_error& e1) { // The range is invalid. Let's see if it's a file. - if (strcmp(range_p, ".") == 0) - { + if (strcmp(range_p, ".") == 0) { // "." means the input file. QTC::TC("qpdf", "QPDFJob pages range omitted with ."); - } - else if (QUtil::file_can_be_opened(range_p)) - { + } else if (QUtil::file_can_be_opened(range_p)) { QTC::TC("qpdf", "QPDFJob pages range omitted in middle"); // Yup, it's a file. - } - else - { + } else { // Give the range error usage(e1.what()); } @@ -340,8 +299,7 @@ ArgParser::argPagesPositional(std::string const& arg) this->c_pages->pageSpec(file, range, this->pages_password.get()); this->accumulated_args.clear(); this->pages_password = nullptr; - if (! next_file.empty()) - { + if (!next_file.empty()) { this->accumulated_args.push_back(next_file); } } @@ -461,27 +419,21 @@ ArgParser::usage(std::string const& message) void ArgParser::parseOptions() { - try - { + try { this->ap.parseArgs(); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { usage(e.what()); } } void -QPDFJob::initializeFromArgv(char const* const argv[], - char const* progname_env) +QPDFJob::initializeFromArgv(char const* const argv[], char const* progname_env) { - if (progname_env == nullptr) - { + if (progname_env == nullptr) { progname_env = "QPDF_EXECUTABLE"; } int argc = 0; - for (auto k = argv; *k; ++k) - { + for (auto k = argv; *k; ++k) { ++argc; } QPDFArgParser qap(argc, argv, progname_env); diff --git a/libqpdf/QPDFJob_config.cc b/libqpdf/QPDFJob_config.cc index 8aac6ca8..286e4056 100644 --- a/libqpdf/QPDFJob_config.cc +++ b/libqpdf/QPDFJob_config.cc @@ -1,7 +1,7 @@ #include -#include #include +#include void QPDFJob::Config::checkConfiguration() @@ -12,12 +12,9 @@ QPDFJob::Config::checkConfiguration() QPDFJob::Config* QPDFJob::Config::inputFile(std::string const& filename) { - if (o.m->infilename == 0) - { + if (o.m->infilename == 0) { o.m->infilename = QUtil::make_shared_cstr(filename); - } - else - { + } else { usage("input file has already been given"); } return this; @@ -26,8 +23,7 @@ QPDFJob::Config::inputFile(std::string const& filename) QPDFJob::Config* QPDFJob::Config::emptyInput() { - if (o.m->infilename == 0) - { + if (o.m->infilename == 0) { // Various places in QPDFJob.cc know that the empty string for // infile means empty. This means that passing "" as the // argument to inputFile, or equivalently using "" as a @@ -36,9 +32,7 @@ QPDFJob::Config::emptyInput() // around, but it would be better if we had a tighter way of // knowing that the input file is empty. o.m->infilename = QUtil::make_shared_cstr(""); - } - else - { + } else { usage("empty input can't be used" " since input file has already been given"); } @@ -48,12 +42,9 @@ QPDFJob::Config::emptyInput() QPDFJob::Config* QPDFJob::Config::outputFile(std::string const& filename) { - if ((o.m->outfilename == 0) && (! o.m->replace_input)) - { + if ((o.m->outfilename == 0) && (!o.m->replace_input)) { o.m->outfilename = QUtil::make_shared_cstr(filename); - } - else - { + } else { usage("output file has already been given"); } return this; @@ -62,12 +53,9 @@ QPDFJob::Config::outputFile(std::string const& filename) QPDFJob::Config* QPDFJob::Config::replaceInput() { - if ((o.m->outfilename == 0) && (! o.m->replace_input)) - { + if ((o.m->outfilename == 0) && (!o.m->replace_input)) { o.m->replace_input = true; - } - else - { + } else { usage("replace-input can't be used" " since output file has already been given"); } @@ -184,16 +172,11 @@ QPDFJob::Config* QPDFJob::Config::flattenAnnotations(std::string const& parameter) { o.m->flatten_annotations = true; - if (parameter == "screen") - { + if (parameter == "screen") { o.m->flatten_annotations_forbidden |= an_no_view; - } - else if (parameter == "print") - { + } else if (parameter == "print") { o.m->flatten_annotations_required |= an_print; - } - else if (parameter != "all") - { + } else if (parameter != "all") { usage("invalid flatten-annotations option"); } return this; @@ -251,21 +234,15 @@ QPDFJob::Config::json() QPDFJob::Config* QPDFJob::Config::json(std::string const& parameter) { - if (parameter.empty()) - { + if (parameter.empty()) { // The default value is 1 for backward compatibility. o.m->json_version = 1; - } - else if (parameter == "latest") - { + } else if (parameter == "latest") { o.m->json_version = 1; - } - else - { + } else { o.m->json_version = QUtil::string_to_int(parameter.c_str()); } - if (o.m->json_version != 1) - { + if (o.m->json_version != 1) { usage(std::string("unsupported json version ") + parameter); } o.m->require_outfile = false; @@ -595,22 +572,17 @@ QPDFJob::Config* QPDFJob::Config::passwordFile(std::string const& parameter) { std::list lines; - if (parameter == "-") - { + if (parameter == "-") { QTC::TC("qpdf", "QPDFJob_config password stdin"); lines = QUtil::read_lines_from_file(std::cin); - } - else - { + } else { QTC::TC("qpdf", "QPDFJob_config password file"); lines = QUtil::read_lines_from_file(parameter.c_str()); } - if (lines.size() >= 1) - { + if (lines.size() >= 1) { o.m->password = QUtil::make_shared_cstr(lines.front()); - if (lines.size() > 1) - { + if (lines.size() > 1) { std::cerr << this->o.m->message_prefix << ": WARNING: all but the first line of" << " the password file are ignored" << std::endl; @@ -622,24 +594,15 @@ QPDFJob::Config::passwordFile(std::string const& parameter) QPDFJob::Config* QPDFJob::Config::passwordMode(std::string const& parameter) { - if (parameter == "bytes") - { + if (parameter == "bytes") { o.m->password_mode = QPDFJob::pm_bytes; - } - else if (parameter == "hex-bytes") - { + } else if (parameter == "hex-bytes") { o.m->password_mode = QPDFJob::pm_hex_bytes; - } - else if (parameter == "unicode") - { + } else if (parameter == "unicode") { o.m->password_mode = QPDFJob::pm_unicode; - } - else if (parameter == "auto") - { + } else if (parameter == "auto") { o.m->password_mode = QPDFJob::pm_auto; - } - else - { + } else { usage("invalid password-mode option"); } return this; @@ -649,20 +612,13 @@ QPDFJob::Config* QPDFJob::Config::streamData(std::string const& parameter) { o.m->stream_data_set = true; - if (parameter == "compress") - { + if (parameter == "compress") { o.m->stream_data_mode = qpdf_s_compress; - } - else if (parameter == "preserve") - { + } else if (parameter == "preserve") { o.m->stream_data_mode = qpdf_s_preserve; - } - else if (parameter == "uncompress") - { + } else if (parameter == "uncompress") { o.m->stream_data_mode = qpdf_s_uncompress; - } - else - { + } else { usage("invalid stream-data option"); } return this; @@ -672,24 +628,15 @@ QPDFJob::Config* QPDFJob::Config::decodeLevel(std::string const& parameter) { o.m->decode_level_set = true; - if (parameter == "none") - { + if (parameter == "none") { o.m->decode_level = qpdf_dl_none; - } - else if (parameter == "generalized") - { + } else if (parameter == "generalized") { o.m->decode_level = qpdf_dl_generalized; - } - else if (parameter == "specialized") - { + } else if (parameter == "specialized") { o.m->decode_level = qpdf_dl_specialized; - } - else if (parameter == "all") - { + } else if (parameter == "all") { o.m->decode_level = qpdf_dl_all; - } - else - { + } else { usage("invalid option"); } return this; @@ -699,20 +646,13 @@ QPDFJob::Config* QPDFJob::Config::objectStreams(std::string const& parameter) { o.m->object_stream_set = true; - if (parameter == "disable") - { + if (parameter == "disable") { o.m->object_stream_mode = qpdf_o_disable; - } - else if (parameter == "preserve") - { + } else if (parameter == "preserve") { o.m->object_stream_mode = qpdf_o_preserve; - } - else if (parameter == "generate") - { + } else if (parameter == "generate") { o.m->object_stream_mode = qpdf_o_generate; - } - else - { + } else { usage("invalid object stream mode"); } return this; @@ -721,20 +661,13 @@ QPDFJob::Config::objectStreams(std::string const& parameter) QPDFJob::Config* QPDFJob::Config::removeUnreferencedResources(std::string const& parameter) { - if (parameter == "auto") - { + if (parameter == "auto") { o.m->remove_unreferenced_page_resources = QPDFJob::re_auto; - } - else if (parameter == "yes") - { + } else if (parameter == "yes") { o.m->remove_unreferenced_page_resources = QPDFJob::re_yes; - } - else if (parameter == "no") - { + } else if (parameter == "no") { o.m->remove_unreferenced_page_resources = QPDFJob::re_no; - } - else - { + } else { usage("invalid value for --remove-unreferenced-page-resources"); } return this; @@ -755,12 +688,9 @@ QPDFJob::Config::jobJsonFile(std::string const& parameter) PointerHolder file_buf; size_t size; QUtil::read_file_into_memory(parameter.c_str(), file_buf, size); - try - { + try { o.initializeFromJson(std::string(file_buf.get(), size), true); - } - catch (std::exception& e) - { + } catch (std::exception& e) { throw std::runtime_error( "error with job-json file " + std::string(parameter) + ": " + e.what() + "\nRun " + this->o.m->message_prefix + @@ -811,8 +741,7 @@ QPDFJob::CopyAttConfig::password(std::string const& parameter) QPDFJob::Config* QPDFJob::CopyAttConfig::endCopyAttachmentsFrom() { - if (this->caf.path.empty()) - { + if (this->caf.path.empty()) { usage("copy attachments: no file specified"); } this->config->o.m->attachments_to_copy.push_back(this->caf); @@ -854,8 +783,7 @@ QPDFJob::AttConfig::filename(std::string const& parameter) QPDFJob::AttConfig* QPDFJob::AttConfig::creationdate(std::string const& parameter) { - if (! QUtil::pdf_time_to_qpdf_time(parameter)) - { + if (!QUtil::pdf_time_to_qpdf_time(parameter)) { usage(std::string(parameter) + " is not a valid PDF timestamp"); } this->att.creationdate = parameter; @@ -865,8 +793,7 @@ QPDFJob::AttConfig::creationdate(std::string const& parameter) QPDFJob::AttConfig* QPDFJob::AttConfig::moddate(std::string const& parameter) { - if (! QUtil::pdf_time_to_qpdf_time(parameter)) - { + if (!QUtil::pdf_time_to_qpdf_time(parameter)) { usage(std::string(parameter) + " is not a valid PDF timestamp"); } this->att.moddate = parameter; @@ -876,8 +803,7 @@ QPDFJob::AttConfig::moddate(std::string const& parameter) QPDFJob::AttConfig* QPDFJob::AttConfig::mimetype(std::string const& parameter) { - if (parameter.find('/') == std::string::npos) - { + if (parameter.find('/') == std::string::npos) { usage("mime type should be specified as type/subtype"); } this->att.mimetype = parameter; @@ -901,31 +827,25 @@ QPDFJob::AttConfig::replace() QPDFJob::Config* QPDFJob::AttConfig::endAddAttachment() { - static std::string now = QUtil::qpdf_time_to_pdf_time( - QUtil::get_current_qpdf_time()); - if (this->att.path.empty()) - { + static std::string now = + QUtil::qpdf_time_to_pdf_time(QUtil::get_current_qpdf_time()); + if (this->att.path.empty()) { usage("add attachment: no file specified"); } std::string last_element = QUtil::path_basename(this->att.path); - if (last_element.empty()) - { + if (last_element.empty()) { usage("file for --add-attachment may not be empty"); } - if (this->att.filename.empty()) - { + if (this->att.filename.empty()) { this->att.filename = last_element; } - if (this->att.key.empty()) - { + if (this->att.key.empty()) { this->att.key = last_element; } - if (this->att.creationdate.empty()) - { + if (this->att.creationdate.empty()) { this->att.creationdate = now; } - if (this->att.moddate.empty()) - { + if (this->att.moddate.empty()) { this->att.moddate = now; } @@ -941,8 +861,7 @@ QPDFJob::PagesConfig::PagesConfig(Config* c) : std::shared_ptr QPDFJob::Config::pages() { - if (! o.m->page_specs.empty()) - { + if (!o.m->page_specs.empty()) { usage("--pages may only be specified one time"); } return std::shared_ptr(new PagesConfig(this)); @@ -951,17 +870,15 @@ QPDFJob::Config::pages() QPDFJob::Config* QPDFJob::PagesConfig::endPages() { - if (this->config->o.m->page_specs.empty()) - { + if (this->config->o.m->page_specs.empty()) { usage("--pages: no page specifications given"); } return this->config; } QPDFJob::PagesConfig* -QPDFJob::PagesConfig::pageSpec(std::string const& filename, - std::string const& range, - char const* password) +QPDFJob::PagesConfig::pageSpec( + std::string const& filename, std::string const& range, char const* password) { this->config->o.m->page_specs.push_back( QPDFJob::PageSpec(filename, password, range)); @@ -990,8 +907,7 @@ QPDFJob::UOConfig::UOConfig(Config* c) : QPDFJob::Config* QPDFJob::UOConfig::endUnderlayOverlay() { - if (config->o.m->under_overlay->filename.empty()) - { + if (config->o.m->under_overlay->filename.empty()) { usage(config->o.m->under_overlay->which + " file not specified"); } config->o.m->under_overlay = 0; @@ -1001,12 +917,9 @@ QPDFJob::UOConfig::endUnderlayOverlay() QPDFJob::UOConfig* QPDFJob::UOConfig::file(std::string const& parameter) { - if (! config->o.m->under_overlay->filename.empty()) - { + if (!config->o.m->under_overlay->filename.empty()) { usage(config->o.m->under_overlay->which + " file already specified"); - } - else - { + } else { config->o.m->under_overlay->filename = parameter; } return this; @@ -1023,8 +936,7 @@ QPDFJob::UOConfig::to(std::string const& parameter) QPDFJob::UOConfig* QPDFJob::UOConfig::from(std::string const& parameter) { - if (! parameter.empty()) - { + if (!parameter.empty()) { config->o.parseNumrange(parameter.c_str(), 0); } config->o.m->under_overlay->from_nr = parameter; @@ -1034,8 +946,7 @@ QPDFJob::UOConfig::from(std::string const& parameter) QPDFJob::UOConfig* QPDFJob::UOConfig::repeat(std::string const& parameter) { - if (! parameter.empty()) - { + if (!parameter.empty()) { config->o.parseNumrange(parameter.c_str(), 0); } config->o.m->under_overlay->repeat_nr = parameter; @@ -1050,13 +961,13 @@ QPDFJob::UOConfig::password(std::string const& parameter) } std::shared_ptr -QPDFJob::Config::encrypt(int keylen, - std::string const& user_password, - std::string const& owner_password) +QPDFJob::Config::encrypt( + int keylen, + std::string const& user_password, + std::string const& owner_password) { o.m->keylen = keylen; - if (keylen == 256) - { + if (keylen == 256) { o.m->use_aes = true; } o.m->user_password = user_password; @@ -1095,12 +1006,9 @@ QPDFJob::EncConfig::accessibility(std::string const& parameter) QPDFJob::EncConfig* QPDFJob::EncConfig::extract(std::string const& parameter) { - if (config->o.m->keylen == 40) - { + if (config->o.m->keylen == 40) { config->o.m->r2_extract = (parameter == "y"); - } - else - { + } else { config->o.m->r3_extract = (parameter == "y"); } return this; @@ -1109,24 +1017,15 @@ QPDFJob::EncConfig::extract(std::string const& parameter) QPDFJob::EncConfig* QPDFJob::EncConfig::print(std::string const& parameter) { - if (config->o.m->keylen == 40) - { + if (config->o.m->keylen == 40) { config->o.m->r2_print = (parameter == "y"); - } - else if (parameter == "full") - { + } else if (parameter == "full") { config->o.m->r3_print = qpdf_r3p_full; - } - else if (parameter == "low") - { + } else if (parameter == "low") { config->o.m->r3_print = qpdf_r3p_low; - } - else if (parameter == "none") - { + } else if (parameter == "none") { config->o.m->r3_print = qpdf_r3p_none; - } - else - { + } else { usage("invalid print option"); } return this; @@ -1135,47 +1034,34 @@ QPDFJob::EncConfig::print(std::string const& parameter) QPDFJob::EncConfig* QPDFJob::EncConfig::modify(std::string const& parameter) { - if (config->o.m->keylen == 40) - { + if (config->o.m->keylen == 40) { config->o.m->r2_modify = (parameter == "y"); - } - else if (parameter == "all") - { + } else if (parameter == "all") { config->o.m->r3_assemble = true; config->o.m->r3_annotate_and_form = true; config->o.m->r3_form_filling = true; config->o.m->r3_modify_other = true; - } - else if (parameter == "annotate") - { + } else if (parameter == "annotate") { config->o.m->r3_assemble = true; config->o.m->r3_annotate_and_form = true; config->o.m->r3_form_filling = true; config->o.m->r3_modify_other = false; - } - else if (parameter == "form") - { + } else if (parameter == "form") { config->o.m->r3_assemble = true; config->o.m->r3_annotate_and_form = false; config->o.m->r3_form_filling = true; config->o.m->r3_modify_other = false; - } - else if (parameter == "assembly") - { + } else if (parameter == "assembly") { config->o.m->r3_assemble = true; config->o.m->r3_annotate_and_form = false; config->o.m->r3_form_filling = false; config->o.m->r3_modify_other = false; - } - else if (parameter == "none") - { + } else if (parameter == "none") { config->o.m->r3_assemble = false; config->o.m->r3_annotate_and_form = false; config->o.m->r3_form_filling = false; config->o.m->r3_modify_other = false; - } - else - { + } else { usage("invalid modify option"); } return this; @@ -1198,12 +1084,9 @@ QPDFJob::EncConfig::assemble(std::string const& parameter) QPDFJob::EncConfig* QPDFJob::EncConfig::annotate(std::string const& parameter) { - if (config->o.m->keylen == 40) - { + if (config->o.m->keylen == 40) { config->o.m->r2_annotate = (parameter == "y"); - } - else - { + } else { config->o.m->r3_annotate_and_form = (parameter == "y"); } return this; diff --git a/libqpdf/QPDFJob_json.cc b/libqpdf/QPDFJob_json.cc index 89b4f09b..c0247e0b 100644 --- a/libqpdf/QPDFJob_json.cc +++ b/libqpdf/QPDFJob_json.cc @@ -2,13 +2,13 @@ #include #include -#include #include +#include -#include -#include -#include #include +#include +#include +#include static JSON JOB_SCHEMA = JSON::parse(QPDFJob::job_json_schema_v1().c_str()); @@ -21,7 +21,7 @@ namespace void handle(JSON&); private: -# include +#include void usage(std::string const& message); void initHandlers(); @@ -56,10 +56,8 @@ namespace void addParameter(param_handler_t); void addChoices(char const** choices, bool required, param_handler_t); void pushKey(std::string const& key); - void beginDict(json_handler_t start_fn, - bare_handler_t end_fn); - void beginArray(json_handler_t start_fn, - bare_handler_t end_fn); + void beginDict(json_handler_t start_fn, bare_handler_t end_fn); + void beginArray(json_handler_t start_fn, bare_handler_t end_fn); void ignoreItem(); void popHandler(); @@ -76,7 +74,7 @@ namespace std::shared_ptr c_uo; std::shared_ptr c_enc; }; -} +} // namespace Handlers::Handlers(bool partial, std::shared_ptr c_main) : partial(partial), @@ -110,18 +108,16 @@ Handlers::initHandlers() this->json_handlers.push_back(std::make_shared()); this->jh = this->json_handlers.back().get(); jh->addDictHandlers( - [](std::string const&, JSON){}, - [this](std::string const&){ - if (! this->partial) - { + [](std::string const&, JSON) {}, + [this](std::string const&) { + if (!this->partial) { c_main->checkConfiguration(); } }); -# include +#include - if (this->json_handlers.size() != 1) - { + if (this->json_handlers.size() != 1) { throw std::logic_error("QPDFJob_json: json_handlers size != 1 at end"); } } @@ -130,24 +126,21 @@ void Handlers::addBare(bare_handler_t fn) { jh->addStringHandler( - [this, fn](std::string const& path, std::string const& parameter){ - if (! parameter.empty()) - { - QTC::TC("qpdf", "QPDFJob json bare not empty"); - usage(path + ": value must be the empty string"); - } - else - { - fn(); - } - }); + [this, fn](std::string const& path, std::string const& parameter) { + if (!parameter.empty()) { + QTC::TC("qpdf", "QPDFJob json bare not empty"); + usage(path + ": value must be the empty string"); + } else { + fn(); + } + }); } void Handlers::addParameter(param_handler_t fn) { jh->addStringHandler( - [fn](std::string const& path, std::string const& parameter){ + [fn](std::string const& path, std::string const& parameter) { fn(parameter.c_str()); }); } @@ -157,40 +150,30 @@ Handlers::addChoices(char const** choices, bool required, param_handler_t fn) { jh->addStringHandler( [fn, choices, required, this]( - std::string const& path, std::string const& parameter){ - + std::string const& path, std::string const& parameter) { char const* p = parameter.c_str(); bool matches = false; - if ((! required) && (parameter.empty())) - { + if ((!required) && (parameter.empty())) { matches = true; } - if (! matches) - { - for (char const** i = choices; *i; ++i) - { - if (strcmp(*i, p) == 0) - { + if (!matches) { + for (char const** i = choices; *i; ++i) { + if (strcmp(*i, p) == 0) { QTC::TC("qpdf", "QPDFJob json choice match"); matches = true; break; } } } - if (! matches) - { + if (!matches) { QTC::TC("qpdf", "QPDFJob json choice mismatch"); std::ostringstream msg; msg << path + ": unexpected value; expected one of "; bool first = true; - for (char const** i = choices; *i; ++i) - { - if (first) - { + for (char const** i = choices; *i; ++i) { + if (first) { first = false; - } - else - { + } else { msg << ", "; } msg << *i; @@ -214,8 +197,8 @@ void Handlers::beginDict(json_handler_t start_fn, bare_handler_t end_fn) { jh->addDictHandlers( - [start_fn](std::string const&, JSON j){ start_fn(j); }, - [end_fn](std::string const&){ end_fn(); }); + [start_fn](std::string const&, JSON j) { start_fn(j); }, + [end_fn](std::string const&) { end_fn(); }); } void @@ -223,8 +206,8 @@ Handlers::beginArray(json_handler_t start_fn, bare_handler_t end_fn) { auto item_jh = std::make_shared(); jh->addArrayHandlers( - [start_fn](std::string const&, JSON j){ start_fn(j); }, - [end_fn](std::string const&){ end_fn(); }, + [start_fn](std::string const&, JSON j) { start_fn(j); }, + [end_fn](std::string const&) { end_fn(); }, item_jh); this->json_handlers.push_back(item_jh); this->jh = item_jh.get(); @@ -233,7 +216,7 @@ Handlers::beginArray(json_handler_t start_fn, bare_handler_t end_fn) void Handlers::ignoreItem() { - jh->addAnyHandler([](std::string const&, JSON){}); + jh->addAnyHandler([](std::string const&, JSON) {}); } void @@ -252,41 +235,31 @@ Handlers::handle(JSON& j) void Handlers::setupInputFile() { - addParameter([this](char const* p) { - c_main->inputFile(p); - }); + addParameter([this](char const* p) { c_main->inputFile(p); }); } void Handlers::setupPassword() { - addParameter([this](char const* p) { - c_main->password(p); - }); + addParameter([this](char const* p) { c_main->password(p); }); } void Handlers::setupEmpty() { - addBare([this]() { - c_main->emptyInput(); - }); + addBare([this]() { c_main->emptyInput(); }); } void Handlers::setupOutputFile() { - addParameter([this](char const* p) { - c_main->outputFile(p); - }); + addParameter([this](char const* p) { c_main->outputFile(p); }); } void Handlers::setupReplaceInput() { - addBare([this]() { - c_main->replaceInput(); - }); + addBare([this]() { c_main->replaceInput(); }); } void @@ -300,34 +273,26 @@ Handlers::beginEncrypt(JSON j) std::string owner_password; bool user_password_seen = false; bool owner_password_seen = false; - j.forEachDictItem([&](std::string const& key, JSON value){ - if ((key == "40bit") || (key == "128bit") || (key == "256bit")) - { - if (key_len != 0) - { + j.forEachDictItem([&](std::string const& key, JSON value) { + if ((key == "40bit") || (key == "128bit") || (key == "256bit")) { + if (key_len != 0) { QTC::TC("qpdf", "QPDFJob json encrypt duplicate key length"); usage("exactly one of 40bit, 128bit, or 256bit must be given"); } key_len = QUtil::string_to_int(key.c_str()); - } - else if (key == "userPassword") - { + } else if (key == "userPassword") { user_password_seen = value.getString(user_password); - } - else if (key == "ownerPassword") - { + } else if (key == "ownerPassword") { owner_password_seen = value.getString(owner_password); } }); - if (key_len == 0) - { + if (key_len == 0) { QTC::TC("qpdf", "QPDFJob json encrypt no key length"); usage("exactly one of 40bit, 128bit, or 256bit must be given;" " an empty dictionary may be supplied for one of them" " to set the key length without imposing any restrictions"); } - if (! (user_password_seen && owner_password_seen)) - { + if (!(user_password_seen && owner_password_seen)) { QTC::TC("qpdf", "QPDFJob json encrypt missing password"); usage("the user and owner password are both required; use the empty" " string for the user password if you don't want a password"); @@ -444,9 +409,7 @@ Handlers::endAddAttachment() void Handlers::setupAddAttachmentFile() { - addParameter([this](char const* p) { - c_att->file(p); - }); + addParameter([this](char const* p) { c_att->file(p); }); } void @@ -477,17 +440,13 @@ Handlers::endCopyAttachmentsFrom() void Handlers::setupCopyAttachmentsFromFile() { - addParameter([this](char const* p) { - c_copy_att->file(p); - }); + addParameter([this](char const* p) { c_copy_att->file(p); }); } void Handlers::setupCopyAttachmentsFromPassword() { - addParameter([this](char const* p) { - c_copy_att->password(p); - }); + addParameter([this](char const* p) { c_copy_att->password(p); }); } void @@ -511,22 +470,16 @@ Handlers::beginPages(JSON j) std::string password; bool file_seen = false; bool password_seen = false; - j.forEachDictItem([&](std::string const& key, JSON value){ - if (key == "file") - { + j.forEachDictItem([&](std::string const& key, JSON value) { + if (key == "file") { file_seen = value.getString(file); - } - else if (key == "range") - { + } else if (key == "range") { value.getString(range); - } - else if (key == "password") - { + } else if (key == "password") { password_seen = value.getString(password); } }); - if (! file_seen) - { + if (!file_seen) { QTC::TC("qpdf", "QPDFJob json pages no file"); usage("file is required in page specification"); } @@ -577,17 +530,13 @@ Handlers::endOverlay() void Handlers::setupOverlayFile() { - addParameter([this](char const* p) { - c_uo->file(p); - }); + addParameter([this](char const* p) { c_uo->file(p); }); } void Handlers::setupOverlayPassword() { - addParameter([this](char const* p) { - c_uo->password(p); - }); + addParameter([this](char const* p) { c_uo->password(p); }); } void @@ -606,17 +555,13 @@ Handlers::endUnderlay() void Handlers::setupUnderlayFile() { - addParameter([this](char const* p) { - c_uo->file(p); - }); + addParameter([this](char const* p) { c_uo->file(p); }); } void Handlers::setupUnderlayPassword() { - addParameter([this](char const* p) { - c_uo->password(p); - }); + addParameter([this](char const* p) { c_uo->password(p); }); } void @@ -624,13 +569,10 @@ QPDFJob::initializeFromJson(std::string const& json, bool partial) { std::list errors; JSON j = JSON::parse(json); - if (! j.checkSchema(JOB_SCHEMA, JSON::f_optional, errors)) - { + if (!j.checkSchema(JOB_SCHEMA, JSON::f_optional, errors)) { std::ostringstream msg; - msg << this->m->message_prefix - << ": job json has errors:"; - for (auto const& error: errors) - { + msg << this->m->message_prefix << ": job json has errors:"; + for (auto const& error : errors) { msg << std::endl << " " << error; } throw std::runtime_error(msg.str()); diff --git a/libqpdf/QPDFMatrix.cc b/libqpdf/QPDFMatrix.cc index 6ee9729e..75049130 100644 --- a/libqpdf/QPDFMatrix.cc +++ b/libqpdf/QPDFMatrix.cc @@ -13,8 +13,8 @@ QPDFMatrix::QPDFMatrix() : { } -QPDFMatrix::QPDFMatrix(double a, double b, double c, - double d, double e, double f) : +QPDFMatrix::QPDFMatrix( + double a, double b, double c, double d, double e, double f) : a(a), b(b), c(c), @@ -34,10 +34,10 @@ QPDFMatrix::QPDFMatrix(QPDFObjectHandle::Matrix const& m) : { } -static double fix_rounding(double d) +static double +fix_rounding(double d) { - if ((d > -0.00001) && (d < 0.00001)) - { + if ((d > -0.00001) && (d < 0.00001)) { d = 0.0; } return d; @@ -46,12 +46,13 @@ static double fix_rounding(double d) std::string QPDFMatrix::unparse() const { - return (QUtil::double_to_string(fix_rounding(a), 5) + " " + - QUtil::double_to_string(fix_rounding(b), 5) + " " + - QUtil::double_to_string(fix_rounding(c), 5) + " " + - QUtil::double_to_string(fix_rounding(d), 5) + " " + - QUtil::double_to_string(fix_rounding(e), 5) + " " + - QUtil::double_to_string(fix_rounding(f), 5)); + return ( + QUtil::double_to_string(fix_rounding(a), 5) + " " + + QUtil::double_to_string(fix_rounding(b), 5) + " " + + QUtil::double_to_string(fix_rounding(c), 5) + " " + + QUtil::double_to_string(fix_rounding(d), 5) + " " + + QUtil::double_to_string(fix_rounding(e), 5) + " " + + QUtil::double_to_string(fix_rounding(f), 5)); } QPDFObjectHandle::Matrix @@ -69,12 +70,12 @@ QPDFMatrix::concat(QPDFMatrix const& other) double dp = (this->b * other.c) + (this->d * other.d); double ep = (this->a * other.e) + (this->c * other.f) + this->e; double fp = (this->b * other.e) + (this->d * other.f) + this->f; - this-> a = ap; - this-> b = bp; - this-> c = cp; - this-> d = dp; - this-> e = ep; - this-> f = fp; + this->a = ap; + this->b = bp; + this->c = cp; + this->d = dp; + this->e = ep; + this->f = fp; } void @@ -92,18 +93,17 @@ QPDFMatrix::translate(double tx, double ty) void QPDFMatrix::rotatex90(int angle) { - switch (angle) - { - case 90: + switch (angle) { + case 90: concat(QPDFMatrix(0, 1, -1, 0, 0, 0)); break; - case 180: + case 180: concat(QPDFMatrix(-1, 0, 0, -1, 0, 0)); break; - case 270: + case 270: concat(QPDFMatrix(0, -1, 1, 0, 0, 0)); break; - default: + default: // ignore break; } @@ -147,10 +147,7 @@ QPDFMatrix::transformRectangle(QPDFObjectHandle::Rectangle r) const bool QPDFMatrix::operator==(QPDFMatrix const& rhs) const { - return ((this->a == rhs.a) && - (this->b == rhs.b) && - (this->c == rhs.c) && - (this->d == rhs.d) && - (this->e == rhs.e) && - (this->f == rhs.f)); + return ( + (this->a == rhs.a) && (this->b == rhs.b) && (this->c == rhs.c) && + (this->d == rhs.d) && (this->e == rhs.e) && (this->f == rhs.f)); } diff --git a/libqpdf/QPDFNameTreeObjectHelper.cc b/libqpdf/QPDFNameTreeObjectHelper.cc index 861e01aa..7ba7abab 100644 --- a/libqpdf/QPDFNameTreeObjectHelper.cc +++ b/libqpdf/QPDFNameTreeObjectHelper.cc @@ -5,20 +5,21 @@ class NameTreeDetails: public NNTreeDetails { public: - virtual std::string const& itemsKey() const override + virtual std::string const& + itemsKey() const override { static std::string k("/Names"); return k; } - virtual bool keyValid(QPDFObjectHandle oh) const override + virtual bool + keyValid(QPDFObjectHandle oh) const override { return oh.isString(); } - virtual int compareKeys( - QPDFObjectHandle a, QPDFObjectHandle b) const override + virtual int + compareKeys(QPDFObjectHandle a, QPDFObjectHandle b) const override { - if (! (keyValid(a) && keyValid(b))) - { + if (!(keyValid(a) && keyValid(b))) { // We don't call this without calling keyValid first throw std::logic_error("comparing invalid keys"); } @@ -95,14 +96,11 @@ QPDFNameTreeObjectHelper::iterator::operator--() void QPDFNameTreeObjectHelper::iterator::updateIValue() { - if (impl->valid()) - { + if (impl->valid()) { auto p = *impl; this->ivalue.first = p->first.getUTF8Value(); this->ivalue.second = p->second; - } - else - { + } else { this->ivalue.first = ""; this->ivalue.second = QPDFObjectHandle(); } @@ -162,26 +160,25 @@ QPDFNameTreeObjectHelper::last() const } QPDFNameTreeObjectHelper::iterator -QPDFNameTreeObjectHelper::find(std::string const& key, - bool return_prev_if_not_found) +QPDFNameTreeObjectHelper::find( + std::string const& key, bool return_prev_if_not_found) { - auto i = this->m->impl->find(QPDFObjectHandle::newUnicodeString(key), - return_prev_if_not_found); + auto i = this->m->impl->find( + QPDFObjectHandle::newUnicodeString(key), return_prev_if_not_found); return iterator(std::make_shared(i)); } QPDFNameTreeObjectHelper::iterator -QPDFNameTreeObjectHelper::insert(std::string const& key, - QPDFObjectHandle value) +QPDFNameTreeObjectHelper::insert(std::string const& key, QPDFObjectHandle value) { - auto i = this->m->impl->insert( - QPDFObjectHandle::newUnicodeString(key), value); + auto i = + this->m->impl->insert(QPDFObjectHandle::newUnicodeString(key), value); return iterator(std::make_shared(i)); } bool -QPDFNameTreeObjectHelper::remove(std::string const& key, - QPDFObjectHandle* value) +QPDFNameTreeObjectHelper::remove( + std::string const& key, QPDFObjectHandle* value) { return this->m->impl->remove( QPDFObjectHandle::newUnicodeString(key), value); @@ -199,8 +196,7 @@ QPDFNameTreeObjectHelper::findObject( std::string const& name, QPDFObjectHandle& oh) { auto i = find(name); - if (i == end()) - { + if (i == end()) { return false; } oh = i->second; diff --git a/libqpdf/QPDFNumberTreeObjectHelper.cc b/libqpdf/QPDFNumberTreeObjectHelper.cc index 0f61874d..81cc0348 100644 --- a/libqpdf/QPDFNumberTreeObjectHelper.cc +++ b/libqpdf/QPDFNumberTreeObjectHelper.cc @@ -6,20 +6,21 @@ class NumberTreeDetails: public NNTreeDetails { public: - virtual std::string const& itemsKey() const override + virtual std::string const& + itemsKey() const override { static std::string k("/Nums"); return k; } - virtual bool keyValid(QPDFObjectHandle oh) const override + virtual bool + keyValid(QPDFObjectHandle oh) const override { return oh.isInteger(); } - virtual int compareKeys( - QPDFObjectHandle a, QPDFObjectHandle b) const override + virtual int + compareKeys(QPDFObjectHandle a, QPDFObjectHandle b) const override { - if (! (keyValid(a) && keyValid(b))) - { + if (!(keyValid(a) && keyValid(b))) { // We don't call this without calling keyValid first throw std::logic_error("comparing invalid keys"); } @@ -92,14 +93,11 @@ QPDFNumberTreeObjectHelper::iterator::operator--() void QPDFNumberTreeObjectHelper::iterator::updateIValue() { - if (impl->valid()) - { + if (impl->valid()) { auto p = *impl; this->ivalue.first = p->first.getIntValue(); this->ivalue.second = p->second; - } - else - { + } else { this->ivalue.first = 0; this->ivalue.second = QPDFObjectHandle(); } @@ -159,36 +157,32 @@ QPDFNumberTreeObjectHelper::last() const } QPDFNumberTreeObjectHelper::iterator -QPDFNumberTreeObjectHelper::find(numtree_number key, - bool return_prev_if_not_found) +QPDFNumberTreeObjectHelper::find( + numtree_number key, bool return_prev_if_not_found) { - auto i = this->m->impl->find(QPDFObjectHandle::newInteger(key), - return_prev_if_not_found); + auto i = this->m->impl->find( + QPDFObjectHandle::newInteger(key), return_prev_if_not_found); return iterator(std::make_shared(i)); } QPDFNumberTreeObjectHelper::iterator QPDFNumberTreeObjectHelper::insert(numtree_number key, QPDFObjectHandle value) { - auto i = this->m->impl->insert( - QPDFObjectHandle::newInteger(key), value); + auto i = this->m->impl->insert(QPDFObjectHandle::newInteger(key), value); return iterator(std::make_shared(i)); } bool -QPDFNumberTreeObjectHelper::remove(numtree_number key, - QPDFObjectHandle* value) +QPDFNumberTreeObjectHelper::remove(numtree_number key, QPDFObjectHandle* value) { - return this->m->impl->remove( - QPDFObjectHandle::newInteger(key), value); + return this->m->impl->remove(QPDFObjectHandle::newInteger(key), value); } QPDFNumberTreeObjectHelper::numtree_number QPDFNumberTreeObjectHelper::getMin() { auto i = begin(); - if (i == end()) - { + if (i == end()) { return 0; } return i->first; @@ -198,8 +192,7 @@ QPDFNumberTreeObjectHelper::numtree_number QPDFNumberTreeObjectHelper::getMax() { auto i = last(); - if (i == end()) - { + if (i == end()) { return 0; } return i->first; @@ -213,12 +206,10 @@ QPDFNumberTreeObjectHelper::hasIndex(numtree_number idx) } bool -QPDFNumberTreeObjectHelper::findObject( - numtree_number idx, QPDFObjectHandle& oh) +QPDFNumberTreeObjectHelper::findObject(numtree_number idx, QPDFObjectHandle& oh) { auto i = find(idx); - if (i == end()) - { + if (i == end()) { return false; } oh = i->second; @@ -227,12 +218,10 @@ QPDFNumberTreeObjectHelper::findObject( bool QPDFNumberTreeObjectHelper::findObjectAtOrBelow( - numtree_number idx, QPDFObjectHandle& oh, - numtree_number& offset) + numtree_number idx, QPDFObjectHandle& oh, numtree_number& offset) { auto i = find(idx, true); - if (i == end()) - { + if (i == end()) { return false; } oh = i->second; diff --git a/libqpdf/QPDFObjGen.cc b/libqpdf/QPDFObjGen.cc index 25ec8dfd..1368b0bf 100644 --- a/libqpdf/QPDFObjGen.cc +++ b/libqpdf/QPDFObjGen.cc @@ -17,8 +17,9 @@ QPDFObjGen::QPDFObjGen(int o, int g) : bool QPDFObjGen::operator<(QPDFObjGen const& rhs) const { - return ((this->obj < rhs.obj) || - ((this->obj == rhs.obj) && (this->gen < rhs.gen))); + return ( + (this->obj < rhs.obj) || + ((this->obj == rhs.obj) && (this->gen < rhs.gen))); } bool @@ -39,7 +40,8 @@ QPDFObjGen::getGen() const return this->gen; } -std::ostream& operator<<(std::ostream& os, const QPDFObjGen& og) +std::ostream& +operator<<(std::ostream& os, const QPDFObjGen& og) { os << og.obj << "," << og.gen; return os; diff --git a/libqpdf/QPDFObjectHandle.cc b/libqpdf/QPDFObjectHandle.cc index 745de6c9..dcd38c82 100644 --- a/libqpdf/QPDFObjectHandle.cc +++ b/libqpdf/QPDFObjectHandle.cc @@ -1,43 +1,42 @@ #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include -#include +#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include #include #include -#include -#include +#include +#include class TerminateParsing { }; -QPDFObjectHandle::StreamDataProvider::StreamDataProvider( - bool supports_retry) : +QPDFObjectHandle::StreamDataProvider::StreamDataProvider(bool supports_retry) : supports_retry(supports_retry) { } @@ -52,8 +51,11 @@ QPDFObjectHandle::StreamDataProvider::provideStreamData( bool QPDFObjectHandle::StreamDataProvider::provideStreamData( - int objid, int generation, Pipeline* pipeline, - bool suppress_warnings, bool will_retry) + int objid, + int generation, + Pipeline* pipeline, + bool suppress_warnings, + bool will_retry) { throw std::logic_error( "you must override provideStreamData -- see QPDFObjectHandle.hh"); @@ -69,8 +71,8 @@ QPDFObjectHandle::StreamDataProvider::supportsRetry() class CoalesceProvider: public QPDFObjectHandle::StreamDataProvider { public: - CoalesceProvider(QPDFObjectHandle containing_page, - QPDFObjectHandle old_contents) : + CoalesceProvider( + QPDFObjectHandle containing_page, QPDFObjectHandle old_contents) : containing_page(containing_page), old_contents(old_contents) { @@ -78,8 +80,8 @@ class CoalesceProvider: public QPDFObjectHandle::StreamDataProvider virtual ~CoalesceProvider() { } - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); private: QPDFObjectHandle containing_page; @@ -111,12 +113,10 @@ QPDFObjectHandle::TokenFilter::setPipeline(Pipeline* p) void QPDFObjectHandle::TokenFilter::write(char const* data, size_t len) { - if (! this->pipeline) - { + if (!this->pipeline) { return; } - if (len) - { + if (len) { this->pipeline->write(QUtil::unsigned_char_pointer(data), len); } } @@ -185,8 +185,7 @@ LastChar::LastChar(Pipeline* next) : void LastChar::write(unsigned char* data, size_t len) { - if (len > 0) - { + if (len > 0) { this->last_char = data[len - 1]; } getNext()->write(data, len); @@ -239,29 +238,27 @@ QPDFObjectHandle::releaseResolved() // Do not cross over indirect object boundaries to avoid an // infinite loop. This method may only be called during final // destruction. See comments in QPDF::~QPDF(). - if (isIndirect()) - { - if (this->obj.get()) - { + if (isIndirect()) { + if (this->obj.get()) { this->obj = 0; } - } - else - { + } else { QPDFObject::ObjAccessor::releaseResolved(this->obj.get()); } } void QPDFObjectHandle::setObjectDescriptionFromInput( - QPDFObjectHandle object, QPDF* context, - std::string const& description, PointerHolder input, + QPDFObjectHandle object, + QPDF* context, + std::string const& description, + PointerHolder input, qpdf_offset_t offset) { object.setObjectDescription( context, - input->getName() + ", " + description + - " at offset " + QUtil::int_to_string(offset)); + input->getName() + ", " + description + " at offset " + + QUtil::int_to_string(offset)); } bool @@ -273,13 +270,10 @@ QPDFObjectHandle::isInitialized() const QPDFObject::object_type_e QPDFObjectHandle::getTypeCode() { - if (this->initialized) - { + if (this->initialized) { dereference(); return this->obj->getTypeCode(); - } - else - { + } else { return QPDFObject::ot_uninitialized; } } @@ -287,13 +281,10 @@ QPDFObjectHandle::getTypeCode() char const* QPDFObjectHandle::getTypeName() { - if (this->initialized) - { + if (this->initialized) { dereference(); return this->obj->getTypeName(); - } - else - { + } else { return "uninitialized"; } } @@ -302,11 +293,13 @@ template class QPDFObjectTypeAccessor { public: - static bool check(QPDFObject* o) + static bool + check(QPDFObject* o) { return (o && dynamic_cast(o)); } - static bool check(QPDFObject const* o) + static bool + check(QPDFObject const* o) { return (o && dynamic_cast(o)); } @@ -315,8 +308,7 @@ class QPDFObjectTypeAccessor bool QPDFObjectHandle::isBool() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -328,15 +320,15 @@ QPDFObjectHandle::isDirectNull() const { // Don't call dereference() -- this is a const method, and we know // objid == 0, so there's nothing to resolve. - return (this->initialized && (this->objid == 0) && - QPDFObjectTypeAccessor::check(obj.get())); + return ( + this->initialized && (this->objid == 0) && + QPDFObjectTypeAccessor::check(obj.get())); } bool QPDFObjectHandle::isNull() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -346,8 +338,7 @@ QPDFObjectHandle::isNull() bool QPDFObjectHandle::isInteger() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -357,8 +348,7 @@ QPDFObjectHandle::isInteger() bool QPDFObjectHandle::isReal() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -375,16 +365,11 @@ double QPDFObjectHandle::getNumericValue() { double result = 0.0; - if (isInteger()) - { + if (isInteger()) { result = static_cast(getIntValue()); - } - else if (isReal()) - { + } else if (isReal()) { result = atof(getRealValue().c_str()); - } - else - { + } else { typeWarning("number", "returning 0"); QTC::TC("qpdf", "QPDFObjectHandle numeric non-numeric"); } @@ -394,8 +379,7 @@ QPDFObjectHandle::getNumericValue() bool QPDFObjectHandle::getValueAsNumber(double& value) { - if (! isNumber()) - { + if (!isNumber()) { return false; } value = getNumericValue(); @@ -405,8 +389,7 @@ QPDFObjectHandle::getValueAsNumber(double& value) bool QPDFObjectHandle::isName() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -416,8 +399,7 @@ QPDFObjectHandle::isName() bool QPDFObjectHandle::isString() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -427,8 +409,7 @@ QPDFObjectHandle::isString() bool QPDFObjectHandle::isOperator() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -438,8 +419,7 @@ QPDFObjectHandle::isOperator() bool QPDFObjectHandle::isInlineImage() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -449,8 +429,7 @@ QPDFObjectHandle::isInlineImage() bool QPDFObjectHandle::isArray() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -460,8 +439,7 @@ QPDFObjectHandle::isArray() bool QPDFObjectHandle::isDictionary() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -471,8 +449,7 @@ QPDFObjectHandle::isDictionary() bool QPDFObjectHandle::isStream() { - if (! this->initialized) - { + if (!this->initialized) { return false; } dereference(); @@ -482,8 +459,7 @@ QPDFObjectHandle::isStream() bool QPDFObjectHandle::isReserved() { - if (! this->initialized) - { + if (!this->initialized) { return false; } // dereference will clear reserved if this has been replaced @@ -494,8 +470,7 @@ QPDFObjectHandle::isReserved() bool QPDFObjectHandle::isIndirect() { - if (! this->initialized) - { + if (!this->initialized) { return false; } return (this->objid != 0); @@ -504,8 +479,9 @@ QPDFObjectHandle::isIndirect() bool QPDFObjectHandle::isScalar() { - return (! (isArray() || isDictionary() || isStream() || - isOperator() || isInlineImage())); + return ( + !(isArray() || isDictionary() || isStream() || isOperator() || + isInlineImage())); } bool @@ -515,17 +491,17 @@ QPDFObjectHandle::isNameAndEquals(std::string const& name) } bool -QPDFObjectHandle::isDictionaryOfType(std::string const& type, - std::string const& subtype) +QPDFObjectHandle::isDictionaryOfType( + std::string const& type, std::string const& subtype) { return isDictionary() && - (type.empty() || getKey("/Type").isNameAndEquals(type)) && - (subtype.empty() || getKey("/Subtype").isNameAndEquals(subtype)); + (type.empty() || getKey("/Type").isNameAndEquals(type)) && + (subtype.empty() || getKey("/Subtype").isNameAndEquals(subtype)); } bool -QPDFObjectHandle::isStreamOfType(std::string const& type, - std::string const& subtype) +QPDFObjectHandle::isStreamOfType( + std::string const& type, std::string const& subtype) { return isStream() && getDict().isDictionaryOfType(type, subtype); } @@ -535,12 +511,9 @@ QPDFObjectHandle::isStreamOfType(std::string const& type, bool QPDFObjectHandle::getBoolValue() { - if (isBool()) - { + if (isBool()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("boolean", "returning false"); QTC::TC("qpdf", "QPDFObjectHandle boolean returning false"); return false; @@ -550,8 +523,7 @@ QPDFObjectHandle::getBoolValue() bool QPDFObjectHandle::getValueAsBool(bool& value) { - if (! isBool()) - { + if (!isBool()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -563,12 +535,9 @@ QPDFObjectHandle::getValueAsBool(bool& value) long long QPDFObjectHandle::getIntValue() { - if (isInteger()) - { + if (isInteger()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("integer", "returning 0"); QTC::TC("qpdf", "QPDFObjectHandle integer returning 0"); return 0; @@ -578,8 +547,7 @@ QPDFObjectHandle::getIntValue() bool QPDFObjectHandle::getValueAsInt(long long& value) { - if (! isInteger()) - { + if (!isInteger()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -591,24 +559,18 @@ QPDFObjectHandle::getIntValueAsInt() { int result = 0; long long v = getIntValue(); - if (v < INT_MIN) - { + if (v < INT_MIN) { QTC::TC("qpdf", "QPDFObjectHandle int returning INT_MIN"); warnIfPossible( "requested value of integer is too small; returning INT_MIN", false); result = INT_MIN; - } - else if (v > INT_MAX) - { + } else if (v > INT_MAX) { QTC::TC("qpdf", "QPDFObjectHandle int returning INT_MAX"); warnIfPossible( - "requested value of integer is too big; returning INT_MAX", - false); + "requested value of integer is too big; returning INT_MAX", false); result = INT_MAX; - } - else - { + } else { result = static_cast(v); } return result; @@ -617,8 +579,7 @@ QPDFObjectHandle::getIntValueAsInt() bool QPDFObjectHandle::getValueAsInt(int& value) { - if (! isInteger()) - { + if (!isInteger()) { return false; } value = getIntValueAsInt(); @@ -630,15 +591,11 @@ QPDFObjectHandle::getUIntValue() { unsigned long long result = 0; long long v = getIntValue(); - if (v < 0) - { + if (v < 0) { QTC::TC("qpdf", "QPDFObjectHandle uint returning 0"); warnIfPossible( - "unsigned value request for negative number; returning 0", - false); - } - else - { + "unsigned value request for negative number; returning 0", false); + } else { result = static_cast(v); } return result; @@ -647,8 +604,7 @@ QPDFObjectHandle::getUIntValue() bool QPDFObjectHandle::getValueAsUInt(unsigned long long& value) { - if (! isInteger()) - { + if (!isInteger()) { return false; } value = getUIntValue(); @@ -660,25 +616,20 @@ QPDFObjectHandle::getUIntValueAsUInt() { unsigned int result = 0; long long v = getIntValue(); - if (v < 0) - { + if (v < 0) { QTC::TC("qpdf", "QPDFObjectHandle uint uint returning 0"); warnIfPossible( "unsigned integer value request for negative number; returning 0", false); result = 0; - } - else if (v > UINT_MAX) - { + } else if (v > UINT_MAX) { QTC::TC("qpdf", "QPDFObjectHandle uint returning UINT_MAX"); warnIfPossible( "requested value of unsigned integer is too big;" " returning UINT_MAX", false); result = UINT_MAX; - } - else - { + } else { result = static_cast(v); } return result; @@ -687,8 +638,7 @@ QPDFObjectHandle::getUIntValueAsUInt() bool QPDFObjectHandle::getValueAsUInt(unsigned int& value) { - if (! isInteger()) - { + if (!isInteger()) { return false; } value = getUIntValueAsUInt(); @@ -700,12 +650,9 @@ QPDFObjectHandle::getValueAsUInt(unsigned int& value) std::string QPDFObjectHandle::getRealValue() { - if (isReal()) - { + if (isReal()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("real", "returning 0.0"); QTC::TC("qpdf", "QPDFObjectHandle real returning 0.0"); return "0.0"; @@ -715,8 +662,7 @@ QPDFObjectHandle::getRealValue() bool QPDFObjectHandle::getValueAsReal(std::string& value) { - if (! isReal()) - { + if (!isReal()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -728,12 +674,9 @@ QPDFObjectHandle::getValueAsReal(std::string& value) std::string QPDFObjectHandle::getName() { - if (isName()) - { + if (isName()) { return dynamic_cast(obj.get())->getName(); - } - else - { + } else { typeWarning("name", "returning dummy name"); QTC::TC("qpdf", "QPDFObjectHandle name returning dummy name"); return "/QPDFFakeName"; @@ -743,8 +686,7 @@ QPDFObjectHandle::getName() bool QPDFObjectHandle::getValueAsName(std::string& value) { - if (! isName()) - { + if (!isName()) { return false; } value = dynamic_cast(obj.get())->getName(); @@ -756,12 +698,9 @@ QPDFObjectHandle::getValueAsName(std::string& value) std::string QPDFObjectHandle::getStringValue() { - if (isString()) - { + if (isString()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("string", "returning empty string"); QTC::TC("qpdf", "QPDFObjectHandle string returning empty string"); return ""; @@ -771,8 +710,7 @@ QPDFObjectHandle::getStringValue() bool QPDFObjectHandle::getValueAsString(std::string& value) { - if (! isString()) - { + if (!isString()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -782,12 +720,9 @@ QPDFObjectHandle::getValueAsString(std::string& value) std::string QPDFObjectHandle::getUTF8Value() { - if (isString()) - { + if (isString()) { return dynamic_cast(obj.get())->getUTF8Val(); - } - else - { + } else { typeWarning("string", "returning empty string"); QTC::TC("qpdf", "QPDFObjectHandle string returning empty utf8"); return ""; @@ -797,8 +732,7 @@ QPDFObjectHandle::getUTF8Value() bool QPDFObjectHandle::getValueAsUTF8(std::string& value) { - if (! isString()) - { + if (!isString()) { return false; } value = dynamic_cast(obj.get())->getUTF8Val(); @@ -810,12 +744,9 @@ QPDFObjectHandle::getValueAsUTF8(std::string& value) std::string QPDFObjectHandle::getOperatorValue() { - if (isOperator()) - { + if (isOperator()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("operator", "returning fake value"); QTC::TC("qpdf", "QPDFObjectHandle operator returning fake value"); return "QPDFFAKE"; @@ -825,8 +756,7 @@ QPDFObjectHandle::getOperatorValue() bool QPDFObjectHandle::getValueAsOperator(std::string& value) { - if (! isOperator()) - { + if (!isOperator()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -836,12 +766,9 @@ QPDFObjectHandle::getValueAsOperator(std::string& value) std::string QPDFObjectHandle::getInlineImageValue() { - if (isInlineImage()) - { + if (isInlineImage()) { return dynamic_cast(obj.get())->getVal(); - } - else - { + } else { typeWarning("inlineimage", "returning empty data"); QTC::TC("qpdf", "QPDFObjectHandle inlineimage returning empty data"); return ""; @@ -851,8 +778,7 @@ QPDFObjectHandle::getInlineImageValue() bool QPDFObjectHandle::getValueAsInlineImage(std::string& value) { - if (! isInlineImage()) - { + if (!isInlineImage()) { return false; } value = dynamic_cast(obj.get())->getVal(); @@ -870,12 +796,9 @@ QPDFObjectHandle::aitems() int QPDFObjectHandle::getArrayNItems() { - if (isArray()) - { + if (isArray()) { return dynamic_cast(obj.get())->getNItems(); - } - else - { + } else { typeWarning("array", "treating as empty"); QTC::TC("qpdf", "QPDFObjectHandle array treating as empty"); return 0; @@ -886,31 +809,23 @@ QPDFObjectHandle QPDFObjectHandle::getArrayItem(int n) { QPDFObjectHandle result; - if (isArray() && (n < getArrayNItems()) && (n >= 0)) - { + if (isArray() && (n < getArrayNItems()) && (n >= 0)) { result = dynamic_cast(obj.get())->getItem(n); - } - else - { + } else { result = newNull(); - if (isArray()) - { + if (isArray()) { objectWarning("returning null for out of bounds array access"); QTC::TC("qpdf", "QPDFObjectHandle array bounds"); - } - else - { + } else { typeWarning("array", "returning null"); QTC::TC("qpdf", "QPDFObjectHandle array null for non-array"); } QPDF* context = 0; std::string description; - if (this->obj->getDescription(context, description)) - { + if (this->obj->getDescription(context, description)) { result.setObjectDescription( context, - description + - " -> null returned from invalid array access"); + description + " -> null returned from invalid array access"); } } return result; @@ -919,18 +834,14 @@ QPDFObjectHandle::getArrayItem(int n) bool QPDFObjectHandle::isRectangle() { - if (! isArray()) - { + if (!isArray()) { return false; } - if (getArrayNItems() != 4) - { + if (getArrayNItems() != 4) { return false; } - for (int i = 0; i < 4; ++i) - { - if (! getArrayItem(i).isNumber()) - { + for (int i = 0; i < 4; ++i) { + if (!getArrayItem(i).isNumber()) { return false; } } @@ -940,18 +851,14 @@ QPDFObjectHandle::isRectangle() bool QPDFObjectHandle::isMatrix() { - if (! isArray()) - { + if (!isArray()) { return false; } - if (getArrayNItems() != 6) - { + if (getArrayNItems() != 6) { return false; } - for (int i = 0; i < 6; ++i) - { - if (! getArrayItem(i).isNumber()) - { + for (int i = 0; i < 6; ++i) { + if (!getArrayItem(i).isNumber()) { return false; } } @@ -962,8 +869,7 @@ QPDFObjectHandle::Rectangle QPDFObjectHandle::getArrayAsRectangle() { Rectangle result; - if (isRectangle()) - { + if (isRectangle()) { // Rectangle coordinates are always supposed to be llx, lly, // urx, ury, but files have been found in the wild where // llx > urx or lly > ury. @@ -971,10 +877,11 @@ QPDFObjectHandle::getArrayAsRectangle() double i1 = getArrayItem(1).getNumericValue(); double i2 = getArrayItem(2).getNumericValue(); double i3 = getArrayItem(3).getNumericValue(); - result = Rectangle(std::min(i0, i2), - std::min(i1, i3), - std::max(i0, i2), - std::max(i1, i3)); + result = Rectangle( + std::min(i0, i2), + std::min(i1, i3), + std::max(i0, i2), + std::max(i1, i3)); } return result; } @@ -983,14 +890,14 @@ QPDFObjectHandle::Matrix QPDFObjectHandle::getArrayAsMatrix() { Matrix result; - if (isMatrix()) - { - result = Matrix(getArrayItem(0).getNumericValue(), - getArrayItem(1).getNumericValue(), - getArrayItem(2).getNumericValue(), - getArrayItem(3).getNumericValue(), - getArrayItem(4).getNumericValue(), - getArrayItem(5).getNumericValue()); + if (isMatrix()) { + result = Matrix( + getArrayItem(0).getNumericValue(), + getArrayItem(1).getNumericValue(), + getArrayItem(2).getNumericValue(), + getArrayItem(3).getNumericValue(), + getArrayItem(4).getNumericValue(), + getArrayItem(5).getNumericValue()); } return result; } @@ -999,12 +906,9 @@ std::vector QPDFObjectHandle::getArrayAsVector() { std::vector result; - if (isArray()) - { + if (isArray()) { dynamic_cast(obj.get())->getAsVector(result); - } - else - { + } else { typeWarning("array", "treating as empty"); QTC::TC("qpdf", "QPDFObjectHandle array treating as empty vector"); } @@ -1016,13 +920,10 @@ QPDFObjectHandle::getArrayAsVector() void QPDFObjectHandle::setArrayItem(int n, QPDFObjectHandle const& item) { - if (isArray()) - { + if (isArray()) { checkOwnership(item); dynamic_cast(obj.get())->setItem(n, item); - } - else - { + } else { typeWarning("array", "ignoring attempt to set item"); QTC::TC("qpdf", "QPDFObjectHandle array ignoring set item"); } @@ -1031,16 +932,12 @@ QPDFObjectHandle::setArrayItem(int n, QPDFObjectHandle const& item) void QPDFObjectHandle::setArrayFromVector(std::vector const& items) { - if (isArray()) - { - for (auto const& item: items) - { + if (isArray()) { + for (auto const& item : items) { checkOwnership(item); } dynamic_cast(obj.get())->setFromVector(items); - } - else - { + } else { typeWarning("array", "ignoring attempt to replace items"); QTC::TC("qpdf", "QPDFObjectHandle array ignoring replace items"); } @@ -1049,12 +946,9 @@ QPDFObjectHandle::setArrayFromVector(std::vector const& items) void QPDFObjectHandle::insertItem(int at, QPDFObjectHandle const& item) { - if (isArray()) - { + if (isArray()) { dynamic_cast(obj.get())->insertItem(at, item); - } - else - { + } else { typeWarning("array", "ignoring attempt to insert item"); QTC::TC("qpdf", "QPDFObjectHandle array ignoring insert item"); } @@ -1063,13 +957,10 @@ QPDFObjectHandle::insertItem(int at, QPDFObjectHandle const& item) void QPDFObjectHandle::appendItem(QPDFObjectHandle const& item) { - if (isArray()) - { + if (isArray()) { checkOwnership(item); dynamic_cast(obj.get())->appendItem(item); - } - else - { + } else { typeWarning("array", "ignoring attempt to append item"); QTC::TC("qpdf", "QPDFObjectHandle array ignoring append item"); } @@ -1078,19 +969,13 @@ QPDFObjectHandle::appendItem(QPDFObjectHandle const& item) void QPDFObjectHandle::eraseItem(int at) { - if (isArray() && (at < getArrayNItems()) && (at >= 0)) - { + if (isArray() && (at < getArrayNItems()) && (at >= 0)) { dynamic_cast(obj.get())->eraseItem(at); - } - else - { - if (isArray()) - { + } else { + if (isArray()) { objectWarning("ignoring attempt to erase out of bounds array item"); QTC::TC("qpdf", "QPDFObjectHandle erase array bounds"); - } - else - { + } else { typeWarning("array", "ignoring attempt to erase item"); QTC::TC("qpdf", "QPDFObjectHandle array ignoring erase item"); } @@ -1108,14 +993,11 @@ QPDFObjectHandle::ditems() bool QPDFObjectHandle::hasKey(std::string const& key) { - if (isDictionary()) - { + if (isDictionary()) { return dynamic_cast(obj.get())->hasKey(key); - } - else - { - typeWarning("dictionary", - "returning false for a key containment request"); + } else { + typeWarning( + "dictionary", "returning false for a key containment request"); QTC::TC("qpdf", "QPDFObjectHandle dictionary false for hasKey"); return false; } @@ -1125,26 +1007,19 @@ QPDFObjectHandle QPDFObjectHandle::getKey(std::string const& key) { QPDFObjectHandle result; - if (isDictionary()) - { - result = dynamic_cast( - obj.get())->getKey(key); - } - else - { - typeWarning( - "dictionary", "returning null for attempted key retrieval"); + if (isDictionary()) { + result = dynamic_cast(obj.get())->getKey(key); + } else { + typeWarning("dictionary", "returning null for attempted key retrieval"); QTC::TC("qpdf", "QPDFObjectHandle dictionary null for getKey"); result = newNull(); QPDF* qpdf = 0; std::string description; - if (this->obj->getDescription(qpdf, description)) - { + if (this->obj->getDescription(qpdf, description)) { result.setObjectDescription( qpdf, - description + - " -> null returned from getting key " + - key + " from non-Dictionary"); + description + " -> null returned from getting key " + key + + " from non-Dictionary"); } } return result; @@ -1160,12 +1035,9 @@ std::set QPDFObjectHandle::getKeys() { std::set result; - if (isDictionary()) - { + if (isDictionary()) { result = dynamic_cast(obj.get())->getKeys(); - } - else - { + } else { typeWarning("dictionary", "treating as empty"); QTC::TC("qpdf", "QPDFObjectHandle dictionary empty set for getKeys"); } @@ -1176,13 +1048,9 @@ std::map QPDFObjectHandle::getDictAsMap() { std::map result; - if (isDictionary()) - { - result = dynamic_cast( - obj.get())->getAsMap(); - } - else - { + if (isDictionary()) { + result = dynamic_cast(obj.get())->getAsMap(); + } else { typeWarning("dictionary", "treating as empty"); QTC::TC("qpdf", "QPDFObjectHandle dictionary empty map for asMap"); } @@ -1193,16 +1061,11 @@ QPDFObjectHandle::getDictAsMap() bool QPDFObjectHandle::isOrHasName(std::string const& value) { - if (isNameAndEquals(value)) - { + if (isNameAndEquals(value)) { return true; - } - else if (isArray()) - { - for (auto& item: aitems()) - { - if (item.isNameAndEquals(value)) - { + } else if (isArray()) { + for (auto& item : aitems()) { + if (item.isNameAndEquals(value)) { return true; } } @@ -1213,23 +1076,18 @@ QPDFObjectHandle::isOrHasName(std::string const& value) void QPDFObjectHandle::makeResourcesIndirect(QPDF& owning_qpdf) { - if (! isDictionary()) - { + if (!isDictionary()) { return; } - for (auto const& i1: ditems()) - { + for (auto const& i1 : ditems()) { QPDFObjectHandle sub = i1.second; - if (! sub.isDictionary()) - { + if (!sub.isDictionary()) { continue; } - for (auto i2: sub.ditems()) - { + for (auto i2 : sub.ditems()) { std::string const& key = i2.first; QPDFObjectHandle val = i2.second; - if (! val.isIndirect()) - { + if (!val.isIndirect()) { sub.replaceKey(key, owning_qpdf.makeIndirectObject(val)); } } @@ -1247,20 +1105,15 @@ QPDFObjectHandle::mergeResources( QPDFObjectHandle other, std::map>* conflicts) { - if (! (isDictionary() && other.isDictionary())) - { + if (!(isDictionary() && other.isDictionary())) { QTC::TC("qpdf", "QPDFObjectHandle merge top type mismatch"); return; } - auto make_og_to_name = []( - QPDFObjectHandle& dict, - std::map& og_to_name) - { - for (auto i: dict.ditems()) - { - if (i.second.isIndirect()) - { + auto make_og_to_name = [](QPDFObjectHandle& dict, + std::map& og_to_name) { + for (auto i : dict.ditems()) { + if (i.second.isIndirect()) { og_to_name[i.second.getObjGen()] = i.first; } } @@ -1268,17 +1121,13 @@ QPDFObjectHandle::mergeResources( // This algorithm is described in comments in QPDFObjectHandle.hh // above the declaration of mergeResources. - for (auto o_top: other.ditems()) - { + for (auto o_top : other.ditems()) { std::string const& rtype = o_top.first; QPDFObjectHandle other_val = o_top.second; - if (hasKey(rtype)) - { + if (hasKey(rtype)) { QPDFObjectHandle this_val = getKey(rtype); - if (this_val.isDictionary() && other_val.isDictionary()) - { - if (this_val.isIndirect()) - { + if (this_val.isDictionary() && other_val.isDictionary()) { + if (this_val.isIndirect()) { // Do this even if there are no keys. Various // places in the code call mergeResources with // resource dictionaries that contain empty @@ -1292,40 +1141,30 @@ QPDFObjectHandle::mergeResources( std::set rnames; int min_suffix = 1; bool initialized_maps = false; - for (auto ov_iter: other_val.ditems()) - { + for (auto ov_iter : other_val.ditems()) { std::string const& key = ov_iter.first; QPDFObjectHandle rval = ov_iter.second; - if (! this_val.hasKey(key)) - { - if (! rval.isIndirect()) - { - QTC::TC("qpdf", "QPDFObjectHandle merge shallow copy"); + if (!this_val.hasKey(key)) { + if (!rval.isIndirect()) { + QTC::TC( + "qpdf", "QPDFObjectHandle merge shallow copy"); rval = rval.shallowCopy(); } this_val.replaceKey(key, rval); - } - else if (conflicts) - { - if (! initialized_maps) - { + } else if (conflicts) { + if (!initialized_maps) { make_og_to_name(this_val, og_to_name); rnames = this_val.getResourceNames(); initialized_maps = true; } auto rval_og = rval.getObjGen(); - if (rval.isIndirect() && - og_to_name.count(rval_og)) - { + if (rval.isIndirect() && og_to_name.count(rval_og)) { QTC::TC("qpdf", "QPDFObjectHandle merge reuse"); auto new_key = og_to_name[rval_og]; - if (new_key != key) - { + if (new_key != key) { (*conflicts)[rtype][key] = new_key; } - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle merge generate"); std::string new_key = getUniqueResourceName( key + "_", min_suffix, &rnames); @@ -1334,36 +1173,25 @@ QPDFObjectHandle::mergeResources( } } } - } - else if (this_val.isArray() && other_val.isArray()) - { + } else if (this_val.isArray() && other_val.isArray()) { std::set scalars; - for (auto this_item: this_val.aitems()) - { - if (this_item.isScalar()) - { + for (auto this_item : this_val.aitems()) { + if (this_item.isScalar()) { scalars.insert(this_item.unparse()); } } - for (auto other_item: other_val.aitems()) - { - if (other_item.isScalar()) - { - if (scalars.count(other_item.unparse()) == 0) - { + for (auto other_item : other_val.aitems()) { + if (other_item.isScalar()) { + if (scalars.count(other_item.unparse()) == 0) { QTC::TC("qpdf", "QPDFObjectHandle merge array"); this_val.appendItem(other_item); - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle merge array dup"); } } } } - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle merge copy from other"); replaceKey(rtype, other_val.shallowCopy()); } @@ -1375,22 +1203,20 @@ QPDFObjectHandle::getResourceNames() { // Return second-level dictionary keys std::set result; - if (! isDictionary()) - { + if (!isDictionary()) { return result; } std::set keys = getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; QPDFObjectHandle val = getKey(key); - if (val.isDictionary()) - { + if (val.isDictionary()) { std::set val_keys = val.getKeys(); for (std::set::iterator i2 = val_keys.begin(); - i2 != val_keys.end(); ++i2) - { + i2 != val_keys.end(); + ++i2) { result.insert(*i2); } } @@ -1399,25 +1225,22 @@ QPDFObjectHandle::getResourceNames() } std::string -QPDFObjectHandle::getUniqueResourceName(std::string const& prefix, - int& min_suffix) +QPDFObjectHandle::getUniqueResourceName( + std::string const& prefix, int& min_suffix) { return getUniqueResourceName(prefix, min_suffix, nullptr); } std::string -QPDFObjectHandle::getUniqueResourceName(std::string const& prefix, - int& min_suffix, - std::set* namesp) +QPDFObjectHandle::getUniqueResourceName( + std::string const& prefix, int& min_suffix, std::set* namesp) { std::set names = (namesp ? *namesp : getResourceNames()); int max_suffix = min_suffix + QIntC::to_int(names.size()); - while (min_suffix <= max_suffix) - { + while (min_suffix <= max_suffix) { std::string candidate = prefix + QUtil::int_to_string(min_suffix); - if (names.count(candidate) == 0) - { + if (names.count(candidate) == 0) { return candidate; } // Increment after return; min_suffix should be the value @@ -1442,17 +1265,12 @@ QPDFObjectHandle::getOwningQPDF() // Dictionary mutators void -QPDFObjectHandle::replaceKey(std::string const& key, - QPDFObjectHandle value) +QPDFObjectHandle::replaceKey(std::string const& key, QPDFObjectHandle value) { - if (isDictionary()) - { + if (isDictionary()) { checkOwnership(value); - dynamic_cast( - obj.get())->replaceKey(key, value); - } - else - { + dynamic_cast(obj.get())->replaceKey(key, value); + } else { typeWarning("dictionary", "ignoring key replacement request"); QTC::TC("qpdf", "QPDFObjectHandle dictionary ignoring replaceKey"); } @@ -1461,29 +1279,23 @@ QPDFObjectHandle::replaceKey(std::string const& key, void QPDFObjectHandle::removeKey(std::string const& key) { - if (isDictionary()) - { + if (isDictionary()) { dynamic_cast(obj.get())->removeKey(key); - } - else - { + } else { typeWarning("dictionary", "ignoring key removal request"); QTC::TC("qpdf", "QPDFObjectHandle dictionary ignoring removeKey"); } } void -QPDFObjectHandle::replaceOrRemoveKey(std::string const& key, - QPDFObjectHandle value) +QPDFObjectHandle::replaceOrRemoveKey( + std::string const& key, QPDFObjectHandle value) { - if (isDictionary()) - { + if (isDictionary()) { checkOwnership(value); - dynamic_cast( - obj.get())->replaceOrRemoveKey(key, value); - } - else - { + dynamic_cast(obj.get())->replaceOrRemoveKey( + key, value); + } else { typeWarning("dictionary", "ignoring key removal/replacement request"); QTC::TC("qpdf", "QPDFObjectHandle dictionary ignoring removereplace"); } @@ -1529,8 +1341,7 @@ PointerHolder QPDFObjectHandle::getStreamData(qpdf_stream_decode_level_e level) { assertStream(); - return dynamic_cast( - obj.get())->getStreamData(level); + return dynamic_cast(obj.get())->getStreamData(level); } PointerHolder @@ -1541,46 +1352,56 @@ QPDFObjectHandle::getRawStreamData() } bool -QPDFObjectHandle::pipeStreamData(Pipeline* p, bool* filtering_attempted, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings, bool will_retry) +QPDFObjectHandle::pipeStreamData( + Pipeline* p, + bool* filtering_attempted, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings, + bool will_retry) { assertStream(); return dynamic_cast(obj.get())->pipeStreamData( - p, filtering_attempted, encode_flags, decode_level, - suppress_warnings, will_retry); + p, + filtering_attempted, + encode_flags, + decode_level, + suppress_warnings, + will_retry); } bool -QPDFObjectHandle::pipeStreamData(Pipeline* p, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings, bool will_retry) +QPDFObjectHandle::pipeStreamData( + Pipeline* p, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings, + bool will_retry) { assertStream(); bool filtering_attempted; dynamic_cast(obj.get())->pipeStreamData( - p, &filtering_attempted, encode_flags, decode_level, - suppress_warnings, will_retry); + p, + &filtering_attempted, + encode_flags, + decode_level, + suppress_warnings, + will_retry); return filtering_attempted; } bool -QPDFObjectHandle::pipeStreamData(Pipeline* p, bool filter, - bool normalize, bool compress) +QPDFObjectHandle::pipeStreamData( + Pipeline* p, bool filter, bool normalize, bool compress) { int encode_flags = 0; qpdf_stream_decode_level_e decode_level = qpdf_dl_none; - if (filter) - { + if (filter) { decode_level = qpdf_dl_generalized; - if (normalize) - { + if (normalize) { encode_flags |= qpdf_ef_normalize; } - if (compress) - { + if (compress) { encode_flags |= qpdf_ef_compress; } } @@ -1588,9 +1409,10 @@ QPDFObjectHandle::pipeStreamData(Pipeline* p, bool filter, } void -QPDFObjectHandle::replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) +QPDFObjectHandle::replaceStreamData( + PointerHolder data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); dynamic_cast(obj.get())->replaceStreamData( @@ -1598,9 +1420,10 @@ QPDFObjectHandle::replaceStreamData(PointerHolder data, } void -QPDFObjectHandle::replaceStreamData(std::string const& data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) +QPDFObjectHandle::replaceStreamData( + std::string const& data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); auto b = make_pointer_holder(data.length()); @@ -1611,9 +1434,10 @@ QPDFObjectHandle::replaceStreamData(std::string const& data, } void -QPDFObjectHandle::replaceStreamData(PointerHolder provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) +QPDFObjectHandle::replaceStreamData( + PointerHolder provider, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); dynamic_cast(obj.get())->replaceStreamData( @@ -1636,14 +1460,16 @@ class FunctionProvider: public QPDFObjectHandle::StreamDataProvider { } - virtual void provideStreamData(int, int, Pipeline* pipeline) override + virtual void + provideStreamData(int, int, Pipeline* pipeline) override { p1(pipeline); } - virtual bool provideStreamData(int, int, Pipeline* pipeline, - bool suppress_warnings, - bool will_retry) override + virtual bool + provideStreamData( + int, int, Pipeline* pipeline, bool suppress_warnings, bool will_retry) + override { return p2(pipeline, suppress_warnings, will_retry); } @@ -1654,13 +1480,14 @@ class FunctionProvider: public QPDFObjectHandle::StreamDataProvider }; void -QPDFObjectHandle::replaceStreamData(std::function provider, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) +QPDFObjectHandle::replaceStreamData( + std::function provider, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { assertStream(); - auto sdp = PointerHolder( - new FunctionProvider(provider)); + auto sdp = + PointerHolder(new FunctionProvider(provider)); dynamic_cast(obj.get())->replaceStreamData( sdp, filter, decode_parms); } @@ -1672,8 +1499,8 @@ QPDFObjectHandle::replaceStreamData( QPDFObjectHandle const& decode_parms) { assertStream(); - auto sdp = PointerHolder( - new FunctionProvider(provider)); + auto sdp = + PointerHolder(new FunctionProvider(provider)); dynamic_cast(obj.get())->replaceStreamData( sdp, filter, decode_parms); } @@ -1708,53 +1535,48 @@ QPDFObjectHandle::arrayOrStreamToStreamArray( { all_description = description; std::vector result; - if (isArray()) - { + if (isArray()) { int n_items = getArrayNItems(); - for (int i = 0; i < n_items; ++i) - { + for (int i = 0; i < n_items; ++i) { QPDFObjectHandle item = getArrayItem(i); - if (item.isStream()) - { + if (item.isStream()) { result.push_back(item); - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle non-stream in stream array"); - warn(item.getOwningQPDF(), - QPDFExc(qpdf_e_damaged_pdf, description, - "item index " + QUtil::int_to_string(i) + - " (from 0)", 0, - "ignoring non-stream in an array of streams")); + warn( + item.getOwningQPDF(), + QPDFExc( + qpdf_e_damaged_pdf, + description, + "item index " + QUtil::int_to_string(i) + " (from 0)", + 0, + "ignoring non-stream in an array of streams")); } } - } - else if (isStream()) - { + } else if (isStream()) { result.push_back(*this); - } - else if (! isNull()) - { - warn(getOwningQPDF(), - QPDFExc(qpdf_e_damaged_pdf, "", description, 0, - " object is supposed to be a stream or an" - " array of streams but is neither")); + } else if (!isNull()) { + warn( + getOwningQPDF(), + QPDFExc( + qpdf_e_damaged_pdf, + "", + description, + 0, + " object is supposed to be a stream or an" + " array of streams but is neither")); } bool first = true; for (std::vector::iterator iter = result.begin(); - iter != result.end(); ++iter) - { + iter != result.end(); + ++iter) { QPDFObjectHandle item = *iter; - std::string og = - QUtil::int_to_string(item.getObjectID()) + " " + + std::string og = QUtil::int_to_string(item.getObjectID()) + " " + QUtil::int_to_string(item.getGeneration()); - if (first) - { + if (first) { first = false; - } - else - { + } else { all_description += ","; } all_description += " stream " + og; @@ -1770,8 +1592,8 @@ QPDFObjectHandle::getPageContents() QUtil::int_to_string(this->objid) + " " + QUtil::int_to_string(this->generation); std::string all_description; - return this->getKey("/Contents").arrayOrStreamToStreamArray( - description, all_description); + return this->getKey("/Contents") + .arrayOrStreamToStreamArray(description, all_description); } void @@ -1782,19 +1604,17 @@ QPDFObjectHandle::addPageContents(QPDFObjectHandle new_contents, bool first) std::vector orig_contents = getPageContents(); std::vector content_streams; - if (first) - { + if (first) { QTC::TC("qpdf", "QPDFObjectHandle prepend page contents"); content_streams.push_back(new_contents); } for (std::vector::iterator iter = orig_contents.begin(); - iter != orig_contents.end(); ++iter) - { + iter != orig_contents.end(); + ++iter) { QTC::TC("qpdf", "QPDFObjectHandle append page contents"); content_streams.push_back(*iter); } - if (! first) - { + if (!first) { content_streams.push_back(new_contents); } @@ -1805,50 +1625,40 @@ QPDFObjectHandle::addPageContents(QPDFObjectHandle new_contents, bool first) void QPDFObjectHandle::rotatePage(int angle, bool relative) { - if ((angle % 90) != 0) - { - throw std::runtime_error( - "QPDF::rotatePage called with an" - " angle that is not a multiple of 90"); + if ((angle % 90) != 0) { + throw std::runtime_error("QPDF::rotatePage called with an" + " angle that is not a multiple of 90"); } int new_angle = angle; - if (relative) - { + if (relative) { int old_angle = 0; bool found_rotate = false; QPDFObjectHandle cur_obj = *this; bool searched_parent = false; std::set visited; - while (! found_rotate) - { - if (visited.count(cur_obj.getObjGen())) - { + while (!found_rotate) { + if (visited.count(cur_obj.getObjGen())) { // Don't get stuck in an infinite loop break; } - if (! visited.empty()) - { + if (!visited.empty()) { searched_parent = true; } visited.insert(cur_obj.getObjGen()); - if (cur_obj.getKey("/Rotate").isInteger()) - { + if (cur_obj.getKey("/Rotate").isInteger()) { found_rotate = true; old_angle = cur_obj.getKey("/Rotate").getIntValueAsInt(); - } - else if (cur_obj.getKey("/Parent").isDictionary()) - { + } else if (cur_obj.getKey("/Parent").isDictionary()) { cur_obj = cur_obj.getKey("/Parent"); - } - else - { + } else { break; } } - QTC::TC("qpdf", "QPDFObjectHandle found old angle", - searched_parent ? 0 : 1); - if ((old_angle % 90) != 0) - { + QTC::TC( + "qpdf", + "QPDFObjectHandle found old angle", + searched_parent ? 0 : 1); + if ((old_angle % 90) != 0) { old_angle = 0; } new_angle += old_angle; @@ -1863,20 +1673,16 @@ void QPDFObjectHandle::coalesceContentStreams() { QPDFObjectHandle contents = this->getKey("/Contents"); - if (contents.isStream()) - { + if (contents.isStream()) { QTC::TC("qpdf", "QPDFObjectHandle coalesce called on stream"); return; - } - else if (! contents.isArray()) - { + } else if (!contents.isArray()) { // /Contents is optional for pages, and some very damaged // files may have pages that are invalid in other ways. return; } QPDF* qpdf = getOwningQPDF(); - if (qpdf == 0) - { + if (qpdf == 0) { // Should not be possible for a page object to not have an // owning PDF unless it was manually constructed in some // incorrect way. However, it can happen in a PDF file whose @@ -1897,13 +1703,10 @@ std::string QPDFObjectHandle::unparse() { std::string result; - if (this->isIndirect()) - { + if (this->isIndirect()) { result = QUtil::int_to_string(this->objid) + " " + QUtil::int_to_string(this->generation) + " R"; - } - else - { + } else { result = unparseResolved(); } return result; @@ -1913,8 +1716,7 @@ std::string QPDFObjectHandle::unparseResolved() { dereference(); - if (this->reserved) - { + if (this->reserved) { throw std::logic_error( "QPDFObjectHandle: attempting to unparse a reserved object"); } @@ -1924,13 +1726,9 @@ QPDFObjectHandle::unparseResolved() std::string QPDFObjectHandle::unparseBinary() { - if (this->isString()) - { - return dynamic_cast( - this->obj.get())->unparse(true); - } - else - { + if (this->isString()) { + return dynamic_cast(this->obj.get())->unparse(true); + } else { return unparse(); } } @@ -1938,15 +1736,11 @@ QPDFObjectHandle::unparseBinary() JSON QPDFObjectHandle::getJSON(bool dereference_indirect) { - if ((! dereference_indirect) && this->isIndirect()) - { + if ((!dereference_indirect) && this->isIndirect()) { return JSON::makeString(unparse()); - } - else - { + } else { dereference(); - if (this->reserved) - { + if (this->reserved) { throw std::logic_error( "QPDFObjectHandle: attempting to unparse a reserved object"); } @@ -1957,8 +1751,7 @@ QPDFObjectHandle::getJSON(bool dereference_indirect) QPDFObjectHandle QPDFObjectHandle::wrapInArray() { - if (isArray()) - { + if (isArray()) { return *this; } QPDFObjectHandle result = QPDFObjectHandle::newArray(); @@ -1967,16 +1760,17 @@ QPDFObjectHandle::wrapInArray() } QPDFObjectHandle -QPDFObjectHandle::parse(std::string const& object_str, - std::string const& object_description) +QPDFObjectHandle::parse( + std::string const& object_str, std::string const& object_description) { return parse(nullptr, object_str, object_description); } QPDFObjectHandle -QPDFObjectHandle::parse(QPDF* context, - std::string const& object_str, - std::string const& object_description) +QPDFObjectHandle::parse( + QPDF* context, + std::string const& object_str, + std::string const& object_description) { auto input = PointerHolder( new BufferInputSource("parsed object", object_str)); @@ -1985,15 +1779,15 @@ QPDFObjectHandle::parse(QPDF* context, QPDFObjectHandle result = parse(input, object_description, tokenizer, empty, 0, context); size_t offset = QIntC::to_size(input->tell()); - while (offset < object_str.length()) - { - if (! isspace(object_str.at(offset))) - { + while (offset < object_str.length()) { + if (!isspace(object_str.at(offset))) { QTC::TC("qpdf", "QPDFObjectHandle trailing data in parse"); - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "trailing data found parsing object from string"); + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "trailing data found parsing object from string"); } ++offset; } @@ -2007,8 +1801,8 @@ QPDFObjectHandle::pipePageContents(Pipeline* p) QUtil::int_to_string(this->objid) + " " + QUtil::int_to_string(this->generation); std::string all_description; - this->getKey("/Contents").pipeContentStreams( - p, description, all_description); + this->getKey("/Contents") + .pipeContentStreams(p, description, all_description); } void @@ -2016,34 +1810,32 @@ QPDFObjectHandle::pipeContentStreams( Pipeline* p, std::string const& description, std::string& all_description) { std::vector streams = - arrayOrStreamToStreamArray( - description, all_description); + arrayOrStreamToStreamArray(description, all_description); bool need_newline = false; Pl_Buffer buf("concatenated content stream buffer"); for (std::vector::iterator iter = streams.begin(); - iter != streams.end(); ++iter) - { - if (need_newline) - { + iter != streams.end(); + ++iter) { + if (need_newline) { buf.write(QUtil::unsigned_char_pointer("\n"), 1); } LastChar lc(&buf); QPDFObjectHandle stream = *iter; - std::string og = - QUtil::int_to_string(stream.getObjectID()) + " " + + std::string og = QUtil::int_to_string(stream.getObjectID()) + " " + QUtil::int_to_string(stream.getGeneration()); std::string w_description = "content stream object " + og; - if (! stream.pipeStreamData(&lc, 0, qpdf_dl_specialized)) - { + if (!stream.pipeStreamData(&lc, 0, qpdf_dl_specialized)) { QTC::TC("qpdf", "QPDFObjectHandle errors in parsecontent"); - throw QPDFExc(qpdf_e_damaged_pdf, "content stream", - w_description, 0, - "errors while decoding content stream"); + throw QPDFExc( + qpdf_e_damaged_pdf, + "content stream", + w_description, + 0, + "errors while decoding content stream"); } lc.finish(); need_newline = (lc.getLastChar() != static_cast('\n')); - QTC::TC("qpdf", "QPDFObjectHandle need_newline", - need_newline ? 0 : 1); + QTC::TC("qpdf", "QPDFObjectHandle need_newline", need_newline ? 0 : 1); } std::unique_ptr b(buf.getBuffer()); p->write(b->getBuffer(), b->getSize()); @@ -2056,16 +1848,15 @@ QPDFObjectHandle::parsePageContents(ParserCallbacks* callbacks) std::string description = "page object " + QUtil::int_to_string(this->objid) + " " + QUtil::int_to_string(this->generation); - this->getKey("/Contents").parseContentStream_internal( - description, callbacks); + this->getKey("/Contents") + .parseContentStream_internal(description, callbacks); } void QPDFObjectHandle::parseAsContents(ParserCallbacks* callbacks) { - std::string description = "object " + - QUtil::int_to_string(this->objid) + " " + - QUtil::int_to_string(this->generation); + std::string description = "object " + QUtil::int_to_string(this->objid) + + " " + QUtil::int_to_string(this->generation); this->parseContentStream_internal(description, callbacks); } @@ -2090,8 +1881,8 @@ QPDFObjectHandle::filterAsContents(TokenFilter* filter, Pipeline* next) } void -QPDFObjectHandle::parseContentStream(QPDFObjectHandle stream_or_array, - ParserCallbacks* callbacks) +QPDFObjectHandle::parseContentStream( + QPDFObjectHandle stream_or_array, ParserCallbacks* callbacks) { stream_or_array.parseContentStream_internal( "content stream objects", callbacks); @@ -2099,21 +1890,17 @@ QPDFObjectHandle::parseContentStream(QPDFObjectHandle stream_or_array, void QPDFObjectHandle::parseContentStream_internal( - std::string const& description, - ParserCallbacks* callbacks) + std::string const& description, ParserCallbacks* callbacks) { Pl_Buffer buf("concatenated stream data buffer"); std::string all_description; pipeContentStreams(&buf, description, all_description); auto stream_data = buf.getBufferSharedPointer(); callbacks->contentSize(stream_data->getSize()); - try - { - parseContentStream_data(stream_data, all_description, - callbacks, getOwningQPDF()); - } - catch (TerminateParsing&) - { + try { + parseContentStream_data( + stream_data, all_description, callbacks, getOwningQPDF()); + } catch (TerminateParsing&) { return; } callbacks->handleEOF(); @@ -2132,8 +1919,7 @@ QPDFObjectHandle::parseContentStream_data( QPDFTokenizer tokenizer; tokenizer.allowEOF(); bool empty = false; - while (QIntC::to_size(input->tell()) < stream_length) - { + while (QIntC::to_size(input->tell()) < stream_length) { // Read a token and seek to the beginning. The offset we get // from this process is the beginning of the next // non-ignorable (space, comment) token. This way, the offset @@ -2142,18 +1928,15 @@ QPDFObjectHandle::parseContentStream_data( qpdf_offset_t offset = input->getLastOffset(); input->seek(offset, SEEK_SET); QPDFObjectHandle obj = - parseInternal(input, "content", tokenizer, - empty, 0, context, true); - if (! obj.isInitialized()) - { + parseInternal(input, "content", tokenizer, empty, 0, context, true); + if (!obj.isInitialized()) { // EOF break; } size_t length = QIntC::to_size(input->tell() - offset); callbacks->handleObject(obj, QIntC::to_size(offset), length); - if (obj.isOperator() && (obj.getOperatorValue() == "ID")) - { + if (obj.isOperator() && (obj.getOperatorValue() == "ID")) { // Discard next character; it is the space after ID that // terminated the token. Read until end of inline image. char ch; @@ -2163,21 +1946,23 @@ QPDFObjectHandle::parseContentStream_data( tokenizer.readToken(input, description, true); offset = input->getLastOffset(); length = QIntC::to_size(input->tell() - offset); - if (t.getType() == QPDFTokenizer::tt_bad) - { + if (t.getType() == QPDFTokenizer::tt_bad) { QTC::TC("qpdf", "QPDFObjectHandle EOF in inline image"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - "stream data", input->tell(), - "EOF found while reading inline image")); - } - else - { + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + "stream data", + input->tell(), + "EOF found while reading inline image")); + } else { std::string inline_image = t.getValue(); QTC::TC("qpdf", "QPDFObjectHandle inline image token"); callbacks->handleObject( QPDFObjectHandle::newInlineImage(inline_image), - QIntC::to_size(offset), length); + QIntC::to_size(offset), + length); } } } @@ -2194,26 +1979,31 @@ void QPDFObjectHandle::addTokenFilter(PointerHolder filter) { assertStream(); - return dynamic_cast( - obj.get())->addTokenFilter(filter); + return dynamic_cast(obj.get())->addTokenFilter(filter); } QPDFObjectHandle -QPDFObjectHandle::parse(PointerHolder input, - std::string const& object_description, - QPDFTokenizer& tokenizer, bool& empty, - StringDecrypter* decrypter, QPDF* context) +QPDFObjectHandle::parse( + PointerHolder input, + std::string const& object_description, + QPDFTokenizer& tokenizer, + bool& empty, + StringDecrypter* decrypter, + QPDF* context) { - return parseInternal(input, object_description, tokenizer, empty, - decrypter, context, false); + return parseInternal( + input, object_description, tokenizer, empty, decrypter, context, false); } QPDFObjectHandle -QPDFObjectHandle::parseInternal(PointerHolder input, - std::string const& object_description, - QPDFTokenizer& tokenizer, bool& empty, - StringDecrypter* decrypter, QPDF* context, - bool content_stream) +QPDFObjectHandle::parseInternal( + PointerHolder input, + std::string const& object_description, + QPDFTokenizer& tokenizer, + bool& empty, + StringDecrypter* decrypter, + QPDF* context, + bool content_stream) { // This method must take care not to resolve any objects. Don't // check the type of any object without first ensuring that it is @@ -2244,8 +2034,7 @@ QPDFObjectHandle::parseInternal(PointerHolder input, contents_string_stack.push_back(""); std::vector contents_offset_stack; contents_offset_stack.push_back(-1); - while (! done) - { + while (!done) { bool bad = false; SparseOHArray& olist = olist_stack.back(); parser_state_e state = state_stack.back(); @@ -2259,163 +2048,166 @@ QPDFObjectHandle::parseInternal(PointerHolder input, QPDFTokenizer::Token token = tokenizer.readToken(input, object_description, true); std::string const& token_error_message = token.getErrorMessage(); - if (! token_error_message.empty()) - { + if (!token_error_message.empty()) { // Tokens other than tt_bad can still generate warnings. - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - token_error_message)); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + token_error_message)); } - switch (token.getType()) - { - case QPDFTokenizer::tt_eof: - if (! content_stream) - { + switch (token.getType()) { + case QPDFTokenizer::tt_eof: + if (!content_stream) { QTC::TC("qpdf", "QPDFObjectHandle eof in parseInternal"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "unexpected EOF")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "unexpected EOF")); } bad = true; state = st_eof; break; - case QPDFTokenizer::tt_bad: + case QPDFTokenizer::tt_bad: QTC::TC("qpdf", "QPDFObjectHandle bad token in parse"); bad = true; object = newNull(); break; - case QPDFTokenizer::tt_brace_open: - case QPDFTokenizer::tt_brace_close: + case QPDFTokenizer::tt_brace_open: + case QPDFTokenizer::tt_brace_close: QTC::TC("qpdf", "QPDFObjectHandle bad brace"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "treating unexpected brace token as null")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "treating unexpected brace token as null")); bad = true; object = newNull(); break; - case QPDFTokenizer::tt_array_close: - if (state == st_array) - { + case QPDFTokenizer::tt_array_close: + if (state == st_array) { state = st_stop; - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle bad array close"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "treating unexpected array close token as null")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "treating unexpected array close token as null")); bad = true; object = newNull(); } break; - case QPDFTokenizer::tt_dict_close: - if (state == st_dictionary) - { + case QPDFTokenizer::tt_dict_close: + if (state == st_dictionary) { state = st_stop; - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle bad dictionary close"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "unexpected dictionary close token")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "unexpected dictionary close token")); bad = true; object = newNull(); } break; - case QPDFTokenizer::tt_array_open: - case QPDFTokenizer::tt_dict_open: - if (olist_stack.size() > 500) - { + case QPDFTokenizer::tt_array_open: + case QPDFTokenizer::tt_dict_open: + if (olist_stack.size() > 500) { QTC::TC("qpdf", "QPDFObjectHandle too deep"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "ignoring excessively deeply nested data structure")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "ignoring excessively deeply nested data structure")); bad = true; object = newNull(); state = st_top; - } - else - { + } else { olist_stack.push_back(SparseOHArray()); state = st_start; offset_stack.push_back(input->tell()); state_stack.push_back( - (token.getType() == QPDFTokenizer::tt_array_open) ? - st_array : st_dictionary); + (token.getType() == QPDFTokenizer::tt_array_open) + ? st_array + : st_dictionary); b_contents = false; contents_string_stack.push_back(""); contents_offset_stack.push_back(-1); } break; - case QPDFTokenizer::tt_bool: + case QPDFTokenizer::tt_bool: object = newBool((token.getValue() == "true")); break; - case QPDFTokenizer::tt_null: + case QPDFTokenizer::tt_null: object = newNull(); break; - case QPDFTokenizer::tt_integer: + case QPDFTokenizer::tt_integer: object = newInteger(QUtil::string_to_ll(token.getValue().c_str())); break; - case QPDFTokenizer::tt_real: + case QPDFTokenizer::tt_real: object = newReal(token.getValue()); break; - case QPDFTokenizer::tt_name: + case QPDFTokenizer::tt_name: { std::string name = token.getValue(); object = newName(name); - if (name == "/Contents") - { + if (name == "/Contents") { b_contents = true; - } - else - { + } else { b_contents = false; } } break; - case QPDFTokenizer::tt_word: + case QPDFTokenizer::tt_word: { std::string const& value = token.getValue(); - if (content_stream) - { + if (content_stream) { object = QPDFObjectHandle::newOperator(value); - } - else if ((value == "R") && (state != st_top) && - (olist.size() >= 2) && - (! olist.at(olist.size() - 1).isIndirect()) && - (olist.at(olist.size() - 1).isInteger()) && - (! olist.at(olist.size() - 2).isIndirect()) && - (olist.at(olist.size() - 2).isInteger())) - { - if (context == 0) - { - QTC::TC("qpdf", "QPDFObjectHandle indirect without context"); + } else if ( + (value == "R") && (state != st_top) && + (olist.size() >= 2) && + (!olist.at(olist.size() - 1).isIndirect()) && + (olist.at(olist.size() - 1).isInteger()) && + (!olist.at(olist.size() - 2).isIndirect()) && + (olist.at(olist.size() - 2).isInteger())) { + if (context == 0) { + QTC::TC( + "qpdf", + "QPDFObjectHandle indirect without context"); throw std::logic_error( "QPDFObjectHandle::parse called without context" " on an object with indirect references"); @@ -2427,38 +2219,35 @@ QPDFObjectHandle::parseInternal(PointerHolder input, olist.at(olist.size() - 1).getIntValueAsInt()); olist.remove_last(); olist.remove_last(); - } - else if ((value == "endobj") && (state == st_top)) - { + } else if ((value == "endobj") && (state == st_top)) { // We just saw endobj without having read // anything. Treat this as a null and do not move // the input source's offset. object = newNull(); input->seek(input->getLastOffset(), SEEK_SET); empty = true; - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle treat word as string"); - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "unknown token while reading object;" - " treating as string")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "unknown token while reading object;" + " treating as string")); bad = true; object = newString(value); } } break; - case QPDFTokenizer::tt_string: + case QPDFTokenizer::tt_string: { std::string val = token.getValue(); - if (decrypter) - { - if (b_contents) - { + if (decrypter) { + if (b_contents) { contents_string = val; contents_offset = input->getLastOffset(); b_contents = false; @@ -2470,103 +2259,102 @@ QPDFObjectHandle::parseInternal(PointerHolder input, break; - default: - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "treating unknown token type as null while " - "reading object")); + default: + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "treating unknown token type as null while " + "reading object")); bad = true; object = newNull(); break; } - if ((! object.isInitialized()) && - (! ((state == st_start) || - (state == st_stop) || - (state == st_eof)))) - { - throw std::logic_error( - "QPDFObjectHandle::parseInternal: " - "unexpected uninitialized object"); + if ((!object.isInitialized()) && + (!((state == st_start) || (state == st_stop) || + (state == st_eof)))) { + throw std::logic_error("QPDFObjectHandle::parseInternal: " + "unexpected uninitialized object"); object = newNull(); } - if (bad) - { + if (bad) { ++bad_count; good_count = 0; - } - else - { + } else { ++good_count; - if (good_count > 3) - { + if (good_count > 3) { bad_count = 0; } } - if (bad_count > 5) - { + if (bad_count > 5) { // We had too many consecutive errors without enough // intervening successful objects. Give up. - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "too many errors; giving up on reading object")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "too many errors; giving up on reading object")); state = st_top; object = newNull(); } - switch (state) - { - case st_eof: - if (state_stack.size() > 1) - { - warn(context, - QPDFExc(qpdf_e_damaged_pdf, input->getName(), - object_description, - input->getLastOffset(), - "parse error while reading object")); + switch (state) { + case st_eof: + if (state_stack.size() > 1) { + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + input->getLastOffset(), + "parse error while reading object")); } done = true; // In content stream mode, leave object uninitialized to // indicate EOF - if (! content_stream) - { + if (!content_stream) { object = newNull(); } break; - case st_dictionary: - case st_array: + case st_dictionary: + case st_array: setObjectDescriptionFromInput( - object, context, object_description, input, + object, + context, + object_description, + input, input->getLastOffset()); object.setParsedOffset(input->getLastOffset()); set_offset = true; olist.append(object); break; - case st_top: + case st_top: done = true; break; - case st_start: + case st_start: break; - case st_stop: - if ((state_stack.size() < 2) || (olist_stack.size() < 2)) - { + case st_stop: + if ((state_stack.size() < 2) || (olist_stack.size() < 2)) { throw std::logic_error( "QPDFObjectHandle::parseInternal: st_stop encountered" " with insufficient elements in stack"); } parser_state_e old_state = state_stack.back(); state_stack.pop_back(); - if (old_state == st_array) - { + if (old_state == st_array) { // There's no newArray(SparseOHArray) since // SparseOHArray is not part of the public API. object = QPDFObjectHandle(new QPDF_Array(olist)); @@ -2580,91 +2368,87 @@ QPDFObjectHandle::parseInternal(PointerHolder input, // therefore can't be used here. object.setParsedOffset(offset - 1); set_offset = true; - } - else if (old_state == st_dictionary) - { + } else if (old_state == st_dictionary) { // Convert list to map. Alternating elements are keys. // Attempt to recover more or less gracefully from // invalid dictionaries. std::set names; size_t n_elements = olist.size(); - for (size_t i = 0; i < n_elements; ++i) - { + for (size_t i = 0; i < n_elements; ++i) { QPDFObjectHandle oh = olist.at(i); - if ((! oh.isIndirect()) && oh.isName()) - { + if ((!oh.isIndirect()) && oh.isName()) { names.insert(oh.getName()); } } std::map dict; int next_fake_key = 1; - for (unsigned int i = 0; i < olist.size(); ++i) - { + for (unsigned int i = 0; i < olist.size(); ++i) { QPDFObjectHandle key_obj = olist.at(i); QPDFObjectHandle val; - if (key_obj.isIndirect() || (! key_obj.isName())) - { + if (key_obj.isIndirect() || (!key_obj.isName())) { bool found_fake = false; std::string candidate; - while (! found_fake) - { - candidate = - "/QPDFFake" + + while (!found_fake) { + candidate = "/QPDFFake" + QUtil::int_to_string(next_fake_key++); found_fake = (names.count(candidate) == 0); - QTC::TC("qpdf", "QPDFObjectHandle found fake", - (found_fake ? 0 : 1)); + QTC::TC( + "qpdf", + "QPDFObjectHandle found fake", + (found_fake ? 0 : 1)); } - warn(context, - QPDFExc( - qpdf_e_damaged_pdf, - input->getName(), object_description, offset, - "expected dictionary key but found" - " non-name object; inserting key " + - candidate)); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + offset, + "expected dictionary key but found" + " non-name object; inserting key " + + candidate)); val = key_obj; key_obj = newName(candidate); - } - else if (i + 1 >= olist.size()) - { + } else if (i + 1 >= olist.size()) { QTC::TC("qpdf", "QPDFObjectHandle no val for last key"); - warn(context, - QPDFExc( - qpdf_e_damaged_pdf, - input->getName(), object_description, offset, - "dictionary ended prematurely; " - "using null as value for last key")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + offset, + "dictionary ended prematurely; " + "using null as value for last key")); val = newNull(); setObjectDescriptionFromInput( val, context, object_description, input, offset); - } - else - { + } else { val = olist.at(++i); } std::string key = key_obj.getName(); - if (dict.count(key) > 0) - { + if (dict.count(key) > 0) { QTC::TC("qpdf", "QPDFObjectHandle duplicate dict key"); - warn(context, - QPDFExc( - qpdf_e_damaged_pdf, - input->getName(), object_description, offset, - "dictionary has duplicated key " + key + - "; last occurrence overrides earlier ones")); + warn( + context, + QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + object_description, + offset, + "dictionary has duplicated key " + key + + "; last occurrence overrides earlier " + "ones")); } dict[key] = val; } - if (!contents_string.empty() && - dict.count("/Type") && + if (!contents_string.empty() && dict.count("/Type") && dict["/Type"].isNameAndEquals("/Sig") && - dict.count("/ByteRange") && - dict.count("/Contents") && - dict["/Contents"].isString()) - { - dict["/Contents"] - = QPDFObjectHandle::newString(contents_string); + dict.count("/ByteRange") && dict.count("/Contents") && + dict["/Contents"].isString()) { + dict["/Contents"] = + QPDFObjectHandle::newString(contents_string); dict["/Contents"].setParsedOffset(contents_offset); } object = newDictionary(dict); @@ -2681,12 +2465,9 @@ QPDFObjectHandle::parseInternal(PointerHolder input, } olist_stack.pop_back(); offset_stack.pop_back(); - if (state_stack.back() == st_top) - { + if (state_stack.back() == st_top) { done = true; - } - else - { + } else { olist_stack.back().append(object); } contents_string_stack.pop_back(); @@ -2694,8 +2475,7 @@ QPDFObjectHandle::parseInternal(PointerHolder input, } } - if (! set_offset) - { + if (!set_offset) { setObjectDescriptionFromInput( object, context, object_description, input, offset); object.setParsedOffset(offset); @@ -2715,8 +2495,7 @@ QPDFObjectHandle::setParsedOffset(qpdf_offset_t offset) { // This is called during parsing on newly created direct objects, // so we can't call dereference() here. - if (this->obj.get()) - { + if (this->obj.get()) { this->obj->setParsedOffset(offset); } } @@ -2724,8 +2503,7 @@ QPDFObjectHandle::setParsedOffset(qpdf_offset_t offset) QPDFObjectHandle QPDFObjectHandle::newIndirect(QPDF* qpdf, int objid, int generation) { - if (objid == 0) - { + if (objid == 0) { // Special case: QPDF uses objid 0 as a sentinel for direct // objects, and the PDF specification doesn't allow for object // 0. Treat indirect references to object 0 as null so that we @@ -2764,13 +2542,12 @@ QPDFObjectHandle::newReal(std::string const& value) QPDFObjectHandle QPDFObjectHandle::newReal(double value, int decimal_places) { - return QPDFObjectHandle( - new QPDF_Real(value, decimal_places, true)); + return QPDFObjectHandle(new QPDF_Real(value, decimal_places, true)); } QPDFObjectHandle -QPDFObjectHandle::newReal(double value, int decimal_places, - bool trim_trailing_zeroes) +QPDFObjectHandle::newReal( + double value, int decimal_places, bool trim_trailing_zeroes) { return QPDFObjectHandle( new QPDF_Real(value, decimal_places, trim_trailing_zeroes)); @@ -2886,17 +2663,18 @@ QPDFObjectHandle::newDictionary( return QPDFObjectHandle(new QPDF_Dictionary(items)); } - QPDFObjectHandle -QPDFObjectHandle::newStream(QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length) +QPDFObjectHandle::newStream( + QPDF* qpdf, + int objid, + int generation, + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, + size_t length) { - QPDFObjectHandle result = QPDFObjectHandle(new QPDF_Stream( - qpdf, objid, generation, - stream_dict, offset, length)); - if (offset) - { + QPDFObjectHandle result = QPDFObjectHandle( + new QPDF_Stream(qpdf, objid, generation, stream_dict, offset, length)); + if (offset) { result.setParsedOffset(offset); } return result; @@ -2905,19 +2683,16 @@ QPDFObjectHandle::newStream(QPDF* qpdf, int objid, int generation, QPDFObjectHandle QPDFObjectHandle::newStream(QPDF* qpdf) { - if (qpdf == 0) - { + if (qpdf == 0) { throw std::runtime_error( "attempt to create stream in null qpdf object"); } QTC::TC("qpdf", "QPDFObjectHandle newStream"); QPDFObjectHandle stream_dict = newDictionary(); QPDFObjectHandle result = qpdf->makeIndirectObject( - QPDFObjectHandle( - new QPDF_Stream(qpdf, 0, 0, stream_dict, 0, 0))); + QPDFObjectHandle(new QPDF_Stream(qpdf, 0, 0, stream_dict, 0, 0))); result.dereference(); - QPDF_Stream* stream = - dynamic_cast(result.obj.get()); + QPDF_Stream* stream = dynamic_cast(result.obj.get()); stream->setObjGen(result.getObjectID(), result.getGeneration()); return result; } @@ -2945,8 +2720,8 @@ QPDFObjectHandle::newReserved(QPDF* qpdf) { // Reserve a spot for this object by assigning it an object // number, but then return an unresolved handle to the object. - QPDFObjectHandle reserved = qpdf->makeIndirectObject( - QPDFObjectHandle(new QPDF_Reserved())); + QPDFObjectHandle reserved = + qpdf->makeIndirectObject(QPDFObjectHandle(new QPDF_Reserved())); QPDFObjectHandle result = newIndirect(qpdf, reserved.objid, reserved.generation); result.reserved = true; @@ -2954,13 +2729,12 @@ QPDFObjectHandle::newReserved(QPDF* qpdf) } void -QPDFObjectHandle::setObjectDescription(QPDF* owning_qpdf, - std::string const& object_description) +QPDFObjectHandle::setObjectDescription( + QPDF* owning_qpdf, std::string const& object_description) { // This is called during parsing on newly created direct objects, // so we can't call dereference() here. - if (isInitialized() && this->obj.get()) - { + if (isInitialized() && this->obj.get()) { this->obj->setDescription(owning_qpdf, object_description); } } @@ -2968,11 +2742,9 @@ QPDFObjectHandle::setObjectDescription(QPDF* owning_qpdf, bool QPDFObjectHandle::hasObjectDescription() { - if (isInitialized()) - { + if (isInitialized()) { dereference(); - if (this->obj.get()) - { + if (this->obj.get()) { return this->obj->hasDescription(); } } @@ -2996,33 +2768,26 @@ QPDFObjectHandle::unsafeShallowCopy() } void -QPDFObjectHandle::shallowCopyInternal(QPDFObjectHandle& new_obj, - bool first_level_only) +QPDFObjectHandle::shallowCopyInternal( + QPDFObjectHandle& new_obj, bool first_level_only) { assertInitialized(); - if (isStream()) - { + if (isStream()) { QTC::TC("qpdf", "QPDFObjectHandle ERR shallow copy stream"); - throw std::runtime_error( - "attempt to make a shallow copy of a stream"); + throw std::runtime_error("attempt to make a shallow copy of a stream"); } - if (isArray()) - { + if (isArray()) { QTC::TC("qpdf", "QPDFObjectHandle shallow copy array"); // No newArray for shallow copying the sparse array QPDF_Array* arr = dynamic_cast(obj.get()); - new_obj = QPDFObjectHandle( - new QPDF_Array(arr->getElementsForShallowCopy())); - } - else if (isDictionary()) - { + new_obj = + QPDFObjectHandle(new QPDF_Array(arr->getElementsForShallowCopy())); + } else if (isDictionary()) { QTC::TC("qpdf", "QPDFObjectHandle shallow copy dictionary"); new_obj = newDictionary(getDictAsMap()); - } - else - { + } else { QTC::TC("qpdf", "QPDFObjectHandle shallow copy scalar"); new_obj = *this; } @@ -3032,18 +2797,18 @@ QPDFObjectHandle::shallowCopyInternal(QPDFObjectHandle& new_obj, } void -QPDFObjectHandle::copyObject(std::set& visited, - bool cross_indirect, bool first_level_only, - bool stop_at_streams) +QPDFObjectHandle::copyObject( + std::set& visited, + bool cross_indirect, + bool first_level_only, + bool stop_at_streams) { assertInitialized(); - if (isStream()) - { - QTC::TC("qpdf", "QPDFObjectHandle copy stream", - stop_at_streams ? 0 : 1); - if (stop_at_streams) - { + if (isStream()) { + QTC::TC( + "qpdf", "QPDFObjectHandle copy stream", stop_at_streams ? 0 : 1); + if (stop_at_streams) { return; } throw std::runtime_error( @@ -3051,10 +2816,8 @@ QPDFObjectHandle::copyObject(std::set& visited, } QPDFObjGen cur_og(this->objid, this->generation); - if (cur_og.getObj() != 0) - { - if (visited.count(cur_og)) - { + if (cur_og.getObj() != 0) { + if (visited.count(cur_og)) { QTC::TC("qpdf", "QPDFObjectHandle makeDirect loop"); throw std::runtime_error( "loop detected while converting object from " @@ -3063,11 +2826,9 @@ QPDFObjectHandle::copyObject(std::set& visited, visited.insert(cur_og); } - if (isReserved()) - { - throw std::logic_error( - "QPDFObjectHandle: attempting to make a" - " reserved object handle direct"); + if (isReserved()) { + throw std::logic_error("QPDFObjectHandle: attempting to make a" + " reserved object handle direct"); } dereference(); @@ -3077,83 +2838,60 @@ QPDFObjectHandle::copyObject(std::set& visited, PointerHolder new_obj; - if (isBool()) - { + if (isBool()) { QTC::TC("qpdf", "QPDFObjectHandle clone bool"); new_obj = PointerHolder(new QPDF_Bool(getBoolValue())); - } - else if (isNull()) - { + } else if (isNull()) { QTC::TC("qpdf", "QPDFObjectHandle clone null"); new_obj = PointerHolder(new QPDF_Null()); - } - else if (isInteger()) - { + } else if (isInteger()) { QTC::TC("qpdf", "QPDFObjectHandle clone integer"); new_obj = PointerHolder(new QPDF_Integer(getIntValue())); - } - else if (isReal()) - { + } else if (isReal()) { QTC::TC("qpdf", "QPDFObjectHandle clone real"); new_obj = PointerHolder(new QPDF_Real(getRealValue())); - } - else if (isName()) - { + } else if (isName()) { QTC::TC("qpdf", "QPDFObjectHandle clone name"); new_obj = PointerHolder(new QPDF_Name(getName())); - } - else if (isString()) - { + } else if (isString()) { QTC::TC("qpdf", "QPDFObjectHandle clone string"); new_obj = PointerHolder(new QPDF_String(getStringValue())); - } - else if (isArray()) - { + } else if (isArray()) { QTC::TC("qpdf", "QPDFObjectHandle clone array"); std::vector items; int n = getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { items.push_back(getArrayItem(i)); - if ((! first_level_only) && - (cross_indirect || (! items.back().isIndirect()))) - { + if ((!first_level_only) && + (cross_indirect || (!items.back().isIndirect()))) { items.back().copyObject( - visited, cross_indirect, - first_level_only, stop_at_streams); + visited, cross_indirect, first_level_only, stop_at_streams); } } new_obj = PointerHolder(new QPDF_Array(items)); - } - else if (isDictionary()) - { + } else if (isDictionary()) { QTC::TC("qpdf", "QPDFObjectHandle clone dictionary"); std::set keys = getKeys(); std::map items; for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { items[*iter] = getKey(*iter); - if ((! first_level_only) && - (cross_indirect || (! items[*iter].isIndirect()))) - { + if ((!first_level_only) && + (cross_indirect || (!items[*iter].isIndirect()))) { items[*iter].copyObject( - visited, cross_indirect, - first_level_only, stop_at_streams); + visited, cross_indirect, first_level_only, stop_at_streams); } } new_obj = PointerHolder(new QPDF_Dictionary(items)); - } - else - { + } else { throw std::logic_error("QPDFObjectHandle::makeDirectInternal: " "unknown object type"); } this->obj = new_obj; - if (cur_og.getObj()) - { + if (cur_og.getObj()) { visited.erase(cur_og); } } @@ -3165,14 +2903,10 @@ QPDFObjectHandle::copyStream() QPDFObjectHandle result = newStream(this->getOwningQPDF()); QPDFObjectHandle dict = result.getDict(); QPDFObjectHandle old_dict = getDict(); - for (auto& iter: QPDFDictItems(old_dict)) - { - if (iter.second.isIndirect()) - { + for (auto& iter : QPDFDictItems(old_dict)) { + if (iter.second.isIndirect()) { dict.replaceKey(iter.first, iter.second); - } - else - { + } else { dict.replaceKey(iter.first, iter.second.shallowCopy()); } } @@ -3196,47 +2930,43 @@ QPDFObjectHandle::makeDirect(bool allow_streams) void QPDFObjectHandle::assertInitialized() const { - if (! this->initialized) - { + if (!this->initialized) { throw std::logic_error("operation attempted on uninitialized " "QPDFObjectHandle"); } } void -QPDFObjectHandle::typeWarning(char const* expected_type, - std::string const& warning) +QPDFObjectHandle::typeWarning( + char const* expected_type, std::string const& warning) { QPDF* context = nullptr; std::string description; dereference(); this->obj->getDescription(context, description); // Null context handled by warn - warn(context, - QPDFExc(qpdf_e_object, - "", description, 0, - std::string("operation for ") + expected_type + - " attempted on object of type " + - getTypeName() + ": " + warning)); + warn( + context, + QPDFExc( + qpdf_e_object, + "", + description, + 0, + std::string("operation for ") + expected_type + + " attempted on object of type " + getTypeName() + ": " + + warning)); } void -QPDFObjectHandle::warnIfPossible(std::string const& warning, - bool throw_if_no_description) +QPDFObjectHandle::warnIfPossible( + std::string const& warning, bool throw_if_no_description) { QPDF* context = 0; std::string description; dereference(); - if (this->obj->getDescription(context, description)) - { - warn(context, - QPDFExc( - qpdf_e_damaged_pdf, - "", description, 0, - warning)); - } - else if (throw_if_no_description) - { + if (this->obj->getDescription(context, description)) { + warn(context, QPDFExc(qpdf_e_damaged_pdf, "", description, 0, warning)); + } else if (throw_if_no_description) { throw std::runtime_error(warning); } } @@ -3255,11 +2985,10 @@ QPDFObjectHandle::objectWarning(std::string const& warning) void QPDFObjectHandle::assertType(char const* type_name, bool istype) { - if (! istype) - { - throw std::runtime_error(std::string("operation for ") + type_name + - " attempted on object of type " + - getTypeName()); + if (!istype) { + throw std::runtime_error( + std::string("operation for ") + type_name + + " attempted on object of type " + getTypeName()); } } @@ -3338,8 +3067,7 @@ QPDFObjectHandle::assertReserved() void QPDFObjectHandle::assertIndirect() { - if (! isIndirect()) - { + if (!isIndirect()) { throw std::logic_error( "operation for indirect object attempted on direct object"); } @@ -3361,30 +3089,23 @@ bool QPDFObjectHandle::isPageObject() { // See comments in QPDFObjectHandle.hh. - if (getOwningQPDF() == nullptr) - { + if (getOwningQPDF() == nullptr) { return false; } // getAllPages repairs /Type when traversing the page tree. getOwningQPDF()->getAllPages(); - if (! this->isDictionary()) - { + if (!this->isDictionary()) { return false; } - if (this->hasKey("/Type")) - { + if (this->hasKey("/Type")) { QPDFObjectHandle type = this->getKey("/Type"); - if (type.isNameAndEquals("/Page")) - { + if (type.isNameAndEquals("/Page")) { return true; } // Files have been seen in the wild that have /Type (Page) - else if (type.isString() && (type.getStringValue() == "Page")) - { + else if (type.isString() && (type.getStringValue() == "Page")) { return true; - } - else - { + } else { return false; } } @@ -3394,8 +3115,7 @@ QPDFObjectHandle::isPageObject() bool QPDFObjectHandle::isPagesObject() { - if (getOwningQPDF() == nullptr) - { + if (getOwningQPDF() == nullptr) { return false; } // getAllPages repairs /Type when traversing the page tree. @@ -3412,19 +3132,18 @@ QPDFObjectHandle::isFormXObject() bool QPDFObjectHandle::isImage(bool exclude_imagemask) { - return (isStreamOfType("", "/Image") && - ((! exclude_imagemask) || - (! (getDict().getKey("/ImageMask").isBool() && - getDict().getKey("/ImageMask").getBoolValue())))); + return ( + isStreamOfType("", "/Image") && + ((!exclude_imagemask) || + (!(getDict().getKey("/ImageMask").isBool() && + getDict().getKey("/ImageMask").getBoolValue())))); } void QPDFObjectHandle::checkOwnership(QPDFObjectHandle const& item) const { - if ((this->qpdf != nullptr) && - (item.qpdf != nullptr) && - (this->qpdf != item.qpdf)) - { + if ((this->qpdf != nullptr) && (item.qpdf != nullptr) && + (this->qpdf != item.qpdf)) { QTC::TC("qpdf", "QPDFObjectHandle check ownership"); throw std::logic_error( "Attempting to add an object from a different QPDF." @@ -3435,8 +3154,7 @@ QPDFObjectHandle::checkOwnership(QPDFObjectHandle const& item) const void QPDFObjectHandle::assertPageObject() { - if (! isPageObject()) - { + if (!isPageObject()) { throw std::runtime_error("page operation called on non-Page object"); } } @@ -3444,33 +3162,25 @@ QPDFObjectHandle::assertPageObject() void QPDFObjectHandle::dereference() { - if (! this->initialized) - { + if (!this->initialized) { throw std::logic_error( "attempted to dereference an uninitialized QPDFObjectHandle"); } if (this->obj.get() && this->objid && QPDF::Resolver::objectChanged( - this->qpdf, QPDFObjGen(this->objid, this->generation), this->obj)) - { + this->qpdf, QPDFObjGen(this->objid, this->generation), this->obj)) { this->obj = nullptr; } - if (this->obj.get() == 0) - { - PointerHolder obj = QPDF::Resolver::resolve( - this->qpdf, this->objid, this->generation); - if (obj.get() == 0) - { + if (this->obj.get() == 0) { + PointerHolder obj = + QPDF::Resolver::resolve(this->qpdf, this->objid, this->generation); + if (obj.get() == 0) { // QPDF::resolve never returns an uninitialized object, but // check just in case. this->obj = PointerHolder(new QPDF_Null()); - } - else if (dynamic_cast(obj.get())) - { + } else if (dynamic_cast(obj.get())) { // Do not resolve - } - else - { + } else { this->reserved = false; this->obj = obj; } @@ -3484,12 +3194,9 @@ QPDFObjectHandle::warn(QPDF* qpdf, QPDFExc const& e) // warning, we can warn through the object. If parsing for some // other reason, such as an explicit creation of an object from a // string, then just throw the exception. - if (qpdf) - { + if (qpdf) { qpdf->warn(e); - } - else - { + } else { throw e; } } @@ -3516,7 +3223,7 @@ QPDFObjectHandle::QPDFDictItems::iterator::operator--() } QPDFObjectHandle::QPDFDictItems::iterator::reference -QPDFObjectHandle::QPDFDictItems::iterator:: operator*() +QPDFObjectHandle::QPDFDictItems::iterator::operator*() { updateIValue(); return this->ivalue; @@ -3533,12 +3240,10 @@ bool QPDFObjectHandle::QPDFDictItems::iterator::operator==( iterator const& other) const { - if (this->m->is_end && other.m->is_end) - { + if (this->m->is_end && other.m->is_end) { return true; } - if (this->m->is_end || other.m->is_end) - { + if (this->m->is_end || other.m->is_end) { return false; } return (this->ivalue.first == other.ivalue.first); @@ -3555,13 +3260,10 @@ void QPDFObjectHandle::QPDFDictItems::iterator::updateIValue() { this->m->is_end = (this->m->iter == this->m->keys.end()); - if (this->m->is_end) - { + if (this->m->is_end) { this->ivalue.first = ""; this->ivalue.second = QPDFObjectHandle(); - } - else - { + } else { this->ivalue.first = *(this->m->iter); this->ivalue.second = this->m->oh.getKey(this->ivalue.first); } @@ -3595,8 +3297,7 @@ QPDFObjectHandle::QPDFArrayItems::QPDFArrayItems(QPDFObjectHandle const& oh) : QPDFObjectHandle::QPDFArrayItems::iterator& QPDFObjectHandle::QPDFArrayItems::iterator::operator++() { - if (! this->m->is_end) - { + if (!this->m->is_end) { ++this->m->item_number; updateIValue(); } @@ -3606,8 +3307,7 @@ QPDFObjectHandle::QPDFArrayItems::iterator::operator++() QPDFObjectHandle::QPDFArrayItems::iterator& QPDFObjectHandle::QPDFArrayItems::iterator::operator--() { - if (this->m->item_number > 0) - { + if (this->m->item_number > 0) { --this->m->item_number; updateIValue(); } @@ -3615,7 +3315,7 @@ QPDFObjectHandle::QPDFArrayItems::iterator::operator--() } QPDFObjectHandle::QPDFArrayItems::iterator::reference -QPDFObjectHandle::QPDFArrayItems::iterator:: operator*() +QPDFObjectHandle::QPDFArrayItems::iterator::operator*() { updateIValue(); return this->ivalue; @@ -3646,12 +3346,9 @@ void QPDFObjectHandle::QPDFArrayItems::iterator::updateIValue() { this->m->is_end = (this->m->item_number >= this->m->oh.getArrayNItems()); - if (this->m->is_end) - { + if (this->m->is_end) { this->ivalue = QPDFObjectHandle(); - } - else - { + } else { this->ivalue = this->m->oh.getArrayItem(this->m->item_number); } } @@ -3675,8 +3372,7 @@ QPDFObjectHandle::QPDFArrayItems::end() return iterator(oh, false); } -QPDFObjectHandle -operator ""_qpdf(char const* v, size_t len) +QPDFObjectHandle operator""_qpdf(char const* v, size_t len) { return QPDFObjectHandle::parse( std::string(v, len), "QPDFObjectHandle literal"); diff --git a/libqpdf/QPDFOutlineDocumentHelper.cc b/libqpdf/QPDFOutlineDocumentHelper.cc index c8d08288..6f3711de 100644 --- a/libqpdf/QPDFOutlineDocumentHelper.cc +++ b/libqpdf/QPDFOutlineDocumentHelper.cc @@ -15,22 +15,18 @@ QPDFOutlineDocumentHelper::QPDFOutlineDocumentHelper(QPDF& qpdf) : m(new Members()) { QPDFObjectHandle root = qpdf.getRoot(); - if (! root.hasKey("/Outlines")) - { + if (!root.hasKey("/Outlines")) { return; } QPDFObjectHandle outlines = root.getKey("/Outlines"); - if (! (outlines.isDictionary() && outlines.hasKey("/First"))) - { + if (!(outlines.isDictionary() && outlines.hasKey("/First"))) { return; } QPDFObjectHandle cur = outlines.getKey("/First"); std::set seen; - while (! cur.isNull()) - { + while (!cur.isNull()) { auto og = cur.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { break; } seen.insert(og); @@ -47,7 +43,7 @@ QPDFOutlineDocumentHelper::~QPDFOutlineDocumentHelper() bool QPDFOutlineDocumentHelper::hasOutlines() { - return ! this->m->outlines.empty(); + return !this->m->outlines.empty(); } std::vector @@ -60,10 +56,10 @@ void QPDFOutlineDocumentHelper::initializeByPage() { std::list queue; - queue.insert(queue.end(), this->m->outlines.begin(), this->m->outlines.end()); + queue.insert( + queue.end(), this->m->outlines.begin(), this->m->outlines.end()); - while (! queue.empty()) - { + while (!queue.empty()) { QPDFOutlineObjectHelper oh = queue.front(); queue.pop_front(); this->m->by_page[oh.getDestPage().getObjGen()].push_back(oh); @@ -75,13 +71,11 @@ QPDFOutlineDocumentHelper::initializeByPage() std::vector QPDFOutlineDocumentHelper::getOutlinesForPage(QPDFObjGen const& og) { - if (this->m->by_page.empty()) - { + if (this->m->by_page.empty()) { initializeByPage(); } std::vector result; - if (this->m->by_page.count(og)) - { + if (this->m->by_page.count(og)) { result = this->m->by_page[og]; } return result; @@ -91,44 +85,33 @@ QPDFObjectHandle QPDFOutlineDocumentHelper::resolveNamedDest(QPDFObjectHandle name) { QPDFObjectHandle result; - if (name.isName()) - { - if (! this->m->dest_dict.isInitialized()) - { + if (name.isName()) { + if (!this->m->dest_dict.isInitialized()) { this->m->dest_dict = this->qpdf.getRoot().getKey("/Dests"); } - if (this->m->dest_dict.isDictionary()) - { + if (this->m->dest_dict.isDictionary()) { QTC::TC("qpdf", "QPDFOutlineDocumentHelper name named dest"); result = this->m->dest_dict.getKey(name.getName()); } - } - else if (name.isString()) - { - if (0 == this->m->names_dest.get()) - { + } else if (name.isString()) { + if (0 == this->m->names_dest.get()) { QPDFObjectHandle names = this->qpdf.getRoot().getKey("/Names"); - if (names.isDictionary()) - { + if (names.isDictionary()) { QPDFObjectHandle dests = names.getKey("/Dests"); - if (dests.isDictionary()) - { + if (dests.isDictionary()) { this->m->names_dest = make_pointer_holder( dests, this->qpdf); } } } - if (this->m->names_dest.get()) - { - if (this->m->names_dest->findObject(name.getUTF8Value(), result)) - { + if (this->m->names_dest.get()) { + if (this->m->names_dest->findObject(name.getUTF8Value(), result)) { QTC::TC("qpdf", "QPDFOutlineDocumentHelper string named dest"); } } } - if (! result.isInitialized()) - { + if (!result.isInitialized()) { result = QPDFObjectHandle::newNull(); } return result; @@ -137,8 +120,7 @@ QPDFOutlineDocumentHelper::resolveNamedDest(QPDFObjectHandle name) bool QPDFOutlineDocumentHelper::checkSeen(QPDFObjGen const& og) { - if (this->m->seen.count(og) > 0) - { + if (this->m->seen.count(og) > 0) { return true; } this->m->seen.insert(og); diff --git a/libqpdf/QPDFOutlineObjectHelper.cc b/libqpdf/QPDFOutlineObjectHelper.cc index cf6d3fcf..713c1412 100644 --- a/libqpdf/QPDFOutlineObjectHelper.cc +++ b/libqpdf/QPDFOutlineObjectHelper.cc @@ -17,22 +17,19 @@ QPDFOutlineObjectHelper::QPDFOutlineObjectHelper( QPDFObjectHelper(oh), m(new Members(dh)) { - if (depth > 50) - { + if (depth > 50) { // Not exercised in test suite, but was tested manually by // temporarily changing max depth to 1. return; } if (QPDFOutlineDocumentHelper::Accessor::checkSeen( - this->m->dh, this->oh.getObjGen())) - { + this->m->dh, this->oh.getObjGen())) { QTC::TC("qpdf", "QPDFOutlineObjectHelper loop"); return; } QPDFObjectHandle cur = oh.getKey("/First"); - while (! cur.isNull()) - { + while (!cur.isNull()) { QPDFOutlineObjectHelper new_ooh(cur, dh, 1 + depth); new_ooh.m->parent = make_pointer_holder(*this); this->m->kids.push_back(new_ooh); @@ -57,26 +54,20 @@ QPDFOutlineObjectHelper::getDest() { QPDFObjectHandle dest; QPDFObjectHandle A; - if (this->oh.hasKey("/Dest")) - { + if (this->oh.hasKey("/Dest")) { QTC::TC("qpdf", "QPDFOutlineObjectHelper direct dest"); dest = this->oh.getKey("/Dest"); - } - else if ((A = this->oh.getKey("/A")).isDictionary() && - A.getKey("/S").isName() && - (A.getKey("/S").getName() == "/GoTo") && - A.hasKey("/D")) - { + } else if ( + (A = this->oh.getKey("/A")).isDictionary() && A.getKey("/S").isName() && + (A.getKey("/S").getName() == "/GoTo") && A.hasKey("/D")) { QTC::TC("qpdf", "QPDFOutlineObjectHelper action dest"); dest = A.getKey("/D"); } - if (! dest.isInitialized()) - { + if (!dest.isInitialized()) { dest = QPDFObjectHandle::newNull(); } - if (dest.isName() || dest.isString()) - { + if (dest.isName() || dest.isString()) { QTC::TC("qpdf", "QPDFOutlineObjectHelper named dest"); dest = this->m->dh.resolveNamedDest(dest); } @@ -88,8 +79,7 @@ QPDFObjectHandle QPDFOutlineObjectHelper::getDestPage() { QPDFObjectHandle dest = getDest(); - if ((dest.isArray()) && (dest.getArrayNItems() > 0)) - { + if ((dest.isArray()) && (dest.getArrayNItems() > 0)) { return dest.getArrayItem(0); } return QPDFObjectHandle::newNull(); @@ -99,8 +89,7 @@ int QPDFOutlineObjectHelper::getCount() { int count = 0; - if (this->oh.hasKey("/Count")) - { + if (this->oh.hasKey("/Count")) { count = this->oh.getKey("/Count").getIntValueAsInt(); } return count; @@ -110,8 +99,7 @@ std::string QPDFOutlineObjectHelper::getTitle() { std::string result; - if (this->oh.hasKey("/Title")) - { + if (this->oh.hasKey("/Title")) { result = this->oh.getKey("/Title").getUTF8Value(); } return result; diff --git a/libqpdf/QPDFPageDocumentHelper.cc b/libqpdf/QPDFPageDocumentHelper.cc index e76c874f..ecfd3713 100644 --- a/libqpdf/QPDFPageDocumentHelper.cc +++ b/libqpdf/QPDFPageDocumentHelper.cc @@ -1,8 +1,8 @@ #include #include -#include #include +#include QPDFPageDocumentHelper::Members::~Members() { @@ -23,8 +23,8 @@ QPDFPageDocumentHelper::getAllPages() std::vector const& pages_v = this->qpdf.getAllPages(); std::vector pages; for (std::vector::const_iterator iter = pages_v.begin(); - iter != pages_v.end(); ++iter) - { + iter != pages_v.end(); + ++iter) { pages.push_back(QPDFPageObjectHelper(*iter)); } return pages; @@ -41,8 +41,8 @@ QPDFPageDocumentHelper::removeUnreferencedResources() { std::vector pages = getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { (*iter).removeUnreferencedResources(); } } @@ -54,11 +54,11 @@ QPDFPageDocumentHelper::addPage(QPDFPageObjectHelper newpage, bool first) } void -QPDFPageDocumentHelper::addPageAt(QPDFPageObjectHelper newpage, bool before, - QPDFPageObjectHelper refpage) +QPDFPageDocumentHelper::addPageAt( + QPDFPageObjectHelper newpage, bool before, QPDFPageObjectHelper refpage) { - this->qpdf.addPageAt(newpage.getObjectHandle(), before, - refpage.getObjectHandle()); + this->qpdf.addPageAt( + newpage.getObjectHandle(), before, refpage.getObjectHandle()); } void @@ -67,36 +67,32 @@ QPDFPageDocumentHelper::removePage(QPDFPageObjectHelper page) this->qpdf.removePage(page.getObjectHandle()); } - void QPDFPageDocumentHelper::flattenAnnotations( - int required_flags, - int forbidden_flags) + int required_flags, int forbidden_flags) { QPDFAcroFormDocumentHelper afdh(this->qpdf); - if (afdh.getNeedAppearances()) - { - this->qpdf.getRoot().getKey("/AcroForm").warnIfPossible( - "document does not have updated appearance streams," - " so form fields will not be flattened"); + if (afdh.getNeedAppearances()) { + this->qpdf.getRoot() + .getKey("/AcroForm") + .warnIfPossible("document does not have updated appearance streams," + " so form fields will not be flattened"); } std::vector pages = getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper ph(*iter); QPDFObjectHandle resources = ph.getAttribute("/Resources", true); - if (! resources.isDictionary()) - { + if (!resources.isDictionary()) { // This should never happen and is not exercised in the // test suite resources = QPDFObjectHandle::newDictionary(); } - flattenAnnotationsForPage(ph, resources, afdh, - required_flags, forbidden_flags); + flattenAnnotationsForPage( + ph, resources, afdh, required_flags, forbidden_flags); } - if (! afdh.getNeedAppearances()) - { + if (!afdh.getNeedAppearances()) { this->qpdf.getRoot().removeKey("/AcroForm"); } } @@ -114,100 +110,82 @@ QPDFPageDocumentHelper::flattenAnnotationsForPage( std::vector new_annots; std::string new_content; int rotate = 0; - QPDFObjectHandle rotate_obj = - page.getObjectHandle().getKey("/Rotate"); - if (rotate_obj.isInteger() && rotate_obj.getIntValue()) - { + QPDFObjectHandle rotate_obj = page.getObjectHandle().getKey("/Rotate"); + if (rotate_obj.isInteger() && rotate_obj.getIntValue()) { rotate = rotate_obj.getIntValueAsInt(); } int next_fx = 1; for (std::vector::iterator iter = annots.begin(); - iter != annots.end(); ++iter) - { + iter != annots.end(); + ++iter) { QPDFAnnotationObjectHelper& aoh(*iter); QPDFObjectHandle as = aoh.getAppearanceStream("/N"); bool is_widget = (aoh.getSubtype() == "/Widget"); bool process = true; - if (need_appearances && is_widget) - { - QTC::TC("qpdf", "QPDFPageDocumentHelper skip widget need appearances"); + if (need_appearances && is_widget) { + QTC::TC( + "qpdf", "QPDFPageDocumentHelper skip widget need appearances"); process = false; } - if (process && as.isStream()) - { - if (is_widget) - { + if (process && as.isStream()) { + if (is_widget) { QTC::TC("qpdf", "QPDFPageDocumentHelper merge DR"); QPDFFormFieldObjectHelper ff = afdh.getFieldForAnnotation(aoh); QPDFObjectHandle as_resources = as.getDict().getKey("/Resources"); - if (as_resources.isIndirect()) - { - QTC::TC("qpdf", "QPDFPageDocumentHelper indirect as resources"); + if (as_resources.isIndirect()) { + QTC::TC( + "qpdf", "QPDFPageDocumentHelper indirect as resources"); as.getDict().replaceKey( "/Resources", as_resources.shallowCopy()); as_resources = as.getDict().getKey("/Resources"); } as_resources.mergeResources(ff.getDefaultResources()); - } - else - { + } else { QTC::TC("qpdf", "QPDFPageDocumentHelper non-widget annotation"); } - std::string name = resources.getUniqueResourceName( - "/Fxo", next_fx); + std::string name = resources.getUniqueResourceName("/Fxo", next_fx); std::string content = aoh.getPageContentForAppearance( name, rotate, required_flags, forbidden_flags); - if (! content.empty()) - { + if (!content.empty()) { resources.mergeResources("<< /XObject << >> >>"_qpdf); resources.getKey("/XObject").replaceKey(name, as); ++next_fx; } new_content += content; - } - else if (process) - { + } else if (process) { // If an annotation has no appearance stream, just drop // the annotation when flattening. This can happen for // unchecked checkboxes and radio buttons, popup windows // associated with comments that aren't visible, and other // types of annotations that aren't visible. - QTC::TC("qpdf", "QPDFPageDocumentHelper ignore annotation with no appearance"); - } - else - { + QTC::TC( + "qpdf", + "QPDFPageDocumentHelper ignore annotation with no appearance"); + } else { new_annots.push_back(aoh.getObjectHandle()); } } - if (new_annots.size() != annots.size()) - { + if (new_annots.size() != annots.size()) { QPDFObjectHandle page_oh = page.getObjectHandle(); - if (new_annots.empty()) - { + if (new_annots.empty()) { QTC::TC("qpdf", "QPDFPageDocumentHelper remove annots"); page_oh.removeKey("/Annots"); - } - else - { + } else { QPDFObjectHandle old_annots = page_oh.getKey("/Annots"); QPDFObjectHandle new_annots_oh = QPDFObjectHandle::newArray(new_annots); - if (old_annots.isIndirect()) - { - QTC::TC("qpdf", "QPDFPageDocumentHelper replace indirect annots"); - this->qpdf.replaceObject( - old_annots.getObjGen(), new_annots_oh); - } - else - { + if (old_annots.isIndirect()) { + QTC::TC( + "qpdf", "QPDFPageDocumentHelper replace indirect annots"); + this->qpdf.replaceObject(old_annots.getObjGen(), new_annots_oh); + } else { QTC::TC("qpdf", "QPDFPageDocumentHelper replace direct annots"); page_oh.replaceKey("/Annots", new_annots_oh); } } - page.addPageContents( - QPDFObjectHandle::newStream(&qpdf, "q\n"), true); + page.addPageContents(QPDFObjectHandle::newStream(&qpdf, "q\n"), true); page.addPageContents( QPDFObjectHandle::newStream(&qpdf, "\nQ\n" + new_content), false); } diff --git a/libqpdf/QPDFPageLabelDocumentHelper.cc b/libqpdf/QPDFPageLabelDocumentHelper.cc index 56d36991..d626be1a 100644 --- a/libqpdf/QPDFPageLabelDocumentHelper.cc +++ b/libqpdf/QPDFPageLabelDocumentHelper.cc @@ -15,8 +15,7 @@ QPDFPageLabelDocumentHelper::QPDFPageLabelDocumentHelper(QPDF& qpdf) : m(new Members()) { QPDFObjectHandle root = qpdf.getRoot(); - if (root.hasKey("/PageLabels")) - { + if (root.hasKey("/PageLabels")) { this->m->labels = make_pointer_holder( root.getKey("/PageLabels"), this->qpdf); } @@ -32,26 +31,22 @@ QPDFObjectHandle QPDFPageLabelDocumentHelper::getLabelForPage(long long page_idx) { QPDFObjectHandle result(QPDFObjectHandle::newNull()); - if (! hasPageLabels()) - { + if (!hasPageLabels()) { return result; } QPDFNumberTreeObjectHelper::numtree_number offset = 0; QPDFObjectHandle label; - if (! this->m->labels->findObjectAtOrBelow(page_idx, label, offset)) - { + if (!this->m->labels->findObjectAtOrBelow(page_idx, label, offset)) { return result; } - if (! label.isDictionary()) - { + if (!label.isDictionary()) { return result; } QPDFObjectHandle S = label.getKey("/S"); // type (D, R, r, A, a) QPDFObjectHandle P = label.getKey("/P"); // prefix QPDFObjectHandle St = label.getKey("/St"); // starting number long long start = 1; - if (St.isInteger()) - { + if (St.isInteger()) { start = St.getIntValue(); } QIntC::range_check(start, offset); @@ -65,7 +60,9 @@ QPDFPageLabelDocumentHelper::getLabelForPage(long long page_idx) void QPDFPageLabelDocumentHelper::getLabelsForPageRange( - long long start_idx, long long end_idx, long long new_start_idx, + long long start_idx, + long long end_idx, + long long new_start_idx, std::vector& new_labels) { // Start off with a suitable label for the first page. For every @@ -75,8 +72,7 @@ QPDFPageLabelDocumentHelper::getLabelsForPageRange( // that would match how the page would look in a new file in which // it also didn't have an explicit label. QPDFObjectHandle label = getLabelForPage(start_idx); - if (label.isNull()) - { + if (label.isNull()) { label = QPDFObjectHandle::newDictionary(); label.replaceKey( "/St", QPDFObjectHandle::newInteger(1 + new_start_idx)); @@ -85,43 +81,33 @@ QPDFPageLabelDocumentHelper::getLabelsForPageRange( // in the vector. If so, don't add it. size_t size = new_labels.size(); bool skip_first = false; - if (size >= 2) - { + if (size >= 2) { QPDFObjectHandle last = new_labels.at(size - 1); QPDFObjectHandle last_idx = new_labels.at(size - 2); if (last_idx.isInteger() && last.isDictionary() && (label.getKey("/S").unparse() == last.getKey("/S").unparse()) && (label.getKey("/P").unparse() == last.getKey("/P").unparse()) && - label.getKey("/St").isInteger() && - last.getKey("/St").isInteger()) - { - long long int st_delta = - label.getKey("/St").getIntValue() - + label.getKey("/St").isInteger() && last.getKey("/St").isInteger()) { + long long int st_delta = label.getKey("/St").getIntValue() - last.getKey("/St").getIntValue(); - long long int idx_delta = - new_start_idx - last_idx.getIntValue(); - if (st_delta == idx_delta) - { + long long int idx_delta = new_start_idx - last_idx.getIntValue(); + if (st_delta == idx_delta) { QTC::TC("qpdf", "QPDFPageLabelDocumentHelper skip first"); skip_first = true; } } } - if (! skip_first) - { + if (!skip_first) { new_labels.push_back(QPDFObjectHandle::newInteger(new_start_idx)); new_labels.push_back(label); } long long int idx_offset = new_start_idx - start_idx; - for (long long i = start_idx + 1; i <= end_idx; ++i) - { + for (long long i = start_idx + 1; i <= end_idx; ++i) { if (this->m->labels->hasIndex(i) && - (label = getLabelForPage(i)).isDictionary()) - { + (label = getLabelForPage(i)).isDictionary()) { new_labels.push_back(QPDFObjectHandle::newInteger(i + idx_offset)); new_labels.push_back(label); } } } - diff --git a/libqpdf/QPDFPageObjectHelper.cc b/libqpdf/QPDFPageObjectHelper.cc index 6d06364a..988068f3 100644 --- a/libqpdf/QPDFPageObjectHelper.cc +++ b/libqpdf/QPDFPageObjectHelper.cc @@ -1,14 +1,14 @@ #include -#include -#include -#include #include -#include +#include +#include +#include +#include #include #include -#include -#include +#include +#include #include class ContentProvider: public QPDFObjectHandle::StreamDataProvider @@ -21,8 +21,8 @@ class ContentProvider: public QPDFObjectHandle::StreamDataProvider virtual ~ContentProvider() { } - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); private: QPDFObjectHandle from_page; @@ -36,8 +36,8 @@ ContentProvider::provideStreamData(int, int, Pipeline* p) QUtil::int_to_string(from_page.getObjectID()) + " " + QUtil::int_to_string(from_page.getGeneration()); std::string all_description; - from_page.getKey("/Contents").pipeContentStreams( - &concat, description, all_description); + from_page.getKey("/Contents") + .pipeContentStreams(&concat, description, all_description); concat.manualFinish(); } @@ -61,8 +61,8 @@ class InlineImageTracker: public QPDFObjectHandle::TokenFilter enum { st_top, st_bi } state; }; -InlineImageTracker::InlineImageTracker(QPDF* qpdf, size_t min_size, - QPDFObjectHandle resources) : +InlineImageTracker::InlineImageTracker( + QPDF* qpdf, size_t min_size, QPDFObjectHandle resources) : qpdf(qpdf), min_size(min_size), resources(resources), @@ -79,154 +79,96 @@ InlineImageTracker::convertIIDict(QPDFObjectHandle odict) dict.replaceKey("/Type", QPDFObjectHandle::newName("/XObject")); dict.replaceKey("/Subtype", QPDFObjectHandle::newName("/Image")); std::set keys = odict.getKeys(); - for (auto key: keys) - { + for (auto key : keys) { QPDFObjectHandle value = odict.getKey(key); - if (key == "/BPC") - { + if (key == "/BPC") { key = "/BitsPerComponent"; - } - else if (key == "/CS") - { + } else if (key == "/CS") { key = "/ColorSpace"; - } - else if (key == "/D") - { + } else if (key == "/D") { key = "/Decode"; - } - else if (key == "/DP") - { + } else if (key == "/DP") { key = "/DecodeParms"; - } - else if (key == "/F") - { + } else if (key == "/F") { key = "/Filter"; - } - else if (key == "/H") - { + } else if (key == "/H") { key = "/Height"; - } - else if (key == "/IM") - { + } else if (key == "/IM") { key = "/ImageMask"; - } - else if (key == "/I") - { + } else if (key == "/I") { key = "/Interpolate"; - } - else if (key == "/W") - { + } else if (key == "/W") { key = "/Width"; } - if (key == "/ColorSpace") - { - if (value.isName()) - { + if (key == "/ColorSpace") { + if (value.isName()) { std::string name = value.getName(); - if (name == "/G") - { + if (name == "/G") { name = "/DeviceGray"; - } - else if (name == "/RGB") - { + } else if (name == "/RGB") { name = "/DeviceRGB"; - } - else if (name == "/CMYK") - { + } else if (name == "/CMYK") { name = "/DeviceCMYK"; - } - else if (name == "/I") - { + } else if (name == "/I") { name = "/Indexed"; - } - else - { + } else { // This is a key in the page's /Resources -> // /ColorSpace dictionary. We need to look it up // and use its value as the color space for the // image. QPDFObjectHandle colorspace = resources.getKey("/ColorSpace"); - if (colorspace.isDictionary() && colorspace.hasKey(name)) - { - QTC::TC("qpdf", "QPDFPageObjectHelper colorspace lookup"); + if (colorspace.isDictionary() && colorspace.hasKey(name)) { + QTC::TC( + "qpdf", "QPDFPageObjectHelper colorspace lookup"); value = colorspace.getKey(name); - } - else - { + } else { resources.warnIfPossible( "unable to resolve colorspace " + name); } name.clear(); } - if (! name.empty()) - { + if (!name.empty()) { value = QPDFObjectHandle::newName(name); } } - } - else if (key == "/Filter") - { + } else if (key == "/Filter") { std::vector filters; - if (value.isName()) - { + if (value.isName()) { filters.push_back(value); - } - else if (value.isArray()) - { + } else if (value.isArray()) { filters = value.getArrayAsVector(); } - for (auto& iter: filters) - { + for (auto& iter : filters) { std::string name; - if (iter.isName()) - { + if (iter.isName()) { name = iter.getName(); } - if (name == "/AHx") - { + if (name == "/AHx") { name = "/ASCIIHexDecode"; - } - else if (name == "/A85") - { + } else if (name == "/A85") { name = "/ASCII85Decode"; - } - else if (name == "/LZW") - { + } else if (name == "/LZW") { name = "/LZWDecode"; - } - else if (name == "/Fl") - { + } else if (name == "/Fl") { name = "/FlateDecode"; - } - else if (name == "/RL") - { + } else if (name == "/RL") { name = "/RunLengthDecode"; - } - else if (name == "/CCF") - { + } else if (name == "/CCF") { name = "/CCITTFaxDecode"; - } - else if (name == "/DCT") - { + } else if (name == "/DCT") { name = "/DCTDecode"; - } - else - { + } else { name.clear(); } - if (! name.empty()) - { + if (!name.empty()) { iter = QPDFObjectHandle::newName(name); } } - if (value.isName() && (filters.size() == 1)) - { + if (value.isName() && (filters.size() == 1)) { value = filters.at(0); - } - else if (value.isArray()) - { + } else if (value.isArray()) { value = QPDFObjectHandle::newArray(filters); } } @@ -238,15 +180,13 @@ InlineImageTracker::convertIIDict(QPDFObjectHandle odict) void InlineImageTracker::handleToken(QPDFTokenizer::Token const& token) { - if (state == st_bi) - { - if (token.getType() == QPDFTokenizer::tt_inline_image) - { + if (state == st_bi) { + if (token.getType() == QPDFTokenizer::tt_inline_image) { std::string image_data(token.getValue()); size_t len = image_data.length(); - if (len >= this->min_size) - { - QTC::TC("qpdf", "QPDFPageObjectHelper externalize inline image"); + if (len >= this->min_size) { + QTC::TC( + "qpdf", "QPDFPageObjectHelper externalize inline image"); Pl_Buffer b("image_data"); b.write(QUtil::unsigned_char_pointer(image_data), len); b.finish(); @@ -255,8 +195,8 @@ InlineImageTracker::handleToken(QPDFTokenizer::Token const& token) dict.replaceKey( "/Length", QPDFObjectHandle::newInteger(QIntC::to_longlong(len))); - std::string name = resources.getUniqueResourceName( - "/IIm", this->min_suffix); + std::string name = + resources.getUniqueResourceName("/IIm", this->min_suffix); QPDFObjectHandle image = QPDFObjectHandle::newStream( this->qpdf, b.getBufferSharedPointer()); image.replaceDict(dict); @@ -264,38 +204,28 @@ InlineImageTracker::handleToken(QPDFTokenizer::Token const& token) write(name); write(" Do\n"); any_images = true; - } - else - { + } else { QTC::TC("qpdf", "QPDFPageObjectHelper keep inline image"); write(bi_str); writeToken(token); state = st_top; } - } - else if (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "ID")) - { + } else if ( + token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "ID")) { bi_str += token.getValue(); dict_str += " >>"; - } - else if (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "EI")) - { + } else if ( + token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "EI")) { state = st_top; - } - else - { + } else { bi_str += token.getRawValue(); dict_str += token.getRawValue(); } - } - else if (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "BI")) - { + } else if (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "BI")) { bi_str = token.getValue(); dict_str = "<< "; state = st_bi; - } - else - { + } else { writeToken(token); } } @@ -314,47 +244,42 @@ QPDFPageObjectHelper::QPDFPageObjectHelper(QPDFObjectHandle oh) : } QPDFObjectHandle -QPDFPageObjectHelper::getAttribute(std::string const& name, - bool copy_if_shared) +QPDFPageObjectHelper::getAttribute(std::string const& name, bool copy_if_shared) { QPDFObjectHandle result; QPDFObjectHandle dict; bool is_form_xobject = this->oh.isFormXObject(); bool inherited = false; - if (is_form_xobject) - { + if (is_form_xobject) { dict = this->oh.getDict(); result = dict.getKey(name); - } - else - { + } else { dict = this->oh; - bool inheritable = ((name == "/MediaBox") || (name == "/CropBox") || - (name == "/Resources") || (name == "/Rotate")); + bool inheritable = + ((name == "/MediaBox") || (name == "/CropBox") || + (name == "/Resources") || (name == "/Rotate")); QPDFObjectHandle node = dict; result = node.getKey(name); std::set seen; - while (inheritable && result.isNull() && node.hasKey("/Parent")) - { + while (inheritable && result.isNull() && node.hasKey("/Parent")) { seen.insert(node.getObjGen()); node = node.getKey("/Parent"); - if (seen.count(node.getObjGen())) - { + if (seen.count(node.getObjGen())) { break; } result = node.getKey(name); - if (! result.isNull()) - { + if (!result.isNull()) { QTC::TC("qpdf", "QPDFPageObjectHelper non-trivial inheritance"); inherited = true; } } } - if (copy_if_shared && (inherited || result.isIndirect())) - { - QTC::TC("qpdf", "QPDFPageObjectHelper copy shared attribute", - is_form_xobject ? 0 : 1); + if (copy_if_shared && (inherited || result.isIndirect())) { + QTC::TC( + "qpdf", + "QPDFPageObjectHelper copy shared attribute", + is_form_xobject ? 0 : 1); result = result.shallowCopy(); dict.replaceKey(name, result); } @@ -365,8 +290,7 @@ QPDFObjectHandle QPDFPageObjectHelper::getTrimBox(bool copy_if_shared) { QPDFObjectHandle result = getAttribute("/TrimBox", copy_if_shared); - if (result.isNull()) - { + if (result.isNull()) { result = getCropBox(copy_if_shared); } return result; @@ -376,8 +300,7 @@ QPDFObjectHandle QPDFPageObjectHelper::getCropBox(bool copy_if_shared) { QPDFObjectHandle result = getAttribute("/CropBox", copy_if_shared); - if (result.isNull()) - { + if (result.isNull()) { result = getMediaBox(); } return result; @@ -392,41 +315,37 @@ QPDFPageObjectHelper::getMediaBox(bool copy_if_shared) void QPDFPageObjectHelper::forEachXObject( bool recursive, - std::function action, + std::function action, std::function selector) { - QTC::TC("qpdf", "QPDFPageObjectHelper::forEachXObject", - recursive - ? (this->oh.isFormXObject() ? 0 : 1) - : (this->oh.isFormXObject() ? 2 : 3)); + QTC::TC( + "qpdf", + "QPDFPageObjectHelper::forEachXObject", + recursive ? (this->oh.isFormXObject() ? 0 : 1) + : (this->oh.isFormXObject() ? 2 : 3)); std::set seen; std::list queue; queue.push_back(*this); - while (! queue.empty()) - { + while (!queue.empty()) { QPDFPageObjectHelper ph = queue.front(); queue.pop_front(); QPDFObjGen og = ph.oh.getObjGen(); - if (seen.count(og)) - { + if (seen.count(og)) { continue; } seen.insert(og); QPDFObjectHandle resources = ph.getAttribute("/Resources", false); - if (resources.isDictionary() && resources.hasKey("/XObject")) - { + if (resources.isDictionary() && resources.hasKey("/XObject")) { QPDFObjectHandle xobj_dict = resources.getKey("/XObject"); - for (auto const& key: xobj_dict.getKeys()) - { + for (auto const& key : xobj_dict.getKeys()) { QPDFObjectHandle obj = xobj_dict.getKey(key); - if ((! selector) || selector(obj)) - { + if ((!selector) || selector(obj)) { action(obj, xobj_dict, key); } - if (recursive && obj.isFormXObject()) - { + if (recursive && obj.isFormXObject()) { queue.push_back(QPDFPageObjectHelper(obj)); } } @@ -437,23 +356,26 @@ QPDFPageObjectHelper::forEachXObject( void QPDFPageObjectHelper::forEachImage( bool recursive, - std::function action) + std::function action) { - forEachXObject(recursive, action, - [](QPDFObjectHandle obj) { return obj.isImage(); }); + forEachXObject( + recursive, action, [](QPDFObjectHandle obj) { return obj.isImage(); }); } void QPDFPageObjectHelper::forEachFormXObject( bool recursive, - std::function action) + std::function action) { - forEachXObject(recursive, action, - [](QPDFObjectHandle obj) { return obj.isFormXObject(); }); + forEachXObject(recursive, action, [](QPDFObjectHandle obj) { + return obj.isFormXObject(); + }); } std::map @@ -466,11 +388,12 @@ std::map QPDFPageObjectHelper::getImages() { std::map result; - forEachImage(false, [&result](QPDFObjectHandle& obj, - QPDFObjectHandle&, - std::string const& key) { - result[key] = obj; - }); + forEachImage( + false, + [&result]( + QPDFObjectHandle& obj, QPDFObjectHandle&, std::string const& key) { + result[key] = obj; + }); return result; } @@ -478,11 +401,12 @@ std::map QPDFPageObjectHelper::getFormXObjects() { std::map result; - forEachFormXObject(false, [&result](QPDFObjectHandle& obj, - QPDFObjectHandle&, - std::string const& key) { - result[key] = obj; - }); + forEachFormXObject( + false, + [&result]( + QPDFObjectHandle& obj, QPDFObjectHandle&, std::string const& key) { + result[key] = obj; + }); return result; } @@ -495,8 +419,7 @@ QPDFPageObjectHelper::externalizeInlineImages(size_t min_size) void QPDFPageObjectHelper::externalizeInlineImages(size_t min_size, bool shallow) { - if (shallow) - { + if (shallow) { QPDFObjectHandle resources = getAttribute("/Resources", true); // Calling mergeResources also ensures that /XObject becomes // direct and is not shared with other pages. @@ -504,44 +427,34 @@ QPDFPageObjectHelper::externalizeInlineImages(size_t min_size, bool shallow) InlineImageTracker iit(this->oh.getOwningQPDF(), min_size, resources); Pl_Buffer b("new page content"); bool filtered = false; - try - { + try { filterContents(&iit, &b); filtered = true; - } - catch (std::exception& e) - { + } catch (std::exception& e) { this->oh.warnIfPossible( std::string("Unable to filter content stream: ") + e.what() + "; not attempting to externalize inline images" " from this stream"); } - if (filtered && iit.any_images) - { - if (this->oh.isFormXObject()) - { + if (filtered && iit.any_images) { + if (this->oh.isFormXObject()) { this->oh.replaceStreamData( b.getBufferSharedPointer(), QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); - } - else - { + } else { this->oh.replaceKey( "/Contents", QPDFObjectHandle::newStream( - this->oh.getOwningQPDF(), - b.getBufferSharedPointer())); + this->oh.getOwningQPDF(), b.getBufferSharedPointer())); } } - } - else - { + } else { externalizeInlineImages(min_size, true); forEachFormXObject( true, - [min_size](QPDFObjectHandle& obj, - QPDFObjectHandle&, std::string const&) { + [min_size]( + QPDFObjectHandle& obj, QPDFObjectHandle&, std::string const&) { QPDFPageObjectHelper(obj).externalizeInlineImages( min_size, true); }); @@ -553,14 +466,11 @@ QPDFPageObjectHelper::getAnnotations(std::string const& only_subtype) { std::vector result; QPDFObjectHandle annots = this->oh.getKey("/Annots"); - if (annots.isArray()) - { + if (annots.isArray()) { int nannots = annots.getArrayNItems(); - for (int i = 0; i < nannots; ++i) - { + for (int i = 0; i < nannots; ++i) { QPDFObjectHandle annot = annots.getArrayItem(i); - if (annot.isDictionaryOfType("", only_subtype)) - { + if (annot.isDictionaryOfType("", only_subtype)) { result.push_back(QPDFAnnotationObjectHelper(annot)); } } @@ -603,35 +513,27 @@ void QPDFPageObjectHelper::parseContents( QPDFObjectHandle::ParserCallbacks* callbacks) { - if (this->oh.isFormXObject()) - { + if (this->oh.isFormXObject()) { this->oh.parseAsContents(callbacks); - } - else - { + } else { this->oh.parsePageContents(callbacks); } } void QPDFPageObjectHelper::filterPageContents( - QPDFObjectHandle::TokenFilter* filter, - Pipeline* next) + QPDFObjectHandle::TokenFilter* filter, Pipeline* next) { return filterContents(filter, next); } void QPDFPageObjectHelper::filterContents( - QPDFObjectHandle::TokenFilter* filter, - Pipeline* next) + QPDFObjectHandle::TokenFilter* filter, Pipeline* next) { - if (this->oh.isFormXObject()) - { + if (this->oh.isFormXObject()) { this->oh.filterAsContents(filter, next); - } - else - { + } else { this->oh.filterPageContents(filter, next); } } @@ -645,12 +547,9 @@ QPDFPageObjectHelper::pipePageContents(Pipeline* p) void QPDFPageObjectHelper::pipeContents(Pipeline* p) { - if (this->oh.isFormXObject()) - { + if (this->oh.isFormXObject()) { this->oh.pipeStreamData(p, 0, qpdf_dl_specialized); - } - else - { + } else { this->oh.pipePageContents(p); } } @@ -659,12 +558,9 @@ void QPDFPageObjectHelper::addContentTokenFilter( PointerHolder token_filter) { - if (this->oh.isFormXObject()) - { + if (this->oh.isFormXObject()) { this->oh.addTokenFilter(token_filter); - } - else - { + } else { this->oh.addContentTokenFilter(token_filter); } } @@ -673,30 +569,25 @@ bool QPDFPageObjectHelper::removeUnreferencedResourcesHelper( QPDFPageObjectHelper ph, std::set& unresolved) { - bool is_page = (! ph.oh.isFormXObject()); - if (! is_page) - { + bool is_page = (!ph.oh.isFormXObject()); + if (!is_page) { QTC::TC("qpdf", "QPDFPageObjectHelper filter form xobject"); } ResourceFinder rf; - try - { + try { auto q = ph.oh.getOwningQPDF(); size_t before_nw = (q ? q->numWarnings() : 0); ph.parseContents(&rf); size_t after_nw = (q ? q->numWarnings() : 0); - if (after_nw > before_nw) - { + if (after_nw > before_nw) { ph.oh.warnIfPossible( "Bad token found while scanning content stream; " "not attempting to remove unreferenced objects from" " this object"); return false; } - } - catch (std::exception& e) - { + } catch (std::exception& e) { QTC::TC("qpdf", "QPDFPageObjectHelper bad token finding names"); ph.oh.warnIfPossible( std::string("Unable to parse content stream: ") + e.what() + @@ -714,13 +605,10 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( std::vector rdicts; std::set known_names; std::vector to_filter = {"/Font", "/XObject"}; - if (resources.isDictionary()) - { - for (auto const& iter: to_filter) - { + if (resources.isDictionary()) { + for (auto const& iter : to_filter) { QPDFObjectHandle dict = resources.getKey(iter); - if (dict.isDictionary()) - { + if (dict.isDictionary()) { dict = dict.shallowCopy(); resources.replaceKey(iter, dict); rdicts.push_back(dict); @@ -732,13 +620,10 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( std::set local_unresolved; auto names_by_rtype = rf.getNamesByResourceType(); - for (auto const& i1: to_filter) - { - for (auto const& n_iter: names_by_rtype[i1]) - { + for (auto const& i1 : to_filter) { + for (auto const& n_iter : names_by_rtype[i1]) { std::string const& name = n_iter.first; - if (! known_names.count(name)) - { + if (!known_names.count(name)) { unresolved.insert(name); local_unresolved.insert(name); } @@ -759,8 +644,7 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( // unresolved names, and for page objects, we avoid removing any // such names found in nested form XObjects. - if ((! local_unresolved.empty()) && resources.isDictionary()) - { + if ((!local_unresolved.empty()) && resources.isDictionary()) { // It's not worth issuing a warning for this case. From qpdf // 10.3, we are hopefully only looking at names that are // referencing fonts and XObjects, but until we're certain @@ -776,18 +660,13 @@ QPDFPageObjectHelper::removeUnreferencedResourcesHelper( return false; } - for (auto& dict: rdicts) - { - for (auto const& key: dict.getKeys()) - { - if (is_page && unresolved.count(key)) - { + for (auto& dict : rdicts) { + for (auto const& key : dict.getKeys()) { + if (is_page && unresolved.count(key)) { // This name is referenced by some nested form // xobject, so don't remove it. QTC::TC("qpdf", "QPDFPageObjectHelper resolving unresolved"); - } - else if (! rf.getNames().count(key)) - { + } else if (!rf.getNames().count(key)) { dict.removeKey(key); } } @@ -805,16 +684,13 @@ QPDFPageObjectHelper::removeUnreferencedResources() forEachFormXObject( true, [&any_failures, &unresolved]( - QPDFObjectHandle& obj, QPDFObjectHandle&, std::string const&) - { - if (! removeUnreferencedResourcesHelper( - QPDFPageObjectHelper(obj), unresolved)) - { + QPDFObjectHandle& obj, QPDFObjectHandle&, std::string const&) { + if (!removeUnreferencedResourcesHelper( + QPDFPageObjectHelper(obj), unresolved)) { any_failures = true; } }); - if (this->oh.isFormXObject() || (! any_failures)) - { + if (this->oh.isFormXObject() || (!any_failures)) { removeUnreferencedResourcesHelper(*this, unresolved); } } @@ -823,11 +699,9 @@ QPDFPageObjectHelper QPDFPageObjectHelper::shallowCopyPage() { QPDF* qpdf = this->oh.getOwningQPDF(); - if (! qpdf) - { - throw std::runtime_error( - "QPDFPageObjectHelper::shallowCopyPage" - " called with a direct object"); + if (!qpdf) { + throw std::runtime_error("QPDFPageObjectHelper::shallowCopyPage" + " called with a direct object"); } QPDFObjectHandle new_page = this->oh.shallowCopy(); return QPDFPageObjectHelper(qpdf->makeIndirectObject(new_page)); @@ -838,27 +712,21 @@ QPDFPageObjectHelper::getMatrixForTransformations(bool invert) { QPDFObjectHandle::Matrix matrix(1, 0, 0, 1, 0, 0); QPDFObjectHandle bbox = getTrimBox(false); - if (! bbox.isRectangle()) - { + if (!bbox.isRectangle()) { return matrix; } QPDFObjectHandle rotate_obj = getAttribute("/Rotate", false); QPDFObjectHandle scale_obj = getAttribute("/UserUnit", false); - if (! (rotate_obj.isNull() && scale_obj.isNull())) - { + if (!(rotate_obj.isNull() && scale_obj.isNull())) { QPDFObjectHandle::Rectangle rect = bbox.getArrayAsRectangle(); double width = rect.urx - rect.llx; double height = rect.ury - rect.lly; - double scale = (scale_obj.isNumber() - ? scale_obj.getNumericValue() - : 1.0); - int rotate = (rotate_obj.isInteger() - ? rotate_obj.getIntValueAsInt() - : 0); - if (invert) - { - if (scale == 0.0) - { + double scale = + (scale_obj.isNumber() ? scale_obj.getNumericValue() : 1.0); + int rotate = + (rotate_obj.isInteger() ? rotate_obj.getIntValueAsInt() : 0); + if (invert) { + if (scale == 0.0) { return matrix; } scale = 1.0 / scale; @@ -866,23 +734,21 @@ QPDFPageObjectHelper::getMatrixForTransformations(bool invert) } // Ignore invalid rotation angle - switch (rotate) - { - case 90: - matrix = QPDFObjectHandle::Matrix( - 0, -scale, scale, 0, 0, width * scale); + switch (rotate) { + case 90: + matrix = + QPDFObjectHandle::Matrix(0, -scale, scale, 0, 0, width * scale); break; - case 180: + case 180: matrix = QPDFObjectHandle::Matrix( -scale, 0, 0, -scale, width * scale, height * scale); break; - case 270: + case 270: matrix = QPDFObjectHandle::Matrix( 0, scale, -scale, 0, height * scale, 0); break; - default: - matrix = QPDFObjectHandle::Matrix( - scale, 0, 0, scale, 0, 0); + default: + matrix = QPDFObjectHandle::Matrix(scale, 0, 0, scale, 0, 0); break; } } @@ -893,26 +759,21 @@ QPDFObjectHandle QPDFPageObjectHelper::getFormXObjectForPage(bool handle_transformations) { QPDF* qpdf = this->oh.getOwningQPDF(); - if (! qpdf) - { - throw std::runtime_error( - "QPDFPageObjectHelper::getFormXObjectForPage" - " called with a direct object"); + if (!qpdf) { + throw std::runtime_error("QPDFPageObjectHelper::getFormXObjectForPage" + " called with a direct object"); } QPDFObjectHandle result = QPDFObjectHandle::newStream(qpdf); QPDFObjectHandle newdict = result.getDict(); newdict.replaceKey("/Type", QPDFObjectHandle::newName("/XObject")); newdict.replaceKey("/Subtype", QPDFObjectHandle::newName("/Form")); - newdict.replaceKey("/Resources", - getAttribute("/Resources", false).shallowCopy()); - newdict.replaceKey("/Group", - getAttribute("/Group", false).shallowCopy()); + newdict.replaceKey( + "/Resources", getAttribute("/Resources", false).shallowCopy()); + newdict.replaceKey("/Group", getAttribute("/Group", false).shallowCopy()); QPDFObjectHandle bbox = getTrimBox(false).shallowCopy(); - if (! bbox.isRectangle()) - { - this->oh.warnIfPossible( - "bounding box is invalid; form" - " XObject created from page will not work"); + if (!bbox.isRectangle()) { + this->oh.warnIfPossible("bounding box is invalid; form" + " XObject created from page will not work"); } newdict.replaceKey("/BBox", bbox); auto provider = PointerHolder( @@ -922,11 +783,10 @@ QPDFPageObjectHelper::getFormXObjectForPage(bool handle_transformations) QPDFObjectHandle rotate_obj = getAttribute("/Rotate", false); QPDFObjectHandle scale_obj = getAttribute("/UserUnit", false); if (handle_transformations && - (! (rotate_obj.isNull() && scale_obj.isNull()))) - { - newdict.replaceKey("/Matrix", - QPDFObjectHandle::newArray( - getMatrixForTransformations())); + (!(rotate_obj.isNull() && scale_obj.isNull()))) { + newdict.replaceKey( + "/Matrix", + QPDFObjectHandle::newArray(getMatrixForTransformations())); } return result; @@ -934,9 +794,11 @@ QPDFPageObjectHelper::getFormXObjectForPage(bool handle_transformations) QPDFMatrix QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( - QPDFObjectHandle fo, QPDFObjectHandle::Rectangle rect, + QPDFObjectHandle fo, + QPDFObjectHandle::Rectangle rect, bool invert_transformations, - bool allow_shrink, bool allow_expand) + bool allow_shrink, + bool allow_expand) { // Calculate the transformation matrix that will place the given // form XObject fully inside the given rectangle, center and @@ -953,16 +815,14 @@ QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( QPDFObjectHandle fdict = fo.getDict(); QPDFObjectHandle bbox_obj = fdict.getKey("/BBox"); - if (! bbox_obj.isRectangle()) - { + if (!bbox_obj.isRectangle()) { return QPDFMatrix(); } - QPDFMatrix wmatrix; // work matrix - QPDFMatrix tmatrix; // "to" matrix - QPDFMatrix fmatrix; // "from" matrix - if (invert_transformations) - { + QPDFMatrix wmatrix; // work matrix + QPDFMatrix tmatrix; // "to" matrix + QPDFMatrix fmatrix; // "from" matrix + if (invert_transformations) { // tmatrix inverts scaling and rotation of the destination // page. Applying this matrix allows the overlaid form // XObject's to be absolute rather than relative to properties @@ -971,8 +831,7 @@ QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( tmatrix = QPDFMatrix(getMatrixForTransformations(true)); wmatrix.concat(tmatrix); } - if (fdict.getKey("/Matrix").isMatrix()) - { + if (fdict.getKey("/Matrix").isMatrix()) { // fmatrix is the transformation matrix that is applied to the // form XObject itself. We need this for calculations, but we // don't explicitly use it in the final result because the PDF @@ -995,8 +854,7 @@ QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( // Calculate a scale factor, if needed. Shrink or expand if needed // and allowed. - if ((T.urx == T.llx) || (T.ury == T.lly)) - { + if ((T.urx == T.llx) || (T.ury == T.lly)) { // avoid division by zero return QPDFMatrix(); } @@ -1007,17 +865,12 @@ QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( double xscale = rect_w / t_w; double yscale = rect_h / t_h; double scale = (xscale < yscale ? xscale : yscale); - if (scale > 1.0) - { - if (! allow_expand) - { + if (scale > 1.0) { + if (!allow_expand) { scale = 1.0; } - } - else if (scale < 1.0) - { - if (! allow_shrink) - { + } else if (scale < 1.0) { + if (!allow_shrink) { scale = 1.0; } } @@ -1049,20 +902,22 @@ QPDFPageObjectHelper::getMatrixForFormXObjectPlacement( std::string QPDFPageObjectHelper::placeFormXObject( - QPDFObjectHandle fo, std::string const& name, + QPDFObjectHandle fo, + std::string const& name, QPDFObjectHandle::Rectangle rect, bool invert_transformations, - bool allow_shrink, bool allow_expand) + bool allow_shrink, + bool allow_expand) { QPDFMatrix cm; return placeFormXObject( - fo, name, rect, cm, invert_transformations, - allow_shrink, allow_expand); + fo, name, rect, cm, invert_transformations, allow_shrink, allow_expand); } std::string QPDFPageObjectHelper::placeFormXObject( - QPDFObjectHandle fo, std::string const& name, + QPDFObjectHandle fo, + std::string const& name, QPDFObjectHandle::Rectangle rect, QPDFMatrix& cm, bool invert_transformations, @@ -1071,11 +926,7 @@ QPDFPageObjectHelper::placeFormXObject( { cm = getMatrixForFormXObjectPlacement( fo, rect, invert_transformations, allow_shrink, allow_expand); - return ( - "q\n" + - cm.unparse() + " cm\n" + - name + " Do\n" + - "Q\n"); + return ("q\n" + cm.unparse() + " cm\n" + name + " Do\n" + "Q\n"); } void @@ -1088,38 +939,35 @@ void QPDFPageObjectHelper::flattenRotation(QPDFAcroFormDocumentHelper* afdh) { QPDF* qpdf = this->oh.getOwningQPDF(); - if (! qpdf) - { - throw std::runtime_error( - "QPDFPageObjectHelper::flattenRotation" - " called with a direct object"); + if (!qpdf) { + throw std::runtime_error("QPDFPageObjectHelper::flattenRotation" + " called with a direct object"); } auto rotate_oh = this->oh.getKey("/Rotate"); int rotate = 0; - if (rotate_oh.isInteger()) - { + if (rotate_oh.isInteger()) { rotate = rotate_oh.getIntValueAsInt(); } - if (! ((rotate == 90) || (rotate == 180) || (rotate == 270))) - { + if (!((rotate == 90) || (rotate == 180) || (rotate == 270))) { return; } auto mediabox = this->oh.getKey("/MediaBox"); - if (! mediabox.isRectangle()) - { + if (!mediabox.isRectangle()) { return; } auto media_rect = mediabox.getArrayAsRectangle(); std::vector boxes = { - "/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox", + "/MediaBox", + "/CropBox", + "/BleedBox", + "/TrimBox", + "/ArtBox", }; - for (auto const& boxkey: boxes) - { + for (auto const& boxkey : boxes) { auto box = this->oh.getKey(boxkey); - if (! box.isRectangle()) - { + if (!box.isRectangle()) { continue; } auto rect = box.getArrayAsRectangle(); @@ -1127,40 +975,39 @@ QPDFPageObjectHelper::flattenRotation(QPDFAcroFormDocumentHelper* afdh) // How far are the edges of our rectangle from the edges // of the media box? - auto left_x = rect.llx - media_rect.llx; - auto right_x = media_rect.urx - rect.urx; + auto left_x = rect.llx - media_rect.llx; + auto right_x = media_rect.urx - rect.urx; auto bottom_y = rect.lly - media_rect.lly; - auto top_y = media_rect.ury - rect.ury; + auto top_y = media_rect.ury - rect.ury; // Rotating the page 180 degrees does not change // /MediaBox. Rotating 90 or 270 degrees reverses llx and // lly and also reverse urx and ury. For all the other // boxes, we want the corners to be the correct distance // away from the corners of the mediabox. - switch (rotate) - { - case 90: + switch (rotate) { + case 90: new_rect.llx = media_rect.lly + bottom_y; new_rect.urx = media_rect.ury - top_y; new_rect.lly = media_rect.llx + right_x; new_rect.ury = media_rect.urx - left_x; break; - case 180: + case 180: new_rect.llx = media_rect.llx + right_x; new_rect.urx = media_rect.urx - left_x; new_rect.lly = media_rect.lly + top_y; new_rect.ury = media_rect.ury - bottom_y; break; - case 270: + case 270: new_rect.llx = media_rect.lly + top_y; new_rect.urx = media_rect.ury - bottom_y; new_rect.lly = media_rect.llx + left_x; new_rect.ury = media_rect.urx - right_x; break; - default: + default: // ignore break; } @@ -1175,61 +1022,53 @@ QPDFPageObjectHelper::flattenRotation(QPDFAcroFormDocumentHelper* afdh) // These calculations have been verified empirically with various // PDF readers. QPDFMatrix cm(0, 0, 0, 0, 0, 0); - switch (rotate) - { - case 90: + switch (rotate) { + case 90: cm.b = -1; cm.c = 1; cm.f = media_rect.urx + media_rect.llx; break; - case 180: + case 180: cm.a = -1; cm.d = -1; cm.e = media_rect.urx + media_rect.llx; cm.f = media_rect.ury + media_rect.lly; break; - case 270: + case 270: cm.b = 1; cm.c = -1; cm.e = media_rect.ury + media_rect.lly; break; - default: + default: break; } - std::string cm_str = - std::string("q\n") + cm.unparse() + " cm\n"; - this->oh.addPageContents( - QPDFObjectHandle::newStream(qpdf, cm_str), true); - this->oh.addPageContents( - QPDFObjectHandle::newStream(qpdf, "\nQ\n"), false); + std::string cm_str = std::string("q\n") + cm.unparse() + " cm\n"; + this->oh.addPageContents(QPDFObjectHandle::newStream(qpdf, cm_str), true); + this->oh.addPageContents(QPDFObjectHandle::newStream(qpdf, "\nQ\n"), false); this->oh.removeKey("/Rotate"); QPDFObjectHandle rotate_obj = getAttribute("/Rotate", false); - if (! rotate_obj.isNull()) - { + if (!rotate_obj.isNull()) { QTC::TC("qpdf", "QPDFPageObjectHelper flatten inherit rotate"); this->oh.replaceKey("/Rotate", QPDFObjectHandle::newInteger(0)); } QPDFObjectHandle annots = this->oh.getKey("/Annots"); - if (annots.isArray()) - { + if (annots.isArray()) { std::vector new_annots; std::vector new_fields; std::set old_fields; PointerHolder afdhph; - if (! afdh) - { + if (!afdh) { afdhph = make_pointer_holder(*qpdf); afdh = afdhph.get(); } afdh->transformAnnotations( annots, new_annots, new_fields, old_fields, cm); afdh->removeFormFields(old_fields); - for (auto const& f: new_fields) - { + for (auto const& f : new_fields) { afdh->addFormField(QPDFFormFieldObjectHelper(f)); } this->oh.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots)); @@ -1238,29 +1077,25 @@ QPDFPageObjectHelper::flattenRotation(QPDFAcroFormDocumentHelper* afdh) void QPDFPageObjectHelper::copyAnnotations( - QPDFPageObjectHelper from_page, QPDFMatrix const& cm, + QPDFPageObjectHelper from_page, + QPDFMatrix const& cm, QPDFAcroFormDocumentHelper* afdh, QPDFAcroFormDocumentHelper* from_afdh) { auto old_annots = from_page.getObjectHandle().getKey("/Annots"); - if (! old_annots.isArray()) - { + if (!old_annots.isArray()) { return; } QPDF* from_qpdf = from_page.getObjectHandle().getOwningQPDF(); - if (! from_qpdf) - { - throw std::runtime_error( - "QPDFPageObjectHelper::copyAnnotations:" - " from page is a direct object"); + if (!from_qpdf) { + throw std::runtime_error("QPDFPageObjectHelper::copyAnnotations:" + " from page is a direct object"); } QPDF* this_qpdf = this->oh.getOwningQPDF(); - if (! this_qpdf) - { - throw std::runtime_error( - "QPDFPageObjectHelper::copyAnnotations:" - " this page is a direct object"); + if (!this_qpdf) { + throw std::runtime_error("QPDFPageObjectHelper::copyAnnotations:" + " this page is a direct object"); } std::vector new_annots; @@ -1268,43 +1103,39 @@ QPDFPageObjectHelper::copyAnnotations( std::set old_fields; PointerHolder afdhph; PointerHolder from_afdhph; - if (! afdh) - { + if (!afdh) { afdhph = make_pointer_holder(*this_qpdf); afdh = afdhph.get(); } - if (this_qpdf == from_qpdf) - { + if (this_qpdf == from_qpdf) { from_afdh = afdh; - } - else if (from_afdh) - { - if (from_afdh->getQPDF().getUniqueId() != from_qpdf->getUniqueId()) - { + } else if (from_afdh) { + if (from_afdh->getQPDF().getUniqueId() != from_qpdf->getUniqueId()) { throw std::logic_error( "QPDFAcroFormDocumentHelper::copyAnnotations: from_afdh" " is not from the same QPDF as from_page"); } - } - else - { + } else { from_afdhph = make_pointer_holder(*from_qpdf); from_afdh = from_afdhph.get(); } afdh->transformAnnotations( - old_annots, new_annots, new_fields, old_fields, cm, - from_qpdf, from_afdh); + old_annots, + new_annots, + new_fields, + old_fields, + cm, + from_qpdf, + from_afdh); afdh->addAndRenameFormFields(new_fields); auto annots = this->oh.getKey("/Annots"); - if (! annots.isArray()) - { + if (!annots.isArray()) { annots = QPDFObjectHandle::newArray(); this->oh.replaceKey("/Annots", annots); } - for (auto const& annot: new_annots) - { + for (auto const& annot : new_annots) { annots.appendItem(annot); } } diff --git a/libqpdf/QPDFSystemError.cc b/libqpdf/QPDFSystemError.cc index 775a65cf..d300a00b 100644 --- a/libqpdf/QPDFSystemError.cc +++ b/libqpdf/QPDFSystemError.cc @@ -3,8 +3,8 @@ #include #include -QPDFSystemError::QPDFSystemError(std::string const& description, - int system_errno) : +QPDFSystemError::QPDFSystemError( + std::string const& description, int system_errno) : std::runtime_error(createWhat(description, system_errno)), description(description), system_errno(system_errno) @@ -16,8 +16,7 @@ QPDFSystemError::~QPDFSystemError() noexcept } std::string -QPDFSystemError::createWhat(std::string const& description, - int system_errno) +QPDFSystemError::createWhat(std::string const& description, int system_errno) { std::string message; #ifdef _MSC_VER @@ -25,12 +24,9 @@ QPDFSystemError::createWhat(std::string const& description, // message is longer. strerror_s is a templated function that // knows the size of buf and truncates. char buf[94]; - if (strerror_s(buf, system_errno) != 0) - { + if (strerror_s(buf, system_errno) != 0) { message = description + ": failed with an unknown error"; - } - else - { + } else { message = description + ": " + buf; } #else diff --git a/libqpdf/QPDFTokenizer.cc b/libqpdf/QPDFTokenizer.cc index decbc511..ade64cb2 100644 --- a/libqpdf/QPDFTokenizer.cc +++ b/libqpdf/QPDFTokenizer.cc @@ -4,17 +4,18 @@ // it's not worth the risk of including it in case it may accidentally // be used. -#include -#include -#include -#include #include +#include +#include +#include +#include #include #include #include -static bool is_delimiter(char ch) +static bool +is_delimiter(char ch) { return (strchr(" \t\n\v\f\r()<>[]{}/%", ch) != 0); } @@ -22,8 +23,7 @@ static bool is_delimiter(char ch) class QPDFWordTokenFinder: public InputSource::Finder { public: - QPDFWordTokenFinder(PointerHolder is, - std::string const& str) : + QPDFWordTokenFinder(PointerHolder is, std::string const& str) : is(is), str(str) { @@ -46,30 +46,24 @@ QPDFWordTokenFinder::check() QPDFTokenizer tokenizer; QPDFTokenizer::Token t = tokenizer.readToken(is, "finder", true); qpdf_offset_t pos = is->tell(); - if (! (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, str))) - { + if (!(t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, str))) { QTC::TC("qpdf", "QPDFTokenizer finder found wrong word"); return false; } qpdf_offset_t token_start = is->getLastOffset(); char next; bool next_okay = false; - if (is->read(&next, 1) == 0) - { + if (is->read(&next, 1) == 0) { QTC::TC("qpdf", "QPDFTokenizer inline image at EOF"); next_okay = true; - } - else - { + } else { next_okay = is_delimiter(next); } is->seek(pos, SEEK_SET); - if (! next_okay) - { + if (!next_okay) { return false; } - if (token_start == 0) - { + if (token_start == 0) { // Can't actually happen...we never start the search at the // beginning of the input. return false; @@ -110,18 +104,13 @@ QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) : value(value), raw_value(value) { - if (type == tt_string) - { + if (type == tt_string) { raw_value = QPDFObjectHandle::newString(value).unparse(); - } - else if (type == tt_name) - { + } else if (type == tt_name) { raw_value = QPDFObjectHandle::newName(value).unparse(); } } - - QPDFTokenizer::QPDFTokenizer() : m(new Members()) { @@ -154,44 +143,35 @@ QPDFTokenizer::isDelimiter(char ch) void QPDFTokenizer::resolveLiteral() { - if ((this->m->val.length() > 0) && (this->m->val.at(0) == '/')) - { + if ((this->m->val.length() > 0) && (this->m->val.at(0) == '/')) { this->m->type = tt_name; // Deal with # in name token. Note: '/' by itself is a // valid name, so don't strip leading /. That way we // don't have to deal with the empty string as a name. std::string nval = "/"; size_t len = this->m->val.length(); - for (size_t i = 1; i < len; ++i) - { + for (size_t i = 1; i < len; ++i) { char ch = this->m->val.at(i); - if (ch == '#') - { + if (ch == '#') { if ((i + 2 < len) && - QUtil::is_hex_digit(this->m->val.at(i+1)) && - QUtil::is_hex_digit(this->m->val.at(i+2))) - { + QUtil::is_hex_digit(this->m->val.at(i + 1)) && + QUtil::is_hex_digit(this->m->val.at(i + 2))) { char num[3]; - num[0] = this->m->val.at(i+1); - num[1] = this->m->val.at(i+2); + num[0] = this->m->val.at(i + 1); + num[1] = this->m->val.at(i + 2); num[2] = '\0'; char ch2 = static_cast(strtol(num, 0, 16)); - if (ch2 == '\0') - { + if (ch2 == '\0') { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer null in name"); this->m->error_message = "null character not allowed in name token"; nval += "#00"; - } - else - { + } else { nval.append(1, ch2); } i += 2; - } - else - { + } else { QTC::TC("qpdf", "QPDFTokenizer bad name"); this->m->error_message = "name with stray # will not work with PDF >= 1.2"; @@ -199,35 +179,22 @@ QPDFTokenizer::resolveLiteral() // in QPDF_Name::normalizeName. nval += '\0'; } - } - else - { + } else { nval.append(1, ch); } } this->m->val = nval; - } - else if (QUtil::is_number(this->m->val.c_str())) - { - if (this->m->val.find('.') != std::string::npos) - { + } else if (QUtil::is_number(this->m->val.c_str())) { + if (this->m->val.find('.') != std::string::npos) { this->m->type = tt_real; - } - else - { + } else { this->m->type = tt_integer; } - } - else if ((this->m->val == "true") || (this->m->val == "false")) - { + } else if ((this->m->val == "true") || (this->m->val == "false")) { this->m->type = tt_bool; - } - else if (this->m->val == "null") - { + } else if (this->m->val == "null") { this->m->type = tt_null; - } - else - { + } else { // I don't really know what it is, so leave it as tt_word. // Lots of cases ($, #, etc.) other than actual words fall // into this category, but that's okay at least for now. @@ -238,8 +205,7 @@ QPDFTokenizer::resolveLiteral() void QPDFTokenizer::presentCharacter(char ch) { - if (this->m->state == st_token_ready) - { + if (this->m->state == st_token_ready) { throw std::logic_error( "INTERNAL ERROR: QPDF tokenizer presented character " "while token is waiting"); @@ -252,140 +218,94 @@ QPDFTokenizer::presentCharacter(char ch) // the character that caused a state change in the new state. bool handled = true; - if (this->m->state == st_top) - { + if (this->m->state == st_top) { // Note: we specifically do not use ctype here. It is // locale-dependent. - if (isSpace(ch)) - { - if (this->m->include_ignorable) - { + if (isSpace(ch)) { + if (this->m->include_ignorable) { this->m->state = st_in_space; this->m->val += ch; } - } - else if (ch == '%') - { + } else if (ch == '%') { this->m->state = st_in_comment; - if (this->m->include_ignorable) - { + if (this->m->include_ignorable) { this->m->val += ch; } - } - else if (ch == '(') - { + } else if (ch == '(') { this->m->string_depth = 1; this->m->string_ignoring_newline = false; - memset(this->m->bs_num_register, '\0', - sizeof(this->m->bs_num_register)); + memset( + this->m->bs_num_register, + '\0', + sizeof(this->m->bs_num_register)); this->m->last_char_was_bs = false; this->m->last_char_was_cr = false; this->m->state = st_in_string; - } - else if (ch == '<') - { + } else if (ch == '<') { this->m->state = st_lt; - } - else if (ch == '>') - { + } else if (ch == '>') { this->m->state = st_gt; - } - else - { + } else { this->m->val += ch; - if (ch == ')') - { + if (ch == ')') { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad )"); this->m->error_message = "unexpected )"; this->m->state = st_token_ready; - } - else if (ch == '[') - { + } else if (ch == '[') { this->m->type = tt_array_open; this->m->state = st_token_ready; - } - else if (ch == ']') - { + } else if (ch == ']') { this->m->type = tt_array_close; this->m->state = st_token_ready; - } - else if (ch == '{') - { + } else if (ch == '{') { this->m->type = tt_brace_open; this->m->state = st_token_ready; - } - else if (ch == '}') - { + } else if (ch == '}') { this->m->type = tt_brace_close; this->m->state = st_token_ready; - } - else - { + } else { this->m->state = st_literal; } } - } - else if (this->m->state == st_in_space) - { + } else if (this->m->state == st_in_space) { // We only enter this state if include_ignorable is true. - if (! isSpace(ch)) - { + if (!isSpace(ch)) { this->m->type = tt_space; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; - } - else - { + } else { this->m->val += ch; } - } - else if (this->m->state == st_in_comment) - { - if ((ch == '\r') || (ch == '\n')) - { - if (this->m->include_ignorable) - { + } else if (this->m->state == st_in_comment) { + if ((ch == '\r') || (ch == '\n')) { + if (this->m->include_ignorable) { this->m->type = tt_comment; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; - } - else - { + } else { this->m->state = st_top; } - } - else if (this->m->include_ignorable) - { + } else if (this->m->include_ignorable) { this->m->val += ch; } - } - else if (this->m->state == st_lt) - { - if (ch == '<') - { + } else if (this->m->state == st_lt) { + if (ch == '<') { this->m->val = "<<"; this->m->type = tt_dict_open; this->m->state = st_token_ready; - } - else - { + } else { handled = false; this->m->state = st_in_hexstring; } - } - else if (this->m->state == st_gt) - { - if (ch == '>') - { + } else if (this->m->state == st_gt) { + if (ch == '>') { this->m->val = ">>"; this->m->type = tt_dict_close; this->m->state = st_token_ready; - } - else - { + } else { this->m->val = ">"; this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad >"); @@ -394,121 +314,96 @@ QPDFTokenizer::presentCharacter(char ch) this->m->char_to_unread = ch; this->m->state = st_token_ready; } - } - else if (this->m->state == st_in_string) - { - if (this->m->string_ignoring_newline && (ch != '\n')) - { + } else if (this->m->state == st_in_string) { + if (this->m->string_ignoring_newline && (ch != '\n')) { this->m->string_ignoring_newline = false; } size_t bs_num_count = strlen(this->m->bs_num_register); bool ch_is_octal = ((ch >= '0') && (ch <= '7')); - if ((bs_num_count == 3) || ((bs_num_count > 0) && (! ch_is_octal))) - { + if ((bs_num_count == 3) || ((bs_num_count > 0) && (!ch_is_octal))) { // We've accumulated \ddd. PDF Spec says to ignore // high-order overflow. - this->m->val += static_cast( - strtol(this->m->bs_num_register, 0, 8)); - memset(this->m->bs_num_register, '\0', - sizeof(this->m->bs_num_register)); + this->m->val += + static_cast(strtol(this->m->bs_num_register, 0, 8)); + memset( + this->m->bs_num_register, + '\0', + sizeof(this->m->bs_num_register)); bs_num_count = 0; } - if (this->m->string_ignoring_newline && (ch == '\n')) - { + if (this->m->string_ignoring_newline && (ch == '\n')) { // ignore this->m->string_ignoring_newline = false; - } - else if (ch_is_octal && - (this->m->last_char_was_bs || (bs_num_count > 0))) - { + } else if ( + ch_is_octal && (this->m->last_char_was_bs || (bs_num_count > 0))) { this->m->bs_num_register[bs_num_count++] = ch; - } - else if (this->m->last_char_was_bs) - { - switch (ch) - { - case 'n': + } else if (this->m->last_char_was_bs) { + switch (ch) { + case 'n': this->m->val += '\n'; break; - case 'r': + case 'r': this->m->val += '\r'; break; - case 't': + case 't': this->m->val += '\t'; break; - case 'b': + case 'b': this->m->val += '\b'; break; - case 'f': + case 'f': this->m->val += '\f'; break; - case '\n': + case '\n': break; - case '\r': + case '\r': this->m->string_ignoring_newline = true; break; - default: + default: // PDF spec says backslash is ignored before anything else this->m->val += ch; break; } - } - else if (ch == '\\') - { + } else if (ch == '\\') { // last_char_was_bs is set/cleared below as appropriate - if (bs_num_count) - { + if (bs_num_count) { throw std::logic_error( "INTERNAL ERROR: QPDFTokenizer: bs_num_count != 0 " "when ch == '\\'"); } - } - else if (ch == '(') - { + } else if (ch == '(') { this->m->val += ch; ++this->m->string_depth; - } - else if ((ch == ')') && (--this->m->string_depth == 0)) - { + } else if ((ch == ')') && (--this->m->string_depth == 0)) { this->m->type = tt_string; this->m->state = st_token_ready; - } - else if (ch == '\r') - { + } else if (ch == '\r') { // CR by itself is converted to LF this->m->val += '\n'; - } - else if (ch == '\n') - { + } else if (ch == '\n') { // CR LF is converted to LF - if (! this->m->last_char_was_cr) - { + if (!this->m->last_char_was_cr) { this->m->val += ch; } - } - else - { + } else { this->m->val += ch; } this->m->last_char_was_cr = - ((! this->m->string_ignoring_newline) && (ch == '\r')); + ((!this->m->string_ignoring_newline) && (ch == '\r')); this->m->last_char_was_bs = - ((! this->m->last_char_was_bs) && (ch == '\\')); - } - else if (this->m->state == st_literal) - { - if (isDelimiter(ch)) - { + ((!this->m->last_char_was_bs) && (ch == '\\')); + } else if (this->m->state == st_literal) { + if (isDelimiter(ch)) { // A C-locale whitespace character or delimiter terminates // token. It is important to unread the whitespace // character even though it is ignored since it may be the @@ -521,41 +416,29 @@ QPDFTokenizer::presentCharacter(char ch) this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; - } - else - { + } else { this->m->val += ch; } - } - else if (this->m->state == st_inline_image) - { + } else if (this->m->state == st_inline_image) { this->m->val += ch; size_t len = this->m->val.length(); - if (len == this->m->inline_image_bytes) - { + if (len == this->m->inline_image_bytes) { QTC::TC("qpdf", "QPDFTokenizer found EI by byte count"); this->m->type = tt_inline_image; this->m->inline_image_bytes = 0; this->m->state = st_token_ready; } - } - else - { + } else { handled = false; } - if (handled) - { + if (handled) { // okay - } - else if (this->m->state == st_in_hexstring) - { - if (ch == '>') - { + } else if (this->m->state == st_in_hexstring) { + if (ch == '>') { this->m->type = tt_string; this->m->state = st_token_ready; - if (this->m->val.length() % 2) - { + if (this->m->val.length() % 2) { // PDF spec says odd hexstrings have implicit // trailing 0. this->m->val += '0'; @@ -563,46 +446,35 @@ QPDFTokenizer::presentCharacter(char ch) char num[3]; num[2] = '\0'; std::string nval; - for (unsigned int i = 0; i < this->m->val.length(); i += 2) - { + for (unsigned int i = 0; i < this->m->val.length(); i += 2) { num[0] = this->m->val.at(i); - num[1] = this->m->val.at(i+1); + num[1] = this->m->val.at(i + 1); char nch = static_cast(strtol(num, 0, 16)); nval += nch; } this->m->val = nval; - } - else if (QUtil::is_hex_digit(ch)) - { + } else if (QUtil::is_hex_digit(ch)) { this->m->val += ch; - } - else if (isSpace(ch)) - { + } else if (isSpace(ch)) { // ignore - } - else - { + } else { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad hexstring character"); - this->m->error_message = std::string("invalid character (") + - ch + ") in hexstring"; + this->m->error_message = + std::string("invalid character (") + ch + ") in hexstring"; this->m->state = st_token_ready; } - } - else - { + } else { throw std::logic_error( "INTERNAL ERROR: invalid state while reading token"); } - if ((this->m->state == st_token_ready) && (this->m->type == tt_word)) - { + if ((this->m->state == st_token_ready) && (this->m->type == tt_word)) { resolveLiteral(); } - if (! (betweenTokens() || - ((this->m->state == st_token_ready) && this->m->unread_char))) - { + if (!(betweenTokens() || + ((this->m->state == st_token_ready) && this->m->unread_char))) { this->m->raw_val += orig_ch; } } @@ -610,25 +482,18 @@ QPDFTokenizer::presentCharacter(char ch) void QPDFTokenizer::presentEOF() { - if (this->m->state == st_literal) - { + if (this->m->state == st_literal) { QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token"); resolveLiteral(); - } - else if ((this->m->include_ignorable) && (this->m->state == st_in_space)) - { + } else if ( + (this->m->include_ignorable) && (this->m->state == st_in_space)) { this->m->type = tt_space; - } - else if ((this->m->include_ignorable) && (this->m->state == st_in_comment)) - { + } else if ( + (this->m->include_ignorable) && (this->m->state == st_in_comment)) { this->m->type = tt_comment; - } - else if (betweenTokens()) - { + } else if (betweenTokens()) { this->m->type = tt_eof; - } - else if (this->m->state != st_token_ready) - { + } else if (this->m->state != st_token_ready) { QTC::TC("qpdf", "QPDFTokenizer EOF reading token"); this->m->type = tt_bad; this->m->error_message = "EOF while reading token"; @@ -640,8 +505,7 @@ QPDFTokenizer::presentEOF() void QPDFTokenizer::expectInlineImage(PointerHolder input) { - if (this->m->state != st_top) - { + if (this->m->state != st_top) { throw std::logic_error("QPDFTokenizer::expectInlineImage called" " when tokenizer is in improper state"); } @@ -652,8 +516,7 @@ QPDFTokenizer::expectInlineImage(PointerHolder input) void QPDFTokenizer::findEI(PointerHolder input) { - if (! input.get()) - { + if (!input.get()) { return; } @@ -671,11 +534,9 @@ QPDFTokenizer::findEI(PointerHolder input) bool okay = false; bool first_try = true; - while (! okay) - { + while (!okay) { QPDFWordTokenFinder f(input, "EI"); - if (! input->findFirst("EI", input->tell(), 0, f)) - { + if (!input->findFirst("EI", input->tell(), 0, f)) { break; } this->m->inline_image_bytes = QIntC::to_size(input->tell() - pos - 2); @@ -689,21 +550,14 @@ QPDFTokenizer::findEI(PointerHolder input) // bits per pixel, and color space are all required as well as // a BI and ID. If we get 10 good tokens in a row or hit EOF, // we can be pretty sure we've found the actual EI. - for (int i = 0; i < 10; ++i) - { - QPDFTokenizer::Token t = - check.readToken(input, "checker", true); + for (int i = 0; i < 10; ++i) { + QPDFTokenizer::Token t = check.readToken(input, "checker", true); token_type_e type = t.getType(); - if (type == tt_eof) - { + if (type == tt_eof) { okay = true; - } - else if (type == tt_bad) - { + } else if (type == tt_bad) { found_bad = true; - } - else if (type == tt_word) - { + } else if (type == tt_word) { // The qpdf tokenizer lumps alphabetic and otherwise // uncategorized characters into "words". We recognize // strings of alphabetic characters as potential valid @@ -717,52 +571,41 @@ QPDFTokenizer::findEI(PointerHolder input) bool found_other = false; std::string value = t.getValue(); for (std::string::iterator iter = value.begin(); - iter != value.end(); ++iter) - { + iter != value.end(); + ++iter) { char ch = *iter; if (((ch >= 'a') && (ch <= 'z')) || - ((ch >= 'A') && (ch <= 'Z')) || - (ch == '*')) - { + ((ch >= 'A') && (ch <= 'Z')) || (ch == '*')) { // Treat '*' as alpha since there are valid // PDF operators that contain * along with // alphabetic characters. found_alpha = true; - } - else if ((static_cast(ch) < 32) && - (! isSpace(ch))) - { + } else if ( + (static_cast(ch) < 32) && (!isSpace(ch))) { // Compare ch as a signed char so characters // outside of 7-bit will be < 0. found_non_printable = true; break; - } - else - { + } else { found_other = true; } } - if (found_non_printable || (found_alpha && found_other)) - { + if (found_non_printable || (found_alpha && found_other)) { found_bad = true; } } - if (okay || found_bad) - { + if (okay || found_bad) { break; } } - if (! found_bad) - { + if (!found_bad) { okay = true; } - if (! okay) - { + if (!okay) { first_try = false; } } - if (okay && (! first_try)) - { + if (okay && (!first_try)) { QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try"); } @@ -776,14 +619,15 @@ QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch) bool ready = (this->m->state == st_token_ready); unread_char = this->m->unread_char; ch = this->m->char_to_unread; - if (ready) - { - if (this->m->type == tt_bad) - { + if (ready) { + if (this->m->type == tt_bad) { this->m->val = this->m->raw_val; } - token = Token(this->m->type, this->m->val, - this->m->raw_val, this->m->error_message); + token = Token( + this->m->type, + this->m->val, + this->m->raw_val, + this->m->error_message); this->m->reset(); } return ready; @@ -792,34 +636,32 @@ QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch) bool QPDFTokenizer::betweenTokens() { - return ((this->m->state == st_top) || - ((! this->m->include_ignorable) && - ((this->m->state == st_in_comment) || - (this->m->state == st_in_space)))); + return ( + (this->m->state == st_top) || + ((!this->m->include_ignorable) && + ((this->m->state == st_in_comment) || + (this->m->state == st_in_space)))); } QPDFTokenizer::Token -QPDFTokenizer::readToken(PointerHolder input, - std::string const& context, - bool allow_bad, - size_t max_len) +QPDFTokenizer::readToken( + PointerHolder input, + std::string const& context, + bool allow_bad, + size_t max_len) { qpdf_offset_t offset = input->tell(); Token token; bool unread_char; char char_to_unread; bool presented_eof = false; - while (! getToken(token, unread_char, char_to_unread)) - { + while (!getToken(token, unread_char, char_to_unread)) { char ch; - if (input->read(&ch, 1) == 0) - { - if (! presented_eof) - { + if (input->read(&ch, 1) == 0) { + if (!presented_eof) { presentEOF(); presented_eof = true; - if ((this->m->type == tt_eof) && (! this->m->allow_eof)) - { + if ((this->m->type == tt_eof) && (!this->m->allow_eof)) { // Nothing in the qpdf library calls readToken // without allowEOF anymore, so this case is not // exercised. @@ -827,23 +669,17 @@ QPDFTokenizer::readToken(PointerHolder input, this->m->error_message = "unexpected EOF"; offset = input->getLastOffset(); } - } - else - { + } else { throw std::logic_error( "getToken returned false after presenting EOF"); } - } - else - { + } else { presentCharacter(ch); - if (betweenTokens() && (input->getLastOffset() == offset)) - { + if (betweenTokens() && (input->getLastOffset() == offset)) { ++offset; } if (max_len && (this->m->raw_val.length() >= max_len) && - (this->m->state != st_token_ready)) - { + (this->m->state != st_token_ready)) { // terminate this token now QTC::TC("qpdf", "QPDFTokenizer block long token"); this->m->type = tt_bad; @@ -854,26 +690,24 @@ QPDFTokenizer::readToken(PointerHolder input, } } - if (unread_char) - { + if (unread_char) { input->unreadCh(char_to_unread); } - if (token.getType() != tt_eof) - { + if (token.getType() != tt_eof) { input->setLastOffset(offset); } - if (token.getType() == tt_bad) - { - if (allow_bad) - { + if (token.getType() == tt_bad) { + if (allow_bad) { QTC::TC("qpdf", "QPDFTokenizer allowing bad token"); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), - context, offset, token.getErrorMessage()); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + input->getName(), + context, + offset, + token.getErrorMessage()); } } diff --git a/libqpdf/QPDFWriter.cc b/libqpdf/QPDFWriter.cc index c8a5bb18..f8320899 100644 --- a/libqpdf/QPDFWriter.cc +++ b/libqpdf/QPDFWriter.cc @@ -1,26 +1,26 @@ -#include // include first for large file support +#include // include first for large file support #include -#include -#include +#include +#include #include #include -#include -#include #include -#include #include -#include -#include -#include +#include +#include +#include #include +#include +#include +#include +#include #include #include #include #include -#include #include #include @@ -76,8 +76,7 @@ QPDFWriter::Members::Members(QPDF& pdf) : QPDFWriter::Members::~Members() { - if (file && close_file) - { + if (file && close_file) { fclose(file); } delete output_buffer; @@ -94,8 +93,8 @@ QPDFWriter::QPDFWriter(QPDF& pdf, char const* filename) : setOutputFilename(filename); } -QPDFWriter::QPDFWriter(QPDF& pdf, char const* description, - FILE *file, bool close_file) : +QPDFWriter::QPDFWriter( + QPDF& pdf, char const* description, FILE* file, bool close_file) : m(new Members(pdf)) { setOutputFile(description, file, close_file); @@ -111,15 +110,12 @@ QPDFWriter::setOutputFilename(char const* filename) char const* description = filename; FILE* f = 0; bool close_file = false; - if (filename == 0) - { + if (filename == 0) { description = "standard output"; QTC::TC("qpdf", "QPDFWriter write to stdout"); f = stdout; QUtil::binary_stdout(); - } - else - { + } else { QTC::TC("qpdf", "QPDFWriter write to file"); f = QUtil::safe_fopen(filename, "wb+"); close_file = true; @@ -133,8 +129,8 @@ QPDFWriter::setOutputFile(char const* description, FILE* file, bool close_file) this->m->filename = description; this->m->file = file; this->m->close_file = close_file; - std::shared_ptr p = std::make_shared( - "qpdf output", file); + std::shared_ptr p = + std::make_shared("qpdf output", file); this->m->to_delete.push_back(p); initializePipelineStack(p.get()); } @@ -179,20 +175,19 @@ QPDFWriter::setObjectStreamMode(qpdf_object_stream_e mode) void QPDFWriter::setStreamDataMode(qpdf_stream_data_e mode) { - switch (mode) - { - case qpdf_s_uncompress: + switch (mode) { + case qpdf_s_uncompress: this->m->stream_decode_level = std::max(qpdf_dl_generalized, this->m->stream_decode_level); this->m->compress_streams = false; break; - case qpdf_s_preserve: + case qpdf_s_preserve: this->m->stream_decode_level = qpdf_dl_none; this->m->compress_streams = false; break; - case qpdf_s_compress: + case qpdf_s_compress: this->m->stream_decode_level = std::max(qpdf_dl_generalized, this->m->stream_decode_level); this->m->compress_streams = true; @@ -202,7 +197,6 @@ QPDFWriter::setStreamDataMode(qpdf_stream_data_e mode) this->m->compress_streams_set = true; } - void QPDFWriter::setCompressStreams(bool val) { @@ -249,49 +243,42 @@ QPDFWriter::setNewlineBeforeEndstream(bool val) } void -QPDFWriter::setMinimumPDFVersion(std::string const& version, - int extension_level) +QPDFWriter::setMinimumPDFVersion( + std::string const& version, int extension_level) { bool set_version = false; bool set_extension_level = false; - if (this->m->min_pdf_version.empty()) - { + if (this->m->min_pdf_version.empty()) { set_version = true; set_extension_level = true; - } - else - { + } else { int old_major = 0; int old_minor = 0; int min_major = 0; int min_minor = 0; parseVersion(version, old_major, old_minor); parseVersion(this->m->min_pdf_version, min_major, min_minor); - int compare = compareVersions( - old_major, old_minor, min_major, min_minor); - if (compare > 0) - { - QTC::TC("qpdf", "QPDFWriter increasing minimum version", - extension_level == 0 ? 0 : 1); + int compare = + compareVersions(old_major, old_minor, min_major, min_minor); + if (compare > 0) { + QTC::TC( + "qpdf", + "QPDFWriter increasing minimum version", + extension_level == 0 ? 0 : 1); set_version = true; set_extension_level = true; - } - else if (compare == 0) - { - if (extension_level > this->m->min_extension_level) - { + } else if (compare == 0) { + if (extension_level > this->m->min_extension_level) { QTC::TC("qpdf", "QPDFWriter increasing extension level"); set_extension_level = true; } } } - if (set_version) - { + if (set_version) { this->m->min_pdf_version = version; } - if (set_extension_level) - { + if (set_extension_level) { this->m->min_extension_level = extension_level; } } @@ -306,8 +293,7 @@ QPDFWriter::setMinimumPDFVersion(PDFVersion const& v) } void -QPDFWriter::forcePDFVersion(std::string const& version, - int extension_level) +QPDFWriter::forcePDFVersion(std::string const& version, int extension_level) { this->m->forced_pdf_version = version; this->m->forced_extension_level = extension_level; @@ -318,13 +304,10 @@ QPDFWriter::setExtraHeaderText(std::string const& text) { this->m->extra_header_text = text; if ((this->m->extra_header_text.length() > 0) && - (*(this->m->extra_header_text.rbegin()) != '\n')) - { + (*(this->m->extra_header_text.rbegin()) != '\n')) { QTC::TC("qpdf", "QPDFWriter extra header text add newline"); this->m->extra_header_text += "\n"; - } - else - { + } else { QTC::TC("qpdf", "QPDFWriter extra header text no newline"); } } @@ -344,8 +327,7 @@ QPDFWriter::setDeterministicID(bool val) void QPDFWriter::setStaticAesIV(bool val) { - if (val) - { + if (val) { Pl_AES_PDF::useStaticIV(); } } @@ -366,8 +348,7 @@ void QPDFWriter::setLinearization(bool val) { this->m->linearized = val; - if (val) - { + if (val) { this->m->pclm = false; } } @@ -382,33 +363,31 @@ void QPDFWriter::setPCLm(bool val) { this->m->pclm = val; - if (val) - { + if (val) { this->m->linearized = false; } } void QPDFWriter::setR2EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_print, bool allow_modify, - bool allow_extract, bool allow_annotate) + char const* user_password, + char const* owner_password, + bool allow_print, + bool allow_modify, + bool allow_extract, + bool allow_annotate) { std::set clear; - if (! allow_print) - { + if (!allow_print) { clear.insert(3); } - if (! allow_modify) - { + if (!allow_modify) { clear.insert(4); } - if (! allow_extract) - { + if (!allow_extract) { clear.insert(5); } - if (! allow_annotate) - { + if (!allow_annotate) { clear.insert(6); } @@ -417,48 +396,81 @@ QPDFWriter::setR2EncryptionParameters( void QPDFWriter::setR3EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify) + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - true, true, true, true, print, modify); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + true, + true, + true, + true, + print, + modify); setEncryptionParameters(user_password, owner_password, 2, 3, 16, clear); } void QPDFWriter::setR3EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, qpdf_r3_print_e print) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - allow_assemble, allow_annotate_and_form, - allow_form_filling, allow_modify_other, - print, qpdf_r3m_all); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + allow_assemble, + allow_annotate_and_form, + allow_form_filling, + allow_modify_other, + print, + qpdf_r3m_all); setEncryptionParameters(user_password, owner_password, 2, 3, 16, clear); } void QPDFWriter::setR4EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, - bool encrypt_metadata, bool use_aes) + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, + bool encrypt_metadata, + bool use_aes) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - true, true, true, true, print, modify); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + true, + true, + true, + true, + print, + modify); this->m->encrypt_use_aes = use_aes; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 4, 4, 16, clear); @@ -466,20 +478,31 @@ QPDFWriter::setR4EncryptionParameters( void QPDFWriter::setR4EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, qpdf_r3_print_e print, - bool encrypt_metadata, bool use_aes) + bool encrypt_metadata, + bool use_aes) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - allow_assemble, allow_annotate_and_form, - allow_form_filling, allow_modify_other, - print, qpdf_r3m_all); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + allow_assemble, + allow_annotate_and_form, + allow_form_filling, + allow_modify_other, + print, + qpdf_r3m_all); this->m->encrypt_use_aes = use_aes; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 4, 4, 16, clear); @@ -487,16 +510,27 @@ QPDFWriter::setR4EncryptionParameters( void QPDFWriter::setR5EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, bool encrypt_metadata) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - true, true, true, true, print, modify); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + true, + true, + true, + true, + print, + modify); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 5, 5, 32, clear); @@ -504,20 +538,30 @@ QPDFWriter::setR5EncryptionParameters( void QPDFWriter::setR5EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, qpdf_r3_print_e print, bool encrypt_metadata) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - allow_assemble, allow_annotate_and_form, - allow_form_filling, allow_modify_other, - print, qpdf_r3m_all); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + allow_assemble, + allow_annotate_and_form, + allow_form_filling, + allow_modify_other, + print, + qpdf_r3m_all); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 5, 5, 32, clear); @@ -525,16 +569,27 @@ QPDFWriter::setR5EncryptionParameters( void QPDFWriter::setR6EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, bool encrypt_metadata) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - true, true, true, true, print, modify); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + true, + true, + true, + true, + print, + modify); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 5, 6, 32, clear); @@ -542,20 +597,30 @@ QPDFWriter::setR6EncryptionParameters( void QPDFWriter::setR6EncryptionParameters( - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, qpdf_r3_print_e print, bool encrypt_metadata) { std::set clear; interpretR3EncryptionParameters( - clear, user_password, owner_password, - allow_accessibility, allow_extract, - allow_assemble, allow_annotate_and_form, - allow_form_filling, allow_modify_other, - print, qpdf_r3m_all); + clear, + user_password, + owner_password, + allow_accessibility, + allow_extract, + allow_assemble, + allow_annotate_and_form, + allow_form_filling, + allow_modify_other, + print, + qpdf_r3m_all); this->m->encrypt_use_aes = true; this->m->encrypt_metadata = encrypt_metadata; setEncryptionParameters(user_password, owner_password, 5, 6, 32, clear); @@ -564,11 +629,16 @@ QPDFWriter::setR6EncryptionParameters( void QPDFWriter::interpretR3EncryptionParameters( std::set& clear, - char const* user_password, char const* owner_password, - bool allow_accessibility, bool allow_extract, - bool allow_assemble, bool allow_annotate_and_form, - bool allow_form_filling, bool allow_modify_other, - qpdf_r3_print_e print, qpdf_r3_modify_e modify) + char const* user_password, + char const* owner_password, + bool allow_accessibility, + bool allow_extract, + bool allow_assemble, + bool allow_annotate_and_form, + bool allow_form_filling, + bool allow_modify_other, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify) { // Acrobat 5 security options: @@ -600,27 +670,24 @@ QPDFWriter::interpretR3EncryptionParameters( // 11: document assembly even if 4 is clear // 12: high-resolution printing - if (! allow_accessibility) - { + if (!allow_accessibility) { // setEncryptionParameters sets this if R > 3 clear.insert(10); } - if (! allow_extract) - { + if (!allow_extract) { clear.insert(5); } // Note: these switch statements all "fall through" (no break // statements). Each option clears successively more access bits. - switch (print) - { - case qpdf_r3p_none: - clear.insert(3); // any printing + switch (print) { + case qpdf_r3p_none: + clear.insert(3); // any printing - case qpdf_r3p_low: - clear.insert(12); // high resolution printing + case qpdf_r3p_low: + clear.insert(12); // high resolution printing - case qpdf_r3p_full: + case qpdf_r3p_full: break; // no default so gcc warns for missing cases @@ -633,49 +700,48 @@ QPDFWriter::interpretR3EncryptionParameters( // individually. // NOT EXERCISED IN TEST SUITE - switch (modify) - { - case qpdf_r3m_none: - clear.insert(11); // document assembly + switch (modify) { + case qpdf_r3m_none: + clear.insert(11); // document assembly - case qpdf_r3m_assembly: - clear.insert(9); // filling in form fields + case qpdf_r3m_assembly: + clear.insert(9); // filling in form fields - case qpdf_r3m_form: - clear.insert(6); // modify annotations, fill in form fields + case qpdf_r3m_form: + clear.insert(6); // modify annotations, fill in form fields - case qpdf_r3m_annotate: - clear.insert(4); // other modifications + case qpdf_r3m_annotate: + clear.insert(4); // other modifications - case qpdf_r3m_all: + case qpdf_r3m_all: break; // no default so gcc warns for missing cases } // END NOT EXERCISED IN TEST SUITE - if (! allow_assemble) - { + if (!allow_assemble) { clear.insert(11); } - if (! allow_annotate_and_form) - { + if (!allow_annotate_and_form) { clear.insert(6); } - if (! allow_form_filling) - { + if (!allow_form_filling) { clear.insert(9); } - if (! allow_modify_other) - { + if (!allow_modify_other) { clear.insert(4); } } void QPDFWriter::setEncryptionParameters( - char const* user_password, char const* owner_password, - int V, int R, int key_len, std::set& bits_to_clear) + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + std::set& bits_to_clear) { // PDF specification refers to bits with the low bit numbered 1. // We have to convert this into a bit field. @@ -684,8 +750,7 @@ QPDFWriter::setEncryptionParameters( bits_to_clear.insert(1); bits_to_clear.insert(2); - if (R > 3) - { + if (R > 3) { // Bit 10 is deprecated and should always be set. This used // to mean accessibility. There is no way to disable // accessibility with R > 3. @@ -695,8 +760,8 @@ QPDFWriter::setEncryptionParameters( int P = 0; // Create the complement of P, then invert. for (std::set::iterator iter = bits_to_clear.begin(); - iter != bits_to_clear.end(); ++iter) - { + iter != bits_to_clear.end(); + ++iter) { P |= (1 << ((*iter) - 1)); } P = ~P; @@ -708,22 +773,48 @@ QPDFWriter::setEncryptionParameters( std::string UE; std::string Perms; std::string encryption_key; - if (V < 5) - { + if (V < 5) { QPDF::compute_encryption_O_U( - user_password, owner_password, V, R, key_len, P, - this->m->encrypt_metadata, this->m->id1, O, U); - } - else - { + user_password, + owner_password, + V, + R, + key_len, + P, + this->m->encrypt_metadata, + this->m->id1, + O, + U); + } else { QPDF::compute_encryption_parameters_V5( - user_password, owner_password, V, R, key_len, P, - this->m->encrypt_metadata, this->m->id1, - encryption_key, O, U, OE, UE, Perms); + user_password, + owner_password, + V, + R, + key_len, + P, + this->m->encrypt_metadata, + this->m->id1, + encryption_key, + O, + U, + OE, + UE, + Perms); } setEncryptionParametersInternal( - V, R, key_len, P, O, U, OE, UE, Perms, - this->m->id1, user_password, encryption_key); + V, + R, + key_len, + P, + O, + U, + OE, + UE, + Perms, + this->m->id1, + user_password, + encryption_key); } void @@ -731,26 +822,21 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) { this->m->preserve_encryption = false; QPDFObjectHandle trailer = qpdf.getTrailer(); - if (trailer.hasKey("/Encrypt")) - { + if (trailer.hasKey("/Encrypt")) { generateID(); - this->m->id1 = - trailer.getKey("/ID").getArrayItem(0).getStringValue(); + this->m->id1 = trailer.getKey("/ID").getArrayItem(0).getStringValue(); QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); int V = encrypt.getKey("/V").getIntValueAsInt(); int key_len = 5; - if (V > 1) - { + if (V > 1) { key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8; } if (encrypt.hasKey("/EncryptMetadata") && - encrypt.getKey("/EncryptMetadata").isBool()) - { + encrypt.getKey("/EncryptMetadata").isBool()) { this->m->encrypt_metadata = encrypt.getKey("/EncryptMetadata").getBoolValue(); } - if (V >= 4) - { + if (V >= 4) { // When copying encryption parameters, use AES even if the // original file did not. Acrobat doesn't create files // with V >= 4 that don't use AES, and the logic of @@ -759,16 +845,19 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) // different values. this->m->encrypt_use_aes = true; } - QTC::TC("qpdf", "QPDFWriter copy encrypt metadata", - this->m->encrypt_metadata ? 0 : 1); - QTC::TC("qpdf", "QPDFWriter copy use_aes", - this->m->encrypt_use_aes ? 0 : 1); + QTC::TC( + "qpdf", + "QPDFWriter copy encrypt metadata", + this->m->encrypt_metadata ? 0 : 1); + QTC::TC( + "qpdf", + "QPDFWriter copy use_aes", + this->m->encrypt_use_aes ? 0 : 1); std::string OE; std::string UE; std::string Perms; std::string encryption_key; - if (V >= 5) - { + if (V >= 5) { QTC::TC("qpdf", "QPDFWriter copy V5"); OE = encrypt.getKey("/OE").getStringValue(); UE = encrypt.getKey("/UE").getStringValue(); @@ -786,85 +875,68 @@ QPDFWriter::copyEncryptionParameters(QPDF& qpdf) OE, UE, Perms, - this->m->id1, // this->m->id1 == the other file's id1 + this->m->id1, // this->m->id1 == the other file's id1 qpdf.getPaddedUserPassword(), encryption_key); } } void -QPDFWriter::disableIncompatibleEncryption(int major, int minor, - int extension_level) +QPDFWriter::disableIncompatibleEncryption( + int major, int minor, int extension_level) { - if (! this->m->encrypted) - { + if (!this->m->encrypted) { return; } bool disable = false; - if (compareVersions(major, minor, 1, 3) < 0) - { + if (compareVersions(major, minor, 1, 3) < 0) { disable = true; - } - else - { - int V = QUtil::string_to_int( - this->m->encryption_dictionary["/V"].c_str()); - int R = QUtil::string_to_int( - this->m->encryption_dictionary["/R"].c_str()); - if (compareVersions(major, minor, 1, 4) < 0) - { - if ((V > 1) || (R > 2)) - { + } else { + int V = + QUtil::string_to_int(this->m->encryption_dictionary["/V"].c_str()); + int R = + QUtil::string_to_int(this->m->encryption_dictionary["/R"].c_str()); + if (compareVersions(major, minor, 1, 4) < 0) { + if ((V > 1) || (R > 2)) { disable = true; } - } - else if (compareVersions(major, minor, 1, 5) < 0) - { - if ((V > 2) || (R > 3)) - { + } else if (compareVersions(major, minor, 1, 5) < 0) { + if ((V > 2) || (R > 3)) { disable = true; } - } - else if (compareVersions(major, minor, 1, 6) < 0) - { - if (this->m->encrypt_use_aes) - { + } else if (compareVersions(major, minor, 1, 6) < 0) { + if (this->m->encrypt_use_aes) { disable = true; } - } - else if ((compareVersions(major, minor, 1, 7) < 0) || - ((compareVersions(major, minor, 1, 7) == 0) && - extension_level < 3)) - { - if ((V >= 5) || (R >= 5)) - { + } else if ( + (compareVersions(major, minor, 1, 7) < 0) || + ((compareVersions(major, minor, 1, 7) == 0) && + extension_level < 3)) { + if ((V >= 5) || (R >= 5)) { disable = true; } } } - if (disable) - { + if (disable) { QTC::TC("qpdf", "QPDFWriter forced version disabled encryption"); this->m->encrypted = false; } } void -QPDFWriter::parseVersion(std::string const& version, - int& major, int& minor) const +QPDFWriter::parseVersion( + std::string const& version, int& major, int& minor) const { major = QUtil::string_to_int(version.c_str()); minor = 0; size_t p = version.find('.'); - if ((p != std::string::npos) && (version.length() > p)) - { + if ((p != std::string::npos) && (version.length() > p)) { minor = QUtil::string_to_int(version.substr(p + 1).c_str()); } - std::string tmp = QUtil::int_to_string(major) + "." + - QUtil::int_to_string(minor); - if (tmp != version) - { + std::string tmp = + QUtil::int_to_string(major) + "." + QUtil::int_to_string(minor); + if (tmp != version) { // The version number in the input is probably invalid. This // happens with some files that are designed to exercise bugs, // such as files in the fuzzer corpus. Unfortunately @@ -874,37 +946,35 @@ QPDFWriter::parseVersion(std::string const& version, } int -QPDFWriter::compareVersions(int major1, int minor1, - int major2, int minor2) const +QPDFWriter::compareVersions( + int major1, int minor1, int major2, int minor2) const { - if (major1 < major2) - { + if (major1 < major2) { return -1; - } - else if (major1 > major2) - { + } else if (major1 > major2) { return 1; - } - else if (minor1 < minor2) - { + } else if (minor1 < minor2) { return -1; - } - else if (minor1 > minor2) - { + } else if (minor1 > minor2) { return 1; - } - else - { + } else { return 0; } } void QPDFWriter::setEncryptionParametersInternal( - int V, int R, int key_len, int P, - std::string const& O, std::string const& U, - std::string const& OE, std::string const& UE, std::string const& Perms, - std::string const& id1, std::string const& user_password, + int V, + int R, + int key_len, + int P, + std::string const& O, + std::string const& U, + std::string const& OE, + std::string const& UE, + std::string const& Perms, + std::string const& id1, + std::string const& user_password, std::string const& encryption_key) { this->m->encryption_V = V; @@ -917,66 +987,51 @@ QPDFWriter::setEncryptionParametersInternal( this->m->encryption_dictionary["/P"] = QUtil::int_to_string(P); this->m->encryption_dictionary["/O"] = QPDF_String(O).unparse(true); this->m->encryption_dictionary["/U"] = QPDF_String(U).unparse(true); - if (V >= 5) - { + if (V >= 5) { this->m->encryption_dictionary["/OE"] = QPDF_String(OE).unparse(true); this->m->encryption_dictionary["/UE"] = QPDF_String(UE).unparse(true); this->m->encryption_dictionary["/Perms"] = QPDF_String(Perms).unparse(true); } - if (R >= 6) - { + if (R >= 6) { setMinimumPDFVersion("1.7", 8); - } - else if (R == 5) - { + } else if (R == 5) { setMinimumPDFVersion("1.7", 3); - } - else if (R == 4) - { + } else if (R == 4) { setMinimumPDFVersion(this->m->encrypt_use_aes ? "1.6" : "1.5"); - } - else if (R == 3) - { + } else if (R == 3) { setMinimumPDFVersion("1.4"); - } - else - { + } else { setMinimumPDFVersion("1.3"); } - if ((R >= 4) && (! this->m->encrypt_metadata)) - { + if ((R >= 4) && (!this->m->encrypt_metadata)) { this->m->encryption_dictionary["/EncryptMetadata"] = "false"; } - if ((V == 4) || (V == 5)) - { + if ((V == 4) || (V == 5)) { // The spec says the value for the crypt filter key can be // anything, and xpdf seems to agree. However, Adobe Reader // won't open our files unless we use /StdCF. this->m->encryption_dictionary["/StmF"] = "/StdCF"; this->m->encryption_dictionary["/StrF"] = "/StdCF"; - std::string method = (this->m->encrypt_use_aes - ? ((V < 5) ? "/AESV2" : "/AESV3") - : "/V2"); + std::string method = + (this->m->encrypt_use_aes ? ((V < 5) ? "/AESV2" : "/AESV3") + : "/V2"); // The PDF spec says the /Length key is optional, but the PDF // previewer on some versions of MacOS won't open encrypted // files without it. this->m->encryption_dictionary["/CF"] = - "<< /StdCF << /AuthEvent /DocOpen /CFM " + method + - " /Length " + std::string((V < 5) ? "16" : "32") + " >> >>"; + "<< /StdCF << /AuthEvent /DocOpen /CFM " + method + " /Length " + + std::string((V < 5) ? "16" : "32") + " >> >>"; } this->m->encrypted = true; QPDF::EncryptionData encryption_data( V, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata); - if (V < 5) - { - this->m->encryption_key = QPDF::compute_encryption_key( - user_password, encryption_data); - } - else - { + if (V < 5) { + this->m->encryption_key = + QPDF::compute_encryption_key(user_password, encryption_data); + } else { this->m->encryption_key = encryption_key; } } @@ -985,16 +1040,19 @@ void QPDFWriter::setDataKey(int objid) { this->m->cur_data_key = QPDF::compute_data_key( - this->m->encryption_key, objid, 0, - this->m->encrypt_use_aes, this->m->encryption_V, this->m->encryption_R); + this->m->encryption_key, + objid, + 0, + this->m->encrypt_use_aes, + this->m->encryption_V, + this->m->encryption_R); } unsigned int QPDFWriter::bytesNeeded(long long n) { unsigned int bytes = 0; - while (n) - { + while (n) { ++bytes; n >>= 8; } @@ -1004,14 +1062,12 @@ QPDFWriter::bytesNeeded(long long n) void QPDFWriter::writeBinary(unsigned long long val, unsigned int bytes) { - if (bytes > sizeof(unsigned long long)) - { + if (bytes > sizeof(unsigned long long)) { throw std::logic_error( "QPDFWriter::writeBinary called with too many bytes"); } unsigned char data[sizeof(unsigned long long)]; - for (unsigned int i = 0; i < bytes; ++i) - { + for (unsigned int i = 0; i < bytes; ++i) { data[bytes - i - 1] = static_cast(val & 0xff); val >>= 8; } @@ -1033,8 +1089,7 @@ QPDFWriter::writeBuffer(PointerHolder& b) void QPDFWriter::writeStringQDF(std::string const& str) { - if (this->m->qdf_mode) - { + if (this->m->qdf_mode) { writeString(str); } } @@ -1042,8 +1097,7 @@ QPDFWriter::writeStringQDF(std::string const& str) void QPDFWriter::writeStringNoQDF(std::string const& str) { - if (! this->m->qdf_mode) - { + if (!this->m->qdf_mode) { writeString(str); } } @@ -1051,8 +1105,7 @@ QPDFWriter::writeStringNoQDF(std::string const& str) void QPDFWriter::writePad(int nspaces) { - for (int i = 0; i < nspaces; ++i) - { + for (int i = 0; i < nspaces; ++i) { writeString(" "); } } @@ -1066,11 +1119,10 @@ QPDFWriter::pushPipeline(Pipeline* p) } void -QPDFWriter::initializePipelineStack(Pipeline *p) +QPDFWriter::initializePipelineStack(Pipeline* p) { this->m->pipeline = new Pl_Count("pipeline stack base", p); - this->m->to_delete.push_back( - std::shared_ptr(this->m->pipeline)); + this->m->to_delete.push_back(std::shared_ptr(this->m->pipeline)); this->m->pipeline_stack.push_back(this->m->pipeline); } @@ -1079,8 +1131,8 @@ QPDFWriter::activatePipelineStack(PipelinePopper& pp) { std::string stack_id( "stack " + QUtil::uint_to_string(this->m->next_stack_id)); - Pl_Count* c = new Pl_Count(stack_id.c_str(), - this->m->pipeline_stack.back()); + Pl_Count* c = + new Pl_Count(stack_id.c_str(), this->m->pipeline_stack.back()); ++this->m->next_stack_id; this->m->pipeline_stack.push_back(c); this->m->pipeline = c; @@ -1089,14 +1141,14 @@ QPDFWriter::activatePipelineStack(PipelinePopper& pp) QPDFWriter::PipelinePopper::~PipelinePopper() { - if (stack_id.empty()) - { + if (stack_id.empty()) { return; } assert(qw->m->pipeline_stack.size() >= 2); qw->m->pipeline->finish(); - assert(dynamic_cast(qw->m->pipeline_stack.back()) == - qw->m->pipeline); + assert( + dynamic_cast(qw->m->pipeline_stack.back()) == + qw->m->pipeline); // It might be possible for this assertion to fail if // writeLinearized exits by exception when deterministic ID, but I // don't think so. As of this writing, this is the only case in @@ -1106,17 +1158,14 @@ QPDFWriter::PipelinePopper::~PipelinePopper() assert(qw->m->pipeline->getIdentifier() == stack_id); delete qw->m->pipeline_stack.back(); qw->m->pipeline_stack.pop_back(); - while (dynamic_cast(qw->m->pipeline_stack.back()) == 0) - { + while (dynamic_cast(qw->m->pipeline_stack.back()) == 0) { Pipeline* p = qw->m->pipeline_stack.back(); - if (dynamic_cast(p) == qw->m->md5_pipeline) - { + if (dynamic_cast(p) == qw->m->md5_pipeline) { qw->m->md5_pipeline = 0; } qw->m->pipeline_stack.pop_back(); Pl_Buffer* buf = dynamic_cast(p); - if (bp && buf) - { + if (bp && buf) { *bp = buf->getBufferSharedPointer(); } delete p; @@ -1127,9 +1176,8 @@ QPDFWriter::PipelinePopper::~PipelinePopper() void QPDFWriter::adjustAESStreamLength(size_t& length) { - if (this->m->encrypted && (! this->m->cur_data_key.empty()) && - this->m->encrypt_use_aes) - { + if (this->m->encrypted && (!this->m->cur_data_key.empty()) && + this->m->encrypt_use_aes) { // Stream length will be padded with 1 to 16 bytes to end up // as a multiple of 16. It will also be prepended by 16 bits // of random data. @@ -1140,21 +1188,21 @@ QPDFWriter::adjustAESStreamLength(size_t& length) void QPDFWriter::pushEncryptionFilter(PipelinePopper& pp) { - if (this->m->encrypted && (! this->m->cur_data_key.empty())) - { + if (this->m->encrypted && (!this->m->cur_data_key.empty())) { Pipeline* p = 0; - if (this->m->encrypt_use_aes) - { + if (this->m->encrypt_use_aes) { p = new Pl_AES_PDF( - "aes stream encryption", this->m->pipeline, true, + "aes stream encryption", + this->m->pipeline, + true, QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); - } - else - { - p = new Pl_RC4("rc4 stream encryption", this->m->pipeline, - QUtil::unsigned_char_pointer(this->m->cur_data_key), - QIntC::to_int(this->m->cur_data_key.length())); + } else { + p = new Pl_RC4( + "rc4 stream encryption", + this->m->pipeline, + QUtil::unsigned_char_pointer(this->m->cur_data_key), + QIntC::to_int(this->m->cur_data_key.length())); } pushPipeline(p); } @@ -1173,12 +1221,10 @@ QPDFWriter::pushDiscardFilter(PipelinePopper& pp) void QPDFWriter::pushMD5Pipeline(PipelinePopper& pp) { - if (! this->m->id2.empty()) - { + if (!this->m->id2.empty()) { // Can't happen in the code - throw std::logic_error( - "Deterministic ID computation enabled after ID" - " generation has already occurred."); + throw std::logic_error("Deterministic ID computation enabled after ID" + " generation has already occurred."); } assert(this->m->deterministic_id); assert(this->m->md5_pipeline == 0); @@ -1203,8 +1249,7 @@ QPDFWriter::computeDeterministicIDData() int QPDFWriter::openObject(int objid) { - if (objid == 0) - { + if (objid == 0) { objid = this->m->next_objid++; } this->m->xref[objid] = QPDFXRefEntry(1, this->m->pipeline->getCount(), 0); @@ -1220,8 +1265,8 @@ QPDFWriter::closeObject(int objid) // repair. writeString("\nendobj\n"); writeStringQDF("\n"); - this->m->lengths[objid] = this->m->pipeline->getCount() - - this->m->xref[objid].getOffset(); + this->m->lengths[objid] = + this->m->pipeline->getCount() - this->m->xref[objid].getOffset(); } void @@ -1229,8 +1274,7 @@ QPDFWriter::assignCompressedObjectNumbers(QPDFObjGen const& og) { int objid = og.getObj(); if ((og.getGen() != 0) || - (this->m->object_stream_to_objects.count(objid) == 0)) - { + (this->m->object_stream_to_objects.count(objid) == 0)) { // This is not an object stream. return; } @@ -1240,8 +1284,7 @@ QPDFWriter::assignCompressedObjectNumbers(QPDFObjGen const& og) for (std::set::iterator iter = this->m->object_stream_to_objects[objid].begin(); iter != this->m->object_stream_to_objects[objid].end(); - ++iter) - { + ++iter) { this->m->obj_renumber[*iter] = this->m->next_objid++; } } @@ -1249,10 +1292,8 @@ QPDFWriter::assignCompressedObjectNumbers(QPDFObjGen const& og) void QPDFWriter::enqueueObject(QPDFObjectHandle object) { - if (object.isIndirect()) - { - if (object.getOwningQPDF() != &(this->m->pdf)) - { + if (object.isIndirect()) { + if (object.getOwningQPDF() != &(this->m->pdf)) { QTC::TC("qpdf", "QPDFWriter foreign object"); throw std::logic_error( "QPDFObjectHandle from different QPDF found while writing." @@ -1260,8 +1301,7 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) " another file."); } - if (this->m->qdf_mode && object.isStreamOfType("/XRef")) - { + if (this->m->qdf_mode && object.isStreamOfType("/XRef")) { // As a special case, do not output any extraneous XRef // streams in QDF mode. Doing so will confuse fix-qdf, // which expects to see only one XRef stream at the end of @@ -1275,10 +1315,8 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) QPDFObjGen og = object.getObjGen(); - if (this->m->obj_renumber.count(og) == 0) - { - if (this->m->object_to_object_stream.count(og)) - { + if (this->m->obj_renumber.count(og) == 0) { + if (this->m->object_to_object_stream.count(og)) { // This is in an object stream. Don't process it // here. Instead, enqueue the object stream. Object // streams always have generation 0. @@ -1287,63 +1325,46 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) // will get overwritten later. this->m->obj_renumber[og] = 0; enqueueObject(this->m->pdf.getObjectByID(stream_id, 0)); - } - else - { + } else { this->m->object_queue.push_back(object); this->m->obj_renumber[og] = this->m->next_objid++; if ((og.getGen() == 0) && - this->m->object_stream_to_objects.count(og.getObj())) - { + this->m->object_stream_to_objects.count(og.getObj())) { // For linearized files, uncompressed objects go // at end, and we take care of assigning numbers // to them elsewhere. - if (! this->m->linearized) - { + if (!this->m->linearized) { assignCompressedObjectNumbers(og); } - } - else if ((! this->m->direct_stream_lengths) && - object.isStream()) - { + } else if ( + (!this->m->direct_stream_lengths) && object.isStream()) { // reserve next object ID for length ++this->m->next_objid; } } - } - else if (this->m->obj_renumber[og] == 0) - { + } else if (this->m->obj_renumber[og] == 0) { // This can happen if a specially constructed file // indicates that an object stream is inside itself. QTC::TC("qpdf", "QPDFWriter ignore self-referential object stream"); } - } - else if (object.isArray()) - { + } else if (object.isArray()) { int n = object.getArrayNItems(); - for (int i = 0; i < n; ++i) - { - if (! this->m->linearized) - { + for (int i = 0; i < n; ++i) { + if (!this->m->linearized) { enqueueObject(object.getArrayItem(i)); } } - } - else if (object.isDictionary()) - { + } else if (object.isDictionary()) { std::set keys = object.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { - if (! this->m->linearized) - { + iter != keys.end(); + ++iter) { + if (!this->m->linearized) { enqueueObject(object.getKey(*iter)); } } - } - else - { + } else { // ignore } } @@ -1351,73 +1372,62 @@ QPDFWriter::enqueueObject(QPDFObjectHandle object) void QPDFWriter::unparseChild(QPDFObjectHandle child, int level, int flags) { - if (! this->m->linearized) - { + if (!this->m->linearized) { enqueueObject(child); } - if (child.isIndirect()) - { + if (child.isIndirect()) { QPDFObjGen old_og = child.getObjGen(); int new_id = this->m->obj_renumber[old_og]; writeString(QUtil::int_to_string(new_id)); writeString(" 0 R"); - } - else - { + } else { unparseObject(child, level, flags); } } void -QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, - qpdf_offset_t prev, int linearization_pass) +QPDFWriter::writeTrailer( + trailer_e which, + int size, + bool xref_stream, + qpdf_offset_t prev, + int linearization_pass) { QPDFObjectHandle trailer = getTrimmedTrailer(); - if (xref_stream) - { + if (xref_stream) { this->m->cur_data_key.clear(); - } - else - { + } else { writeString("trailer <<"); } writeStringQDF("\n"); - if (which == t_lin_second) - { + if (which == t_lin_second) { writeString(" /Size "); writeString(QUtil::int_to_string(size)); - } - else - { + } else { std::set keys = trailer.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; writeStringQDF(" "); writeStringNoQDF(" "); writeString(QPDF_Name::normalizeName(key)); writeString(" "); - if (key == "/Size") - { + if (key == "/Size") { writeString(QUtil::int_to_string(size)); - if (which == t_lin_first) - { + if (which == t_lin_first) { writeString(" /Prev "); qpdf_offset_t pos = this->m->pipeline->getCount(); writeString(QUtil::int_to_string(prev)); int nspaces = QIntC::to_int(pos - this->m->pipeline->getCount() + 21); - if (nspaces < 0) - { + if (nspaces < 0) { throw std::logic_error( "QPDFWriter: no padding required in trailer"); } writePad(nspaces); } - } - else - { + } else { unparseChild(trailer.getKey(key), 1, 0); } writeStringQDF("\n"); @@ -1427,15 +1437,11 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, // Write ID writeStringQDF(" "); writeString(" /ID ["); - if (linearization_pass == 1) - { + if (linearization_pass == 1) { std::string original_id1 = getOriginalID1(); - if (original_id1.empty()) - { + if (original_id1.empty()) { writeString("<00000000000000000000000000000000>"); - } - else - { + } else { // Write a string of zeroes equal in length to the // representation of the original ID. While writing the // original ID would have the same number of bytes, it @@ -1444,18 +1450,14 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, // length of the ID to 16 bytes. writeString("<"); size_t len = QPDF_String(original_id1).unparse(true).length() - 2; - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { writeString("0"); } writeString(">"); } writeString("<00000000000000000000000000000000>"); - } - else - { - if ((linearization_pass == 0) && (this->m->deterministic_id)) - { + } else { + if ((linearization_pass == 0) && (this->m->deterministic_id)) { computeDeterministicIDData(); } generateID(); @@ -1464,11 +1466,9 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, } writeString("]"); - if (which != t_lin_second) - { + if (which != t_lin_second) { // Write reference to encryption dictionary - if (this->m->encrypted) - { + if (this->m->encrypted) { writeString(" /Encrypt "); writeString(QUtil::int_to_string(this->m->encryption_dict_objid)); writeString(" 0 R"); @@ -1481,9 +1481,11 @@ QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream, } bool -QPDFWriter::willFilterStream(QPDFObjectHandle stream, - bool& compress_stream, bool& is_metadata, - PointerHolder* stream_data) +QPDFWriter::willFilterStream( + QPDFObjectHandle stream, + bool& compress_stream, + bool& is_metadata, + PointerHolder* stream_data) { compress_stream = false; is_metadata = false; @@ -1491,21 +1493,18 @@ QPDFWriter::willFilterStream(QPDFObjectHandle stream, QPDFObjGen old_og = stream.getObjGen(); QPDFObjectHandle stream_dict = stream.getDict(); - if (stream_dict.isDictionaryOfType("/Metadata")) - { + if (stream_dict.isDictionaryOfType("/Metadata")) { is_metadata = true; } - bool filter = (stream.isDataModified() || - this->m->compress_streams || - this->m->stream_decode_level); + bool filter = + (stream.isDataModified() || this->m->compress_streams || + this->m->stream_decode_level); bool filter_on_write = stream.getFilterOnWrite(); - if (! filter_on_write) - { + if (!filter_on_write) { QTC::TC("qpdf", "QPDFWriter getFilterOnWrite false"); filter = false; } - if (filter_on_write && this->m->compress_streams) - { + if (filter_on_write && this->m->compress_streams) { // Don't filter if the stream is already compressed with // FlateDecode. This way we don't make it worse if the // original file used a better Flate algorithm, and we @@ -1513,12 +1512,10 @@ QPDFWriter::willFilterStream(QPDFObjectHandle stream, // recompressing stuff. This can be overridden with // setRecompressFlate(true). QPDFObjectHandle filter_obj = stream_dict.getKey("/Filter"); - if ((! this->m->recompress_flate) && - (! stream.isDataModified()) && + if ((!this->m->recompress_flate) && (!stream.isDataModified()) && filter_obj.isName() && ((filter_obj.getName() == "/FlateDecode") || - (filter_obj.getName() == "/Fl"))) - { + (filter_obj.getName() == "/Fl"))) { QTC::TC("qpdf", "QPDFWriter not recompressing /FlateDecode"); filter = false; } @@ -1526,72 +1523,64 @@ QPDFWriter::willFilterStream(QPDFObjectHandle stream, bool normalize = false; bool uncompress = false; if (filter_on_write && is_metadata && - ((! this->m->encrypted) || (this->m->encrypt_metadata == false))) - { + ((!this->m->encrypted) || (this->m->encrypt_metadata == false))) { QTC::TC("qpdf", "QPDFWriter not compressing metadata"); filter = true; compress_stream = false; uncompress = true; - } - else if (filter_on_write && this->m->normalize_content && - this->m->normalized_streams.count(old_og)) - { + } else if ( + filter_on_write && this->m->normalize_content && + this->m->normalized_streams.count(old_og)) { normalize = true; filter = true; - } - else if (filter_on_write && filter && this->m->compress_streams) - { + } else if (filter_on_write && filter && this->m->compress_streams) { compress_stream = true; QTC::TC("qpdf", "QPDFWriter compressing uncompressed stream"); } bool filtered = false; - for (int attempt = 1; attempt <= 2; ++attempt) - { + for (int attempt = 1; attempt <= 2; ++attempt) { pushPipeline(new Pl_Buffer("stream data")); PipelinePopper pp_stream_data(this, stream_data); activatePipelineStack(pp_stream_data); - filtered = - stream.pipeStreamData( - this->m->pipeline, - (((filter && normalize) ? qpdf_ef_normalize : 0) | - ((filter && compress_stream) ? qpdf_ef_compress : 0)), - (filter - ? (uncompress ? qpdf_dl_all : this->m->stream_decode_level) - : qpdf_dl_none), false, (attempt == 1)); - if (filter && (! filtered)) - { + filtered = stream.pipeStreamData( + this->m->pipeline, + (((filter && normalize) ? qpdf_ef_normalize : 0) | + ((filter && compress_stream) ? qpdf_ef_compress : 0)), + (filter ? (uncompress ? qpdf_dl_all : this->m->stream_decode_level) + : qpdf_dl_none), + false, + (attempt == 1)); + if (filter && (!filtered)) { // Try again filter = false; - } - else - { + } else { break; } } - if (! filtered) - { + if (!filtered) { compress_stream = false; } return filtered; } void -QPDFWriter::unparseObject(QPDFObjectHandle object, int level, - int flags, size_t stream_length, - bool compress) +QPDFWriter::unparseObject( + QPDFObjectHandle object, + int level, + int flags, + size_t stream_length, + bool compress) { QPDFObjGen old_og = object.getObjGen(); int child_flags = flags & ~f_stream; std::string indent; - for (int i = 0; i < level; ++i) - { + for (int i = 0; i < level; ++i) { indent += " "; } - if (object.isArray()) - { + if (object.isArray()) { // Note: PDF spec 1.4 implementation note 121 states that // Acrobat requires a space after the [ in the /H key of the // linearization parameter dictionary. We'll do this @@ -1600,8 +1589,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, writeString("["); writeStringQDF("\n"); int n = object.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { writeStringQDF(indent); writeStringQDF(" "); writeStringNoQDF(" "); @@ -1611,9 +1599,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, writeStringQDF(indent); writeStringNoQDF(" "); writeString("]"); - } - else if (object.isDictionary()) - { + } else if (object.isDictionary()) { // Make a shallow copy of this object so we can modify it // safely without affecting the original. This code has logic // to skip certain keys in agreement with prepareFileForWrite @@ -1650,51 +1636,42 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, QPDFObjectHandle extensions; if ((old_og.getObj() != 0) && - (old_og == this->m->pdf.getRoot().getObjGen())) - { + (old_og == this->m->pdf.getRoot().getObjGen())) { is_root = true; if (object.hasKey("/Extensions") && - object.getKey("/Extensions").isDictionary()) - { + object.getKey("/Extensions").isDictionary()) { extensions = object.getKey("/Extensions"); } } - if (extensions.isInitialized()) - { + if (extensions.isInitialized()) { std::set keys = extensions.getKeys(); - if (keys.count("/ADBE") > 0) - { + if (keys.count("/ADBE") > 0) { have_extensions_adbe = true; keys.erase("/ADBE"); } - if (keys.size() > 0) - { + if (keys.size() > 0) { have_extensions_other = true; } } bool need_extensions_adbe = (this->m->final_extension_level > 0); - if (is_root) - { - if (need_extensions_adbe) - { - if (! (have_extensions_other || have_extensions_adbe)) - { + if (is_root) { + if (need_extensions_adbe) { + if (!(have_extensions_other || have_extensions_adbe)) { // We need Extensions and don't have it. Create // it here. - QTC::TC("qpdf", "QPDFWriter create Extensions", - this->m->qdf_mode ? 0 : 1); + QTC::TC( + "qpdf", + "QPDFWriter create Extensions", + this->m->qdf_mode ? 0 : 1); extensions = QPDFObjectHandle::newDictionary(); object.replaceKey("/Extensions", extensions); } - } - else if (! have_extensions_other) - { + } else if (!have_extensions_other) { // We have Extensions dictionary and don't want one. - if (have_extensions_adbe) - { + if (have_extensions_adbe) { QTC::TC("qpdf", "QPDFWriter remove existing Extensions"); object.removeKey("/Extensions"); extensions = QPDFObjectHandle(); // uninitialized @@ -1702,23 +1679,18 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, } } - if (extensions.isInitialized()) - { + if (extensions.isInitialized()) { QTC::TC("qpdf", "QPDFWriter preserve Extensions"); QPDFObjectHandle adbe = extensions.getKey("/ADBE"); if (adbe.isDictionary() && - adbe.getKey("/BaseVersion").isNameAndEquals( - "/" + this->m->final_pdf_version) && + adbe.getKey("/BaseVersion") + .isNameAndEquals("/" + this->m->final_pdf_version) && adbe.getKey("/ExtensionLevel").isInteger() && (adbe.getKey("/ExtensionLevel").getIntValue() == - this->m->final_extension_level)) - { + this->m->final_extension_level)) { QTC::TC("qpdf", "QPDFWriter preserve ADBE"); - } - else - { - if (need_extensions_adbe) - { + } else { + if (need_extensions_adbe) { extensions.replaceKey( "/ADBE", QPDFObjectHandle::parse( @@ -1727,9 +1699,7 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, QUtil::int_to_string( this->m->final_extension_level) + " >>")); - } - else - { + } else { QTC::TC("qpdf", "QPDFWriter remove ADBE"); extensions.removeKey("/ADBE"); } @@ -1738,53 +1708,41 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, // Stream dictionaries. - if (flags & f_stream) - { + if (flags & f_stream) { // Suppress /Length since we will write it manually object.removeKey("/Length"); // If /DecodeParms is an empty list, remove it. if (object.getKey("/DecodeParms").isArray() && - (0 == object.getKey("/DecodeParms").getArrayNItems())) - { + (0 == object.getKey("/DecodeParms").getArrayNItems())) { QTC::TC("qpdf", "QPDFWriter remove empty DecodeParms"); object.removeKey("/DecodeParms"); } - if (flags & f_filtered) - { + if (flags & f_filtered) { // We will supply our own filter and decode // parameters. object.removeKey("/Filter"); object.removeKey("/DecodeParms"); - } - else - { + } else { // Make sure, no matter what else we have, that we // don't have /Crypt in the output filters. QPDFObjectHandle filter = object.getKey("/Filter"); QPDFObjectHandle decode_parms = object.getKey("/DecodeParms"); - if (filter.isOrHasName("/Crypt")) - { - if (filter.isName()) - { + if (filter.isOrHasName("/Crypt")) { + if (filter.isName()) { object.removeKey("/Filter"); object.removeKey("/DecodeParms"); - } - else - { + } else { int idx = -1; - for (int i = 0; i < filter.getArrayNItems(); ++i) - { + for (int i = 0; i < filter.getArrayNItems(); ++i) { QPDFObjectHandle item = filter.getArrayItem(i); - if (item.isNameAndEquals("/Crypt")) - { + if (item.isNameAndEquals("/Crypt")) { idx = i; break; } } - if (idx >= 0) - { + if (idx >= 0) { // If filter is an array, then the code in // QPDF_Stream has already verified that // DecodeParms and Filters are arrays of @@ -1805,8 +1763,8 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, std::set keys = object.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; writeStringQDF(indent); @@ -1814,40 +1772,33 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, writeStringNoQDF(" "); writeString(QPDF_Name::normalizeName(key)); writeString(" "); - if (key == "/Contents" && - object.isDictionaryOfType("/Sig") && - object.hasKey("/ByteRange")) - { + if (key == "/Contents" && object.isDictionaryOfType("/Sig") && + object.hasKey("/ByteRange")) { QTC::TC("qpdf", "QPDFWriter no encryption sig contents"); - unparseChild(object.getKey(key), level + 1, - child_flags | f_hex_string | f_no_encryption); - } - else - { + unparseChild( + object.getKey(key), + level + 1, + child_flags | f_hex_string | f_no_encryption); + } else { unparseChild(object.getKey(key), level + 1, child_flags); } writeStringQDF("\n"); } - if (flags & f_stream) - { + if (flags & f_stream) { writeStringQDF(indent); writeStringQDF(" "); writeString(" /Length "); - if (this->m->direct_stream_lengths) - { + if (this->m->direct_stream_lengths) { writeString(QUtil::uint_to_string(stream_length)); - } - else - { + } else { writeString( QUtil::int_to_string(this->m->cur_stream_length_id)); writeString(" 0 R"); } writeStringQDF("\n"); - if (compress && (flags & f_filtered)) - { + if (compress && (flags & f_filtered)) { writeStringQDF(indent); writeStringQDF(" "); writeString(" /Filter /FlateDecode"); @@ -1858,13 +1809,10 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, writeStringQDF(indent); writeStringNoQDF(" "); writeString(">>"); - } - else if (object.isStream()) - { + } else if (object.isStream()) { // Write stream data to a buffer. int new_id = this->m->obj_renumber[old_og]; - if (! this->m->direct_stream_lengths) - { + if (!this->m->direct_stream_lengths) { this->m->cur_stream_length_id = new_id + 1; } @@ -1872,22 +1820,20 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, bool compress_stream = false; bool is_metadata = false; PointerHolder stream_data; - if (willFilterStream(object, compress_stream, - is_metadata, &stream_data)) - { + if (willFilterStream( + object, compress_stream, is_metadata, &stream_data)) { flags |= f_filtered; } QPDFObjectHandle stream_dict = object.getDict(); this->m->cur_stream_length = stream_data->getSize(); - if (is_metadata && this->m->encrypted && (! this->m->encrypt_metadata)) - { + if (is_metadata && this->m->encrypted && (!this->m->encrypt_metadata)) { // Don't encrypt stream data for the metadata stream this->m->cur_data_key.clear(); } adjustAESStreamLength(this->m->cur_stream_length); - unparseObject(stream_dict, 0, flags, - this->m->cur_stream_length, compress_stream); + unparseObject( + stream_dict, 0, flags, this->m->cur_stream_length, compress_stream); unsigned char last_char = '\0'; writeString("\nstream\n"); { @@ -1898,75 +1844,60 @@ QPDFWriter::unparseObject(QPDFObjectHandle object, int level, } if (this->m->newline_before_endstream || - (this->m->qdf_mode && (last_char != '\n'))) - { + (this->m->qdf_mode && (last_char != '\n'))) { writeString("\n"); this->m->added_newline = true; - } - else - { + } else { this->m->added_newline = false; } writeString("endstream"); - } - else if (object.isString()) - { + } else if (object.isString()) { std::string val; - if (this->m->encrypted && - (! (flags & f_in_ostream)) && - (! (flags & f_no_encryption)) && - (! this->m->cur_data_key.empty())) - { + if (this->m->encrypted && (!(flags & f_in_ostream)) && + (!(flags & f_no_encryption)) && (!this->m->cur_data_key.empty())) { val = object.getStringValue(); - if (this->m->encrypt_use_aes) - { + if (this->m->encrypt_use_aes) { Pl_Buffer bufpl("encrypted string"); Pl_AES_PDF pl( - "aes encrypt string", &bufpl, true, + "aes encrypt string", + &bufpl, + true, QUtil::unsigned_char_pointer(this->m->cur_data_key), this->m->cur_data_key.length()); pl.write(QUtil::unsigned_char_pointer(val), val.length()); pl.finish(); auto buf = bufpl.getBufferSharedPointer(); - val = QPDF_String( - std::string(reinterpret_cast(buf->getBuffer()), - buf->getSize())).unparse(true); - } - else - { + val = QPDF_String(std::string( + reinterpret_cast(buf->getBuffer()), + buf->getSize())) + .unparse(true); + } else { auto tmp_ph = QUtil::make_unique_cstr(val); char* tmp = tmp_ph.get(); size_t vlen = val.length(); - RC4 rc4(QUtil::unsigned_char_pointer(this->m->cur_data_key), - QIntC::to_int(this->m->cur_data_key.length())); + RC4 rc4( + QUtil::unsigned_char_pointer(this->m->cur_data_key), + QIntC::to_int(this->m->cur_data_key.length())); rc4.process(QUtil::unsigned_char_pointer(tmp), vlen); val = QPDF_String(std::string(tmp, vlen)).unparse(); } - } - else if (flags & f_hex_string) - { + } else if (flags & f_hex_string) { val = QPDF_String(object.getStringValue()).unparse(true); - } - else - { + } else { val = object.unparseResolved(); } writeString(val); - } - else - { + } else { writeString(object.unparseResolved()); } } void -QPDFWriter::writeObjectStreamOffsets(std::vector& offsets, - int first_obj) +QPDFWriter::writeObjectStreamOffsets( + std::vector& offsets, int first_obj) { - for (size_t i = 0; i < offsets.size(); ++i) - { - if (i != 0) - { + for (size_t i = 0; i < offsets.size(); ++i) { + if (i != 0) { writeStringQDF("\n"); writeStringNoQDF(" "); } @@ -1996,22 +1927,18 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) PointerHolder stream_buffer; int first_obj = -1; bool compressed = false; - for (int pass = 1; pass <= 2; ++pass) - { + for (int pass = 1; pass <= 2; ++pass) { // stream_buffer will be initialized only for pass 2 PipelinePopper pp_ostream(this, &stream_buffer); - if (pass == 1) - { + if (pass == 1) { pushDiscardFilter(pp_ostream); - } - else - { + } else { // Adjust offsets to skip over comment before first object first = offsets.at(0); for (std::vector::iterator iter = offsets.begin(); - iter != offsets.end(); ++iter) - { + iter != offsets.end(); + ++iter) { *iter -= first; } @@ -2028,12 +1955,10 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) Pipeline* next = pushPipeline(new Pl_Buffer("object stream")); if ((this->m->compress_streams || (this->m->stream_decode_level == qpdf_dl_none)) && - (! this->m->qdf_mode)) - { + (!this->m->qdf_mode)) { compressed = true; - next = pushPipeline( - new Pl_Flate("compress object stream", next, - Pl_Flate::a_deflate)); + next = pushPipeline(new Pl_Flate( + "compress object stream", next, Pl_Flate::a_deflate)); } activatePipelineStack(pp_ostream); writeObjectStreamOffsets(offsets, first_obj); @@ -2043,48 +1968,42 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) for (std::set::iterator iter = this->m->object_stream_to_objects[old_id].begin(); iter != this->m->object_stream_to_objects[old_id].end(); - ++iter, ++count) - { + ++iter, ++count) { QPDFObjGen obj = *iter; int new_obj = this->m->obj_renumber[obj]; - if (first_obj == -1) - { + if (first_obj == -1) { first_obj = new_obj; } - if (this->m->qdf_mode) - { - writeString("%% Object stream: object " + - QUtil::int_to_string(new_obj) + ", index " + - QUtil::int_to_string(count)); - if (! this->m->suppress_original_object_ids) - { - writeString("; original object ID: " + - QUtil::int_to_string(obj.getObj())); + if (this->m->qdf_mode) { + writeString( + "%% Object stream: object " + + QUtil::int_to_string(new_obj) + ", index " + + QUtil::int_to_string(count)); + if (!this->m->suppress_original_object_ids) { + writeString( + "; original object ID: " + + QUtil::int_to_string(obj.getObj())); // For compatibility, only write the generation if // non-zero. While object streams only allow // objects with generation 0, if we are generating // object streams, the old object could have a // non-zero generation. - if (obj.getGen() != 0) - { + if (obj.getGen() != 0) { QTC::TC("qpdf", "QPDFWriter original obj non-zero gen"); writeString(" " + QUtil::int_to_string(obj.getGen())); } } writeString("\n"); } - if (pass == 1) - { + if (pass == 1) { offsets.push_back(this->m->pipeline->getCount()); // To avoid double-counting objects being written in // object streams for progress reporting, decrement in // pass 1. indicateProgress(true, false); } - QPDFObjectHandle obj_to_write = - this->m->pdf.getObjectByObjGen(obj); - if (obj_to_write.isStream()) - { + QPDFObjectHandle obj_to_write = this->m->pdf.getObjectByObjGen(obj); + if (obj_to_write.isStream()) { // This condition occurred in a fuzz input. Ideally we // should block it at at parse time, but it's not // clear to me how to construct a case for this. @@ -2110,20 +2029,17 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) adjustAESStreamLength(length); writeString(" /Length " + QUtil::uint_to_string(length)); writeStringQDF("\n "); - if (compressed) - { + if (compressed) { writeString(" /Filter /FlateDecode"); } writeString(" /N " + QUtil::uint_to_string(offsets.size())); writeStringQDF("\n "); writeString(" /First " + QUtil::int_to_string(first)); - if (! object.isNull()) - { + if (!object.isNull()) { // If the original object has an /Extends key, preserve it. QPDFObjectHandle dict = object.getDict(); QPDFObjectHandle extends = dict.getKey("/Extends"); - if (extends.isIndirect()) - { + if (extends.isIndirect()) { QTC::TC("qpdf", "QPDFWriter copy Extends"); writeStringQDF("\n "); writeString(" /Extends "); @@ -2133,8 +2049,7 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) writeStringQDF("\n"); writeStringNoQDF(" "); writeString(">>\nstream\n"); - if (this->m->encrypted) - { + if (this->m->encrypted) { QTC::TC("qpdf", "QPDFWriter encrypt object stream"); } { @@ -2142,8 +2057,7 @@ QPDFWriter::writeObjectStream(QPDFObjectHandle object) pushEncryptionFilter(pp_enc); writeBuffer(stream_buffer); } - if (this->m->newline_before_endstream) - { + if (this->m->newline_before_endstream) { writeString("\n"); } writeString("endstream"); @@ -2156,61 +2070,48 @@ QPDFWriter::writeObject(QPDFObjectHandle object, int object_stream_index) { QPDFObjGen old_og = object.getObjGen(); - if ((object_stream_index == -1) && - (old_og.getGen() == 0) && - (this->m->object_stream_to_objects.count(old_og.getObj()))) - { + if ((object_stream_index == -1) && (old_og.getGen() == 0) && + (this->m->object_stream_to_objects.count(old_og.getObj()))) { writeObjectStream(object); return; } indicateProgress(false, false); int new_id = this->m->obj_renumber[old_og]; - if (this->m->qdf_mode) - { - if (this->m->page_object_to_seq.count(old_og)) - { + if (this->m->qdf_mode) { + if (this->m->page_object_to_seq.count(old_og)) { writeString("%% Page "); writeString( - QUtil::int_to_string( - this->m->page_object_to_seq[old_og])); + QUtil::int_to_string(this->m->page_object_to_seq[old_og])); writeString("\n"); } - if (this->m->contents_to_page_seq.count(old_og)) - { + if (this->m->contents_to_page_seq.count(old_og)) { writeString("%% Contents for page "); writeString( - QUtil::int_to_string( - this->m->contents_to_page_seq[old_og])); + QUtil::int_to_string(this->m->contents_to_page_seq[old_og])); writeString("\n"); } } - if (object_stream_index == -1) - { - if (this->m->qdf_mode && (! this->m->suppress_original_object_ids)) - { - writeString("%% Original object ID: " + - QUtil::int_to_string(object.getObjectID()) + " " + - QUtil::int_to_string(object.getGeneration()) + "\n"); + if (object_stream_index == -1) { + if (this->m->qdf_mode && (!this->m->suppress_original_object_ids)) { + writeString( + "%% Original object ID: " + + QUtil::int_to_string(object.getObjectID()) + " " + + QUtil::int_to_string(object.getGeneration()) + "\n"); } openObject(new_id); setDataKey(new_id); unparseObject(object, 0, 0); this->m->cur_data_key.clear(); closeObject(new_id); - } - else - { + } else { unparseObject(object, 0, f_in_ostream); writeString("\n"); } - if ((! this->m->direct_stream_lengths) && object.isStream()) - { - if (this->m->qdf_mode) - { - if (this->m->added_newline) - { + if ((!this->m->direct_stream_lengths) && object.isStream()) { + if (this->m->qdf_mode) { + if (this->m->added_newline) { writeString("%QDF: ignore_newline\n"); } } @@ -2224,12 +2125,9 @@ std::string QPDFWriter::getOriginalID1() { QPDFObjectHandle trailer = this->m->pdf.getTrailer(); - if (trailer.hasKey("/ID")) - { + if (trailer.hasKey("/ID")) { return trailer.getKey("/ID").getArrayItem(0).getStringValue(); - } - else - { + } else { return ""; } } @@ -2240,8 +2138,7 @@ QPDFWriter::generateID() // Generate the ID lazily so that we can handle the user's // preference to use static or deterministic ID generation. - if (! this->m->id2.empty()) - { + if (!this->m->id2.empty()) { return; } @@ -2249,18 +2146,28 @@ QPDFWriter::generateID() std::string result; - if (this->m->static_id) - { + if (this->m->static_id) { // For test suite use only... - static unsigned char tmp[] = {0x31, 0x41, 0x59, 0x26, - 0x53, 0x58, 0x97, 0x93, - 0x23, 0x84, 0x62, 0x64, - 0x33, 0x83, 0x27, 0x95, - 0x00}; + static unsigned char tmp[] = { + 0x31, + 0x41, + 0x59, + 0x26, + 0x53, + 0x58, + 0x97, + 0x93, + 0x23, + 0x84, + 0x62, + 0x64, + 0x33, + 0x83, + 0x27, + 0x95, + 0x00}; result = reinterpret_cast(tmp); - } - else - { + } else { // The PDF specification has guidelines for creating IDs, but // it states clearly that the only thing that's really // important is that it is very likely to be unique. We can't @@ -2275,10 +2182,8 @@ QPDFWriter::generateID() // ID regardless of the output file's name. std::string seed; - if (this->m->deterministic_id) - { - if (this->m->deterministic_id_data.empty()) - { + if (this->m->deterministic_id) { + if (this->m->deterministic_id_data.empty()) { QTC::TC("qpdf", "QPDFWriter deterministic with no data"); throw std::logic_error( "INTERNAL ERROR: QPDFWriter::generateID has no" @@ -2287,24 +2192,20 @@ QPDFWriter::generateID() " together."); } seed += this->m->deterministic_id_data; - } - else - { + } else { seed += QUtil::int_to_string(QUtil::get_current_time()); seed += this->m->filename; seed += " "; } seed += " QPDF "; - if (trailer.hasKey("/Info")) - { + if (trailer.hasKey("/Info")) { QPDFObjectHandle info = trailer.getKey("/Info"); std::set keys = info.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { QPDFObjectHandle obj = info.getKey(*iter); - if (obj.isString()) - { + if (obj.isString()) { seed += " "; seed += obj.getStringValue(); } @@ -2315,8 +2216,8 @@ QPDFWriter::generateID() m.encodeString(seed.c_str()); MD5::Digest digest; m.digest(digest); - result = std::string(reinterpret_cast(digest), - sizeof(MD5::Digest)); + result = + std::string(reinterpret_cast(digest), sizeof(MD5::Digest)); } // If /ID already exists, follow the spec: use the original first @@ -2326,8 +2227,7 @@ QPDFWriter::generateID() this->m->id2 = result; // Note: keep /ID from old file even if --static-id was given. this->m->id1 = getOriginalID1(); - if (this->m->id1.empty()) - { + if (this->m->id1.empty()) { this->m->id1 = this->m->id2; } } @@ -2340,28 +2240,23 @@ QPDFWriter::initializeSpecialStreams() std::vector pages = this->m->pdf.getAllPages(); int num = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFObjectHandle& page = *iter; this->m->page_object_to_seq[page.getObjGen()] = ++num; QPDFObjectHandle contents = page.getKey("/Contents"); std::vector contents_objects; - if (contents.isArray()) - { + if (contents.isArray()) { int n = contents.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { contents_objects.push_back( contents.getArrayItem(i).getObjGen()); } - } - else if (contents.isStream()) - { + } else if (contents.isStream()) { contents_objects.push_back(contents.getObjGen()); } - for (auto const& c: contents_objects) - { + for (auto const& c : contents_objects) { this->m->contents_to_page_seq[c] = num; this->m->normalized_streams.insert(c); } @@ -2373,8 +2268,7 @@ QPDFWriter::preserveObjectStreams() { std::map omap; QPDF::Writer::getObjectStreamData(this->m->pdf, omap); - if (omap.empty()) - { + if (omap.empty()) { return; } // Our object_to_object_stream map has to map ObjGen -> ObjGen @@ -2388,23 +2282,20 @@ QPDFWriter::preserveObjectStreams() // source PDF, it also prevents unreferenced objects from being // included. std::set eligible; - if (! this->m->preserve_unreferenced_objects) - { + if (!this->m->preserve_unreferenced_objects) { std::vector eligible_v = QPDF::Writer::getCompressibleObjGens(this->m->pdf); eligible = std::set(eligible_v.begin(), eligible_v.end()); } - QTC::TC("qpdf", "QPDFWriter preserve object streams", - this->m->preserve_unreferenced_objects ? 0 : 1); - for (auto iter: omap) - { + QTC::TC( + "qpdf", + "QPDFWriter preserve object streams", + this->m->preserve_unreferenced_objects ? 0 : 1); + for (auto iter : omap) { QPDFObjGen og(iter.first, 0); - if (eligible.count(og) || this->m->preserve_unreferenced_objects) - { + if (eligible.count(og) || this->m->preserve_unreferenced_objects) { this->m->object_to_object_stream[og] = iter.second; - } - else - { + } else { QTC::TC("qpdf", "QPDFWriter exclude from object stream"); } } @@ -2426,35 +2317,31 @@ QPDFWriter::generateObjectStreams() std::vector eligible = QPDF::Writer::getCompressibleObjGens(this->m->pdf); size_t n_object_streams = (eligible.size() + 99U) / 100U; - if (n_object_streams == 0) - { + if (n_object_streams == 0) { return; } size_t n_per = eligible.size() / n_object_streams; - if (n_per * n_object_streams < eligible.size()) - { + if (n_per * n_object_streams < eligible.size()) { ++n_per; } unsigned int n = 0; int cur_ostream = 0; for (std::vector::const_iterator iter = eligible.begin(); - iter != eligible.end(); ++iter) - { - if ((n % n_per) == 0) - { - if (n > 0) - { + iter != eligible.end(); + ++iter) { + if ((n % n_per) == 0) { + if (n > 0) { QTC::TC("qpdf", "QPDFWriter generate >1 ostream"); } n = 0; } - if (n == 0) - { + if (n == 0) { // Construct a new null object as the "original" object // stream. The rest of the code knows that this means // we're creating the object stream from scratch. - cur_ostream = this->m->pdf.makeIndirectObject( - QPDFObjectHandle::newNull()).getObjectID(); + cur_ostream = + this->m->pdf.makeIndirectObject(QPDFObjectHandle::newNull()) + .getObjectID(); } this->m->object_to_object_stream[*iter] = cur_ostream; ++n; @@ -2497,26 +2384,23 @@ QPDFWriter::prepareFileForWrite() this->m->pdf.fixDanglingReferences(true); QPDFObjectHandle root = this->m->pdf.getRoot(); - for (auto const& key: root.getKeys()) - { + for (auto const& key : root.getKeys()) { QPDFObjectHandle oh = root.getKey(key); - if ((key == "/Extensions") && (oh.isDictionary())) - { + if ((key == "/Extensions") && (oh.isDictionary())) { bool extensions_indirect = false; - if (oh.isIndirect()) - { + if (oh.isIndirect()) { QTC::TC("qpdf", "QPDFWriter make Extensions direct"); extensions_indirect = true; oh = oh.shallowCopy(); root.replaceKey(key, oh); } - if (oh.hasKey("/ADBE")) - { + if (oh.hasKey("/ADBE")) { QPDFObjectHandle adbe = oh.getKey("/ADBE"); - if (adbe.isIndirect()) - { - QTC::TC("qpdf", "QPDFWriter make ADBE direct", - extensions_indirect ? 0 : 1); + if (adbe.isIndirect()) { + QTC::TC( + "qpdf", + "QPDFWriter make ADBE direct", + extensions_indirect ? 0 : 1); adbe.makeDirect(); oh.replaceKey("/ADBE", adbe); } @@ -2528,84 +2412,68 @@ QPDFWriter::prepareFileForWrite() void QPDFWriter::doWriteSetup() { - if (this->m->did_write_setup) - { + if (this->m->did_write_setup) { return; } this->m->did_write_setup = true; // Do preliminary setup - if (this->m->linearized) - { + if (this->m->linearized) { this->m->qdf_mode = false; } - if (this->m->pclm) - { + if (this->m->pclm) { this->m->stream_decode_level = qpdf_dl_none; this->m->compress_streams = false; this->m->encrypted = false; } - if (this->m->qdf_mode) - { - if (! this->m->normalize_content_set) - { + if (this->m->qdf_mode) { + if (!this->m->normalize_content_set) { this->m->normalize_content = true; } - if (! this->m->compress_streams_set) - { + if (!this->m->compress_streams_set) { this->m->compress_streams = false; } - if (! this->m->stream_decode_level_set) - { + if (!this->m->stream_decode_level_set) { this->m->stream_decode_level = qpdf_dl_generalized; } } - if (this->m->encrypted) - { + if (this->m->encrypted) { // Encryption has been explicitly set this->m->preserve_encryption = false; - } - else if (this->m->normalize_content || - this->m->stream_decode_level || - this->m->pclm || - this->m->qdf_mode) - { + } else if ( + this->m->normalize_content || this->m->stream_decode_level || + this->m->pclm || this->m->qdf_mode) { // Encryption makes looking at contents pretty useless. If // the user explicitly encrypted though, we still obey that. this->m->preserve_encryption = false; } - if (this->m->preserve_encryption) - { + if (this->m->preserve_encryption) { copyEncryptionParameters(this->m->pdf); } - if (! this->m->forced_pdf_version.empty()) - { + if (!this->m->forced_pdf_version.empty()) { int major = 0; int minor = 0; parseVersion(this->m->forced_pdf_version, major, minor); - disableIncompatibleEncryption(major, minor, - this->m->forced_extension_level); - if (compareVersions(major, minor, 1, 5) < 0) - { + disableIncompatibleEncryption( + major, minor, this->m->forced_extension_level); + if (compareVersions(major, minor, 1, 5) < 0) { QTC::TC("qpdf", "QPDFWriter forcing object stream disable"); this->m->object_stream_mode = qpdf_o_disable; } } if (this->m->qdf_mode || this->m->normalize_content || - this->m->stream_decode_level) - { + this->m->stream_decode_level) { initializeSpecialStreams(); } - if (this->m->qdf_mode) - { + if (this->m->qdf_mode) { // Generate indirect stream lengths for qdf mode since fix-qdf // uses them for storing recomputed stream length data. // Certain streams such as object streams, xref streams, and @@ -2613,50 +2481,45 @@ QPDFWriter::doWriteSetup() this->m->direct_stream_lengths = false; } - switch (this->m->object_stream_mode) - { - case qpdf_o_disable: + switch (this->m->object_stream_mode) { + case qpdf_o_disable: // no action required break; - case qpdf_o_preserve: + case qpdf_o_preserve: preserveObjectStreams(); break; - case qpdf_o_generate: + case qpdf_o_generate: generateObjectStreams(); break; // no default so gcc will warn for missing case tag } - if (this->m->linearized) - { + if (this->m->linearized) { // Page dictionaries are not allowed to be compressed objects. std::vector pages = this->m->pdf.getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFObjectHandle& page = *iter; QPDFObjGen og = page.getObjGen(); - if (this->m->object_to_object_stream.count(og)) - { + if (this->m->object_to_object_stream.count(og)) { QTC::TC("qpdf", "QPDFWriter uncompressing page dictionary"); this->m->object_to_object_stream.erase(og); } } } - if (this->m->linearized || this->m->encrypted) - { + if (this->m->linearized || this->m->encrypted) { // The document catalog is not allowed to be compressed in // linearized files either. It also appears that Adobe Reader // 8.0.0 has a bug that prevents it from being able to handle // encrypted files with compressed document catalogs, so we // disable them in that case as well. QPDFObjGen og = this->m->pdf.getRoot().getObjGen(); - if (this->m->object_to_object_stream.count(og)) - { + if (this->m->object_to_object_stream.count(og)) { QTC::TC("qpdf", "QPDFWriter uncompressing root"); this->m->object_to_object_stream.erase(og); } @@ -2665,28 +2528,26 @@ QPDFWriter::doWriteSetup() // Generate reverse mapping from object stream to objects for (std::map::iterator iter = this->m->object_to_object_stream.begin(); - iter != this->m->object_to_object_stream.end(); ++iter) - { + iter != this->m->object_to_object_stream.end(); + ++iter) { QPDFObjGen obj = (*iter).first; int stream = (*iter).second; this->m->object_stream_to_objects[stream].insert(obj); - this->m->max_ostream_index = - std::max(this->m->max_ostream_index, - QIntC::to_int( - this->m->object_stream_to_objects[stream].size()) - 1); + this->m->max_ostream_index = std::max( + this->m->max_ostream_index, + QIntC::to_int(this->m->object_stream_to_objects[stream].size()) - + 1); } - if (! this->m->object_stream_to_objects.empty()) - { + if (!this->m->object_stream_to_objects.empty()) { setMinimumPDFVersion("1.5"); } - setMinimumPDFVersion(this->m->pdf.getPDFVersion(), - this->m->pdf.getExtensionLevel()); + setMinimumPDFVersion( + this->m->pdf.getPDFVersion(), this->m->pdf.getExtensionLevel()); this->m->final_pdf_version = this->m->min_pdf_version; this->m->final_extension_level = this->m->min_extension_level; - if (! this->m->forced_pdf_version.empty()) - { + if (!this->m->forced_pdf_version.empty()) { QTC::TC("qpdf", "QPDFWriter using forced PDF version"); this->m->final_pdf_version = this->m->forced_pdf_version; this->m->final_extension_level = this->m->forced_extension_level; @@ -2706,23 +2567,18 @@ QPDFWriter::write() prepareFileForWrite(); - if (this->m->linearized) - { + if (this->m->linearized) { writeLinearized(); - } - else - { + } else { writeStandard(); } this->m->pipeline->finish(); - if (this->m->close_file) - { + if (this->m->close_file) { fclose(this->m->file); } this->m->file = 0; - if (this->m->buffer_pipeline) - { + if (this->m->buffer_pipeline) { this->m->output_buffer = this->m->buffer_pipeline->getBuffer(); this->m->buffer_pipeline = 0; } @@ -2741,10 +2597,9 @@ QPDFWriter::getWrittenXRefTable() std::map result; for (std::map::iterator iter = this->m->xref.begin(); - iter != this->m->xref.end(); ++iter) - { - if (iter->first != 0 && iter->second.getType() != 0) - { + iter != this->m->xref.end(); + ++iter) { + if (iter->first != 0 && iter->second.getType() != 0) { result[QPDFObjGen(iter->first, 0)] = iter->second; } } @@ -2756,8 +2611,8 @@ void QPDFWriter::enqueuePart(std::vector& part) { for (std::vector::iterator iter = part.begin(); - iter != part.end(); ++iter) - { + iter != part.end(); + ++iter) { enqueueObject(*iter); } } @@ -2769,8 +2624,8 @@ QPDFWriter::writeEncryptionDictionary() writeString("<<"); for (std::map::iterator iter = this->m->encryption_dictionary.begin(); - iter != this->m->encryption_dictionary.end(); ++iter) - { + iter != this->m->encryption_dictionary.end(); + ++iter) { writeString(" "); writeString((*iter).first); writeString(" "); @@ -2792,13 +2647,10 @@ QPDFWriter::writeHeader() { writeString("%PDF-"); writeString(this->m->final_pdf_version); - if (this->m->pclm) - { + if (this->m->pclm) { // PCLm version writeString("\n%PCLm 1.0\n"); - } - else - { + } else { // This string of binary characters would not be valid UTF-8, so // it really should be treated as binary. writeString("\n%\xbf\xf7\xa2\xfe\n"); @@ -2819,9 +2671,13 @@ QPDFWriter::writeHintStream(int hint_id) int S = 0; int O = 0; QPDF::Writer::generateHintStream( - this->m->pdf, this->m->xref, this->m->lengths, + this->m->pdf, + this->m->xref, + this->m->lengths, this->m->obj_renumber_no_gen, - hint_buffer, S, O); + hint_buffer, + S, + O); openObject(hint_id); setDataKey(hint_id); @@ -2830,8 +2686,7 @@ QPDFWriter::writeHintStream(int hint_id) writeString("<< /Filter /FlateDecode /S "); writeString(QUtil::int_to_string(S)); - if (O) - { + if (O) { writeString(" /O "); writeString(QUtil::int_to_string(O)); } @@ -2840,8 +2695,7 @@ QPDFWriter::writeHintStream(int hint_id) writeString(QUtil::uint_to_string(hlen)); writeString(" >>\nstream\n"); - if (this->m->encrypted) - { + if (this->m->encrypted) { QTC::TC("qpdf", "QPDFWriter encrypted hint stream"); } unsigned char last_char = '\0'; @@ -2852,8 +2706,7 @@ QPDFWriter::writeHintStream(int hint_id) last_char = this->m->pipeline->getLastChar(); } - if (last_char != '\n') - { + if (last_char != '\n') { writeString("\n"); } writeString("endstream"); @@ -2870,10 +2723,17 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size) } qpdf_offset_t -QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, - qpdf_offset_t prev, bool suppress_offsets, - int hint_id, qpdf_offset_t hint_offset, - qpdf_offset_t hint_length, int linearization_pass) +QPDFWriter::writeXRefTable( + trailer_e which, + int first, + int last, + int size, + qpdf_offset_t prev, + bool suppress_offsets, + int hint_id, + qpdf_offset_t hint_offset, + qpdf_offset_t hint_length, + int linearization_pass) { writeString("xref\n"); writeString(QUtil::int_to_string(first)); @@ -2881,22 +2741,15 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, writeString(QUtil::int_to_string(last - first + 1)); qpdf_offset_t space_before_zero = this->m->pipeline->getCount(); writeString("\n"); - for (int i = first; i <= last; ++i) - { - if (i == 0) - { + for (int i = first; i <= last; ++i) { + if (i == 0) { writeString("0000000000 65535 f \n"); - } - else - { + } else { qpdf_offset_t offset = 0; - if (! suppress_offsets) - { + if (!suppress_offsets) { offset = this->m->xref[i].getOffset(); - if ((hint_id != 0) && - (i != hint_id) && - (offset >= hint_offset)) - { + if ((hint_id != 0) && (i != hint_id) && + (offset >= hint_offset)) { offset += hint_length; } } @@ -2910,31 +2763,56 @@ QPDFWriter::writeXRefTable(trailer_e which, int first, int last, int size, } qpdf_offset_t -QPDFWriter::writeXRefStream(int objid, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size) +QPDFWriter::writeXRefStream( + int objid, + int max_id, + qpdf_offset_t max_offset, + trailer_e which, + int first, + int last, + int size) { // There are too many extra arguments to replace overloaded // function with defaults in the header file...too much risk of // leaving something off. - return writeXRefStream(objid, max_id, max_offset, - which, first, last, size, 0, 0, 0, 0, false, 0); + return writeXRefStream( + objid, + max_id, + max_offset, + which, + first, + last, + size, + 0, + 0, + 0, + 0, + false, + 0); } qpdf_offset_t -QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, - trailer_e which, int first, int last, int size, - qpdf_offset_t prev, int hint_id, - qpdf_offset_t hint_offset, - qpdf_offset_t hint_length, - bool skip_compression, - int linearization_pass) +QPDFWriter::writeXRefStream( + int xref_id, + int max_id, + qpdf_offset_t max_offset, + trailer_e which, + int first, + int last, + int size, + qpdf_offset_t prev, + int hint_id, + qpdf_offset_t hint_offset, + qpdf_offset_t hint_length, + bool skip_compression, + int linearization_pass) { qpdf_offset_t xref_offset = this->m->pipeline->getCount(); qpdf_offset_t space_before_zero = xref_offset - 1; // field 1 contains offsets and object stream identifiers - unsigned int f1_size = std::max(bytesNeeded(max_offset + hint_length), - bytesNeeded(max_id)); + unsigned int f1_size = + std::max(bytesNeeded(max_offset + hint_length), bytesNeeded(max_id)); // field 2 contains object stream indices unsigned int f2_size = bytesNeeded(this->m->max_ostream_index); @@ -2949,11 +2827,9 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, bool compressed = false; if ((this->m->compress_streams || (this->m->stream_decode_level == qpdf_dl_none)) && - (! this->m->qdf_mode)) - { + (!this->m->qdf_mode)) { compressed = true; - if (! skip_compression) - { + if (!skip_compression) { // Write the stream dictionary for compression but don't // actually compress. This helps us with computation of // padding for pass 1 of linearization. @@ -2961,31 +2837,26 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, new Pl_Flate("compress xref", p, Pl_Flate::a_deflate)); } p = pushPipeline( - new Pl_PNGFilter( - "pngify xref", p, Pl_PNGFilter::a_encode, esize)); + new Pl_PNGFilter("pngify xref", p, Pl_PNGFilter::a_encode, esize)); } PointerHolder xref_data; { PipelinePopper pp_xref(this, &xref_data); activatePipelineStack(pp_xref); - for (int i = first; i <= last; ++i) - { + for (int i = first; i <= last; ++i) { QPDFXRefEntry& e = this->m->xref[i]; - switch (e.getType()) - { - case 0: + switch (e.getType()) { + case 0: writeBinary(0, 1); writeBinary(0, f1_size); writeBinary(0, f2_size); break; - case 1: + case 1: { qpdf_offset_t offset = e.getOffset(); - if ((hint_id != 0) && - (i != hint_id) && - (offset >= hint_offset)) - { + if ((hint_id != 0) && (i != hint_id) && + (offset >= hint_offset)) { offset += hint_length; } writeBinary(1, 1); @@ -2994,13 +2865,15 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, } break; - case 2: + case 2: writeBinary(2, 1); - writeBinary(QIntC::to_ulonglong(e.getObjStreamNumber()), f1_size); - writeBinary(QIntC::to_ulonglong(e.getObjStreamIndex()), f2_size); + writeBinary( + QIntC::to_ulonglong(e.getObjStreamNumber()), f1_size); + writeBinary( + QIntC::to_ulonglong(e.getObjStreamIndex()), f2_size); break; - default: + default: throw std::logic_error("invalid type writing xref stream"); break; } @@ -3013,23 +2886,22 @@ QPDFWriter::writeXRefStream(int xref_id, int max_id, qpdf_offset_t max_offset, writeString(" /Type /XRef"); writeStringQDF("\n "); writeString(" /Length " + QUtil::uint_to_string(xref_data->getSize())); - if (compressed) - { + if (compressed) { writeStringQDF("\n "); writeString(" /Filter /FlateDecode"); writeStringQDF("\n "); - writeString(" /DecodeParms << /Columns " + - QUtil::int_to_string(esize) + " /Predictor 12 >>"); + writeString( + " /DecodeParms << /Columns " + QUtil::int_to_string(esize) + + " /Predictor 12 >>"); } writeStringQDF("\n "); - writeString(" /W [ 1 " + - QUtil::int_to_string(f1_size) + " " + - QUtil::int_to_string(f2_size) + " ]"); - if (! ((first == 0) && (last == size - 1))) - { - writeString(" /Index [ " + - QUtil::int_to_string(first) + " " + - QUtil::int_to_string(last - first + 1) + " ]"); + writeString( + " /W [ 1 " + QUtil::int_to_string(f1_size) + " " + + QUtil::int_to_string(f2_size) + " ]"); + if (!((first == 0) && (last == size - 1))) { + writeString( + " /Index [ " + QUtil::int_to_string(first) + " " + + QUtil::int_to_string(last - first + 1) + " ]"); } writeTrailer(which, size, true, prev, linearization_pass); writeString("\nstream\n"); @@ -3054,8 +2926,8 @@ QPDFWriter::calculateXrefStreamPadding(qpdf_offset_t xref_bytes) } void -QPDFWriter::discardGeneration(std::map const& in, - std::map& out) +QPDFWriter::discardGeneration( + std::map const& in, std::map& out) { // There are deep assumptions in the linearization code in QPDF // that there is only one object with each object number; i.e., @@ -3071,10 +2943,9 @@ QPDFWriter::discardGeneration(std::map const& in, out.clear(); for (std::map::const_iterator iter = in.begin(); - iter != in.end(); ++iter) - { - if (out.count((*iter).first.getObj())) - { + iter != in.end(); + ++iter) { + if (out.count((*iter).first.getObj())) { throw std::runtime_error( "QPDF cannot currently linearize files that contain" " multiple objects with the same object ID and different" @@ -3093,24 +2964,22 @@ QPDFWriter::writeLinearized() { // Optimize file and enqueue objects in order - discardGeneration(this->m->object_to_object_stream, - this->m->object_to_object_stream_no_gen); + discardGeneration( + this->m->object_to_object_stream, + this->m->object_to_object_stream_no_gen); auto skip_stream_parameters = [this](QPDFObjectHandle& stream) { bool compress_stream; bool is_metadata; - if (willFilterStream(stream, compress_stream, is_metadata, nullptr)) - { + if (willFilterStream(stream, compress_stream, is_metadata, nullptr)) { return 2; - } - else - { + } else { return 1; } }; - this->m->pdf.optimize(this->m->object_to_object_stream_no_gen, - true, skip_stream_parameters); + this->m->pdf.optimize( + this->m->object_to_object_stream_no_gen, true, skip_stream_parameters); std::vector part4; std::vector part6; @@ -3118,8 +2987,13 @@ QPDFWriter::writeLinearized() std::vector part8; std::vector part9; QPDF::Writer::getLinearizedParts( - this->m->pdf, this->m->object_to_object_stream_no_gen, - part4, part6, part7, part8, part9); + this->m->pdf, + this->m->object_to_object_stream_no_gen, + part4, + part6, + part7, + part8, + part9); // Object number sequence: // @@ -3144,18 +3018,16 @@ QPDFWriter::writeLinearized() int after_second_half = 1 + second_half_uncompressed; this->m->next_objid = after_second_half; int second_half_xref = 0; - bool need_xref_stream = (! this->m->object_to_object_stream.empty()); - if (need_xref_stream) - { + bool need_xref_stream = (!this->m->object_to_object_stream.empty()); + if (need_xref_stream) { second_half_xref = this->m->next_objid++; } // Assign numbers to all compressed objects in the second half. std::vector* vecs2[] = {&part7, &part8, &part9}; - for (int i = 0; i < 3; ++i) - { + for (int i = 0; i < 3; ++i) { for (std::vector::iterator iter = (*vecs2[i]).begin(); - iter != (*vecs2[i]).end(); ++iter) - { + iter != (*vecs2[i]).end(); + ++iter) { assignCompressedObjectNumbers((*iter).getObjGen()); } } @@ -3166,15 +3038,13 @@ QPDFWriter::writeLinearized() int first_half_start = this->m->next_objid; int lindict_id = this->m->next_objid++; int first_half_xref = 0; - if (need_xref_stream) - { + if (need_xref_stream) { first_half_xref = this->m->next_objid++; } int part4_first_obj = this->m->next_objid; this->m->next_objid += QIntC::to_int(part4.size()); int after_part4 = this->m->next_objid; - if (this->m->encrypted) - { + if (this->m->encrypted) { this->m->encryption_dict_objid = this->m->next_objid++; } int hint_id = this->m->next_objid++; @@ -3183,11 +3053,10 @@ QPDFWriter::writeLinearized() int after_part6 = this->m->next_objid; // Assign numbers to all compressed objects in the first half std::vector* vecs1[] = {&part4, &part6}; - for (int i = 0; i < 2; ++i) - { + for (int i = 0; i < 2; ++i) { for (std::vector::iterator iter = (*vecs1[i]).begin(); - iter != (*vecs1[i]).end(); ++iter) - { + iter != (*vecs1[i]).end(); + ++iter) { assignCompressedObjectNumbers((*iter).getObjGen()); } } @@ -3206,32 +3075,26 @@ QPDFWriter::writeLinearized() this->m->next_objid = part4_first_obj; enqueuePart(part4); - if (this->m->next_objid != after_part4) - { + if (this->m->next_objid != after_part4) { // This can happen with very botched files as in the fuzzer // test. There are likely some faulty assumptions in // calculateLinearizationData - throw std::runtime_error( - "error encountered after" - " writing part 4 of linearized data"); + throw std::runtime_error("error encountered after" + " writing part 4 of linearized data"); } this->m->next_objid = part6_first_obj; enqueuePart(part6); - if (this->m->next_objid != after_part6) - { - throw std::runtime_error( - "error encountered after" - " writing part 6 of linearized data"); + if (this->m->next_objid != after_part6) { + throw std::runtime_error("error encountered after" + " writing part 6 of linearized data"); } this->m->next_objid = second_half_first_obj; enqueuePart(part7); enqueuePart(part8); enqueuePart(part9); - if (this->m->next_objid != after_second_half) - { - throw std::runtime_error( - "error encountered after" - " writing part 9 of linearized data"); + if (this->m->next_objid != after_second_half) { + throw std::runtime_error("error encountered after" + " writing part 9 of linearized data"); } qpdf_offset_t hint_length = 0; @@ -3242,25 +3105,18 @@ QPDFWriter::writeLinearized() FILE* lin_pass1_file = 0; auto pp_pass1 = make_pointer_holder(this); auto pp_md5 = make_pointer_holder(this); - for (int pass = 1; pass <= 2; ++pass) - { - if (pass == 1) - { - if (! this->m->lin_pass1_filename.empty()) - { - lin_pass1_file = - QUtil::safe_fopen( - this->m->lin_pass1_filename.c_str(), "wb"); + for (int pass = 1; pass <= 2; ++pass) { + if (pass == 1) { + if (!this->m->lin_pass1_filename.empty()) { + lin_pass1_file = QUtil::safe_fopen( + this->m->lin_pass1_filename.c_str(), "wb"); pushPipeline( new Pl_StdioFile("linearization pass1", lin_pass1_file)); activatePipelineStack(*pp_pass1); - } - else - { + } else { pushDiscardFilter(*pp_pass1); } - if (this->m->deterministic_id) - { + if (this->m->deterministic_id) { pushMD5Pipeline(*pp_md5); } } @@ -3280,8 +3136,7 @@ QPDFWriter::writeLinearized() qpdf_offset_t pos = this->m->pipeline->getCount(); openObject(lindict_id); writeString("<<"); - if (pass == 2) - { + if (pass == 2) { std::vector const& pages = this->m->pdf.getAllPages(); int first_page_object = @@ -3293,8 +3148,8 @@ QPDFWriter::writeLinearized() // Implementation note 121 states that a space is // mandatory after this open bracket. writeString(" /H [ "); - writeString(QUtil::int_to_string( - this->m->xref[hint_id].getOffset())); + writeString( + QUtil::int_to_string(this->m->xref[hint_id].getOffset())); writeString(" "); writeString(QUtil::int_to_string(hint_length)); writeString(" ] /O "); @@ -3322,15 +3177,12 @@ QPDFWriter::writeLinearized() qpdf_offset_t first_xref_offset = this->m->pipeline->getCount(); qpdf_offset_t hint_offset = 0; - if (pass == 2) - { + if (pass == 2) { hint_offset = this->m->xref[hint_id].getOffset(); } - if (need_xref_stream) - { + if (need_xref_stream) { // Must pad here too. - if (pass == 1) - { + if (pass == 1) { // Set first_half_max_obj_offset to a value large // enough to force four bytes to be reserved for each // file offset. This would provide adequate space for @@ -3342,29 +3194,32 @@ QPDFWriter::writeLinearized() first_half_max_obj_offset = 1 << 25; } pos = this->m->pipeline->getCount(); - writeXRefStream(first_half_xref, first_half_end, - first_half_max_obj_offset, - t_lin_first, first_half_start, first_half_end, - first_trailer_size, - hint_length + second_xref_offset, - hint_id, hint_offset, hint_length, - (pass == 1), pass); + writeXRefStream( + first_half_xref, + first_half_end, + first_half_max_obj_offset, + t_lin_first, + first_half_start, + first_half_end, + first_trailer_size, + hint_length + second_xref_offset, + hint_id, + hint_offset, + hint_length, + (pass == 1), + pass); qpdf_offset_t endpos = this->m->pipeline->getCount(); - if (pass == 1) - { + if (pass == 1) { // Pad so we have enough room for the real xref // stream. writePad(calculateXrefStreamPadding(endpos - pos)); first_xref_end = this->m->pipeline->getCount(); - } - else - { + } else { // Pad so that the next object starts at the same // place as in pass 1. writePad(QIntC::to_int(first_xref_end - endpos)); - if (this->m->pipeline->getCount() != first_xref_end) - { + if (this->m->pipeline->getCount() != first_xref_end) { throw std::logic_error( "insufficient padding for first pass xref stream; " "first_xref_end=" + @@ -3373,13 +3228,18 @@ QPDFWriter::writeLinearized() } } writeString("\n"); - } - else - { - writeXRefTable(t_lin_first, first_half_start, first_half_end, - first_trailer_size, hint_length + second_xref_offset, - (pass == 1), hint_id, hint_offset, hint_length, - pass); + } else { + writeXRefTable( + t_lin_first, + first_half_start, + first_half_end, + first_trailer_size, + hint_length + second_xref_offset, + (pass == 1), + hint_id, + hint_offset, + hint_length, + pass); writeString("startxref\n0\n%%EOF\n"); } @@ -3387,33 +3247,26 @@ QPDFWriter::writeLinearized() for (std::list::iterator iter = this->m->object_queue.begin(); - iter != this->m->object_queue.end(); ++iter) - { + iter != this->m->object_queue.end(); + ++iter) { QPDFObjectHandle cur_object = (*iter); - if (cur_object.getObjectID() == part6_end_marker) - { + if (cur_object.getObjectID() == part6_end_marker) { first_half_max_obj_offset = this->m->pipeline->getCount(); } writeObject(cur_object); - if (cur_object.getObjectID() == part4_end_marker) - { - if (this->m->encrypted) - { + if (cur_object.getObjectID() == part4_end_marker) { + if (this->m->encrypted) { writeEncryptionDictionary(); } - if (pass == 1) - { + if (pass == 1) { this->m->xref[hint_id] = QPDFXRefEntry(1, this->m->pipeline->getCount(), 0); - } - else - { + } else { // Part 5: hint stream writeBuffer(hint_buffer); } } - if (cur_object.getObjectID() == part6_end_marker) - { + if (cur_object.getObjectID() == part6_end_marker) { part6_end_offset = this->m->pipeline->getCount(); } } @@ -3423,50 +3276,58 @@ QPDFWriter::writeLinearized() // Part 11: main cross reference table and trailer second_xref_offset = this->m->pipeline->getCount(); - if (need_xref_stream) - { + if (need_xref_stream) { pos = this->m->pipeline->getCount(); - space_before_zero = - writeXRefStream(second_half_xref, - second_half_end, second_xref_offset, - t_lin_second, 0, second_half_end, - second_trailer_size, - 0, 0, 0, 0, (pass == 1), pass); + space_before_zero = writeXRefStream( + second_half_xref, + second_half_end, + second_xref_offset, + t_lin_second, + 0, + second_half_end, + second_trailer_size, + 0, + 0, + 0, + 0, + (pass == 1), + pass); qpdf_offset_t endpos = this->m->pipeline->getCount(); - if (pass == 1) - { + if (pass == 1) { // Pad so we have enough room for the real xref // stream. See comments for previous xref stream on // how we calculate the padding. writePad(calculateXrefStreamPadding(endpos - pos)); writeString("\n"); second_xref_end = this->m->pipeline->getCount(); - } - else - { + } else { // Make the file size the same. - writePad( - QIntC::to_int(second_xref_end + hint_length - - 1 - this->m->pipeline->getCount())); + writePad(QIntC::to_int( + second_xref_end + hint_length - 1 - + this->m->pipeline->getCount())); writeString("\n"); // If this assertion fails, maybe we didn't have // enough padding above. if (this->m->pipeline->getCount() != - second_xref_end + hint_length) - { - throw std::logic_error( - "count mismatch after xref stream;" - " possible insufficient padding?"); + second_xref_end + hint_length) { + throw std::logic_error("count mismatch after xref stream;" + " possible insufficient padding?"); } } - } - else - { - space_before_zero = - writeXRefTable(t_lin_second, 0, second_half_end, - second_trailer_size, 0, false, 0, 0, 0, pass); + } else { + space_before_zero = writeXRefTable( + t_lin_second, + 0, + second_half_end, + second_trailer_size, + 0, + false, + 0, + 0, + 0, + pass); } writeString("startxref\n"); writeString(QUtil::int_to_string(first_xref_offset)); @@ -3474,12 +3335,12 @@ QPDFWriter::writeLinearized() discardGeneration(this->m->obj_renumber, this->m->obj_renumber_no_gen); - if (pass == 1) - { - if (this->m->deterministic_id) - { - QTC::TC("qpdf", "QPDFWriter linearized deterministic ID", - need_xref_stream ? 0 : 1); + if (pass == 1) { + if (this->m->deterministic_id) { + QTC::TC( + "qpdf", + "QPDFWriter linearized deterministic ID", + need_xref_stream ? 0 : 1); computeDeterministicIDData(); pp_md5 = 0; assert(this->m->md5_pipeline == 0); @@ -3504,17 +3365,24 @@ QPDFWriter::writeLinearized() // Restore hint offset this->m->xref[hint_id] = QPDFXRefEntry(1, hint_offset1, 0); - if (lin_pass1_file) - { + if (lin_pass1_file) { // Write some debugging information - fprintf(lin_pass1_file, "%% hint_offset=%s\n", - QUtil::int_to_string(hint_offset1).c_str()); - fprintf(lin_pass1_file, "%% hint_length=%s\n", - QUtil::int_to_string(hint_length).c_str()); - fprintf(lin_pass1_file, "%% second_xref_offset=%s\n", - QUtil::int_to_string(second_xref_offset).c_str()); - fprintf(lin_pass1_file, "%% second_xref_end=%s\n", - QUtil::int_to_string(second_xref_end).c_str()); + fprintf( + lin_pass1_file, + "%% hint_offset=%s\n", + QUtil::int_to_string(hint_offset1).c_str()); + fprintf( + lin_pass1_file, + "%% hint_length=%s\n", + QUtil::int_to_string(hint_length).c_str()); + fprintf( + lin_pass1_file, + "%% second_xref_offset=%s\n", + QUtil::int_to_string(second_xref_offset).c_str()); + fprintf( + lin_pass1_file, + "%% second_xref_end=%s\n", + QUtil::int_to_string(second_xref_end).c_str()); fclose(lin_pass1_file); lin_pass1_file = 0; } @@ -3525,13 +3393,12 @@ QPDFWriter::writeLinearized() void QPDFWriter::enqueueObjectsStandard() { - if (this->m->preserve_unreferenced_objects) - { + if (this->m->preserve_unreferenced_objects) { QTC::TC("qpdf", "QPDFWriter preserve unreferenced standard"); std::vector all = this->m->pdf.getAllObjects(); for (std::vector::iterator iter = all.begin(); - iter != all.end(); ++iter) - { + iter != all.end(); + ++iter) { enqueueObject(*iter); } } @@ -3546,8 +3413,8 @@ QPDFWriter::enqueueObjectsStandard() // no-op. std::set keys = trailer.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { enqueueObject(trailer.getKey(*iter)); } } @@ -3563,8 +3430,8 @@ QPDFWriter::enqueueObjectsPCLm() // enqueue all pages first std::vector all = this->m->pdf.getAllPages(); for (std::vector::iterator iter = all.begin(); - iter != all.end(); ++iter) - { + iter != all.end(); + ++iter) { // enqueue page enqueueObject(*iter); @@ -3576,11 +3443,11 @@ QPDFWriter::enqueueObjectsPCLm() (*iter).getKey("/Resources").getKey("/XObject"); std::set keys = strips.getKeys(); for (std::set::iterator image = keys.begin(); - image != keys.end(); ++image) - { + image != keys.end(); + ++image) { enqueueObject(strips.getKey(*image)); enqueueObject(QPDFObjectHandle::newStream( - &this->m->pdf, image_transform_content)); + &this->m->pdf, image_transform_content)); } } @@ -3592,33 +3459,31 @@ QPDFWriter::enqueueObjectsPCLm() void QPDFWriter::indicateProgress(bool decrement, bool finished) { - if (decrement) - { + if (decrement) { --this->m->events_seen; return; } ++this->m->events_seen; - if (! this->m->progress_reporter.get()) - { + if (!this->m->progress_reporter.get()) { return; } - if (finished || (this->m->events_seen >= this->m->next_progress_report)) - { - int percentage = ( - finished - ? 100 - : this->m->next_progress_report == 0 - ? 0 - : std::min(99, 1 + ((100 * this->m->events_seen) / - this->m->events_expected))); + if (finished || (this->m->events_seen >= this->m->next_progress_report)) { + int percentage = + (finished ? 100 + : this->m->next_progress_report == 0 + ? 0 + : std::min( + 99, + 1 + + ((100 * this->m->events_seen) / + this->m->events_expected))); this->m->progress_reporter->reportProgress(percentage); } int increment = std::max(1, (this->m->events_expected / 100)); - while (this->m->events_seen >= this->m->next_progress_report) - { + while (this->m->events_seen >= this->m->next_progress_report) { this->m->next_progress_report += increment; } } @@ -3633,8 +3498,7 @@ void QPDFWriter::writeStandard() { auto pp_md5 = make_pointer_holder(this); - if (this->m->deterministic_id) - { + if (this->m->deterministic_id) { pushMD5Pipeline(*pp_md5); } @@ -3643,52 +3507,51 @@ QPDFWriter::writeStandard() writeHeader(); writeString(this->m->extra_header_text); - if (this->m->pclm) - { + if (this->m->pclm) { enqueueObjectsPCLm(); - } - else - { + } else { enqueueObjectsStandard(); } // Now start walking queue, outputting each object. - while (this->m->object_queue.size()) - { + while (this->m->object_queue.size()) { QPDFObjectHandle cur_object = this->m->object_queue.front(); this->m->object_queue.pop_front(); writeObject(cur_object); } // Write out the encryption dictionary, if any - if (this->m->encrypted) - { + if (this->m->encrypted) { writeEncryptionDictionary(); } // Now write out xref. next_objid is now the number of objects. qpdf_offset_t xref_offset = this->m->pipeline->getCount(); - if (this->m->object_stream_to_objects.empty()) - { + if (this->m->object_stream_to_objects.empty()) { // Write regular cross-reference table - writeXRefTable(t_normal, 0, this->m->next_objid - 1, - this->m->next_objid); - } - else - { + writeXRefTable( + t_normal, 0, this->m->next_objid - 1, this->m->next_objid); + } else { // Write cross-reference stream. int xref_id = this->m->next_objid++; - writeXRefStream(xref_id, xref_id, xref_offset, t_normal, - 0, this->m->next_objid - 1, this->m->next_objid); + writeXRefStream( + xref_id, + xref_id, + xref_offset, + t_normal, + 0, + this->m->next_objid - 1, + this->m->next_objid); } writeString("startxref\n"); writeString(QUtil::int_to_string(xref_offset)); writeString("\n%%EOF\n"); - if (this->m->deterministic_id) - { - QTC::TC("qpdf", "QPDFWriter standard deterministic ID", - this->m->object_stream_to_objects.empty() ? 0 : 1); + if (this->m->deterministic_id) { + QTC::TC( + "qpdf", + "QPDFWriter standard deterministic ID", + this->m->object_stream_to_objects.empty() ? 0 : 1); pp_md5 = 0; assert(this->m->md5_pipeline == 0); } diff --git a/libqpdf/QPDFXRefEntry.cc b/libqpdf/QPDFXRefEntry.cc index 8eb2ee1e..8c8ada5e 100644 --- a/libqpdf/QPDFXRefEntry.cc +++ b/libqpdf/QPDFXRefEntry.cc @@ -1,8 +1,8 @@ #include +#include #include #include -#include QPDFXRefEntry::QPDFXRefEntry() : type(0), @@ -16,8 +16,7 @@ QPDFXRefEntry::QPDFXRefEntry(int type, qpdf_offset_t field1, int field2) : field1(field1), field2(field2) { - if ((type < 1) || (type > 2)) - { + if ((type < 1) || (type > 2)) { throw std::logic_error( "invalid xref type " + QUtil::int_to_string(type)); } @@ -32,10 +31,8 @@ QPDFXRefEntry::getType() const qpdf_offset_t QPDFXRefEntry::getOffset() const { - if (this->type != 1) - { - throw std::logic_error( - "getOffset called for xref entry of type != 1"); + if (this->type != 1) { + throw std::logic_error("getOffset called for xref entry of type != 1"); } return this->field1; } @@ -43,8 +40,7 @@ QPDFXRefEntry::getOffset() const int QPDFXRefEntry::getObjStreamNumber() const { - if (this->type != 2) - { + if (this->type != 2) { throw std::logic_error( "getObjStreamNumber called for xref entry of type != 2"); } @@ -54,8 +50,7 @@ QPDFXRefEntry::getObjStreamNumber() const int QPDFXRefEntry::getObjStreamIndex() const { - if (this->type != 2) - { + if (this->type != 2) { throw std::logic_error( "getObjStreamIndex called for xref entry of type != 2"); } diff --git a/libqpdf/QPDF_Array.cc b/libqpdf/QPDF_Array.cc index bc6496f3..1026e263 100644 --- a/libqpdf/QPDF_Array.cc +++ b/libqpdf/QPDF_Array.cc @@ -1,7 +1,7 @@ #include -#include #include +#include #include QPDF_Array::QPDF_Array(std::vector const& v) @@ -29,8 +29,7 @@ QPDF_Array::unparse() { std::string result = "[ "; size_t size = this->elements.size(); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { result += this->elements.at(i).unparse(); result += " "; } @@ -43,8 +42,7 @@ QPDF_Array::getJSON() { JSON j = JSON::makeArray(); size_t size = this->elements.size(); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { j.addArrayElement(this->elements.at(i).getJSON()); } return j; @@ -79,8 +77,7 @@ QPDF_Array::getNItems() const QPDFObjectHandle QPDF_Array::getItem(int n) const { - if ((n < 0) || (n >= QIntC::to_int(elements.size()))) - { + if ((n < 0) || (n >= QIntC::to_int(elements.size()))) { throw std::logic_error( "INTERNAL ERROR: bounds error accessing QPDF_Array element"); } @@ -91,8 +88,7 @@ void QPDF_Array::getAsVector(std::vector& v) const { size_t size = this->elements.size(); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { v.push_back(this->elements.at(i)); } } @@ -108,8 +104,8 @@ QPDF_Array::setFromVector(std::vector const& v) { this->elements = SparseOHArray(); for (std::vector::const_iterator iter = v.begin(); - iter != v.end(); ++iter) - { + iter != v.end(); + ++iter) { this->elements.append(*iter); } } @@ -118,8 +114,7 @@ void QPDF_Array::insertItem(int at, QPDFObjectHandle const& item) { // As special case, also allow insert beyond the end - if ((at < 0) || (at > QIntC::to_int(this->elements.size()))) - { + if ((at < 0) || (at > QIntC::to_int(this->elements.size()))) { throw std::logic_error( "INTERNAL ERROR: bounds error accessing QPDF_Array element"); } @@ -147,8 +142,7 @@ QPDF_Array::getElementsForShallowCopy() const void QPDF_Array::addExplicitElementsToList(std::list& l) const { - for (auto const& iter: this->elements) - { + for (auto const& iter : this->elements) { l.push_back(iter.second); } } diff --git a/libqpdf/QPDF_Dictionary.cc b/libqpdf/QPDF_Dictionary.cc index 918b46b4..39708fe7 100644 --- a/libqpdf/QPDF_Dictionary.cc +++ b/libqpdf/QPDF_Dictionary.cc @@ -1,7 +1,7 @@ #include -#include #include +#include QPDF_Dictionary::QPDF_Dictionary( std::map const& items) : @@ -18,8 +18,8 @@ QPDF_Dictionary::releaseResolved() { for (std::map::iterator iter = this->items.begin(); - iter != this->items.end(); ++iter) - { + iter != this->items.end(); + ++iter) { QPDFObjectHandle::ReleaseResolver::releaseResolved((*iter).second); } } @@ -30,10 +30,10 @@ QPDF_Dictionary::unparse() std::string result = "<< "; for (std::map::iterator iter = this->items.begin(); - iter != this->items.end(); ++iter) - { - result += QPDF_Name::normalizeName((*iter).first) + - " " + (*iter).second.unparse() + " "; + iter != this->items.end(); + ++iter) { + result += QPDF_Name::normalizeName((*iter).first) + " " + + (*iter).second.unparse() + " "; } result += ">>"; return result; @@ -45,10 +45,10 @@ QPDF_Dictionary::getJSON() JSON j = JSON::makeDictionary(); for (std::map::iterator iter = this->items.begin(); - iter != this->items.end(); ++iter) - { - j.addDictionaryMember(QPDF_Name::normalizeName((*iter).first), - (*iter).second.getJSON()); + iter != this->items.end(); + ++iter) { + j.addDictionaryMember( + QPDF_Name::normalizeName((*iter).first), (*iter).second.getJSON()); } return j; } @@ -74,8 +74,7 @@ QPDF_Dictionary::setDescription(QPDF* qpdf, std::string const& description) bool QPDF_Dictionary::hasKey(std::string const& key) { - return ((this->items.count(key) > 0) && - (! this->items[key].isNull())); + return ((this->items.count(key) > 0) && (!this->items[key].isNull())); } QPDFObjectHandle @@ -83,18 +82,14 @@ QPDF_Dictionary::getKey(std::string const& key) { // PDF spec says fetching a non-existent key from a dictionary // returns the null object. - if (this->items.count(key)) - { + if (this->items.count(key)) { // May be a null object return (*(this->items.find(key))).second; - } - else - { + } else { QPDFObjectHandle null = QPDFObjectHandle::newNull(); QPDF* qpdf = 0; std::string description; - if (getDescription(qpdf, description)) - { + if (getDescription(qpdf, description)) { null.setObjectDescription( qpdf, description + " -> dictionary key " + key); } @@ -108,10 +103,9 @@ QPDF_Dictionary::getKeys() std::set result; for (std::map::const_iterator iter = this->items.begin(); - iter != this->items.end(); ++iter) - { - if (hasKey((*iter).first)) - { + iter != this->items.end(); + ++iter) { + if (hasKey((*iter).first)) { result.insert((*iter).first); } } @@ -125,8 +119,7 @@ QPDF_Dictionary::getAsMap() const } void -QPDF_Dictionary::replaceKey(std::string const& key, - QPDFObjectHandle value) +QPDF_Dictionary::replaceKey(std::string const& key, QPDFObjectHandle value) { // add or replace value this->items[key] = value; @@ -140,15 +133,12 @@ QPDF_Dictionary::removeKey(std::string const& key) } void -QPDF_Dictionary::replaceOrRemoveKey(std::string const& key, - QPDFObjectHandle value) +QPDF_Dictionary::replaceOrRemoveKey( + std::string const& key, QPDFObjectHandle value) { - if (value.isNull()) - { + if (value.isNull()) { removeKey(key); - } - else - { + } else { replaceKey(key, value); } } diff --git a/libqpdf/QPDF_Name.cc b/libqpdf/QPDF_Name.cc index 7972210c..85ca3059 100644 --- a/libqpdf/QPDF_Name.cc +++ b/libqpdf/QPDF_Name.cc @@ -1,8 +1,8 @@ #include -#include -#include #include +#include +#include QPDF_Name::QPDF_Name(std::string const& name) : name(name) @@ -16,28 +16,21 @@ QPDF_Name::~QPDF_Name() std::string QPDF_Name::normalizeName(std::string const& name) { - if (name.empty()) - { + if (name.empty()) { return name; } std::string result; result += name.at(0); - for (size_t i = 1; i < name.length(); ++i) - { + for (size_t i = 1; i < name.length(); ++i) { char ch = name.at(i); // Don't use locale/ctype here; follow PDF spec guidelines. - if (ch == '\0') - { + if (ch == '\0') { // QPDFTokenizer embeds a null character to encode an // invalid #. result += "#"; - } - else if (strchr("#()<>[]{}/%", ch) || (ch < 33) || (ch > 126)) - { + } else if (strchr("#()<>[]{}/%", ch) || (ch < 33) || (ch > 126)) { result += "#" + QUtil::hex_encode(std::string(&ch, 1)); - } - else - { + } else { result += ch; } } diff --git a/libqpdf/QPDF_Real.cc b/libqpdf/QPDF_Real.cc index 55f61b35..345f30b6 100644 --- a/libqpdf/QPDF_Real.cc +++ b/libqpdf/QPDF_Real.cc @@ -7,8 +7,8 @@ QPDF_Real::QPDF_Real(std::string const& val) : { } -QPDF_Real::QPDF_Real(double value, int decimal_places, - bool trim_trailing_zeroes) : +QPDF_Real::QPDF_Real( + double value, int decimal_places, bool trim_trailing_zeroes) : val(QUtil::double_to_string(value, decimal_places, trim_trailing_zeroes)) { } @@ -30,23 +30,16 @@ QPDF_Real::getJSON() // converting from string to double and back, just handle this as a // special case for JSON. std::string result; - if (this->val.length() == 0) - { + if (this->val.length() == 0) { // Can't really happen... result = "0"; - } - else if (this->val.at(0) == '.') - { + } else if (this->val.at(0) == '.') { result = "0" + this->val; - } - else if ((this->val.length() >= 2) && - (this->val.at(0) == '-') && - (this->val.at(1) == '.')) - { + } else if ( + (this->val.length() >= 2) && (this->val.at(0) == '-') && + (this->val.at(1) == '.')) { result = "-0." + this->val.substr(2); - } - else - { + } else { result = this->val; } return JSON::makeNumber(result); diff --git a/libqpdf/QPDF_Stream.cc b/libqpdf/QPDF_Stream.cc index 9e995e1f..1521cc99 100644 --- a/libqpdf/QPDF_Stream.cc +++ b/libqpdf/QPDF_Stream.cc @@ -1,21 +1,21 @@ #include -#include +#include #include -#include #include #include -#include -#include -#include -#include +#include #include #include -#include -#include -#include +#include +#include +#include +#include #include #include +#include +#include +#include #include @@ -25,30 +25,27 @@ class SF_Crypt: public QPDFStreamFilter SF_Crypt() = default; virtual ~SF_Crypt() = default; - virtual bool setDecodeParms(QPDFObjectHandle decode_parms) + virtual bool + setDecodeParms(QPDFObjectHandle decode_parms) { - if (decode_parms.isNull()) - { + if (decode_parms.isNull()) { return true; } bool filterable = true; - for (auto const& key: decode_parms.getKeys()) - { + for (auto const& key : decode_parms.getKeys()) { if (((key == "/Type") || (key == "/Name")) && - ((! decode_parms.hasKey("/Type")) || - decode_parms.isDictionaryOfType("/CryptFilterDecodeParms"))) - { + ((!decode_parms.hasKey("/Type")) || + decode_parms.isDictionaryOfType("/CryptFilterDecodeParms"))) { // we handle this in decryptStream - } - else - { + } else { filterable = false; } } return filterable; } - virtual Pipeline* getDecodePipeline(Pipeline*) + virtual Pipeline* + getDecodePipeline(Pipeline*) { // Not used -- handled by pipeStreamData return nullptr; @@ -69,22 +66,24 @@ std::map QPDF_Stream::filter_abbreviations = { {"/DCT", "/DCTDecode"}, }; -std::map< - std::string, - std::function()>> -QPDF_Stream::filter_factories = { - {"/Crypt", []() { return std::make_shared(); }}, - {"/FlateDecode", SF_FlateLzwDecode::flate_factory}, - {"/LZWDecode", SF_FlateLzwDecode::lzw_factory}, - {"/RunLengthDecode", SF_RunLengthDecode::factory}, - {"/DCTDecode", SF_DCTDecode::factory}, - {"/ASCII85Decode", SF_ASCII85Decode::factory}, - {"/ASCIIHexDecode", SF_ASCIIHexDecode::factory}, +std::map()>> + QPDF_Stream::filter_factories = { + {"/Crypt", []() { return std::make_shared(); }}, + {"/FlateDecode", SF_FlateLzwDecode::flate_factory}, + {"/LZWDecode", SF_FlateLzwDecode::lzw_factory}, + {"/RunLengthDecode", SF_RunLengthDecode::factory}, + {"/DCTDecode", SF_DCTDecode::factory}, + {"/ASCII85Decode", SF_ASCII85Decode::factory}, + {"/ASCIIHexDecode", SF_ASCIIHexDecode::factory}, }; -QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length) : +QPDF_Stream::QPDF_Stream( + QPDF* qpdf, + int objid, + int generation, + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, + size_t length) : qpdf(qpdf), objid(objid), generation(generation), @@ -93,11 +92,9 @@ QPDF_Stream::QPDF_Stream(QPDF* qpdf, int objid, int generation, offset(offset), length(length) { - if (! stream_dict.isDictionary()) - { - throw std::logic_error( - "stream object instantiated with non-dictionary " - "object for dictionary"); + if (!stream_dict.isDictionary()) { + throw std::logic_error("stream object instantiated with non-dictionary " + "object for dictionary"); } setStreamDescription(); } @@ -136,8 +133,7 @@ QPDF_Stream::releaseResolved() void QPDF_Stream::setObjGen(int objid, int generation) { - if (! ((this->objid == 0) && (this->generation == 0))) - { + if (!((this->objid == 0) && (this->generation == 0))) { throw std::logic_error( "attempt to set object ID and generation of a stream" " that already has them"); @@ -184,9 +180,9 @@ QPDF_Stream::setStreamDescription() { setDescription( this->qpdf, - this->qpdf->getFilename() + - ", stream object " + QUtil::int_to_string(this->objid) + " " + - QUtil::int_to_string(this->generation)); + this->qpdf->getFilename() + ", stream object " + + QUtil::int_to_string(this->objid) + " " + + QUtil::int_to_string(this->generation)); } void @@ -194,9 +190,8 @@ QPDF_Stream::setDictDescription() { QPDF* qpdf = 0; std::string description; - if ((! this->stream_dict.hasObjectDescription()) && - getDescription(qpdf, description)) - { + if ((!this->stream_dict.hasObjectDescription()) && + getDescription(qpdf, description)) { this->stream_dict.setObjectDescription( qpdf, description + " -> stream dictionary"); } @@ -211,7 +206,7 @@ QPDF_Stream::getDict() const bool QPDF_Stream::isDataModified() const { - return (! this->token_filters.empty()); + return (!this->token_filters.empty()); } qpdf_offset_t @@ -244,11 +239,13 @@ QPDF_Stream::getStreamData(qpdf_stream_decode_level_e decode_level) Pl_Buffer buf("stream data buffer"); bool filtered; pipeStreamData(&buf, &filtered, 0, decode_level, false, false); - if (! filtered) - { - throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), - "", this->offset, - "getStreamData called on unfilterable stream"); + if (!filtered) { + throw QPDFExc( + qpdf_e_unsupported, + qpdf->getFilename(), + "", + this->offset, + "getStreamData called on unfilterable stream"); } QTC::TC("qpdf", "QPDF_Stream getStreamData"); return buf.getBufferSharedPointer(); @@ -258,11 +255,13 @@ PointerHolder QPDF_Stream::getRawStreamData() { Pl_Buffer buf("stream data buffer"); - if (! pipeStreamData(&buf, nullptr, 0, qpdf_dl_none, false, false)) - { - throw QPDFExc(qpdf_e_unsupported, qpdf->getFilename(), - "", this->offset, - "error getting raw stream data"); + if (!pipeStreamData(&buf, nullptr, 0, qpdf_dl_none, false, false)) { + throw QPDFExc( + qpdf_e_unsupported, + qpdf->getFilename(), + "", + this->offset, + "error getting raw stream data"); } QTC::TC("qpdf", "QPDF_Stream getRawStreamData"); return buf.getBufferSharedPointer(); @@ -281,69 +280,54 @@ QPDF_Stream::filterable( std::vector filter_names; - if (filter_obj.isNull()) - { + if (filter_obj.isNull()) { // No filters - } - else if (filter_obj.isName()) - { + } else if (filter_obj.isName()) { // One filter filter_names.push_back(filter_obj.getName()); - } - else if (filter_obj.isArray()) - { + } else if (filter_obj.isArray()) { // Potentially multiple filters int n = filter_obj.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { QPDFObjectHandle item = filter_obj.getArrayItem(i); - if (item.isName()) - { + if (item.isName()) { filter_names.push_back(item.getName()); - } - else - { + } else { filters_okay = false; } } - } - else - { + } else { filters_okay = false; } - if (! filters_okay) - { + if (!filters_okay) { QTC::TC("qpdf", "QPDF_Stream invalid filter"); - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, - "stream filter type is not name or array")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + "stream filter type is not name or array")); return false; } bool filterable = true; - for (auto& filter_name: filter_names) - { - if (filter_abbreviations.count(filter_name)) - { + for (auto& filter_name : filter_names) { + if (filter_abbreviations.count(filter_name)) { QTC::TC("qpdf", "QPDF_Stream expand filter abbreviation"); filter_name = filter_abbreviations[filter_name]; } auto ff = filter_factories.find(filter_name); - if (ff == filter_factories.end()) - { + if (ff == filter_factories.end()) { filterable = false; - } - else - { + } else { filters.push_back((ff->second)()); } } - if (! filterable) - { + if (!filterable) { return false; } @@ -354,21 +338,15 @@ QPDF_Stream::filterable( QPDFObjectHandle decode_obj = this->stream_dict.getKey("/DecodeParms"); std::vector decode_parms; - if (decode_obj.isArray() && (decode_obj.getArrayNItems() == 0)) - { + if (decode_obj.isArray() && (decode_obj.getArrayNItems() == 0)) { decode_obj = QPDFObjectHandle::newNull(); } - if (decode_obj.isArray()) - { - for (int i = 0; i < decode_obj.getArrayNItems(); ++i) - { + if (decode_obj.isArray()) { + for (int i = 0; i < decode_obj.getArrayNItems(); ++i) { decode_parms.push_back(decode_obj.getArrayItem(i)); } - } - else - { - for (unsigned int i = 0; i < filter_names.size(); ++i) - { + } else { + for (unsigned int i = 0; i < filter_names.size(); ++i) { decode_parms.push_back(decode_obj); } } @@ -376,39 +354,34 @@ QPDF_Stream::filterable( // Ignore /DecodeParms entirely if /Filters is empty. At least // one case of a file whose /DecodeParms was [ << >> ] when // /Filters was empty has been seen in the wild. - if ((filters.size() != 0) && (decode_parms.size() != filters.size())) - { - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, - "stream /DecodeParms length is" - " inconsistent with filters")); + if ((filters.size() != 0) && (decode_parms.size() != filters.size())) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + "stream /DecodeParms length is" + " inconsistent with filters")); filterable = false; } - if (! filterable) - { + if (!filterable) { return false; } - for (size_t i = 0; i < filters.size(); ++i) - { + for (size_t i = 0; i < filters.size(); ++i) { auto filter = filters.at(i); auto decode_item = decode_parms.at(i); - if (filter->setDecodeParms(decode_item)) - { - if (filter->isSpecializedCompression()) - { + if (filter->setDecodeParms(decode_item)) { + if (filter->isSpecializedCompression()) { specialized_compression = true; } - if (filter->isLossyCompression()) - { + if (filter->isLossyCompression()) { specialized_compression = true; lossy_compression = true; } - } - else - { + } else { filterable = false; } } @@ -417,43 +390,43 @@ QPDF_Stream::filterable( } bool -QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings, bool will_retry) +QPDF_Stream::pipeStreamData( + Pipeline* pipeline, + bool* filterp, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings, + bool will_retry) { std::vector> filters; bool specialized_compression = false; bool lossy_compression = false; bool ignored; - if (filterp == nullptr) - { + if (filterp == nullptr) { filterp = &ignored; } bool& filter = *filterp; - filter = (! ((encode_flags == 0) && (decode_level == qpdf_dl_none))); + filter = (!((encode_flags == 0) && (decode_level == qpdf_dl_none))); bool success = true; - if (filter) - { - filter = filterable( - filters, specialized_compression, lossy_compression); - if ((decode_level < qpdf_dl_all) && lossy_compression) - { + if (filter) { + filter = + filterable(filters, specialized_compression, lossy_compression); + if ((decode_level < qpdf_dl_all) && lossy_compression) { filter = false; } - if ((decode_level < qpdf_dl_specialized) && specialized_compression) - { + if ((decode_level < qpdf_dl_specialized) && specialized_compression) { filter = false; } - QTC::TC("qpdf", "QPDF_Stream special filters", - (! filter) ? 0 : - lossy_compression ? 1 : - specialized_compression ? 2 : - 3); + QTC::TC( + "qpdf", + "QPDF_Stream special filters", + (!filter) ? 0 + : lossy_compression ? 1 + : specialized_compression ? 2 + : 3); } - if (pipeline == 0) - { + if (pipeline == 0) { QTC::TC("qpdf", "QPDF_Stream pipeStreamData with null pipeline"); // Return value is whether we can filter in this case. return filter; @@ -467,18 +440,15 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, PointerHolder normalizer; std::shared_ptr new_pipeline; - if (filter) - { - if (encode_flags & qpdf_ef_compress) - { + if (filter) { + if (encode_flags & qpdf_ef_compress) { new_pipeline = std::make_shared( "compress stream", pipeline, Pl_Flate::a_deflate); to_delete.push_back(new_pipeline); pipeline = new_pipeline.get(); } - if (encode_flags & qpdf_ef_normalize) - { + if (encode_flags & qpdf_ef_normalize) { normalizer = make_pointer_holder(); new_pipeline = std::make_shared( "normalizer", normalizer.get(), pipeline); @@ -487,143 +457,138 @@ QPDF_Stream::pipeStreamData(Pipeline* pipeline, bool* filterp, } for (auto iter = this->token_filters.rbegin(); - iter != this->token_filters.rend(); ++iter) - { + iter != this->token_filters.rend(); + ++iter) { new_pipeline = std::make_shared( "token filter", (*iter).get(), pipeline); to_delete.push_back(new_pipeline); pipeline = new_pipeline.get(); } - for (auto f_iter = filters.rbegin(); - f_iter != filters.rend(); ++f_iter) - { + for (auto f_iter = filters.rbegin(); f_iter != filters.rend(); + ++f_iter) { auto decode_pipeline = (*f_iter)->getDecodePipeline(pipeline); - if (decode_pipeline) - { + if (decode_pipeline) { pipeline = decode_pipeline; } Pl_Flate* flate = dynamic_cast(pipeline); - if (flate != nullptr) - { + if (flate != nullptr) { flate->setWarnCallback([this](char const* msg, int code) { - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, msg)); + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + msg)); }); } } } - if (this->stream_data.get()) - { + if (this->stream_data.get()) { QTC::TC("qpdf", "QPDF_Stream pipe replaced stream data"); - pipeline->write(this->stream_data->getBuffer(), - this->stream_data->getSize()); + pipeline->write( + this->stream_data->getBuffer(), this->stream_data->getSize()); pipeline->finish(); - } - else if (this->stream_provider.get()) - { + } else if (this->stream_provider.get()) { Pl_Count count("stream provider count", pipeline); - if (this->stream_provider->supportsRetry()) - { - if (! this->stream_provider->provideStreamData( - this->objid, this->generation, &count, - suppress_warnings, will_retry)) - { + if (this->stream_provider->supportsRetry()) { + if (!this->stream_provider->provideStreamData( + this->objid, + this->generation, + &count, + suppress_warnings, + will_retry)) { filter = false; success = false; } - } - else - { + } else { this->stream_provider->provideStreamData( this->objid, this->generation, &count); } qpdf_offset_t actual_length = count.getCount(); qpdf_offset_t desired_length = 0; - if (success && this->stream_dict.hasKey("/Length")) - { + if (success && this->stream_dict.hasKey("/Length")) { desired_length = this->stream_dict.getKey("/Length").getIntValue(); - if (actual_length == desired_length) - { + if (actual_length == desired_length) { QTC::TC("qpdf", "QPDF_Stream pipe use stream provider"); - } - else - { + } else { QTC::TC("qpdf", "QPDF_Stream provider length mismatch"); // This would be caused by programmer error on the // part of a library user, not by invalid input data. throw std::runtime_error( "stream data provider for " + QUtil::int_to_string(this->objid) + " " + - QUtil::int_to_string(this->generation) + - " provided " + + QUtil::int_to_string(this->generation) + " provided " + QUtil::int_to_string(actual_length) + " bytes instead of expected " + QUtil::int_to_string(desired_length) + " bytes"); } - } - else if (success) - { + } else if (success) { QTC::TC("qpdf", "QPDF_Stream provider length not provided"); this->stream_dict.replaceKey( "/Length", QPDFObjectHandle::newInteger(actual_length)); } - } - else if (this->offset == 0) - { + } else if (this->offset == 0) { QTC::TC("qpdf", "QPDF_Stream pipe no stream data"); - throw std::logic_error( - "pipeStreamData called for stream with no data"); - } - else - { + throw std::logic_error("pipeStreamData called for stream with no data"); + } else { QTC::TC("qpdf", "QPDF_Stream pipe original stream data"); - if (! QPDF::Pipe::pipeStreamData(this->qpdf, this->objid, this->generation, - this->offset, this->length, - this->stream_dict, pipeline, - suppress_warnings, - will_retry)) - { + if (!QPDF::Pipe::pipeStreamData( + this->qpdf, + this->objid, + this->generation, + this->offset, + this->length, + this->stream_dict, + pipeline, + suppress_warnings, + will_retry)) { filter = false; success = false; } } - if (filter && - (! suppress_warnings) && - normalizer.get() && - normalizer->anyBadTokens()) - { - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, - "content normalization encountered bad tokens")); - if (normalizer->lastTokenWasBad()) - { + if (filter && (!suppress_warnings) && normalizer.get() && + normalizer->anyBadTokens()) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + "content normalization encountered bad tokens")); + if (normalizer->lastTokenWasBad()) { QTC::TC("qpdf", "QPDF_Stream bad token at end during normalize"); - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, - "normalized content ended with a bad token;" - " you may be able to resolve this by" - " coalescing content streams in combination" - " with normalizing content. From the command" - " line, specify --coalesce-contents")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + "normalized content ended with a bad token;" + " you may be able to resolve this by" + " coalescing content streams in combination" + " with normalizing content. From the command" + " line, specify --coalesce-contents")); } - warn(QPDFExc(qpdf_e_damaged_pdf, qpdf->getFilename(), - "", this->offset, - "Resulting stream data may be corrupted but is" - " may still useful for manual inspection." - " For more information on this warning, search" - " for content normalization in the manual.")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + qpdf->getFilename(), + "", + this->offset, + "Resulting stream data may be corrupted but is" + " may still useful for manual inspection." + " For more information on this warning, search" + " for content normalization in the manual.")); } return success; } void -QPDF_Stream::replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms) +QPDF_Stream::replaceStreamData( + PointerHolder data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms) { this->stream_data = data; this->stream_provider = 0; @@ -649,22 +614,20 @@ QPDF_Stream::addTokenFilter( } void -QPDF_Stream::replaceFilterData(QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms, - size_t length) +QPDF_Stream::replaceFilterData( + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms, + size_t length) { this->stream_dict.replaceOrRemoveKey("/Filter", filter); this->stream_dict.replaceOrRemoveKey("/DecodeParms", decode_parms); - if (length == 0) - { + if (length == 0) { QTC::TC("qpdf", "QPDF_Stream unknown stream length"); this->stream_dict.removeKey("/Length"); - } - else - { + } else { this->stream_dict.replaceKey( - "/Length", QPDFObjectHandle::newInteger( - QIntC::to_longlong(length))); + "/Length", + QPDFObjectHandle::newInteger(QIntC::to_longlong(length))); } } @@ -674,12 +637,9 @@ QPDF_Stream::replaceDict(QPDFObjectHandle new_dict) this->stream_dict = new_dict; setDictDescription(); QPDFObjectHandle length_obj = new_dict.getKey("/Length"); - if (length_obj.isInteger()) - { + if (length_obj.isInteger()) { this->length = QIntC::to_size(length_obj.getUIntValue()); - } - else - { + } else { this->length = 0; } } diff --git a/libqpdf/QPDF_String.cc b/libqpdf/QPDF_String.cc index 5604ff10..7d7ee84d 100644 --- a/libqpdf/QPDF_String.cc +++ b/libqpdf/QPDF_String.cc @@ -1,7 +1,7 @@ #include -#include #include +#include // DO NOT USE ctype -- it is locale dependent for some things, and // it's not worth the risk of including it in case it may accidentally @@ -9,14 +9,16 @@ #include // See above about ctype. -static bool is_ascii_printable(char ch) +static bool +is_ascii_printable(char ch) { return ((ch >= 32) && (ch <= 126)); } -static bool is_iso_latin1_printable(char ch) +static bool +is_iso_latin1_printable(char ch) { - return (((ch >= 32) && (ch <= 126)) || - (static_cast(ch) >= 160)); + return ( + ((ch >= 32) && (ch <= 126)) || (static_cast(ch) >= 160)); } QPDF_String::QPDF_String(std::string const& val) : @@ -32,8 +34,7 @@ QPDF_String* QPDF_String::new_utf16(std::string const& utf8_val) { std::string result; - if (! QUtil::utf8_to_pdf_doc(utf8_val, result, '?')) - { + if (!QUtil::utf8_to_pdf_doc(utf8_val, result, '?')) { result = QUtil::utf8_to_utf16(utf8_val); } return new QPDF_String(result); @@ -67,12 +68,10 @@ std::string QPDF_String::unparse(bool force_binary) { bool use_hexstring = force_binary; - if (! use_hexstring) - { + if (!use_hexstring) { unsigned int nonprintable = 0; int consecutive_printable = 0; - for (unsigned int i = 0; i < this->val.length(); ++i) - { + for (unsigned int i = 0; i < this->val.length(); ++i) { char ch = this->val.at(i); // Note: do not use locale to determine printability. The // PDF specification accepts arbitrary binary data. Some @@ -80,16 +79,12 @@ QPDF_String::unparse(bool force_binary) // something printable if it is printable in 7-bit ASCII. // We'll code this manually rather than being rude and // setting locale. - if ((ch == 0) || (! (is_ascii_printable(ch) || - strchr("\n\r\t\b\f", ch)))) - { + if ((ch == 0) || + (!(is_ascii_printable(ch) || strchr("\n\r\t\b\f", ch)))) { ++nonprintable; consecutive_printable = 0; - } - else - { - if (++consecutive_printable > 5) - { + } else { + if (++consecutive_printable > 5) { // If there are more than 5 consecutive printable // characters, I want to see them as such. nonprintable = 0; @@ -100,66 +95,60 @@ QPDF_String::unparse(bool force_binary) // Use hex notation if more than 20% of the characters are not // printable in plain ASCII. - if (5 * nonprintable > val.length()) - { + if (5 * nonprintable > val.length()) { use_hexstring = true; } } std::string result; - if (use_hexstring) - { + if (use_hexstring) { result += "<" + QUtil::hex_encode(this->val) + ">"; - } - else - { + } else { result += "("; - for (unsigned int i = 0; i < this->val.length(); ++i) - { + for (unsigned int i = 0; i < this->val.length(); ++i) { char ch = this->val.at(i); - switch (ch) - { - case '\n': + switch (ch) { + case '\n': result += "\\n"; break; - case '\r': + case '\r': result += "\\r"; break; - case '\t': + case '\t': result += "\\t"; break; - case '\b': + case '\b': result += "\\b"; break; - case '\f': + case '\f': result += "\\f"; break; - case '(': + case '(': result += "\\("; break; - case ')': + case ')': result += "\\)"; break; - case '\\': + case '\\': result += "\\\\"; break; - default: - if (is_iso_latin1_printable(ch)) - { + default: + if (is_iso_latin1_printable(ch)) { result += this->val.at(i); - } - else - { - result += "\\" + QUtil::int_to_string_base( - static_cast(static_cast(ch)), - 8, 3); + } else { + result += + "\\" + + QUtil::int_to_string_base( + static_cast(static_cast(ch)), + 8, + 3); } break; } @@ -179,21 +168,15 @@ QPDF_String::getVal() const std::string QPDF_String::getUTF8Val() const { - if (QUtil::is_utf16(this->val)) - { + if (QUtil::is_utf16(this->val)) { return QUtil::utf16_to_utf8(this->val); - } - else if ((val.length() >= 3) && - (val.at(0) == '\xEF') && - (val.at(1) == '\xBB') && - (val.at(2) == '\xBF')) - { + } else if ( + (val.length() >= 3) && (val.at(0) == '\xEF') && (val.at(1) == '\xBB') && + (val.at(2) == '\xBF')) { // PDF 2.0 allows UTF-8 strings when explicitly prefixed with // the above bytes, which is just UTF-8 encoding of U+FEFF. return this->val.substr(3); - } - else - { + } else { return QUtil::pdf_doc_to_utf8(this->val); } } diff --git a/libqpdf/QPDF_encryption.cc b/libqpdf/QPDF_encryption.cc index 75b45aef..86e2a906 100644 --- a/libqpdf/QPDF_encryption.cc +++ b/libqpdf/QPDF_encryption.cc @@ -5,25 +5,23 @@ #include -#include -#include -#include +#include #include #include +#include #include +#include +#include #include -#include #include #include #include static unsigned char const padding_string[] = { - 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, - 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, - 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, - 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a -}; + 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, + 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, + 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a}; static unsigned int const key_bytes = 32; @@ -130,8 +128,8 @@ QPDF::EncryptionData::setV5EncryptionParameters( static void pad_or_truncate_password_V4(std::string const& password, char k1[key_bytes]) { - size_t password_bytes = std::min(QIntC::to_size(key_bytes), - password.length()); + size_t password_bytes = + std::min(QIntC::to_size(key_bytes), password.length()); size_t pad_bytes = key_bytes - password_bytes; memcpy(k1, password.c_str(), password_bytes); memcpy(k1 + password_bytes, padding_string, pad_bytes); @@ -145,23 +143,18 @@ QPDF::trim_user_password(std::string& user_password) // recovery of user passwords which is done in the test suite. char const* cstr = user_password.c_str(); size_t len = user_password.length(); - if (len < key_bytes) - { + if (len < key_bytes) { return; } char const* p1 = cstr; char const* p2 = 0; - while ((p2 = strchr(p1, '\x28')) != 0) - { + while ((p2 = strchr(p1, '\x28')) != 0) { size_t idx = toS(p2 - cstr); - if (memcmp(p2, padding_string, len - idx) == 0) - { + if (memcmp(p2, padding_string, len - idx) == 0) { user_password = user_password.substr(0, idx); return; - } - else - { + } else { QTC::TC("qpdf", "QPDF_encryption skip 0x28"); p1 = p2 + 1; } @@ -184,33 +177,32 @@ truncate_password_V5(std::string const& password) } static void -iterate_md5_digest(MD5& md5, MD5::Digest& digest, - int iterations, int key_len) +iterate_md5_digest(MD5& md5, MD5::Digest& digest, int iterations, int key_len) { md5.digest(digest); - for (int i = 0; i < iterations; ++i) - { + for (int i = 0; i < iterations; ++i) { MD5 m; - m.encodeDataIncrementally(reinterpret_cast(digest), - QIntC::to_size(key_len)); + m.encodeDataIncrementally( + reinterpret_cast(digest), QIntC::to_size(key_len)); m.digest(digest); } } - static void -iterate_rc4(unsigned char* data, size_t data_len, - unsigned char* okey, int key_len, - int iterations, bool reverse) +iterate_rc4( + unsigned char* data, + size_t data_len, + unsigned char* okey, + int key_len, + int iterations, + bool reverse) { auto key_ph = std::make_unique(QIntC::to_size(key_len)); unsigned char* key = key_ph.get(); - for (int i = 0; i < iterations; ++i) - { + for (int i = 0; i < iterations; ++i) { int const xor_value = (reverse ? iterations - 1 - i : i); - for (int j = 0; j < key_len; ++j) - { + for (int j = 0; j < key_len; ++j) { key[j] = static_cast(okey[j] ^ xor_value); } RC4 rc4(key, QIntC::to_int(key_len)); @@ -219,49 +211,47 @@ iterate_rc4(unsigned char* data, size_t data_len, } static std::string -process_with_aes(std::string const& key, - bool encrypt, - std::string const& data, - size_t outlength = 0, - unsigned int repetitions = 1, - unsigned char const* iv = 0, - size_t iv_length = 0) +process_with_aes( + std::string const& key, + bool encrypt, + std::string const& data, + size_t outlength = 0, + unsigned int repetitions = 1, + unsigned char const* iv = 0, + size_t iv_length = 0) { Pl_Buffer buffer("buffer"); - Pl_AES_PDF aes("aes", &buffer, encrypt, - QUtil::unsigned_char_pointer(key), - QIntC::to_uint(key.length())); - if (iv) - { + Pl_AES_PDF aes( + "aes", + &buffer, + encrypt, + QUtil::unsigned_char_pointer(key), + QIntC::to_uint(key.length())); + if (iv) { aes.setIV(iv, iv_length); - } - else - { + } else { aes.useZeroIV(); } aes.disablePadding(); - for (unsigned int i = 0; i < repetitions; ++i) - { + for (unsigned int i = 0; i < repetitions; ++i) { aes.write(QUtil::unsigned_char_pointer(data), data.length()); } aes.finish(); auto bufp = buffer.getBufferSharedPointer(); - if (outlength == 0) - { + if (outlength == 0) { outlength = bufp->getSize(); - } - else - { + } else { outlength = std::min(outlength, bufp->getSize()); } return std::string(reinterpret_cast(bufp->getBuffer()), outlength); } static std::string -hash_V5(std::string const& password, - std::string const& salt, - std::string const& udata, - QPDF::EncryptionData const& data) +hash_V5( + std::string const& password, + std::string const& salt, + std::string const& udata, + QPDF::EncryptionData const& data) { Pl_SHA2 hash(256); hash.write(QUtil::unsigned_char_pointer(password), password.length()); @@ -271,18 +261,14 @@ hash_V5(std::string const& password, std::string K = hash.getRawDigest(); std::string result; - if (data.getR() < 6) - { + if (data.getR() < 6) { result = K; - } - else - { + } else { // Algorithm 2.B from ISO 32000-1 chapter 7: Computing a hash int round_number = 0; bool done = false; - while (! done) - { + while (!done) { // The hash algorithm has us setting K initially to the R5 // value and then repeating a series of steps 64 times // before starting with the termination case testing. The @@ -304,8 +290,13 @@ hash_V5(std::string const& password, std::string K1 = password + K + udata; assert(K.length() >= 32); std::string E = process_with_aes( - K.substr(0, 16), true, K1, 0, 64, - QUtil::unsigned_char_pointer(K.substr(16, 16)), 16); + K.substr(0, 16), + true, + K1, + 0, + 64, + QUtil::unsigned_char_pointer(K.substr(16, 16)), + 16); // E_mod_3 is supposed to be mod 3 of the first 16 bytes // of E taken as as a (128-bit) big-endian number. Since @@ -313,25 +304,20 @@ hash_V5(std::string const& password, // and since 256 mod n is 1, we can just take the sums of // the the mod 3s of each byte to get the same result. int E_mod_3 = 0; - for (unsigned int i = 0; i < 16; ++i) - { + for (unsigned int i = 0; i < 16; ++i) { E_mod_3 += static_cast(E.at(i)); } E_mod_3 %= 3; - int next_hash = ((E_mod_3 == 0) ? 256 : - (E_mod_3 == 1) ? 384 : - 512); + int next_hash = ((E_mod_3 == 0) ? 256 : (E_mod_3 == 1) ? 384 : 512); Pl_SHA2 sha2(next_hash); sha2.write(QUtil::unsigned_char_pointer(E), E.length()); sha2.finish(); K = sha2.getRawDigest(); - if (round_number >= 64) - { + if (round_number >= 64) { unsigned int ch = static_cast(*(E.rbegin())); - if (ch <= QIntC::to_uint(round_number - 32)) - { + if (ch <= QIntC::to_uint(round_number - 32)) { done = true; } } @@ -342,27 +328,29 @@ hash_V5(std::string const& password, return result; } -static -void pad_short_parameter(std::string& param, size_t max_len) +static void +pad_short_parameter(std::string& param, size_t max_len) { - if (param.length() < max_len) - { + if (param.length() < max_len) { QTC::TC("qpdf", "QPDF_encryption pad short parameter"); param.append(max_len - param.length(), '\0'); } } std::string -QPDF::compute_data_key(std::string const& encryption_key, - int objid, int generation, bool use_aes, - int encryption_V, int encryption_R) +QPDF::compute_data_key( + std::string const& encryption_key, + int objid, + int generation, + bool use_aes, + int encryption_V, + int encryption_R) { // Algorithm 3.1 from the PDF 1.7 Reference Manual std::string result = encryption_key; - if (encryption_V >= 5) - { + if (encryption_V >= 5) { // Algorithm 3.1a (PDF 1.7 extension level 3): just use // encryption key straight. return result; @@ -374,8 +362,7 @@ QPDF::compute_data_key(std::string const& encryption_key, result.append(1, static_cast((objid >> 16) & 0xff)); result.append(1, static_cast(generation & 0xff)); result.append(1, static_cast((generation >> 8) & 0xff)); - if (use_aes) - { + if (use_aes) { result += "sAlT"; } @@ -383,23 +370,20 @@ QPDF::compute_data_key(std::string const& encryption_key, md5.encodeDataIncrementally(result.c_str(), result.length()); MD5::Digest digest; md5.digest(digest); - return std::string(reinterpret_cast(digest), - std::min(result.length(), toS(16))); + return std::string( + reinterpret_cast(digest), std::min(result.length(), toS(16))); } std::string QPDF::compute_encryption_key( std::string const& password, EncryptionData const& data) { - if (data.getV() >= 5) - { + if (data.getV() >= 5) { // For V >= 5, the encryption key is generated and stored in // the file, encrypted separately with both user and owner // passwords. return recover_encryption_key_with_password(password, data); - } - else - { + } else { // For V < 5, the encryption key is derived from the user // password. return compute_encryption_key_from_password(password, data); @@ -430,10 +414,8 @@ QPDF::compute_encryption_key_from_password( pbytes[2] = static_cast((P >> 16) & 0xff); pbytes[3] = static_cast((P >> 24) & 0xff); md5.encodeDataIncrementally(pbytes, 4); - md5.encodeDataIncrementally(data.getId1().c_str(), - data.getId1().length()); - if ((data.getR() >= 4) && (! data.getEncryptMetadata())) - { + md5.encodeDataIncrementally(data.getId1().c_str(), data.getId1().length()); + if ((data.getR() >= 4) && (!data.getEncryptMetadata())) { char bytes[4]; memset(bytes, 0xff, 4); md5.encodeDataIncrementally(bytes, 4); @@ -442,40 +424,39 @@ QPDF::compute_encryption_key_from_password( int key_len = std::min(QIntC::to_int(sizeof(digest)), data.getLengthBytes()); iterate_md5_digest(md5, digest, ((data.getR() >= 3) ? 50 : 0), key_len); - return std::string(reinterpret_cast(digest), - QIntC::to_size(key_len)); + return std::string( + reinterpret_cast(digest), QIntC::to_size(key_len)); } static void -compute_O_rc4_key(std::string const& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data, - unsigned char key[OU_key_bytes_V4]) +compute_O_rc4_key( + std::string const& user_password, + std::string const& owner_password, + QPDF::EncryptionData const& data, + unsigned char key[OU_key_bytes_V4]) { - if (data.getV() >= 5) - { - throw std::logic_error( - "compute_O_rc4_key called for file with V >= 5"); + if (data.getV() >= 5) { + throw std::logic_error("compute_O_rc4_key called for file with V >= 5"); } std::string password = owner_password; - if (password.empty()) - { + if (password.empty()) { password = user_password; } MD5 md5; md5.encodeDataIncrementally( pad_or_truncate_password_V4(password).c_str(), key_bytes); MD5::Digest digest; - int key_len = std::min(QIntC::to_int(sizeof(digest)), - data.getLengthBytes()); + int key_len = + std::min(QIntC::to_int(sizeof(digest)), data.getLengthBytes()); iterate_md5_digest(md5, digest, ((data.getR() >= 3) ? 50 : 0), key_len); memcpy(key, digest, OU_key_bytes_V4); } static std::string -compute_O_value(std::string const& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data) +compute_O_value( + std::string const& user_password, + std::string const& owner_password, + QPDF::EncryptionData const& data) { // Algorithm 3.3 from the PDF 1.7 Reference Manual @@ -486,16 +467,19 @@ compute_O_value(std::string const& user_password, pad_or_truncate_password_V4(user_password, upass); std::string k1(reinterpret_cast(O_key), OU_key_bytes_V4); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); - iterate_rc4(QUtil::unsigned_char_pointer(upass), key_bytes, - O_key, data.getLengthBytes(), - (data.getR() >= 3) ? 20 : 1, false); + iterate_rc4( + QUtil::unsigned_char_pointer(upass), + key_bytes, + O_key, + data.getLengthBytes(), + (data.getR() >= 3) ? 20 : 1, + false); return std::string(upass, key_bytes); } -static -std::string -compute_U_value_R2(std::string const& user_password, - QPDF::EncryptionData const& data) +static std::string +compute_U_value_R2( + std::string const& user_password, QPDF::EncryptionData const& data) { // Algorithm 3.4 from the PDF 1.7 Reference Manual @@ -503,16 +487,19 @@ compute_U_value_R2(std::string const& user_password, char udata[key_bytes]; pad_or_truncate_password_V4("", udata); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); - iterate_rc4(QUtil::unsigned_char_pointer(udata), key_bytes, - QUtil::unsigned_char_pointer(k1), - data.getLengthBytes(), 1, false); + iterate_rc4( + QUtil::unsigned_char_pointer(udata), + key_bytes, + QUtil::unsigned_char_pointer(k1), + data.getLengthBytes(), + 1, + false); return std::string(udata, key_bytes); } -static -std::string -compute_U_value_R3(std::string const& user_password, - QPDF::EncryptionData const& data) +static std::string +compute_U_value_R3( + std::string const& user_password, QPDF::EncryptionData const& data) { // Algorithm 3.5 from the PDF 1.7 Reference Manual @@ -520,31 +507,32 @@ compute_U_value_R3(std::string const& user_password, MD5 md5; md5.encodeDataIncrementally( pad_or_truncate_password_V4("").c_str(), key_bytes); - md5.encodeDataIncrementally(data.getId1().c_str(), - data.getId1().length()); + md5.encodeDataIncrementally(data.getId1().c_str(), data.getId1().length()); MD5::Digest digest; md5.digest(digest); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); - iterate_rc4(digest, sizeof(MD5::Digest), - QUtil::unsigned_char_pointer(k1), - data.getLengthBytes(), 20, false); + iterate_rc4( + digest, + sizeof(MD5::Digest), + QUtil::unsigned_char_pointer(k1), + data.getLengthBytes(), + 20, + false); char result[key_bytes]; memcpy(result, digest, sizeof(MD5::Digest)); // pad with arbitrary data -- make it consistent for the sake of // testing - for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i) - { + for (unsigned int i = sizeof(MD5::Digest); i < key_bytes; ++i) { result[i] = static_cast((i * i) % 0xff); } return std::string(result, key_bytes); } static std::string -compute_U_value(std::string const& user_password, - QPDF::EncryptionData const& data) +compute_U_value( + std::string const& user_password, QPDF::EncryptionData const& data) { - if (data.getR() >= 3) - { + if (data.getR() >= 3) { return compute_U_value_R3(user_password, data); } @@ -552,20 +540,19 @@ compute_U_value(std::string const& user_password, } static bool -check_user_password_V4(std::string const& user_password, - QPDF::EncryptionData const& data) +check_user_password_V4( + std::string const& user_password, QPDF::EncryptionData const& data) { // Algorithm 3.6 from the PDF 1.7 Reference Manual std::string u_value = compute_U_value(user_password, data); - size_t to_compare = ((data.getR() >= 3) ? sizeof(MD5::Digest) - : key_bytes); + size_t to_compare = ((data.getR() >= 3) ? sizeof(MD5::Digest) : key_bytes); return (memcmp(data.getU().c_str(), u_value.c_str(), to_compare) == 0); } static bool -check_user_password_V5(std::string const& user_password, - QPDF::EncryptionData const& data) +check_user_password_V5( + std::string const& user_password, QPDF::EncryptionData const& data) { // Algorithm 3.11 from the PDF 1.7 extension level 3 @@ -576,23 +563,21 @@ check_user_password_V5(std::string const& user_password, } static bool -check_user_password(std::string const& user_password, - QPDF::EncryptionData const& data) +check_user_password( + std::string const& user_password, QPDF::EncryptionData const& data) { - if (data.getV() < 5) - { + if (data.getV() < 5) { return check_user_password_V4(user_password, data); - } - else - { + } else { return check_user_password_V5(user_password, data); } } static bool -check_owner_password_V4(std::string& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data) +check_owner_password_V4( + std::string& user_password, + std::string const& owner_password, + QPDF::EncryptionData const& data) { // Algorithm 3.7 from the PDF 1.7 Reference Manual @@ -602,14 +587,17 @@ check_owner_password_V4(std::string& user_password, memcpy(O_data, QUtil::unsigned_char_pointer(data.getO()), key_bytes); std::string k1(reinterpret_cast(key), OU_key_bytes_V4); pad_short_parameter(k1, QIntC::to_size(data.getLengthBytes())); - iterate_rc4(O_data, key_bytes, QUtil::unsigned_char_pointer(k1), - data.getLengthBytes(), - (data.getR() >= 3) ? 20 : 1, true); + iterate_rc4( + O_data, + key_bytes, + QUtil::unsigned_char_pointer(k1), + data.getLengthBytes(), + (data.getR() >= 3) ? 20 : 1, + true); std::string new_user_password = std::string(reinterpret_cast(O_data), key_bytes); bool result = false; - if (check_user_password(new_user_password, data)) - { + if (check_user_password(new_user_password, data)) { result = true; user_password = new_user_password; } @@ -617,8 +605,8 @@ check_owner_password_V4(std::string& user_password, } static bool -check_owner_password_V5(std::string const& owner_password, - QPDF::EncryptionData const& data) +check_owner_password_V5( + std::string const& owner_password, QPDF::EncryptionData const& data) { // Algorithm 3.12 from the PDF 1.7 extension level 3 @@ -626,21 +614,18 @@ check_owner_password_V5(std::string const& owner_password, std::string owner_data = data.getO().substr(0, 32); std::string validation_salt = data.getO().substr(32, 8); std::string password = truncate_password_V5(owner_password); - return (hash_V5(password, validation_salt, user_data, - data) == owner_data); + return (hash_V5(password, validation_salt, user_data, data) == owner_data); } static bool -check_owner_password(std::string& user_password, - std::string const& owner_password, - QPDF::EncryptionData const& data) +check_owner_password( + std::string& user_password, + std::string const& owner_password, + QPDF::EncryptionData const& data) { - if (data.getV() < 5) - { + if (data.getV() < 5) { return check_owner_password_V4(user_password, owner_password, data); - } - else - { + } else { return check_owner_password_V5(owner_password, data); } } @@ -655,10 +640,12 @@ QPDF::recover_encryption_key_with_password( } static void -compute_U_UE_value_V5(std::string const& user_password, - std::string const& encryption_key, - QPDF::EncryptionData const& data, - std::string& U, std::string& UE) +compute_U_UE_value_V5( + std::string const& user_password, + std::string const& encryption_key, + QPDF::EncryptionData const& data, + std::string& U, + std::string& UE) { // Algorithm 3.8 from the PDF 1.7 extension level 3 char k[16]; @@ -666,18 +653,20 @@ compute_U_UE_value_V5(std::string const& user_password, reinterpret_cast(k), sizeof(k)); std::string validation_salt(k, 8); std::string key_salt(k + 8, 8); - U = hash_V5(user_password, validation_salt, "", data) + - validation_salt + key_salt; + U = hash_V5(user_password, validation_salt, "", data) + validation_salt + + key_salt; std::string intermediate_key = hash_V5(user_password, key_salt, "", data); UE = process_with_aes(intermediate_key, true, encryption_key); } static void -compute_O_OE_value_V5(std::string const& owner_password, - std::string const& encryption_key, - QPDF::EncryptionData const& data, - std::string const& U, - std::string& O, std::string& OE) +compute_O_OE_value_V5( + std::string const& owner_password, + std::string const& encryption_key, + QPDF::EncryptionData const& data, + std::string const& U, + std::string& O, + std::string& OE) { // Algorithm 3.9 from the PDF 1.7 extension level 3 char k[16]; @@ -685,22 +674,22 @@ compute_O_OE_value_V5(std::string const& owner_password, reinterpret_cast(k), sizeof(k)); std::string validation_salt(k, 8); std::string key_salt(k + 8, 8); - O = hash_V5(owner_password, validation_salt, U, data) + - validation_salt + key_salt; + O = hash_V5(owner_password, validation_salt, U, data) + validation_salt + + key_salt; std::string intermediate_key = hash_V5(owner_password, key_salt, U, data); OE = process_with_aes(intermediate_key, true, encryption_key); } void -compute_Perms_value_V5_clear(std::string const& encryption_key, - QPDF::EncryptionData const& data, - unsigned char k[16]) +compute_Perms_value_V5_clear( + std::string const& encryption_key, + QPDF::EncryptionData const& data, + unsigned char k[16]) { // From algorithm 3.10 from the PDF 1.7 extension level 3 unsigned long long extended_perms = 0xffffffff00000000LL | static_cast(data.getP()); - for (int i = 0; i < 8; ++i) - { + for (int i = 0; i < 8; ++i) { k[i] = static_cast(extended_perms & 0xff); extended_perms >>= 8; } @@ -712,21 +701,21 @@ compute_Perms_value_V5_clear(std::string const& encryption_key, } static std::string -compute_Perms_value_V5(std::string const& encryption_key, - QPDF::EncryptionData const& data) +compute_Perms_value_V5( + std::string const& encryption_key, QPDF::EncryptionData const& data) { // Algorithm 3.10 from the PDF 1.7 extension level 3 unsigned char k[16]; compute_Perms_value_V5_clear(encryption_key, data, k); return process_with_aes( - encryption_key, true, + encryption_key, + true, std::string(reinterpret_cast(k), sizeof(k))); } std::string QPDF::recover_encryption_key_with_password( - std::string const& password, EncryptionData const& data, - bool& perms_valid) + std::string const& password, EncryptionData const& data, bool& perms_valid) { // Algorithm 3.2a from the PDF 1.7 extension level 3 @@ -741,14 +730,11 @@ QPDF::recover_encryption_key_with_password( std::string key_salt; std::string user_data; std::string encrypted_file_key; - if (check_owner_password_V5(key_password, data)) - { + if (check_owner_password_V5(key_password, data)) { key_salt = data.getO().substr(40, 8); user_data = data.getU().substr(0, 48); encrypted_file_key = data.getOE().substr(0, 32); - } - else if (check_user_password_V5(key_password, data)) - { + } else if (check_user_password_V5(key_password, data)) { key_salt = data.getU().substr(40, 8); encrypted_file_key = data.getUE().substr(0, 32); } @@ -768,27 +754,18 @@ QPDF::recover_encryption_key_with_password( } QPDF::encryption_method_e -QPDF::interpretCF( - PointerHolder encp, QPDFObjectHandle cf) +QPDF::interpretCF(PointerHolder encp, QPDFObjectHandle cf) { - if (cf.isName()) - { + if (cf.isName()) { std::string filter = cf.getName(); - if (encp->crypt_filters.count(filter) != 0) - { + if (encp->crypt_filters.count(filter) != 0) { return encp->crypt_filters[filter]; - } - else if (filter == "/Identity") - { + } else if (filter == "/Identity") { return e_none; - } - else - { + } else { return e_unknown; } - } - else - { + } else { // Default: /Identity return e_none; } @@ -797,8 +774,7 @@ QPDF::interpretCF( void QPDF::initializeEncryption() { - if (this->m->encp->encryption_initialized) - { + if (this->m->encp->encryption_initialized) { return; } this->m->encp->encryption_initialized = true; @@ -808,8 +784,7 @@ QPDF::initializeEncryption() // things could go wrong if someone mutates the encryption // dictionary. - if (! this->m->trailer.hasKey("/Encrypt")) - { + if (!this->m->trailer.hasKey("/Encrypt")) { return; } @@ -820,56 +795,62 @@ QPDF::initializeEncryption() std::string id1; QPDFObjectHandle id_obj = this->m->trailer.getKey("/ID"); - if ((id_obj.isArray() && - (id_obj.getArrayNItems() == 2) && - id_obj.getArrayItem(0).isString())) - { + if ((id_obj.isArray() && (id_obj.getArrayNItems() == 2) && + id_obj.getArrayItem(0).isString())) { id1 = id_obj.getArrayItem(0).getStringValue(); - } - else - { + } else { // Treating a missing ID as the empty string enables qpdf to // decrypt some invalid encrypted files with no /ID that // poppler can read but Adobe Reader can't. - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "trailer", this->m->file->getLastOffset(), - "invalid /ID in trailer dictionary")); + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "trailer", + this->m->file->getLastOffset(), + "invalid /ID in trailer dictionary")); } QPDFObjectHandle encryption_dict = this->m->trailer.getKey("/Encrypt"); - if (! encryption_dict.isDictionary()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "/Encrypt in trailer dictionary is not a dictionary"); + if (!encryption_dict.isDictionary()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "/Encrypt in trailer dictionary is not a dictionary"); } - if (! (encryption_dict.getKey("/Filter").isName() && - (encryption_dict.getKey("/Filter").getName() == "/Standard"))) - { - throw QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "unsupported encryption filter"); + if (!(encryption_dict.getKey("/Filter").isName() && + (encryption_dict.getKey("/Filter").getName() == "/Standard"))) { + throw QPDFExc( + qpdf_e_unsupported, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "unsupported encryption filter"); } - if (! encryption_dict.getKey("/SubFilter").isNull()) - { - warn(QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "file uses encryption SubFilters," - " which qpdf does not support")); + if (!encryption_dict.getKey("/SubFilter").isNull()) { + warn(QPDFExc( + qpdf_e_unsupported, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "file uses encryption SubFilters," + " which qpdf does not support")); } - if (! (encryption_dict.getKey("/V").isInteger() && - encryption_dict.getKey("/R").isInteger() && - encryption_dict.getKey("/O").isString() && - encryption_dict.getKey("/U").isString() && - encryption_dict.getKey("/P").isInteger())) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "some encryption dictionary parameters are missing " - "or the wrong type"); + if (!(encryption_dict.getKey("/V").isInteger() && + encryption_dict.getKey("/R").isInteger() && + encryption_dict.getKey("/O").isString() && + encryption_dict.getKey("/U").isString() && + encryption_dict.getKey("/P").isInteger())) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "some encryption dictionary parameters are missing " + "or the wrong type"); } int V = encryption_dict.getKey("/V").getIntValueAsInt(); @@ -880,14 +861,16 @@ QPDF::initializeEncryption() // If supporting new encryption R/V values, remember to update // error message inside this if statement. - if (! (((R >= 2) && (R <= 6)) && - ((V == 1) || (V == 2) || (V == 4) || (V == 5)))) - { - throw QPDFExc(qpdf_e_unsupported, this->m->file->getName(), - "encryption dictionary", this->m->file->getLastOffset(), - "Unsupported /R or /V in encryption dictionary; R = " + - QUtil::int_to_string(R) + " (max 6), V = " + - QUtil::int_to_string(V) + " (max 5)"); + if (!(((R >= 2) && (R <= 6)) && + ((V == 1) || (V == 2) || (V == 4) || (V == 5)))) { + throw QPDFExc( + qpdf_e_unsupported, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "Unsupported /R or /V in encryption dictionary; R = " + + QUtil::int_to_string(R) + + " (max 6), V = " + QUtil::int_to_string(V) + " (max 5)"); } this->m->encp->encryption_V = V; @@ -898,31 +881,30 @@ QPDF::initializeEncryption() std::string UE; std::string Perms; - if (V < 5) - { + if (V < 5) { // These must be exactly the right number of bytes. pad_short_parameter(O, key_bytes); pad_short_parameter(U, key_bytes); - if (! ((O.length() == key_bytes) && (U.length() == key_bytes))) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "encryption dictionary", - this->m->file->getLastOffset(), - "incorrect length for /O and/or /U in " - "encryption dictionary"); + if (!((O.length() == key_bytes) && (U.length() == key_bytes))) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "incorrect length for /O and/or /U in " + "encryption dictionary"); } - } - else - { - if (! (encryption_dict.getKey("/OE").isString() && - encryption_dict.getKey("/UE").isString() && - encryption_dict.getKey("/Perms").isString())) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "encryption dictionary", - this->m->file->getLastOffset(), - "some V=5 encryption dictionary parameters are " - "missing or the wrong type"); + } else { + if (!(encryption_dict.getKey("/OE").isString() && + encryption_dict.getKey("/UE").isString() && + encryption_dict.getKey("/Perms").isString())) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "some V=5 encryption dictionary parameters are " + "missing or the wrong type"); } OE = encryption_dict.getKey("/OE").getStringValue(); UE = encryption_dict.getKey("/UE").getStringValue(); @@ -937,74 +919,53 @@ QPDF::initializeEncryption() } int Length = 0; - if (V <= 1) - { + if (V <= 1) { Length = 40; - } - else if (V == 4) - { + } else if (V == 4) { Length = 128; - } - else if (V == 5) - { + } else if (V == 5) { Length = 256; - } - else - { - if (encryption_dict.getKey("/Length").isInteger()) - { + } else { + if (encryption_dict.getKey("/Length").isInteger()) { Length = encryption_dict.getKey("/Length").getIntValueAsInt(); - if ((Length % 8) || (Length < 40) || (Length > 128)) - { + if ((Length % 8) || (Length < 40) || (Length > 128)) { Length = 0; } } } - if (Length == 0) - { + if (Length == 0) { // Still no Length? Just take a guess. Length = 128; } this->m->encp->encrypt_metadata = true; - if ((V >= 4) && (encryption_dict.getKey("/EncryptMetadata").isBool())) - { + if ((V >= 4) && (encryption_dict.getKey("/EncryptMetadata").isBool())) { this->m->encp->encrypt_metadata = encryption_dict.getKey("/EncryptMetadata").getBoolValue(); } - if ((V == 4) || (V == 5)) - { + if ((V == 4) || (V == 5)) { QPDFObjectHandle CF = encryption_dict.getKey("/CF"); std::set keys = CF.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& filter = *iter; QPDFObjectHandle cdict = CF.getKey(filter); - if (cdict.isDictionary()) - { + if (cdict.isDictionary()) { encryption_method_e method = e_none; - if (cdict.getKey("/CFM").isName()) - { + if (cdict.getKey("/CFM").isName()) { std::string method_name = cdict.getKey("/CFM").getName(); - if (method_name == "/V2") - { + if (method_name == "/V2") { QTC::TC("qpdf", "QPDF_encryption CFM V2"); method = e_rc4; - } - else if (method_name == "/AESV2") - { + } else if (method_name == "/AESV2") { QTC::TC("qpdf", "QPDF_encryption CFM AESV2"); method = e_aes; - } - else if (method_name == "/AESV3") - { + } else if (method_name == "/AESV3") { QTC::TC("qpdf", "QPDF_encryption CFM AESV3"); method = e_aesv3; - } - else - { + } else { // Don't complain now -- maybe we won't need // to reference this type. method = e_unknown; @@ -1019,8 +980,7 @@ QPDF::initializeEncryption() QPDFObjectHandle EFF = encryption_dict.getKey("/EFF"); this->m->encp->cf_stream = interpretCF(this->m->encp, StmF); this->m->encp->cf_string = interpretCF(this->m->encp, StrF); - if (EFF.isName()) - { + if (EFF.isName()) { // qpdf does not use this for anything other than // informational purposes. This is intended to instruct // conforming writers on which crypt filter should be used @@ -1036,87 +996,83 @@ QPDF::initializeEncryption() // when specifying that only attachments should be // encrypted. this->m->encp->cf_file = interpretCF(this->m->encp, EFF); - } - else - { + } else { this->m->encp->cf_file = this->m->encp->cf_stream; } } - EncryptionData data(V, R, Length / 8, - P, O, U, OE, UE, Perms, - id1, this->m->encp->encrypt_metadata); - if (this->m->provided_password_is_hex_key) - { + EncryptionData data( + V, + R, + Length / 8, + P, + O, + U, + OE, + UE, + Perms, + id1, + this->m->encp->encrypt_metadata); + if (this->m->provided_password_is_hex_key) { // ignore passwords in file - } - else - { + } else { this->m->encp->owner_password_matched = check_owner_password( this->m->encp->user_password, - this->m->encp->provided_password, data); - if (this->m->encp->owner_password_matched && (V < 5)) - { + this->m->encp->provided_password, + data); + if (this->m->encp->owner_password_matched && (V < 5)) { // password supplied was owner password; user_password has // been initialized for V < 5 - if (getTrimmedUserPassword() == this->m->encp->provided_password) - { + if (getTrimmedUserPassword() == this->m->encp->provided_password) { this->m->encp->user_password_matched = true; QTC::TC("qpdf", "QPDF_encryption user matches owner V < 5"); } - } - else - { - this->m->encp->user_password_matched = check_user_password( - this->m->encp->provided_password, data); - if (this->m->encp->user_password_matched) - { - this->m->encp->user_password = - this->m->encp->provided_password; + } else { + this->m->encp->user_password_matched = + check_user_password(this->m->encp->provided_password, data); + if (this->m->encp->user_password_matched) { + this->m->encp->user_password = this->m->encp->provided_password; } } if (this->m->encp->user_password_matched && - this->m->encp->owner_password_matched) - { - QTC::TC("qpdf", "QPDF_encryption same password", - (V < 5) ? 0 : 1); + this->m->encp->owner_password_matched) { + QTC::TC("qpdf", "QPDF_encryption same password", (V < 5) ? 0 : 1); } - if (! (this->m->encp->owner_password_matched || - this->m->encp->user_password_matched)) - { - throw QPDFExc(qpdf_e_password, this->m->file->getName(), - "", 0, "invalid password"); + if (!(this->m->encp->owner_password_matched || + this->m->encp->user_password_matched)) { + throw QPDFExc( + qpdf_e_password, + this->m->file->getName(), + "", + 0, + "invalid password"); } } - if (this->m->provided_password_is_hex_key) - { + if (this->m->provided_password_is_hex_key) { this->m->encp->encryption_key = QUtil::hex_decode(this->m->encp->provided_password); - } - else if (V < 5) - { + } else if (V < 5) { // For V < 5, the user password is encrypted with the owner // password, and the user password is always used for // computing the encryption key. - this->m->encp->encryption_key = compute_encryption_key( - this->m->encp->user_password, data); - } - else - { + this->m->encp->encryption_key = + compute_encryption_key(this->m->encp->user_password, data); + } else { // For V >= 5, either password can be used independently to // compute the encryption key, and neither password can be // used to recover the other. bool perms_valid; this->m->encp->encryption_key = recover_encryption_key_with_password( this->m->encp->provided_password, data, perms_valid); - if (! perms_valid) - { - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "encryption dictionary", - this->m->file->getLastOffset(), - "/Perms field in encryption dictionary" - " doesn't match expected value")); + if (!perms_valid) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "encryption dictionary", + this->m->file->getLastOffset(), + "/Perms field in encryption dictionary" + " doesn't match expected value")); } } } @@ -1124,21 +1080,24 @@ QPDF::initializeEncryption() std::string QPDF::getKeyForObject( PointerHolder encp, - int objid, int generation, bool use_aes) + int objid, + int generation, + bool use_aes) { - if (! encp->encrypted) - { + if (!encp->encrypted) { throw std::logic_error( "request for encryption key in non-encrypted PDF"); } - if (! ((objid == encp->cached_key_objid) && - (generation == encp->cached_key_generation))) - { - encp->cached_object_encryption_key = - compute_data_key(encp->encryption_key, objid, generation, - use_aes, encp->encryption_V, - encp->encryption_R); + if (!((objid == encp->cached_key_objid) && + (generation == encp->cached_key_generation))) { + encp->cached_object_encryption_key = compute_data_key( + encp->encryption_key, + objid, + generation, + use_aes, + encp->encryption_V, + encp->encryption_R); encp->cached_key_objid = objid; encp->cached_key_generation = generation; } @@ -1149,36 +1108,35 @@ QPDF::getKeyForObject( void QPDF::decryptString(std::string& str, int objid, int generation) { - if (objid == 0) - { + if (objid == 0) { return; } bool use_aes = false; - if (this->m->encp->encryption_V >= 4) - { - switch (this->m->encp->cf_string) - { - case e_none: + if (this->m->encp->encryption_V >= 4) { + switch (this->m->encp->cf_string) { + case e_none: return; - case e_aes: + case e_aes: use_aes = true; break; - case e_aesv3: + case e_aesv3: use_aes = true; break; - case e_rc4: + case e_rc4: break; - default: - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "unknown encryption filter for strings" - " (check /StrF in /Encrypt dictionary);" - " strings may be decrypted improperly")); + default: + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "unknown encryption filter for strings" + " (check /StrF in /Encrypt dictionary);" + " strings may be decrypted improperly")); // To avoid repeated warnings, reset cf_string. Assume // we'd want to use AES if V == 4. this->m->encp->cf_string = e_aes; @@ -1187,25 +1145,24 @@ QPDF::decryptString(std::string& str, int objid, int generation) } } - std::string key = getKeyForObject( - this->m->encp, objid, generation, use_aes); - try - { - if (use_aes) - { + std::string key = + getKeyForObject(this->m->encp, objid, generation, use_aes); + try { + if (use_aes) { QTC::TC("qpdf", "QPDF_encryption aes decode string"); Pl_Buffer bufpl("decrypted string"); - Pl_AES_PDF pl("aes decrypt string", &bufpl, false, - QUtil::unsigned_char_pointer(key), - key.length()); + Pl_AES_PDF pl( + "aes decrypt string", + &bufpl, + false, + QUtil::unsigned_char_pointer(key), + key.length()); pl.write(QUtil::unsigned_char_pointer(str), str.length()); pl.finish(); auto buf = bufpl.getBufferSharedPointer(); - str = std::string(reinterpret_cast(buf->getBuffer()), - buf->getSize()); - } - else - { + str = std::string( + reinterpret_cast(buf->getBuffer()), buf->getSize()); + } else { QTC::TC("qpdf", "QPDF_encryption rc4 decode string"); size_t vlen = str.length(); // Using PointerHolder guarantees that tmp will @@ -1215,80 +1172,71 @@ QPDF::decryptString(std::string& str, int objid, int generation) rc4.process(QUtil::unsigned_char_pointer(tmp.get()), vlen); str = std::string(tmp.get(), vlen); } - } - catch (QPDFExc&) - { + } catch (QPDFExc&) { throw; - } - catch (std::runtime_error& e) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "error decrypting string for object " + - QUtil::int_to_string(objid) + " " + - QUtil::int_to_string(generation) + ": " + e.what()); + } catch (std::runtime_error& e) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "error decrypting string for object " + + QUtil::int_to_string(objid) + " " + + QUtil::int_to_string(generation) + ": " + e.what()); } } void -QPDF::decryptStream(PointerHolder encp, - PointerHolder file, - QPDF& qpdf_for_warning, Pipeline*& pipeline, - int objid, int generation, - QPDFObjectHandle& stream_dict, - std::vector>& heap) +QPDF::decryptStream( + PointerHolder encp, + PointerHolder file, + QPDF& qpdf_for_warning, + Pipeline*& pipeline, + int objid, + int generation, + QPDFObjectHandle& stream_dict, + std::vector>& heap) { std::string type; - if (stream_dict.getKey("/Type").isName()) - { + if (stream_dict.getKey("/Type").isName()) { type = stream_dict.getKey("/Type").getName(); } - if (type == "/XRef") - { + if (type == "/XRef") { QTC::TC("qpdf", "QPDF_encryption xref stream from encrypted file"); return; } bool use_aes = false; - if (encp->encryption_V >= 4) - { + if (encp->encryption_V >= 4) { encryption_method_e method = e_unknown; std::string method_source = "/StmF from /Encrypt dictionary"; - if (stream_dict.getKey("/Filter").isOrHasName("/Crypt")) - { - if (stream_dict.getKey("/DecodeParms").isDictionary()) - { + if (stream_dict.getKey("/Filter").isOrHasName("/Crypt")) { + if (stream_dict.getKey("/DecodeParms").isDictionary()) { QPDFObjectHandle decode_parms = stream_dict.getKey("/DecodeParms"); - if (decode_parms.isDictionaryOfType("/CryptFilterDecodeParms")) - { + if (decode_parms.isDictionaryOfType( + "/CryptFilterDecodeParms")) { QTC::TC("qpdf", "QPDF_encryption stream crypt filter"); method = interpretCF(encp, decode_parms.getKey("/Name")); method_source = "stream's Crypt decode parameters"; } - } - else if (stream_dict.getKey("/DecodeParms").isArray() && - stream_dict.getKey("/Filter").isArray()) - { + } else if ( + stream_dict.getKey("/DecodeParms").isArray() && + stream_dict.getKey("/Filter").isArray()) { QPDFObjectHandle filter = stream_dict.getKey("/Filter"); QPDFObjectHandle decode = stream_dict.getKey("/DecodeParms"); - if (filter.getArrayNItems() == decode.getArrayNItems()) - { - for (int i = 0; i < filter.getArrayNItems(); ++i) - { - if (filter.getArrayItem(i).isNameAndEquals("/Crypt")) - { + if (filter.getArrayNItems() == decode.getArrayNItems()) { + for (int i = 0; i < filter.getArrayNItems(); ++i) { + if (filter.getArrayItem(i).isNameAndEquals("/Crypt")) { QPDFObjectHandle crypt_params = decode.getArrayItem(i); if (crypt_params.isDictionary() && - crypt_params.getKey("/Name").isName()) - { + crypt_params.getKey("/Name").isName()) { QTC::TC("qpdf", "QPDF_encrypt crypt array"); method = interpretCF( encp, crypt_params.getKey("/Name")); method_source = "stream's Crypt " - "decode parameters (array)"; + "decode parameters (array)"; } } } @@ -1296,44 +1244,43 @@ QPDF::decryptStream(PointerHolder encp, } } - if (method == e_unknown) - { - if ((! encp->encrypt_metadata) && (type == "/Metadata")) - { + if (method == e_unknown) { + if ((!encp->encrypt_metadata) && (type == "/Metadata")) { QTC::TC("qpdf", "QPDF_encryption cleartext metadata"); method = e_none; - } - else - { + } else { method = encp->cf_stream; } } use_aes = false; - switch (method) - { - case e_none: + switch (method) { + case e_none: return; break; - case e_aes: + case e_aes: use_aes = true; break; - case e_aesv3: + case e_aesv3: use_aes = true; break; - case e_rc4: + case e_rc4: break; - default: + default: // filter local to this stream. - qpdf_for_warning.warn( - QPDFExc(qpdf_e_damaged_pdf, file->getName(), - "", file->getLastOffset(), - "unknown encryption filter for streams" - " (check " + method_source + ");" - " streams may be decrypted improperly")); + qpdf_for_warning.warn(QPDFExc( + qpdf_e_damaged_pdf, + file->getName(), + "", + file->getLastOffset(), + "unknown encryption filter for streams" + " (check " + + method_source + + ");" + " streams may be decrypted improperly")); // To avoid repeated warnings, reset cf_stream. Assume // we'd want to use AES if V == 4. encp->cf_stream = e_aes; @@ -1343,19 +1290,19 @@ QPDF::decryptStream(PointerHolder encp, } std::string key = getKeyForObject(encp, objid, generation, use_aes); std::shared_ptr new_pipeline; - if (use_aes) - { + if (use_aes) { QTC::TC("qpdf", "QPDF_encryption aes decode stream"); new_pipeline = std::make_shared( - "AES stream decryption", pipeline, - false, QUtil::unsigned_char_pointer(key), + "AES stream decryption", + pipeline, + false, + QUtil::unsigned_char_pointer(key), key.length()); - } - else - { + } else { QTC::TC("qpdf", "QPDF_encryption rc4 decode stream"); new_pipeline = std::make_shared( - "RC4 stream decryption", pipeline, + "RC4 stream decryption", + pipeline, QUtil::unsigned_char_pointer(key), toI(key.length())); } @@ -1365,17 +1312,23 @@ QPDF::decryptStream(PointerHolder encp, void QPDF::compute_encryption_O_U( - char const* user_password, char const* owner_password, - int V, int R, int key_len, int P, bool encrypt_metadata, - std::string const& id1, std::string& O, std::string& U) + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + int P, + bool encrypt_metadata, + std::string const& id1, + std::string& O, + std::string& U) { - if (V >= 5) - { + if (V >= 5) { throw std::logic_error( "compute_encryption_O_U called for file with V >= 5"); } - EncryptionData data(V, R, key_len, P, "", "", "", "", "", - id1, encrypt_metadata); + EncryptionData data( + V, R, key_len, P, "", "", "", "", "", id1, encrypt_metadata); data.setO(compute_O_value(user_password, owner_password, data)); O = data.getO(); data.setU(compute_U_value(user_password, data)); @@ -1384,15 +1337,23 @@ QPDF::compute_encryption_O_U( void QPDF::compute_encryption_parameters_V5( - char const* user_password, char const* owner_password, - int V, int R, int key_len, int P, bool encrypt_metadata, + char const* user_password, + char const* owner_password, + int V, + int R, + int key_len, + int P, + bool encrypt_metadata, std::string const& id1, std::string& encryption_key, - std::string& O, std::string& U, - std::string& OE, std::string& UE, std::string& Perms) + std::string& O, + std::string& U, + std::string& OE, + std::string& UE, + std::string& Perms) { - EncryptionData data(V, R, key_len, P, "", "", "", "", "", - id1, encrypt_metadata); + EncryptionData data( + V, R, key_len, P, "", "", "", "", "", id1, encrypt_metadata); unsigned char k[key_bytes]; QUtil::initializeWithRandomBytes(k, key_bytes); encryption_key = std::string(reinterpret_cast(k), key_bytes); @@ -1437,13 +1398,15 @@ QPDF::isEncrypted(int& R, int& P) } bool -QPDF::isEncrypted(int& R, int& P, int& V, - encryption_method_e& stream_method, - encryption_method_e& string_method, - encryption_method_e& file_method) +QPDF::isEncrypted( + int& R, + int& P, + int& V, + encryption_method_e& stream_method, + encryption_method_e& string_method, + encryption_method_e& file_method) { - if (this->m->encp->encrypted) - { + if (this->m->encp->encrypted) { QPDFObjectHandle trailer = getTrailer(); QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); QPDFObjectHandle Pkey = encrypt.getKey("/P"); @@ -1456,9 +1419,7 @@ QPDF::isEncrypted(int& R, int& P, int& V, string_method = this->m->encp->cf_string; file_method = this->m->encp->cf_file; return true; - } - else - { + } else { return false; } } @@ -1488,14 +1449,10 @@ QPDF::allowAccessibility() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { - if (R < 3) - { + if (isEncrypted(R, P)) { + if (R < 3) { status = is_bit_set(P, 5); - } - else - { + } else { status = is_bit_set(P, 10); } } @@ -1508,8 +1465,7 @@ QPDF::allowExtractAll() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = is_bit_set(P, 5); } return status; @@ -1521,8 +1477,7 @@ QPDF::allowPrintLowRes() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = is_bit_set(P, 3); } return status; @@ -1534,11 +1489,9 @@ QPDF::allowPrintHighRes() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = is_bit_set(P, 3); - if ((R >= 3) && (! is_bit_set(P, 12))) - { + if ((R >= 3) && (!is_bit_set(P, 12))) { status = false; } } @@ -1551,14 +1504,10 @@ QPDF::allowModifyAssembly() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { - if (R < 3) - { + if (isEncrypted(R, P)) { + if (R < 3) { status = is_bit_set(P, 4); - } - else - { + } else { status = is_bit_set(P, 11); } } @@ -1571,14 +1520,10 @@ QPDF::allowModifyForm() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { - if (R < 3) - { + if (isEncrypted(R, P)) { + if (R < 3) { status = is_bit_set(P, 6); - } - else - { + } else { status = is_bit_set(P, 9); } } @@ -1591,8 +1536,7 @@ QPDF::allowModifyAnnotation() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = is_bit_set(P, 6); } return status; @@ -1604,8 +1548,7 @@ QPDF::allowModifyOther() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = is_bit_set(P, 4); } return status; @@ -1617,11 +1560,9 @@ QPDF::allowModifyAll() int R = 0; int P = 0; bool status = true; - if (isEncrypted(R, P)) - { + if (isEncrypted(R, P)) { status = (is_bit_set(P, 4) && is_bit_set(P, 6)); - if (R >= 3) - { + if (R >= 3) { status = status && (is_bit_set(P, 9) && is_bit_set(P, 11)); } } diff --git a/libqpdf/QPDF_linearization.cc b/libqpdf/QPDF_linearization.cc index 443ae662..7c5fa4fa 100644 --- a/libqpdf/QPDF_linearization.cc +++ b/libqpdf/QPDF_linearization.cc @@ -2,40 +2,41 @@ #include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include #include #include +#include #include #include template static void -load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, - int bits_wanted, int_type T::*field) +load_vector_int( + BitStream& bit_stream, + int nitems, + std::vector& vec, + int bits_wanted, + int_type T::*field) { bool append = vec.empty(); // nitems times, read bits_wanted from the given bit stream, // storing results in the ith vector entry. - for (size_t i = 0; i < QIntC::to_size(nitems); ++i) - { - if (append) - { + for (size_t i = 0; i < QIntC::to_size(nitems); ++i) { + if (append) { vec.push_back(T()); } vec.at(i).*field = bit_stream.getBitsInt(QIntC::to_size(bits_wanted)); } - if (QIntC::to_int(vec.size()) != nitems) - { + if (QIntC::to_int(vec.size()) != nitems) { throw std::logic_error("vector has wrong size in load_vector_int"); } // The PDF spec says that each hint table starts at a byte @@ -45,18 +46,20 @@ load_vector_int(BitStream& bit_stream, int nitems, std::vector& vec, template static void -load_vector_vector(BitStream& bit_stream, - int nitems1, std::vector& vec1, int T::*nitems2, - int bits_wanted, std::vector T::*vec2) +load_vector_vector( + BitStream& bit_stream, + int nitems1, + std::vector& vec1, + int T::*nitems2, + int bits_wanted, + std::vector T::*vec2) { // nitems1 times, read nitems2 (from the ith element of vec1) items // into the vec2 vector field of the ith item of vec1. - for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) - { - for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) - { - (vec1.at(i1).*vec2).push_back( - bit_stream.getBitsInt(QIntC::to_size(bits_wanted))); + for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) { + for (int i2 = 0; i2 < vec1.at(i1).*nitems2; ++i2) { + (vec1.at(i1).*vec2) + .push_back(bit_stream.getBitsInt(QIntC::to_size(bits_wanted))); } } bit_stream.skipToNextByte(); @@ -66,13 +69,10 @@ bool QPDF::checkLinearization() { bool result = false; - try - { + try { readLinearizationData(); result = checkLinearizationInternal(); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { *this->m->err_stream << "WARNING: error encountered while checking linearization data: " << e.what() << std::endl; @@ -105,22 +105,18 @@ QPDF::isLinearized() int lindict_obj = -1; char* p = buf; - while (lindict_obj == -1) - { + while (lindict_obj == -1) { // Find a digit or end of buffer - while (((p - buf) < tbuf_size) && (! QUtil::is_digit(*p))) - { + while (((p - buf) < tbuf_size) && (!QUtil::is_digit(*p))) { ++p; } - if (p - buf == tbuf_size) - { + if (p - buf == tbuf_size) { break; } // Seek to the digit. Then skip over digits for a potential // next iteration. this->m->file->seek(p - buf, SEEK_SET); - while (((p - buf) < tbuf_size) && QUtil::is_digit(*p)) - { + while (((p - buf) < tbuf_size) && QUtil::is_digit(*p)) { ++p; } @@ -131,44 +127,36 @@ QPDF::isLinearized() if ((t1.getType() == QPDFTokenizer::tt_integer) && (t2.getType() == QPDFTokenizer::tt_integer) && (t3 == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "obj")) && - (t4.getType() == QPDFTokenizer::tt_dict_open)) - { + (t4.getType() == QPDFTokenizer::tt_dict_open)) { lindict_obj = QIntC::to_int(QUtil::string_to_ll(t1.getValue().c_str())); } } - if (lindict_obj <= 0) - { + if (lindict_obj <= 0) { return false; } - QPDFObjectHandle candidate = QPDFObjectHandle::Factory::newIndirect( - this, lindict_obj, 0); - if (! candidate.isDictionary()) - { + QPDFObjectHandle candidate = + QPDFObjectHandle::Factory::newIndirect(this, lindict_obj, 0); + if (!candidate.isDictionary()) { return false; } QPDFObjectHandle linkey = candidate.getKey("/Linearized"); - if (! (linkey.isNumber() && - (QIntC::to_int(floor(linkey.getNumericValue())) == 1))) - { + if (!(linkey.isNumber() && + (QIntC::to_int(floor(linkey.getNumericValue())) == 1))) { return false; } QPDFObjectHandle L = candidate.getKey("/L"); - if (L.isInteger()) - { + if (L.isInteger()) { qpdf_offset_t Li = L.getIntValue(); this->m->file->seek(0, SEEK_END); - if (Li != this->m->file->tell()) - { + if (Li != this->m->file->tell()) { QTC::TC("qpdf", "QPDF /L mismatch"); return false; - } - else - { + } else { this->m->linp.file_size = Li; } } @@ -187,8 +175,7 @@ QPDF::readLinearizationData() // Hint table parsing code needs at least 32 bits in a long. assert(sizeof(long) >= 4); - if (! isLinearized()) - { + if (!isLinearized()) { throw std::logic_error("called readLinearizationData for file" " that is not linearized"); } @@ -201,44 +188,40 @@ QPDF::readLinearizationData() QPDFObjectHandle T = this->m->lindict.getKey("/T"); QPDFObjectHandle P = this->m->lindict.getKey("/P"); - if (! (H.isArray() && - O.isInteger() && - E.isInteger() && - N.isInteger() && - T.isInteger() && - (P.isInteger() || P.isNull()))) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "some keys in linearization dictionary are of " - "the wrong type"); + if (!(H.isArray() && O.isInteger() && E.isInteger() && N.isInteger() && + T.isInteger() && (P.isInteger() || P.isNull()))) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "some keys in linearization dictionary are of " + "the wrong type"); } // Hint table array: offset length [ offset length ] size_t n_H_items = toS(H.getArrayNItems()); - if (! ((n_H_items == 2) || (n_H_items == 4))) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "H has the wrong number of items"); + if (!((n_H_items == 2) || (n_H_items == 4))) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "H has the wrong number of items"); } std::vector H_items; - for (size_t i = 0; i < n_H_items; ++i) - { + for (size_t i = 0; i < n_H_items; ++i) { QPDFObjectHandle oh(H.getArrayItem(toI(i))); - if (oh.isInteger()) - { + if (oh.isInteger()) { H_items.push_back(oh.getIntValueAsInt()); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "some H items are of the wrong type"); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "some H items are of the wrong type"); } } @@ -247,8 +230,7 @@ QPDF::readLinearizationData() int H0_length = H_items.at(1); int H1_offset = 0; int H1_length = 0; - if (H_items.size() == 4) - { + if (H_items.size() == 4) { // Acrobat doesn't read or write these (as PDF 1.4), so we // don't have a way to generate a test case. // QTC::TC("qpdf", "QPDF overflow hint table"); @@ -258,13 +240,10 @@ QPDF::readLinearizationData() // P: first page number int first_page = 0; - if (P.isInteger()) - { + if (P.isInteger()) { QTC::TC("qpdf", "QPDF P present in lindict"); first_page = P.getIntValueAsInt(); - } - else - { + } else { QTC::TC("qpdf", "QPDF P absent in lindict"); } @@ -273,12 +252,13 @@ QPDF::readLinearizationData() // Various places in the code use linp.npages, which is // initialized from N, to pre-allocate memory, so make sure it's // accurate and bail right now if it's not. - if (N.getIntValue() != static_cast(getAllPages().size())) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization hint table", - this->m->file->getLastOffset(), - "/N does not match number of pages"); + if (N.getIntValue() != static_cast(getAllPages().size())) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization hint table", + this->m->file->getLastOffset(), + "/N does not match number of pages"); } // file_size initialized by isLinearized() @@ -294,9 +274,8 @@ QPDF::readLinearizationData() Pl_Buffer pb("hint buffer"); QPDFObjectHandle H0 = readHintStream(pb, H0_offset, toS(H0_length)); - if (H1_offset) - { - (void) readHintStream(pb, H1_offset, toS(H1_length)); + if (H1_offset) { + (void)readHintStream(pb, H1_offset, toS(H1_length)); } // PDF 1.4 hint tables that we ignore: @@ -321,27 +300,28 @@ QPDF::readLinearizationData() readHPageOffset(BitStream(h_buf, h_size)); int HSi = HS.getIntValueAsInt(); - if ((HSi < 0) || (toS(HSi) >= h_size)) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization hint table", - this->m->file->getLastOffset(), - "/S (shared object) offset is out of bounds"); + if ((HSi < 0) || (toS(HSi) >= h_size)) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization hint table", + this->m->file->getLastOffset(), + "/S (shared object) offset is out of bounds"); } readHSharedObject(BitStream(h_buf + HSi, h_size - toS(HSi))); - if (HO.isInteger()) - { + if (HO.isInteger()) { int HOi = HO.getIntValueAsInt(); - if ((HOi < 0) || (toS(HOi) >= h_size)) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization hint table", - this->m->file->getLastOffset(), - "/O (outline) offset is out of bounds"); + if ((HOi < 0) || (toS(HOi) >= h_size)) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization hint table", + this->m->file->getLastOffset(), + "/O (outline) offset is out of bounds"); } - readHGeneric(BitStream(h_buf + HOi, h_size - toS(HOi)), - this->m->outline_hints); + readHGeneric( + BitStream(h_buf + HOi, h_size - toS(HOi)), this->m->outline_hints); } } @@ -355,12 +335,13 @@ QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) ObjCache& oc = this->m->obj_cache[QPDFObjGen(obj, gen)]; qpdf_offset_t min_end_offset = oc.end_before_space; qpdf_offset_t max_end_offset = oc.end_after_space; - if (! H.isStream()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "hint table is not a stream"); + if (!H.isStream()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "hint table is not a stream"); } QPDFObjectHandle Hdict = H.getDict(); @@ -371,30 +352,27 @@ QPDF::readHintStream(Pipeline& pl, qpdf_offset_t offset, size_t length) // linearization parameter dictionary must be direct. We have to // get the file position of the end of length in this case. QPDFObjectHandle length_obj = Hdict.getKey("/Length"); - if (length_obj.isIndirect()) - { + if (length_obj.isIndirect()) { QTC::TC("qpdf", "QPDF hint table length indirect"); // Force resolution - (void) length_obj.getIntValue(); + (void)length_obj.getIntValue(); ObjCache& oc2 = this->m->obj_cache[length_obj.getObjGen()]; min_end_offset = oc2.end_before_space; max_end_offset = oc2.end_after_space; - } - else - { + } else { QTC::TC("qpdf", "QPDF hint table length direct"); } qpdf_offset_t computed_end = offset + toO(length); - if ((computed_end < min_end_offset) || - (computed_end > max_end_offset)) - { + if ((computed_end < min_end_offset) || (computed_end > max_end_offset)) { *this->m->err_stream << "expected = " << computed_end << "; actual = " << min_end_offset << ".." << max_end_offset << std::endl; - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "linearization dictionary", - this->m->file->getLastOffset(), - "hint table length mismatch"); + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "linearization dictionary", + this->m->file->getLastOffset(), + "hint table length mismatch"); } H.pipeStreamData(&pl, 0, qpdf_dl_specialized); return Hdict; @@ -408,46 +386,67 @@ QPDF::readHPageOffset(BitStream h) HPageOffset& t = this->m->page_offset_hints; - t.min_nobjects = h.getBitsInt(32); // 1 - t.first_page_offset = h.getBitsInt(32); // 2 - t.nbits_delta_nobjects = h.getBitsInt(16); // 3 - t.min_page_length = h.getBitsInt(32); // 4 - t.nbits_delta_page_length = h.getBitsInt(16); // 5 - t.min_content_offset = h.getBitsInt(32); // 6 - t.nbits_delta_content_offset = h.getBitsInt(16); // 7 - t.min_content_length = h.getBitsInt(32); // 8 - t.nbits_delta_content_length = h.getBitsInt(16); // 9 - t.nbits_nshared_objects = h.getBitsInt(16); // 10 - t.nbits_shared_identifier = h.getBitsInt(16); // 11 - t.nbits_shared_numerator = h.getBitsInt(16); // 12 - t.shared_denominator = h.getBitsInt(16); // 13 + t.min_nobjects = h.getBitsInt(32); // 1 + t.first_page_offset = h.getBitsInt(32); // 2 + t.nbits_delta_nobjects = h.getBitsInt(16); // 3 + t.min_page_length = h.getBitsInt(32); // 4 + t.nbits_delta_page_length = h.getBitsInt(16); // 5 + t.min_content_offset = h.getBitsInt(32); // 6 + t.nbits_delta_content_offset = h.getBitsInt(16); // 7 + t.min_content_length = h.getBitsInt(32); // 8 + t.nbits_delta_content_length = h.getBitsInt(16); // 9 + t.nbits_nshared_objects = h.getBitsInt(16); // 10 + t.nbits_shared_identifier = h.getBitsInt(16); // 11 + t.nbits_shared_numerator = h.getBitsInt(16); // 12 + t.shared_denominator = h.getBitsInt(16); // 13 std::vector& entries = t.entries; entries.clear(); int nitems = this->m->linp.npages; - load_vector_int(h, nitems, entries, - t.nbits_delta_nobjects, - &HPageOffsetEntry::delta_nobjects); - load_vector_int(h, nitems, entries, - t.nbits_delta_page_length, - &HPageOffsetEntry::delta_page_length); - load_vector_int(h, nitems, entries, - t.nbits_nshared_objects, - &HPageOffsetEntry::nshared_objects); - load_vector_vector(h, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_identifier, - &HPageOffsetEntry::shared_identifiers); - load_vector_vector(h, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_numerator, - &HPageOffsetEntry::shared_numerators); - load_vector_int(h, nitems, entries, - t.nbits_delta_content_offset, - &HPageOffsetEntry::delta_content_offset); - load_vector_int(h, nitems, entries, - t.nbits_delta_content_length, - &HPageOffsetEntry::delta_content_length); + load_vector_int( + h, + nitems, + entries, + t.nbits_delta_nobjects, + &HPageOffsetEntry::delta_nobjects); + load_vector_int( + h, + nitems, + entries, + t.nbits_delta_page_length, + &HPageOffsetEntry::delta_page_length); + load_vector_int( + h, + nitems, + entries, + t.nbits_nshared_objects, + &HPageOffsetEntry::nshared_objects); + load_vector_vector( + h, + nitems, + entries, + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_identifier, + &HPageOffsetEntry::shared_identifiers); + load_vector_vector( + h, + nitems, + entries, + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_numerator, + &HPageOffsetEntry::shared_numerators); + load_vector_int( + h, + nitems, + entries, + t.nbits_delta_content_offset, + &HPageOffsetEntry::delta_content_offset); + load_vector_int( + h, + nitems, + entries, + t.nbits_delta_content_length, + &HPageOffsetEntry::delta_content_length); } void @@ -455,50 +454,55 @@ QPDF::readHSharedObject(BitStream h) { HSharedObject& t = this->m->shared_object_hints; - t.first_shared_obj = h.getBitsInt(32); // 1 - t.first_shared_offset = h.getBitsInt(32); // 2 - t.nshared_first_page = h.getBitsInt(32); // 3 - t.nshared_total = h.getBitsInt(32); // 4 - t.nbits_nobjects = h.getBitsInt(16); // 5 - t.min_group_length = h.getBitsInt(32); // 6 - t.nbits_delta_group_length = h.getBitsInt(16); // 7 + t.first_shared_obj = h.getBitsInt(32); // 1 + t.first_shared_offset = h.getBitsInt(32); // 2 + t.nshared_first_page = h.getBitsInt(32); // 3 + t.nshared_total = h.getBitsInt(32); // 4 + t.nbits_nobjects = h.getBitsInt(16); // 5 + t.min_group_length = h.getBitsInt(32); // 6 + t.nbits_delta_group_length = h.getBitsInt(16); // 7 - QTC::TC("qpdf", "QPDF lin nshared_total > nshared_first_page", - (t.nshared_total > t.nshared_first_page) ? 1 : 0); + QTC::TC( + "qpdf", + "QPDF lin nshared_total > nshared_first_page", + (t.nshared_total > t.nshared_first_page) ? 1 : 0); std::vector& entries = t.entries; entries.clear(); int nitems = t.nshared_total; - load_vector_int(h, nitems, entries, - t.nbits_delta_group_length, - &HSharedObjectEntry::delta_group_length); - load_vector_int(h, nitems, entries, - 1, &HSharedObjectEntry::signature_present); - for (size_t i = 0; i < toS(nitems); ++i) - { - if (entries.at(i).signature_present) - { + load_vector_int( + h, + nitems, + entries, + t.nbits_delta_group_length, + &HSharedObjectEntry::delta_group_length); + load_vector_int( + h, nitems, entries, 1, &HSharedObjectEntry::signature_present); + for (size_t i = 0; i < toS(nitems); ++i) { + if (entries.at(i).signature_present) { // Skip 128-bit MD5 hash. These are not supported by // acrobat, so they should probably never be there. We // have no test case for this. - for (int j = 0; j < 4; ++j) - { - (void) h.getBits(32); + for (int j = 0; j < 4; ++j) { + (void)h.getBits(32); } } } - load_vector_int(h, nitems, entries, - t.nbits_nobjects, - &HSharedObjectEntry::nobjects_minus_one); + load_vector_int( + h, + nitems, + entries, + t.nbits_nobjects, + &HSharedObjectEntry::nobjects_minus_one); } void QPDF::readHGeneric(BitStream h, HGeneric& t) { - t.first_object = h.getBitsInt(32); // 1 - t.first_object_offset = h.getBitsInt(32); // 2 - t.nobjects = h.getBitsInt(32); // 3 - t.group_length = h.getBitsInt(32); // 4 + t.first_object = h.getBitsInt(32); // 1 + t.first_object_offset = h.getBitsInt(32); // 2 + t.nobjects = h.getBitsInt(32); // 3 + t.group_length = h.getBitsInt(32); // 4 } bool @@ -518,51 +522,45 @@ QPDF::checkLinearizationInternal() // O: object number of first page std::vector const& pages = getAllPages(); - if (p.first_page_object != pages.at(0).getObjectID()) - { + if (p.first_page_object != pages.at(0).getObjectID()) { QTC::TC("qpdf", "QPDF err /O mismatch"); errors.push_back("first page object (/O) mismatch"); } // N: number of pages int npages = toI(pages.size()); - if (p.npages != npages) - { + if (p.npages != npages) { // Not tested in the test suite errors.push_back("page count (/N) mismatch"); } - for (size_t i = 0; i < toS(npages); ++i) - { + for (size_t i = 0; i < toS(npages); ++i) { QPDFObjectHandle const& page = pages.at(i); QPDFObjGen og(page.getObjGen()); - if (this->m->xref_table[og].getType() == 2) - { - errors.push_back("page dictionary for page " + - QUtil::uint_to_string(i) + " is compressed"); + if (this->m->xref_table[og].getType() == 2) { + errors.push_back( + "page dictionary for page " + QUtil::uint_to_string(i) + + " is compressed"); } } // T: offset of whitespace character preceding xref entry for object 0 this->m->file->seek(p.xref_zero_offset, SEEK_SET); - while (1) - { + while (1) { char ch; this->m->file->read(&ch, 1); - if (! ((ch == ' ') || (ch == '\r') || (ch == '\n'))) - { + if (!((ch == ' ') || (ch == '\r') || (ch == '\n'))) { this->m->file->seek(-1, SEEK_CUR); break; } } - if (this->m->file->tell() != this->m->first_xref_item_offset) - { + if (this->m->file->tell() != this->m->first_xref_item_offset) { QTC::TC("qpdf", "QPDF err /T mismatch"); - errors.push_back("space before first xref item (/T) mismatch " - "(computed = " + - QUtil::int_to_string(this->m->first_xref_item_offset) + - "; file = " + - QUtil::int_to_string(this->m->file->tell())); + errors.push_back( + "space before first xref item (/T) mismatch " + "(computed = " + + QUtil::int_to_string(this->m->first_xref_item_offset) + + "; file = " + QUtil::int_to_string(this->m->file->tell())); } // P: first page number -- Implementation note 124 says Acrobat @@ -573,8 +571,7 @@ QPDF::checkLinearizationInternal() // at the end of the containing xref section if any object streams // are in use. - if (this->m->uncompressed_after_compressed) - { + if (this->m->uncompressed_after_compressed) { errors.push_back("linearized file contains an uncompressed object" " after a compressed one in a cross-reference stream"); } @@ -588,12 +585,11 @@ QPDF::checkLinearizationInternal() std::map object_stream_data; for (std::map::const_iterator iter = this->m->xref_table.begin(); - iter != this->m->xref_table.end(); ++iter) - { + iter != this->m->xref_table.end(); + ++iter) { QPDFObjGen const& og = (*iter).first; QPDFXRefEntry const& entry = (*iter).second; - if (entry.getType() == 2) - { + if (entry.getType() == 2) { object_stream_data[og.getObj()] = entry.getObjStreamNumber(); } } @@ -612,18 +608,16 @@ QPDF::checkLinearizationInternal() // agree with pdlin. As of this writing, the test suite doesn't // contain any files with threads. - if (this->m->part6.empty()) - { + if (this->m->part6.empty()) { stopOnError("linearization part 6 unexpectedly empty"); } qpdf_offset_t min_E = -1; qpdf_offset_t max_E = -1; for (std::vector::iterator iter = this->m->part6.begin(); - iter != this->m->part6.end(); ++iter) - { + iter != this->m->part6.end(); + ++iter) { QPDFObjGen og((*iter).getObjGen()); - if (this->m->obj_cache.count(og) == 0) - { + if (this->m->obj_cache.count(og) == 0) { // All objects have to have been dereferenced to be classified. throw std::logic_error("linearization part6 object not in cache"); } @@ -631,14 +625,12 @@ QPDF::checkLinearizationInternal() min_E = std::max(min_E, oc.end_before_space); max_E = std::max(max_E, oc.end_after_space); } - if ((p.first_page_end < min_E) || (p.first_page_end > max_E)) - { + if ((p.first_page_end < min_E) || (p.first_page_end > max_E)) { QTC::TC("qpdf", "QPDF warn /E mismatch"); - warnings.push_back("end of first page section (/E) mismatch: /E = " + - QUtil::int_to_string(p.first_page_end) + - "; computed = " + - QUtil::int_to_string(min_E) + ".." + - QUtil::int_to_string(max_E)); + warnings.push_back( + "end of first page section (/E) mismatch: /E = " + + QUtil::int_to_string(p.first_page_end) + "; computed = " + + QUtil::int_to_string(min_E) + ".." + QUtil::int_to_string(max_E)); } // Check hint tables @@ -657,22 +649,20 @@ QPDF::checkLinearizationInternal() // them as errors. We'll hang onto the distinction in the code for // now in case we ever have a chance to clean up the linearization // code. - if (! errors.empty()) - { + if (!errors.empty()) { result = false; for (std::list::iterator iter = errors.begin(); - iter != errors.end(); ++iter) - { + iter != errors.end(); + ++iter) { *this->m->err_stream << "WARNING: " << (*iter) << std::endl; } } - if (! warnings.empty()) - { + if (!warnings.empty()) { result = false; for (std::list::iterator iter = warnings.begin(); - iter != warnings.end(); ++iter) - { + iter != warnings.end(); + ++iter) { *this->m->err_stream << "WARNING: " << (*iter) << std::endl; } } @@ -683,18 +673,16 @@ QPDF::checkLinearizationInternal() qpdf_offset_t QPDF::maxEnd(ObjUser const& ou) { - if (this->m->obj_user_to_objects.count(ou) == 0) - { + if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("no entry in object user table for requested object user"); } std::set const& ogs = this->m->obj_user_to_objects[ou]; qpdf_offset_t end = 0; for (std::set::const_iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { + iter != ogs.end(); + ++iter) { QPDFObjGen const& og = *iter; - if (this->m->obj_cache.count(og) == 0) - { + if (this->m->obj_cache.count(og) == 0) { stopOnError("unknown object referenced in object user table"); } end = std::max(end, this->m->obj_cache[og].end_after_space); @@ -707,20 +695,19 @@ QPDF::getLinearizationOffset(QPDFObjGen const& og) { QPDFXRefEntry entry = this->m->xref_table[og]; qpdf_offset_t result = 0; - switch (entry.getType()) - { - case 1: + switch (entry.getType()) { + case 1: result = entry.getOffset(); break; - case 2: + case 2: // For compressed objects, return the offset of the object // stream that contains them. - result = getLinearizationOffset( - QPDFObjGen(entry.getObjStreamNumber(), 0)); + result = + getLinearizationOffset(QPDFObjGen(entry.getObjStreamNumber(), 0)); break; - default: + default: stopOnError( "getLinearizationOffset called for xref entry not of type 1 or 2"); break; @@ -729,53 +716,46 @@ QPDF::getLinearizationOffset(QPDFObjGen const& og) } QPDFObjectHandle -QPDF::getUncompressedObject(QPDFObjectHandle& obj, - std::map const& object_stream_data) +QPDF::getUncompressedObject( + QPDFObjectHandle& obj, std::map const& object_stream_data) { - if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0)) - { + if (obj.isNull() || (object_stream_data.count(obj.getObjectID()) == 0)) { return obj; - } - else - { + } else { int repl = (*(object_stream_data.find(obj.getObjectID()))).second; return objGenToIndirect(QPDFObjGen(repl, 0)); } } int -QPDF::lengthNextN(int first_object, int n, - std::list& errors) +QPDF::lengthNextN(int first_object, int n, std::list& errors) { int length = 0; - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { QPDFObjGen og(first_object + i, 0); - if (this->m->xref_table.count(og) == 0) - { + if (this->m->xref_table.count(og) == 0) { errors.push_back( "no xref table entry for " + QUtil::int_to_string(first_object + i) + " 0"); - } - else - { - if (this->m->obj_cache.count(og) == 0) - { + } else { + if (this->m->obj_cache.count(og) == 0) { stopOnError("found unknown object while" " calculating length for linearization data"); } - length += toI(this->m->obj_cache[og].end_after_space - - getLinearizationOffset(og)); + length += + toI(this->m->obj_cache[og].end_after_space - + getLinearizationOffset(og)); } } return length; } void -QPDF::checkHPageOffset(std::list& errors, - std::list& warnings, - std::vector const& pages, - std::map& shared_idx_to_obj) +QPDF::checkHPageOffset( + std::list& errors, + std::list& warnings, + std::vector const& pages, + std::map& shared_idx_to_obj) { // Implementation note 126 says Acrobat always sets // delta_content_offset and delta_content_length in the page @@ -795,25 +775,21 @@ QPDF::checkHPageOffset(std::list& errors, // even when they are private. int npages = toI(pages.size()); - qpdf_offset_t table_offset = adjusted_offset( - this->m->page_offset_hints.first_page_offset); + qpdf_offset_t table_offset = + adjusted_offset(this->m->page_offset_hints.first_page_offset); QPDFObjGen first_page_og(pages.at(0).getObjGen()); - if (this->m->xref_table.count(first_page_og) == 0) - { + if (this->m->xref_table.count(first_page_og) == 0) { stopOnError("supposed first page object is not known"); } qpdf_offset_t offset = getLinearizationOffset(first_page_og); - if (table_offset != offset) - { + if (table_offset != offset) { warnings.push_back("first page object offset mismatch"); } - for (int pageno = 0; pageno < npages; ++pageno) - { + for (int pageno = 0; pageno < npages; ++pageno) { QPDFObjGen page_og(pages.at(toS(pageno)).getObjGen()); int first_object = page_og.getObj(); - if (this->m->xref_table.count(page_og) == 0) - { + if (this->m->xref_table.count(page_og) == 0) { stopOnError("unknown object in page offset hint table"); } offset = getLinearizationOffset(page_og); @@ -822,33 +798,31 @@ QPDF::checkHPageOffset(std::list& errors, this->m->page_offset_hints.entries.at(toS(pageno)); CHPageOffsetEntry& ce = this->m->c_page_offset_data.entries.at(toS(pageno)); - int h_nobjects = he.delta_nobjects + - this->m->page_offset_hints.min_nobjects; - if (h_nobjects != ce.nobjects) - { + int h_nobjects = + he.delta_nobjects + this->m->page_offset_hints.min_nobjects; + if (h_nobjects != ce.nobjects) { // This happens with pdlin when there are thumbnails. warnings.push_back( "object count mismatch for page " + - QUtil::int_to_string(pageno) + ": hint table = " + - QUtil::int_to_string(h_nobjects) + "; computed = " + - QUtil::int_to_string(ce.nobjects)); + QUtil::int_to_string(pageno) + + ": hint table = " + QUtil::int_to_string(h_nobjects) + + "; computed = " + QUtil::int_to_string(ce.nobjects)); } // Use value for number of objects in hint table rather than // computed value if there is a discrepancy. int length = lengthNextN(first_object, h_nobjects, errors); - int h_length = toI(he.delta_page_length + - this->m->page_offset_hints.min_page_length); - if (length != h_length) - { + int h_length = toI( + he.delta_page_length + this->m->page_offset_hints.min_page_length); + if (length != h_length) { // This condition almost certainly indicates a bad hint // table or a bug in this code. errors.push_back( "page length mismatch for page " + - QUtil::int_to_string(pageno) + ": hint table = " + - QUtil::int_to_string(h_length) + "; computed length = " + - QUtil::int_to_string(length) + " (offset = " + - QUtil::int_to_string(offset) + ")"); + QUtil::int_to_string(pageno) + + ": hint table = " + QUtil::int_to_string(h_length) + + "; computed length = " + QUtil::int_to_string(length) + + " (offset = " + QUtil::int_to_string(offset) + ")"); } offset += h_length; @@ -857,42 +831,34 @@ QPDF::checkHPageOffset(std::list& errors, std::set hint_shared; std::set computed_shared; - if ((pageno == 0) && (he.nshared_objects > 0)) - { + if ((pageno == 0) && (he.nshared_objects > 0)) { // pdlin and Acrobat both do this even though the spec // states clearly and unambiguously that they should not. warnings.push_back("page 0 has shared identifier entries"); } - for (size_t i = 0; i < toS(he.nshared_objects); ++i) - { + for (size_t i = 0; i < toS(he.nshared_objects); ++i) { int idx = he.shared_identifiers.at(i); - if (shared_idx_to_obj.count(idx) == 0) - { - stopOnError( - "unable to get object for item in" - " shared objects hint table"); + if (shared_idx_to_obj.count(idx) == 0) { + stopOnError("unable to get object for item in" + " shared objects hint table"); } hint_shared.insert(shared_idx_to_obj[idx]); } - for (size_t i = 0; i < toS(ce.nshared_objects); ++i) - { + for (size_t i = 0; i < toS(ce.nshared_objects); ++i) { int idx = ce.shared_identifiers.at(i); - if (idx >= this->m->c_shared_object_data.nshared_total) - { - stopOnError( - "index out of bounds for shared object hint table"); + if (idx >= this->m->c_shared_object_data.nshared_total) { + stopOnError("index out of bounds for shared object hint table"); } int obj = this->m->c_shared_object_data.entries.at(toS(idx)).object; computed_shared.insert(obj); } for (std::set::iterator iter = hint_shared.begin(); - iter != hint_shared.end(); ++iter) - { - if (! computed_shared.count(*iter)) - { + iter != hint_shared.end(); + ++iter) { + if (!computed_shared.count(*iter)) { // pdlin puts thumbnails here even though it shouldn't warnings.push_back( "page " + QUtil::int_to_string(pageno) + @@ -902,10 +868,9 @@ QPDF::checkHPageOffset(std::list& errors, } for (std::set::iterator iter = computed_shared.begin(); - iter != computed_shared.end(); ++iter) - { - if (! hint_shared.count(*iter)) - { + iter != computed_shared.end(); + ++iter) { + if (!hint_shared.count(*iter)) { // Acrobat does not put some things including at least // built-in fonts and procsets here, at least in some // cases. @@ -919,10 +884,11 @@ QPDF::checkHPageOffset(std::list& errors, } void -QPDF::checkHSharedObject(std::list& errors, - std::list& warnings, - std::vector const& pages, - std::map& idx_to_obj) +QPDF::checkHSharedObject( + std::list& errors, + std::list& warnings, + std::vector const& pages, + std::map& idx_to_obj) { // Implementation note 125 says shared object groups always // contain only one object. Implementation note 128 says that @@ -943,57 +909,44 @@ QPDF::checkHSharedObject(std::list& errors, // the first page (i.e., nshared_total == nshared_first_page). HSharedObject& so = this->m->shared_object_hints; - if (so.nshared_total < so.nshared_first_page) - { + if (so.nshared_total < so.nshared_first_page) { errors.push_back("shared object hint table: ntotal < nfirst_page"); - } - else - { + } else { // The first nshared_first_page objects are consecutive // objects starting with the first page object. The rest are // consecutive starting from the first_shared_obj object. int cur_object = pages.at(0).getObjectID(); - for (int i = 0; i < so.nshared_total; ++i) - { - if (i == so.nshared_first_page) - { + for (int i = 0; i < so.nshared_total; ++i) { + if (i == so.nshared_first_page) { QTC::TC("qpdf", "QPDF lin check shared past first page"); - if (this->m->part8.empty()) - { - errors.push_back( - "part 8 is empty but nshared_total > " - "nshared_first_page"); - } - else - { + if (this->m->part8.empty()) { + errors.push_back("part 8 is empty but nshared_total > " + "nshared_first_page"); + } else { int obj = this->m->part8.at(0).getObjectID(); - if (obj != so.first_shared_obj) - { + if (obj != so.first_shared_obj) { errors.push_back( "first shared object number mismatch: " "hint table = " + QUtil::int_to_string(so.first_shared_obj) + - "; computed = " + - QUtil::int_to_string(obj)); + "; computed = " + QUtil::int_to_string(obj)); } } cur_object = so.first_shared_obj; QPDFObjGen og(cur_object, 0); - if (this->m->xref_table.count(og) == 0) - { + if (this->m->xref_table.count(og) == 0) { stopOnError("unknown object in shared object hint table"); } qpdf_offset_t offset = getLinearizationOffset(og); qpdf_offset_t h_offset = adjusted_offset(so.first_shared_offset); - if (offset != h_offset) - { + if (offset != h_offset) { errors.push_back( "first shared object offset mismatch: hint table = " + - QUtil::int_to_string(h_offset) + "; computed = " + - QUtil::int_to_string(offset)); + QUtil::int_to_string(h_offset) + + "; computed = " + QUtil::int_to_string(offset)); } } @@ -1002,13 +955,12 @@ QPDF::checkHSharedObject(std::list& errors, int nobjects = se.nobjects_minus_one + 1; int length = lengthNextN(cur_object, nobjects, errors); int h_length = so.min_group_length + se.delta_group_length; - if (length != h_length) - { + if (length != h_length) { errors.push_back( "shared object " + QUtil::int_to_string(i) + " length mismatch: hint table = " + - QUtil::int_to_string(h_length) + "; computed = " + - QUtil::int_to_string(length)); + QUtil::int_to_string(h_length) + + "; computed = " + QUtil::int_to_string(length)); } cur_object += nobjects; } @@ -1026,20 +978,16 @@ QPDF::checkHOutlines(std::list& warnings) // wrong starting place). pdlin appears to generate correct // values in those cases. - if (this->m->c_outline_data.nobjects == this->m->outline_hints.nobjects) - { - if (this->m->c_outline_data.nobjects == 0) - { + if (this->m->c_outline_data.nobjects == this->m->outline_hints.nobjects) { + if (this->m->c_outline_data.nobjects == 0) { return; } if (this->m->c_outline_data.first_object == - this->m->outline_hints.first_object) - { + this->m->outline_hints.first_object) { // Check length and offset. Acrobat gets these wrong. QPDFObjectHandle outlines = getRoot().getKey("/Outlines"); - if (! outlines.isIndirect()) - { + if (!outlines.isIndirect()) { // This case is not exercised in test suite since not // permitted by the spec, but if this does occur, the // code below would fail. @@ -1048,8 +996,7 @@ QPDF::checkHOutlines(std::list& warnings) return; } QPDFObjGen og(outlines.getObjGen()); - if (this->m->xref_table.count(og) == 0) - { + if (this->m->xref_table.count(og) == 0) { stopOnError("unknown object in outlines hint table"); } qpdf_offset_t offset = getLinearizationOffset(og); @@ -1057,30 +1004,24 @@ QPDF::checkHOutlines(std::list& warnings) int length = toI(maxEnd(ou) - offset); qpdf_offset_t table_offset = adjusted_offset(this->m->outline_hints.first_object_offset); - if (offset != table_offset) - { + if (offset != table_offset) { warnings.push_back( "incorrect offset in outlines table: hint table = " + QUtil::int_to_string(table_offset) + "; computed = " + QUtil::int_to_string(offset)); } int table_length = this->m->outline_hints.group_length; - if (length != table_length) - { + if (length != table_length) { warnings.push_back( "incorrect length in outlines table: hint table = " + QUtil::int_to_string(table_length) + "; computed = " + QUtil::int_to_string(length)); } - } - else - { + } else { warnings.push_back("incorrect first object number in outline " "hints table."); } - } - else - { + } else { warnings.push_back("incorrect object count in outline hint table"); } } @@ -1088,14 +1029,11 @@ QPDF::checkHOutlines(std::list& warnings) void QPDF::showLinearizationData() { - try - { + try { readLinearizationData(); checkLinearizationInternal(); dumpLinearizationDataInternal(); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { *this->m->err_stream << e.what() << std::endl; } } @@ -1103,9 +1041,9 @@ QPDF::showLinearizationData() void QPDF::dumpLinearizationDataInternal() { - *this->m->out_stream - << this->m->file->getName() << ": linearization data:" << std::endl - << std::endl; + *this->m->out_stream << this->m->file->getName() + << ": linearization data:" << std::endl + << std::endl; *this->m->out_stream << "file_size: " << this->m->linp.file_size << std::endl @@ -1118,16 +1056,14 @@ QPDF::dumpLinearizationDataInternal() << "H_length: " << this->m->linp.H_length << std::endl << std::endl; - *this->m->out_stream << "Page Offsets Hint Table" << std::endl - << std::endl; + *this->m->out_stream << "Page Offsets Hint Table" << std::endl << std::endl; dumpHPageOffset(); *this->m->out_stream << std::endl << "Shared Objects Hint Table" << std::endl << std::endl; dumpHSharedObject(); - if (this->m->outline_hints.nobjects > 0) - { + if (this->m->outline_hints.nobjects > 0) { *this->m->out_stream << std::endl << "Outlines Hint Table" << std::endl << std::endl; @@ -1141,53 +1077,39 @@ QPDF::adjusted_offset(qpdf_offset_t offset) // All offsets >= H_offset have to be increased by H_length // since all hint table location values disregard the hint table // itself. - if (offset >= this->m->linp.H_offset) - { + if (offset >= this->m->linp.H_offset) { return offset + this->m->linp.H_length; } return offset; } - void QPDF::dumpHPageOffset() { HPageOffset& t = this->m->page_offset_hints; *this->m->out_stream - << "min_nobjects: " << t.min_nobjects - << std::endl + << "min_nobjects: " << t.min_nobjects << std::endl << "first_page_offset: " << adjusted_offset(t.first_page_offset) << std::endl - << "nbits_delta_nobjects: " << t.nbits_delta_nobjects - << std::endl - << "min_page_length: " << t.min_page_length - << std::endl - << "nbits_delta_page_length: " << t.nbits_delta_page_length - << std::endl - << "min_content_offset: " << t.min_content_offset - << std::endl + << "nbits_delta_nobjects: " << t.nbits_delta_nobjects << std::endl + << "min_page_length: " << t.min_page_length << std::endl + << "nbits_delta_page_length: " << t.nbits_delta_page_length << std::endl + << "min_content_offset: " << t.min_content_offset << std::endl << "nbits_delta_content_offset: " << t.nbits_delta_content_offset << std::endl - << "min_content_length: " << t.min_content_length - << std::endl + << "min_content_length: " << t.min_content_length << std::endl << "nbits_delta_content_length: " << t.nbits_delta_content_length << std::endl - << "nbits_nshared_objects: " << t.nbits_nshared_objects - << std::endl - << "nbits_shared_identifier: " << t.nbits_shared_identifier - << std::endl - << "nbits_shared_numerator: " << t.nbits_shared_numerator - << std::endl - << "shared_denominator: " << t.shared_denominator - << std::endl; + << "nbits_nshared_objects: " << t.nbits_nshared_objects << std::endl + << "nbits_shared_identifier: " << t.nbits_shared_identifier << std::endl + << "nbits_shared_numerator: " << t.nbits_shared_numerator << std::endl + << "shared_denominator: " << t.shared_denominator << std::endl; - for (size_t i1 = 0; i1 < toS(this->m->linp.npages); ++i1) - { + for (size_t i1 = 0; i1 < toS(this->m->linp.npages); ++i1) { HPageOffsetEntry& pe = t.entries.at(i1); *this->m->out_stream << "Page " << i1 << ":" << std::endl - << " nobjects: " << pe.delta_nobjects + t.min_nobjects - << std::endl + << " nobjects: " << pe.delta_nobjects + t.min_nobjects << std::endl << " length: " << pe.delta_page_length + t.min_page_length << std::endl // content offset is relative to page, not file @@ -1196,8 +1118,7 @@ QPDF::dumpHPageOffset() << " content_length: " << pe.delta_content_length + t.min_content_length << std::endl << " nshared_objects: " << pe.nshared_objects << std::endl; - for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) - { + for (size_t i2 = 0; i2 < toS(pe.nshared_objects); ++i2) { *this->m->out_stream << " identifier " << i2 << ": " << pe.shared_identifiers.at(i2) << std::endl; *this->m->out_stream << " numerator " << i2 << ": " @@ -1210,39 +1131,33 @@ void QPDF::dumpHSharedObject() { HSharedObject& t = this->m->shared_object_hints; - *this->m->out_stream - << "first_shared_obj: " << t.first_shared_obj - << std::endl - << "first_shared_offset: " << adjusted_offset(t.first_shared_offset) - << std::endl - << "nshared_first_page: " << t.nshared_first_page - << std::endl - << "nshared_total: " << t.nshared_total - << std::endl - << "nbits_nobjects: " << t.nbits_nobjects - << std::endl - << "min_group_length: " << t.min_group_length - << std::endl - << "nbits_delta_group_length: " << t.nbits_delta_group_length - << std::endl; + *this->m->out_stream << "first_shared_obj: " << t.first_shared_obj + << std::endl + << "first_shared_offset: " + << adjusted_offset(t.first_shared_offset) << std::endl + << "nshared_first_page: " << t.nshared_first_page + << std::endl + << "nshared_total: " << t.nshared_total << std::endl + << "nbits_nobjects: " << t.nbits_nobjects << std::endl + << "min_group_length: " << t.min_group_length + << std::endl + << "nbits_delta_group_length: " + << t.nbits_delta_group_length << std::endl; - for (size_t i = 0; i < toS(t.nshared_total); ++i) - { + for (size_t i = 0; i < toS(t.nshared_total); ++i) { HSharedObjectEntry& se = t.entries.at(i); *this->m->out_stream << "Shared Object " << i << ":" << std::endl - << " group length: " - << se.delta_group_length + t.min_group_length << std::endl; + << " group length: " << se.delta_group_length + t.min_group_length + << std::endl; // PDF spec says signature present nobjects_minus_one are // always 0, so print them only if they have a non-zero value. - if (se.signature_present) - { + if (se.signature_present) { *this->m->out_stream << " signature present" << std::endl; } - if (se.nobjects_minus_one != 0) - { - *this->m->out_stream << " nobjects: " - << se.nobjects_minus_one + 1 << std::endl; + if (se.nobjects_minus_one != 0) { + *this->m->out_stream << " nobjects: " << se.nobjects_minus_one + 1 + << std::endl; } } } @@ -1250,15 +1165,11 @@ QPDF::dumpHSharedObject() void QPDF::dumpHGeneric(HGeneric& t) { - *this->m->out_stream - << "first_object: " << t.first_object - << std::endl - << "first_object_offset: " << adjusted_offset(t.first_object_offset) - << std::endl - << "nobjects: " << t.nobjects - << std::endl - << "group_length: " << t.group_length - << std::endl; + *this->m->out_stream << "first_object: " << t.first_object << std::endl + << "first_object_offset: " + << adjusted_offset(t.first_object_offset) << std::endl + << "nobjects: " << t.nobjects << std::endl + << "group_length: " << t.group_length << std::endl; } QPDFObjectHandle @@ -1277,8 +1188,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // this function. Note that actual offsets and lengths are not // computed here, but anything related to object ordering is. - if (this->m->object_to_obj_users.empty()) - { + if (this->m->object_to_obj_users.empty()) { // Note that we can't call optimize here because we don't know // whether it should be called with or without allow changes. throw std::logic_error( @@ -1346,23 +1256,20 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) QPDFObjectHandle root = getRoot(); bool outlines_in_first_page = false; QPDFObjectHandle pagemode = root.getKey("/PageMode"); - QTC::TC("qpdf", "QPDF categorize pagemode present", - pagemode.isName() ? 1 : 0); - if (pagemode.isName()) - { - if (pagemode.getName() == "/UseOutlines") - { - if (root.hasKey("/Outlines")) - { + QTC::TC( + "qpdf", "QPDF categorize pagemode present", pagemode.isName() ? 1 : 0); + if (pagemode.isName()) { + if (pagemode.getName() == "/UseOutlines") { + if (root.hasKey("/Outlines")) { outlines_in_first_page = true; - } - else - { + } else { QTC::TC("qpdf", "QPDF UseOutlines but no Outlines"); } } - QTC::TC("qpdf", "QPDF categorize pagemode outlines", - outlines_in_first_page ? 1 : 0); + QTC::TC( + "qpdf", + "QPDF categorize pagemode outlines", + outlines_in_first_page ? 1 : 0); } std::set open_document_keys; @@ -1383,10 +1290,10 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) std::set lc_outlines; std::set lc_root; - for (std::map >::iterator oiter = + for (std::map>::iterator oiter = this->m->object_to_obj_users.begin(); - oiter != this->m->object_to_obj_users.end(); ++oiter) - { + oiter != this->m->object_to_obj_users.end(); + ++oiter) { QPDFObjGen const& og = (*oiter).first; std::set& ous = (*oiter).second; @@ -1400,103 +1307,72 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) bool is_root = false; for (std::set::iterator uiter = ous.begin(); - uiter != ous.end(); ++uiter) - { + uiter != ous.end(); + ++uiter) { ObjUser const& ou = *uiter; - switch (ou.ou_type) - { - case ObjUser::ou_trailer_key: - if (ou.key == "/Encrypt") - { + switch (ou.ou_type) { + case ObjUser::ou_trailer_key: + if (ou.key == "/Encrypt") { in_open_document = true; - } - else - { + } else { ++others; } break; - case ObjUser::ou_thumb: + case ObjUser::ou_thumb: ++thumbs; break; - case ObjUser::ou_root_key: - if (open_document_keys.count(ou.key) > 0) - { + case ObjUser::ou_root_key: + if (open_document_keys.count(ou.key) > 0) { in_open_document = true; - } - else if (ou.key == "/Outlines") - { + } else if (ou.key == "/Outlines") { in_outlines = true; - } - else - { + } else { ++others; } break; - case ObjUser::ou_page: - if (ou.pageno == 0) - { + case ObjUser::ou_page: + if (ou.pageno == 0) { in_first_page = true; - } - else - { + } else { ++other_pages; } break; - case ObjUser::ou_root: + case ObjUser::ou_root: is_root = true; break; - case ObjUser::ou_bad: - stopOnError( - "INTERNAL ERROR: QPDF::calculateLinearizationData: " - "invalid user type"); + case ObjUser::ou_bad: + stopOnError("INTERNAL ERROR: QPDF::calculateLinearizationData: " + "invalid user type"); break; } } - if (is_root) - { + if (is_root) { lc_root.insert(og); - } - else if (in_outlines) - { + } else if (in_outlines) { lc_outlines.insert(og); - } - else if (in_open_document) - { + } else if (in_open_document) { lc_open_document.insert(og); - } - else if ((in_first_page) && - (others == 0) && (other_pages == 0) && (thumbs == 0)) - { + } else if ( + (in_first_page) && (others == 0) && (other_pages == 0) && + (thumbs == 0)) { lc_first_page_private.insert(og); - } - else if (in_first_page) - { + } else if (in_first_page) { lc_first_page_shared.insert(og); - } - else if ((other_pages == 1) && (others == 0) && (thumbs == 0)) - { + } else if ((other_pages == 1) && (others == 0) && (thumbs == 0)) { lc_other_page_private.insert(og); - } - else if (other_pages > 1) - { + } else if (other_pages > 1) { lc_other_page_shared.insert(og); - } - else if ((thumbs == 1) && (others == 0)) - { + } else if ((thumbs == 1) && (others == 0)) { lc_thumbnail_private.insert(og); - } - else if (thumbs > 1) - { + } else if (thumbs > 1) { lc_thumbnail_shared.insert(og); - } - else - { + } else { lc_other.insert(og); } } @@ -1522,8 +1398,8 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // should be a no-op in a properly linearized file. std::vector t = getAllPages(); for (std::vector::iterator iter = t.begin(); - iter != t.end(); ++iter) - { + iter != t.end(); + ++iter) { pages.push_back(getUncompressedObject(*iter, object_stream_data)); } } @@ -1546,15 +1422,14 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Part 4: open document objects. We don't care about the order. - if (lc_root.size() != 1) - { + if (lc_root.size() != 1) { stopOnError("found other than one root while" " calculating linearization data"); } this->m->part4.push_back(objGenToIndirect(*(lc_root.begin()))); for (std::set::iterator iter = lc_open_document.begin(); - iter != lc_open_document.end(); ++iter) - { + iter != lc_open_document.end(); + ++iter) { this->m->part4.push_back(objGenToIndirect(*iter)); } @@ -1565,13 +1440,11 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // will do the same. // First, place the actual first page object itself. - if (pages.empty()) - { + if (pages.empty()) { stopOnError("no pages found while calculating linearization data"); } QPDFObjGen first_page_og(pages.at(0).getObjGen()); - if (! lc_first_page_private.count(first_page_og)) - { + if (!lc_first_page_private.count(first_page_og)) { stopOnError( "INTERNAL ERROR: QPDF::calculateLinearizationData: first page " "object not in lc_first_page_private"); @@ -1586,20 +1459,19 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // hint tables. for (std::set::iterator iter = lc_first_page_private.begin(); - iter != lc_first_page_private.end(); ++iter) - { + iter != lc_first_page_private.end(); + ++iter) { this->m->part6.push_back(objGenToIndirect(*iter)); } for (std::set::iterator iter = lc_first_page_shared.begin(); - iter != lc_first_page_shared.end(); ++iter) - { + iter != lc_first_page_shared.end(); + ++iter) { this->m->part6.push_back(objGenToIndirect(*iter)); } // Place the outline dictionary if it goes in the first page section. - if (outlines_in_first_page) - { + if (outlines_in_first_page) { pushOutlinesToPart(this->m->part6, lc_outlines, object_stream_data); } @@ -1615,13 +1487,11 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Part 7: other pages' private objects // For each page in order: - for (size_t i = 1; i < toS(npages); ++i) - { + for (size_t i = 1; i < toS(npages); ++i) { // Place this page's page object QPDFObjGen page_og(pages.at(i).getObjGen()); - if (! lc_other_page_private.count(page_og)) - { + if (!lc_other_page_private.count(page_og)) { stopOnError( "INTERNAL ERROR: " "QPDF::calculateLinearizationData: page object for page " + @@ -1636,18 +1506,16 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) this->m->c_page_offset_data.entries.at(i).nobjects = 1; ObjUser ou(ObjUser::ou_page, toI(i)); - if (this->m->obj_user_to_objects.count(ou) == 0) - { + if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } std::set ogs = this->m->obj_user_to_objects[ou]; for (std::set::iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { + iter != ogs.end(); + ++iter) { QPDFObjGen const& og = (*iter); - if (lc_other_page_private.count(og)) - { + if (lc_other_page_private.count(og)) { lc_other_page_private.erase(og); this->m->part7.push_back(objGenToIndirect(og)); ++this->m->c_page_offset_data.entries.at(i).nobjects; @@ -1655,8 +1523,7 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) } } // That should have covered all part7 objects. - if (! lc_other_page_private.empty()) - { + if (!lc_other_page_private.empty()) { stopOnError( "INTERNAL ERROR:" " QPDF::calculateLinearizationData: lc_other_page_private is " @@ -1667,8 +1534,8 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Order is unimportant. for (std::set::iterator iter = lc_other_page_shared.begin(); - iter != lc_other_page_shared.end(); ++iter) - { + iter != lc_other_page_shared.end(); + ++iter) { this->m->part8.push_back(objGenToIndirect(*iter)); } @@ -1684,17 +1551,15 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Place the pages tree. std::set pages_ogs = this->m->obj_user_to_objects[ObjUser(ObjUser::ou_root_key, "/Pages")]; - if (pages_ogs.empty()) - { + if (pages_ogs.empty()) { stopOnError("found empty pages tree while" " calculating linearization data"); } for (std::set::iterator iter = pages_ogs.begin(); - iter != pages_ogs.end(); ++iter) - { + iter != pages_ogs.end(); + ++iter) { QPDFObjGen const& og = *iter; - if (lc_other.count(og)) - { + if (lc_other.count(og)) { lc_other.erase(og); this->m->part9.push_back(objGenToIndirect(og)); } @@ -1703,21 +1568,16 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // Place private thumbnail images in page order. Slightly more // information would be required if we were going to bother with // thumbnail hint tables. - for (size_t i = 0; i < toS(npages); ++i) - { + for (size_t i = 0; i < toS(npages); ++i) { QPDFObjectHandle thumb = pages.at(i).getKey("/Thumb"); thumb = getUncompressedObject(thumb, object_stream_data); - if (! thumb.isNull()) - { + if (!thumb.isNull()) { // Output the thumbnail itself QPDFObjGen thumb_og(thumb.getObjGen()); - if (lc_thumbnail_private.count(thumb_og)) - { + if (lc_thumbnail_private.count(thumb_og)) { lc_thumbnail_private.erase(thumb_og); this->m->part9.push_back(thumb); - } - else - { + } else { // No internal error this time...there's nothing to // stop this object from having been referred to // somewhere else outside of a page's /Thumb, and if @@ -1726,62 +1586,55 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) // lc_thumbnail_private. } std::set& ogs = - this->m->obj_user_to_objects[ - ObjUser(ObjUser::ou_thumb, toI(i))]; + this->m + ->obj_user_to_objects[ObjUser(ObjUser::ou_thumb, toI(i))]; for (std::set::iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { + iter != ogs.end(); + ++iter) { QPDFObjGen const& og = *iter; - if (lc_thumbnail_private.count(og)) - { + if (lc_thumbnail_private.count(og)) { lc_thumbnail_private.erase(og); this->m->part9.push_back(objGenToIndirect(og)); } } } } - if (! lc_thumbnail_private.empty()) - { - stopOnError( - "INTERNAL ERROR: " - "QPDF::calculateLinearizationData: lc_thumbnail_private " - "not empty after placing thumbnails"); + if (!lc_thumbnail_private.empty()) { + stopOnError("INTERNAL ERROR: " + "QPDF::calculateLinearizationData: lc_thumbnail_private " + "not empty after placing thumbnails"); } // Place shared thumbnail objects for (std::set::iterator iter = lc_thumbnail_shared.begin(); - iter != lc_thumbnail_shared.end(); ++iter) - { + iter != lc_thumbnail_shared.end(); + ++iter) { this->m->part9.push_back(objGenToIndirect(*iter)); } // Place outlines unless in first page - if (! outlines_in_first_page) - { + if (!outlines_in_first_page) { pushOutlinesToPart(this->m->part9, lc_outlines, object_stream_data); } // Place all remaining objects for (std::set::iterator iter = lc_other.begin(); - iter != lc_other.end(); ++iter) - { + iter != lc_other.end(); + ++iter) { this->m->part9.push_back(objGenToIndirect(*iter)); } // Make sure we got everything exactly once. - size_t num_placed = - this->m->part4.size() + this->m->part6.size() + this->m->part7.size() + - this->m->part8.size() + this->m->part9.size(); + size_t num_placed = this->m->part4.size() + this->m->part6.size() + + this->m->part7.size() + this->m->part8.size() + this->m->part9.size(); size_t num_wanted = this->m->object_to_obj_users.size(); - if (num_placed != num_wanted) - { + if (num_placed != num_wanted) { stopOnError( "INTERNAL ERROR: QPDF::calculateLinearizationData: wrong " "number of objects placed (num_placed = " + QUtil::uint_to_string(num_placed) + - "; number of objects: " + - QUtil::uint_to_string(num_wanted)); + "; number of objects: " + QUtil::uint_to_string(num_wanted)); } // Calculate shared object hint table information including @@ -1806,22 +1659,21 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) std::vector& shared = this->m->c_shared_object_data.entries; for (std::vector::iterator iter = this->m->part6.begin(); - iter != this->m->part6.end(); ++iter) - { + iter != this->m->part6.end(); + ++iter) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); obj_to_index[obj] = toI(shared.size()); shared.push_back(CHSharedObjectEntry(obj)); } QTC::TC("qpdf", "QPDF lin part 8 empty", this->m->part8.empty() ? 1 : 0); - if (! this->m->part8.empty()) - { + if (!this->m->part8.empty()) { this->m->c_shared_object_data.first_shared_obj = this->m->part8.at(0).getObjectID(); for (std::vector::iterator iter = this->m->part8.begin(); - iter != this->m->part8.end(); ++iter) - { + iter != this->m->part8.end(); + ++iter) { QPDFObjectHandle& oh = *iter; int obj = oh.getObjectID(); obj_to_index[obj] = toI(shared.size()); @@ -1829,32 +1681,27 @@ QPDF::calculateLinearizationData(std::map const& object_stream_data) } } if (static_cast(this->m->c_shared_object_data.nshared_total) != - this->m->c_shared_object_data.entries.size()) - { - stopOnError( - "shared object hint table has wrong number of entries"); + this->m->c_shared_object_data.entries.size()) { + stopOnError("shared object hint table has wrong number of entries"); } // Now compute the list of shared objects for each page after the // first page. - for (size_t i = 1; i < toS(npages); ++i) - { + for (size_t i = 1; i < toS(npages); ++i) { CHPageOffsetEntry& pe = this->m->c_page_offset_data.entries.at(i); ObjUser ou(ObjUser::ou_page, toI(i)); - if (this->m->obj_user_to_objects.count(ou) == 0) - { + if (this->m->obj_user_to_objects.count(ou) == 0) { stopOnError("found unreferenced page while" " calculating linearization data"); } std::set const& ogs = this->m->obj_user_to_objects[ou]; for (std::set::const_iterator iter = ogs.begin(); - iter != ogs.end(); ++iter) - { + iter != ogs.end(); + ++iter) { QPDFObjGen const& og = *iter; if ((this->m->object_to_obj_users[og].size() > 1) && - (obj_to_index.count(og.getObj()) > 0)) - { + (obj_to_index.count(og.getObj()) > 0)) { int idx = obj_to_index[og.getObj()]; ++pe.nshared_objects; pe.shared_identifiers.push_back(idx); @@ -1871,23 +1718,24 @@ QPDF::pushOutlinesToPart( { QPDFObjectHandle root = getRoot(); QPDFObjectHandle outlines = root.getKey("/Outlines"); - if (outlines.isNull()) - { + if (outlines.isNull()) { return; } outlines = getUncompressedObject(outlines, object_stream_data); QPDFObjGen outlines_og(outlines.getObjGen()); - QTC::TC("qpdf", "QPDF lin outlines in part", - ((&part == (&this->m->part6)) ? 0 + QTC::TC( + "qpdf", + "QPDF lin outlines in part", + ((&part == (&this->m->part6)) ? 0 : (&part == (&this->m->part9)) ? 1 - : 9999)); // can't happen + : 9999)); // can't happen this->m->c_outline_data.first_object = outlines_og.getObj(); this->m->c_outline_data.nobjects = 1; lc_outlines.erase(outlines_og); part.push_back(outlines); for (std::set::iterator iter = lc_outlines.begin(); - iter != lc_outlines.end(); ++iter) - { + iter != lc_outlines.end(); + ++iter) { part.push_back(objGenToIndirect(*iter)); ++this->m->c_outline_data.nobjects; } @@ -1910,14 +1758,16 @@ QPDF::getLinearizedParts( part9 = this->m->part9; } -static inline int nbits(int val) +static inline int +nbits(int val) { return (val == 0 ? 0 : (1 + nbits(val >> 1))); } int QPDF::outputLengthNextN( - int in_object, int n, + int in_object, + int n, std::map const& lengths, std::map const& obj_renumber) { @@ -1925,17 +1775,14 @@ QPDF::outputLengthNextN( // the output file starting with whatever object in_object from // the input file mapped to. - if (obj_renumber.count(in_object) == 0) - { + if (obj_renumber.count(in_object) == 0) { stopOnError("found object that is not renumbered while" " writing linearization data"); } int first = (*(obj_renumber.find(in_object))).second; int length = 0; - for (int i = 0; i < n; ++i) - { - if (lengths.count(first + i) == 0) - { + for (int i = 0; i < n; ++i) { + if (lengths.count(first + i) == 0) { stopOnError("found item with unknown length" " while writing linearization data"); } @@ -1975,8 +1822,7 @@ QPDF::calculateHPageOffset( // npages is the size of the existing pages array. phe = std::vector(npages); - for (unsigned int i = 0; i < npages; ++i) - { + for (unsigned int i = 0; i < npages; ++i) { // Calculate values for each page, assigning full values to // the delta items. They will be adjusted later. @@ -2009,7 +1855,7 @@ QPDF::calculateHPageOffset( ph.nbits_nshared_objects = nbits(max_shared); ph.nbits_shared_identifier = nbits(this->m->c_shared_object_data.nshared_total); - ph.shared_denominator = 4; // doesn't matter + ph.shared_denominator = 4; // doesn't matter // It isn't clear how to compute content offset and content // length. Since we are not interleaving page objects with the @@ -2019,12 +1865,10 @@ QPDF::calculateHPageOffset( ph.nbits_delta_content_length = ph.nbits_delta_page_length; ph.min_content_length = ph.min_page_length; - for (size_t i = 0; i < npages; ++i) - { + for (size_t i = 0; i < npages; ++i) { // Adjust delta entries if ((phe.at(i).delta_nobjects < min_nobjects) || - (phe.at(i).delta_page_length < min_length)) - { + (phe.at(i).delta_page_length < min_length)) { stopOnError("found too small delta nobjects or delta page length" " while writing linearization data"); } @@ -2032,8 +1876,7 @@ QPDF::calculateHPageOffset( phe.at(i).delta_page_length -= min_length; phe.at(i).delta_content_length = phe.at(i).delta_page_length; - for (size_t j = 0; j < toS(cphe.at(i).nshared_objects); ++j) - { + for (size_t j = 0; j < toS(cphe.at(i).nshared_objects); ++j) { phe.at(i).shared_identifiers.push_back( cphe.at(i).shared_identifiers.at(j)); phe.at(i).shared_numerators.push_back(0); @@ -2053,29 +1896,26 @@ QPDF::calculateHSharedObject( std::vector& soe = so.entries; soe.clear(); - int min_length = outputLengthNextN( - csoe.at(0).object, 1, lengths, obj_renumber); + int min_length = + outputLengthNextN(csoe.at(0).object, 1, lengths, obj_renumber); int max_length = min_length; - for (size_t i = 0; i < toS(cso.nshared_total); ++i) - { + for (size_t i = 0; i < toS(cso.nshared_total); ++i) { // Assign absolute numbers to deltas; adjust later - int length = outputLengthNextN( - csoe.at(i).object, 1, lengths, obj_renumber); + int length = + outputLengthNextN(csoe.at(i).object, 1, lengths, obj_renumber); min_length = std::min(min_length, length); max_length = std::max(max_length, length); soe.push_back(HSharedObjectEntry()); soe.at(i).delta_group_length = length; } - if (soe.size() != QIntC::to_size(cso.nshared_total)) - { + if (soe.size() != QIntC::to_size(cso.nshared_total)) { stopOnError("soe has wrong size after initialization"); } so.nshared_total = cso.nshared_total; so.nshared_first_page = cso.nshared_first_page; - if (so.nshared_total > so.nshared_first_page) - { + if (so.nshared_total > so.nshared_first_page) { so.first_shared_obj = (*(obj_renumber.find(cso.first_shared_obj))).second; so.first_shared_offset = @@ -2084,11 +1924,9 @@ QPDF::calculateHSharedObject( so.min_group_length = min_length; so.nbits_delta_group_length = nbits(max_length - min_length); - for (size_t i = 0; i < toS(cso.nshared_total); ++i) - { + for (size_t i = 0; i < toS(cso.nshared_total); ++i) { // Adjust deltas - if (soe.at(i).delta_group_length < min_length) - { + if (soe.at(i).delta_group_length < min_length) { stopOnError("found too small group length while" " writing linearization data"); } @@ -2104,34 +1942,30 @@ QPDF::calculateHOutline( { HGeneric& cho = this->m->c_outline_data; - if (cho.nobjects == 0) - { + if (cho.nobjects == 0) { return; } HGeneric& ho = this->m->outline_hints; - ho.first_object = - (*(obj_renumber.find(cho.first_object))).second; - ho.first_object_offset = - (*(xref.find(ho.first_object))).second.getOffset(); + ho.first_object = (*(obj_renumber.find(cho.first_object))).second; + ho.first_object_offset = (*(xref.find(ho.first_object))).second.getOffset(); ho.nobjects = cho.nobjects; - ho.group_length = outputLengthNextN( - cho.first_object, ho.nobjects, lengths, obj_renumber); + ho.group_length = + outputLengthNextN(cho.first_object, ho.nobjects, lengths, obj_renumber); } template static void -write_vector_int(BitWriter& w, int nitems, std::vector& vec, - int bits, int_type T::*field) +write_vector_int( + BitWriter& w, int nitems, std::vector& vec, int bits, int_type T::*field) { // nitems times, write bits bits from the given field of the ith // vector to the given bit writer. - for (size_t i = 0; i < QIntC::to_size(nitems); ++i) - { - w.writeBits(QIntC::to_ulonglong(vec.at(i).*field), - QIntC::to_size(bits)); + for (size_t i = 0; i < QIntC::to_size(nitems); ++i) { + w.writeBits( + QIntC::to_ulonglong(vec.at(i).*field), QIntC::to_size(bits)); } // The PDF spec says that each hint table starts at a byte // boundary. Each "row" actually must start on a byte boundary. @@ -2140,69 +1974,92 @@ write_vector_int(BitWriter& w, int nitems, std::vector& vec, template static void -write_vector_vector(BitWriter& w, - int nitems1, std::vector& vec1, int T::*nitems2, - int bits, std::vector T::*vec2) +write_vector_vector( + BitWriter& w, + int nitems1, + std::vector& vec1, + int T::*nitems2, + int bits, + std::vector T::*vec2) { // nitems1 times, write nitems2 (from the ith element of vec1) items // from the vec2 vector field of the ith item of vec1. - for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) - { - for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2) - { - w.writeBits(QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)), - QIntC::to_size(bits)); + for (size_t i1 = 0; i1 < QIntC::to_size(nitems1); ++i1) { + for (size_t i2 = 0; i2 < QIntC::to_size(vec1.at(i1).*nitems2); ++i2) { + w.writeBits( + QIntC::to_ulonglong((vec1.at(i1).*vec2).at(i2)), + QIntC::to_size(bits)); } } w.flush(); } - void QPDF::writeHPageOffset(BitWriter& w) { HPageOffset& t = this->m->page_offset_hints; - w.writeBitsInt(t.min_nobjects, 32); // 1 - w.writeBitsInt(toI(t.first_page_offset), 32); // 2 - w.writeBitsInt(t.nbits_delta_nobjects, 16); // 3 - w.writeBitsInt(t.min_page_length, 32); // 4 - w.writeBitsInt(t.nbits_delta_page_length, 16); // 5 - w.writeBitsInt(t.min_content_offset, 32); // 6 - w.writeBitsInt(t.nbits_delta_content_offset, 16); // 7 - w.writeBitsInt(t.min_content_length, 32); // 8 - w.writeBitsInt(t.nbits_delta_content_length, 16); // 9 - w.writeBitsInt(t.nbits_nshared_objects, 16); // 10 - w.writeBitsInt(t.nbits_shared_identifier, 16); // 11 - w.writeBitsInt(t.nbits_shared_numerator, 16); // 12 - w.writeBitsInt(t.shared_denominator, 16); // 13 + w.writeBitsInt(t.min_nobjects, 32); // 1 + w.writeBitsInt(toI(t.first_page_offset), 32); // 2 + w.writeBitsInt(t.nbits_delta_nobjects, 16); // 3 + w.writeBitsInt(t.min_page_length, 32); // 4 + w.writeBitsInt(t.nbits_delta_page_length, 16); // 5 + w.writeBitsInt(t.min_content_offset, 32); // 6 + w.writeBitsInt(t.nbits_delta_content_offset, 16); // 7 + w.writeBitsInt(t.min_content_length, 32); // 8 + w.writeBitsInt(t.nbits_delta_content_length, 16); // 9 + w.writeBitsInt(t.nbits_nshared_objects, 16); // 10 + w.writeBitsInt(t.nbits_shared_identifier, 16); // 11 + w.writeBitsInt(t.nbits_shared_numerator, 16); // 12 + w.writeBitsInt(t.shared_denominator, 16); // 13 int nitems = toI(getAllPages().size()); std::vector& entries = t.entries; - write_vector_int(w, nitems, entries, - t.nbits_delta_nobjects, - &HPageOffsetEntry::delta_nobjects); - write_vector_int(w, nitems, entries, - t.nbits_delta_page_length, - &HPageOffsetEntry::delta_page_length); - write_vector_int(w, nitems, entries, - t.nbits_nshared_objects, - &HPageOffsetEntry::nshared_objects); - write_vector_vector(w, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_identifier, - &HPageOffsetEntry::shared_identifiers); - write_vector_vector(w, nitems, entries, - &HPageOffsetEntry::nshared_objects, - t.nbits_shared_numerator, - &HPageOffsetEntry::shared_numerators); - write_vector_int(w, nitems, entries, - t.nbits_delta_content_offset, - &HPageOffsetEntry::delta_content_offset); - write_vector_int(w, nitems, entries, - t.nbits_delta_content_length, - &HPageOffsetEntry::delta_content_length); + write_vector_int( + w, + nitems, + entries, + t.nbits_delta_nobjects, + &HPageOffsetEntry::delta_nobjects); + write_vector_int( + w, + nitems, + entries, + t.nbits_delta_page_length, + &HPageOffsetEntry::delta_page_length); + write_vector_int( + w, + nitems, + entries, + t.nbits_nshared_objects, + &HPageOffsetEntry::nshared_objects); + write_vector_vector( + w, + nitems, + entries, + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_identifier, + &HPageOffsetEntry::shared_identifiers); + write_vector_vector( + w, + nitems, + entries, + &HPageOffsetEntry::nshared_objects, + t.nbits_shared_numerator, + &HPageOffsetEntry::shared_numerators); + write_vector_int( + w, + nitems, + entries, + t.nbits_delta_content_offset, + &HPageOffsetEntry::delta_content_offset); + write_vector_int( + w, + nitems, + entries, + t.nbits_delta_content_length, + &HPageOffsetEntry::delta_content_length); } void @@ -2210,54 +2067,62 @@ QPDF::writeHSharedObject(BitWriter& w) { HSharedObject& t = this->m->shared_object_hints; - w.writeBitsInt(t.first_shared_obj, 32); // 1 - w.writeBitsInt(toI(t.first_shared_offset), 32); // 2 - w.writeBitsInt(t.nshared_first_page, 32); // 3 - w.writeBitsInt(t.nshared_total, 32); // 4 - w.writeBitsInt(t.nbits_nobjects, 16); // 5 - w.writeBitsInt(t.min_group_length, 32); // 6 - w.writeBitsInt(t.nbits_delta_group_length, 16); // 7 + w.writeBitsInt(t.first_shared_obj, 32); // 1 + w.writeBitsInt(toI(t.first_shared_offset), 32); // 2 + w.writeBitsInt(t.nshared_first_page, 32); // 3 + w.writeBitsInt(t.nshared_total, 32); // 4 + w.writeBitsInt(t.nbits_nobjects, 16); // 5 + w.writeBitsInt(t.min_group_length, 32); // 6 + w.writeBitsInt(t.nbits_delta_group_length, 16); // 7 - QTC::TC("qpdf", "QPDF lin write nshared_total > nshared_first_page", - (t.nshared_total > t.nshared_first_page) ? 1 : 0); + QTC::TC( + "qpdf", + "QPDF lin write nshared_total > nshared_first_page", + (t.nshared_total > t.nshared_first_page) ? 1 : 0); int nitems = t.nshared_total; std::vector& entries = t.entries; - write_vector_int(w, nitems, entries, - t.nbits_delta_group_length, - &HSharedObjectEntry::delta_group_length); - write_vector_int(w, nitems, entries, - 1, &HSharedObjectEntry::signature_present); - for (size_t i = 0; i < toS(nitems); ++i) - { + write_vector_int( + w, + nitems, + entries, + t.nbits_delta_group_length, + &HSharedObjectEntry::delta_group_length); + write_vector_int( + w, nitems, entries, 1, &HSharedObjectEntry::signature_present); + for (size_t i = 0; i < toS(nitems); ++i) { // If signature were present, we'd have to write a 128-bit hash. - if (entries.at(i).signature_present != 0) - { + if (entries.at(i).signature_present != 0) { stopOnError("found unexpected signature present" " while writing linearization data"); } } - write_vector_int(w, nitems, entries, - t.nbits_nobjects, - &HSharedObjectEntry::nobjects_minus_one); + write_vector_int( + w, + nitems, + entries, + t.nbits_nobjects, + &HSharedObjectEntry::nobjects_minus_one); } void QPDF::writeHGeneric(BitWriter& w, HGeneric& t) { - w.writeBitsInt(t.first_object, 32); // 1 - w.writeBitsInt(toI(t.first_object_offset), 32); // 2 - w.writeBitsInt(t.nobjects, 32); // 3 - w.writeBitsInt(t.group_length, 32); // 4 + w.writeBitsInt(t.first_object, 32); // 1 + w.writeBitsInt(toI(t.first_object_offset), 32); // 2 + w.writeBitsInt(t.nobjects, 32); // 3 + w.writeBitsInt(t.group_length, 32); // 4 } void -QPDF::generateHintStream(std::map const& xref, - std::map const& lengths, - std::map const& obj_renumber, - PointerHolder& hint_buffer, - int& S, int& O) +QPDF::generateHintStream( + std::map const& xref, + std::map const& lengths, + std::map const& obj_renumber, + PointerHolder& hint_buffer, + int& S, + int& O) { // Populate actual hint table values calculateHPageOffset(xref, lengths, obj_renumber); @@ -2275,8 +2140,7 @@ QPDF::generateHintStream(std::map const& xref, S = toI(c.getCount()); writeHSharedObject(w); O = 0; - if (this->m->outline_hints.nobjects > 0) - { + if (this->m->outline_hints.nobjects > 0) { O = toI(c.getCount()); writeHGeneric(w, this->m->outline_hints); } diff --git a/libqpdf/QPDF_optimization.cc b/libqpdf/QPDF_optimization.cc index bf799a78..3d262b03 100644 --- a/libqpdf/QPDF_optimization.cc +++ b/libqpdf/QPDF_optimization.cc @@ -2,10 +2,10 @@ #include -#include #include -#include #include +#include +#include #include QPDF::ObjUser::ObjUser() : @@ -39,18 +39,12 @@ QPDF::ObjUser::ObjUser(user_e type, std::string const& key) : bool QPDF::ObjUser::operator<(ObjUser const& rhs) const { - if (this->ou_type < rhs.ou_type) - { + if (this->ou_type < rhs.ou_type) { return true; - } - else if (this->ou_type == rhs.ou_type) - { - if (this->pageno < rhs.pageno) - { + } else if (this->ou_type == rhs.ou_type) { + if (this->pageno < rhs.pageno) { return true; - } - else if (this->pageno == rhs.pageno) - { + } else if (this->pageno == rhs.pageno) { return (this->key < rhs.key); } } @@ -59,19 +53,18 @@ QPDF::ObjUser::operator<(ObjUser const& rhs) const } void -QPDF::optimize(std::map const& object_stream_data, - bool allow_changes) +QPDF::optimize(std::map const& object_stream_data, bool allow_changes) { optimize(object_stream_data, allow_changes, nullptr); } void -QPDF::optimize(std::map const& object_stream_data, - bool allow_changes, - std::function skip_stream_parameters) +QPDF::optimize( + std::map const& object_stream_data, + bool allow_changes, + std::function skip_stream_parameters) { - if (! this->m->obj_user_to_objects.empty()) - { + if (!this->m->obj_user_to_objects.empty()) { // already optimized return; } @@ -80,11 +73,9 @@ QPDF::optimize(std::map const& object_stream_data, // be an indirect reference. Force it to be so if it exists and // is direct. (This has been seen in the wild.) QPDFObjectHandle root = getRoot(); - if (root.getKey("/Outlines").isDictionary()) - { + if (root.getKey("/Outlines").isDictionary()) { QPDFObjectHandle outlines = root.getKey("/Outlines"); - if (! outlines.isIndirect()) - { + if (!outlines.isIndirect()) { QTC::TC("qpdf", "QPDF_optimization indirect outlines"); root.replaceKey("/Outlines", makeIndirectObject(outlines)); } @@ -96,35 +87,33 @@ QPDF::optimize(std::map const& object_stream_data, // Traverse pages int n = toI(this->m->all_pages.size()); - for (int pageno = 0; pageno < n; ++pageno) - { - updateObjectMaps(ObjUser(ObjUser::ou_page, pageno), - this->m->all_pages.at(toS(pageno)), - skip_stream_parameters); + for (int pageno = 0; pageno < n; ++pageno) { + updateObjectMaps( + ObjUser(ObjUser::ou_page, pageno), + this->m->all_pages.at(toS(pageno)), + skip_stream_parameters); } // Traverse document-level items std::set keys = this->m->trailer.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; - if (key == "/Root") - { + if (key == "/Root") { // handled separately - } - else - { - updateObjectMaps(ObjUser(ObjUser::ou_trailer_key, key), - this->m->trailer.getKey(key), - skip_stream_parameters); + } else { + updateObjectMaps( + ObjUser(ObjUser::ou_trailer_key, key), + this->m->trailer.getKey(key), + skip_stream_parameters); } } keys = root.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { // Technically, /I keys from /Thread dictionaries are supposed // to be handled separately, but we are going to disregard // that specification for now. There is loads of evidence @@ -133,9 +122,10 @@ QPDF::optimize(std::map const& object_stream_data, // problems. std::string const& key = *iter; - updateObjectMaps(ObjUser(ObjUser::ou_root_key, key), - root.getKey(key), - skip_stream_parameters); + updateObjectMaps( + ObjUser(ObjUser::ou_root_key, key), + root.getKey(key), + skip_stream_parameters); } ObjUser root_ou = ObjUser(ObjUser::ou_root); @@ -162,8 +152,7 @@ QPDF::pushInheritedAttributesToPage(bool allow_changes, bool warn_skipped_keys) // The record of whether we've done this is cleared by // updateAllPagesCache(). If we're warning for skipped keys, // re-traverse unconditionally. - if (this->m->pushed_inherited_attributes_to_pages && (! warn_skipped_keys)) - { + if (this->m->pushed_inherited_attributes_to_pages && (!warn_skipped_keys)) { return; } @@ -172,18 +161,19 @@ QPDF::pushInheritedAttributesToPage(bool allow_changes, bool warn_skipped_keys) // key_ancestors is a mapping of page attribute keys to a stack of // Pages nodes that contain values for them. - std::map > key_ancestors; + std::map> key_ancestors; this->m->all_pages.clear(); std::set visited; pushInheritedAttributesToPageInternal( this->m->trailer.getKey("/Root").getKey("/Pages"), - key_ancestors, this->m->all_pages, allow_changes, warn_skipped_keys, + key_ancestors, + this->m->all_pages, + allow_changes, + warn_skipped_keys, visited); - if (! key_ancestors.empty()) - { - throw std::logic_error( - "key_ancestors not empty after" - " pushing inherited attributes to pages"); + if (!key_ancestors.empty()) { + throw std::logic_error("key_ancestors not empty after" + " pushing inherited attributes to pages"); } this->m->pushed_inherited_attributes_to_pages = true; } @@ -191,34 +181,36 @@ QPDF::pushInheritedAttributesToPage(bool allow_changes, bool warn_skipped_keys) void QPDF::pushInheritedAttributesToPageInternal( QPDFObjectHandle cur_pages, - std::map >& key_ancestors, + std::map>& key_ancestors, std::vector& pages, - bool allow_changes, bool warn_skipped_keys, + bool allow_changes, + bool warn_skipped_keys, std::set& visited) { QPDFObjGen this_og = cur_pages.getObjGen(); - if (visited.count(this_og) > 0) - { + if (visited.count(this_og) > 0) { throw QPDFExc( - qpdf_e_pages, this->m->file->getName(), - this->m->last_object_description, 0, + qpdf_e_pages, + this->m->file->getName(), + this->m->last_object_description, + 0, "Loop detected in /Pages structure (inherited attributes)"); } visited.insert(this_og); - if (! cur_pages.isDictionary()) - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "invalid object in page tree"); + if (!cur_pages.isDictionary()) { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "invalid object in page tree"); } // Extract the underlying dictionary object std::string type = cur_pages.getKey("/Type").getName(); - if (type == "/Pages") - { + if (type == "/Pages") { // Make a list of inheritable keys. Only the keys /MediaBox, // /CropBox, /Resources, and /Rotate are inheritable // attributes. Push this object onto the stack of pages nodes @@ -227,69 +219,68 @@ QPDF::pushInheritedAttributesToPageInternal( std::set inheritable_keys; std::set keys = cur_pages.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; - if ( (key == "/MediaBox") || (key == "/CropBox") || - (key == "/Resources") || (key == "/Rotate") ) - { - if (! allow_changes) - { - throw QPDFExc(qpdf_e_internal, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "optimize detected an " - "inheritable attribute when called " - "in no-change mode"); + if ((key == "/MediaBox") || (key == "/CropBox") || + (key == "/Resources") || (key == "/Rotate")) { + if (!allow_changes) { + throw QPDFExc( + qpdf_e_internal, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "optimize detected an " + "inheritable attribute when called " + "in no-change mode"); } // This is an inheritable resource inheritable_keys.insert(key); QPDFObjectHandle oh = cur_pages.getKey(key); - QTC::TC("qpdf", "QPDF opt direct pages resource", - oh.isIndirect() ? 0 : 1); - if (! oh.isIndirect()) - { - if (! oh.isScalar()) - { + QTC::TC( + "qpdf", + "QPDF opt direct pages resource", + oh.isIndirect() ? 0 : 1); + if (!oh.isIndirect()) { + if (!oh.isScalar()) { // Replace shared direct object non-scalar // resources with indirect objects to avoid // copying large structures around. cur_pages.replaceKey(key, makeIndirectObject(oh)); oh = cur_pages.getKey(key); - } - else - { + } else { // It's okay to copy scalars. QTC::TC("qpdf", "QPDF opt inherited scalar"); } } key_ancestors[key].push_back(oh); - if (key_ancestors[key].size() > 1) - { + if (key_ancestors[key].size() > 1) { QTC::TC("qpdf", "QPDF opt key ancestors depth > 1"); } // Remove this resource from this node. It will be // reattached at the page level. cur_pages.removeKey(key); - } - else if (! ((key == "/Type") || (key == "/Parent") || - (key == "/Kids") || (key == "/Count"))) - { + } else if (!((key == "/Type") || (key == "/Parent") || + (key == "/Kids") || (key == "/Count"))) { // Warn when flattening, but not if the key is at the top // level (i.e. "/Parent" not set), as we don't change these; // but flattening removes intermediate /Pages nodes. - if ( (warn_skipped_keys) && (cur_pages.hasKey("/Parent")) ) - { + if ((warn_skipped_keys) && (cur_pages.hasKey("/Parent"))) { QTC::TC("qpdf", "QPDF unknown key not inherited"); - setLastObjectDescription("Pages object", - cur_pages.getObjectID(), - cur_pages.getGeneration()); - warn(QPDFExc(qpdf_e_pages, this->m->file->getName(), - this->m->last_object_description, 0, - "Unknown key " + key + " in /Pages object" - " is being discarded as a result of" - " flattening the /Pages tree")); + setLastObjectDescription( + "Pages object", + cur_pages.getObjectID(), + cur_pages.getGeneration()); + warn(QPDFExc( + qpdf_e_pages, + this->m->file->getName(), + this->m->last_object_description, + 0, + "Unknown key " + key + + " in /Pages object" + " is being discarded as a result of" + " flattening the /Pages tree")); } } } @@ -297,11 +288,14 @@ QPDF::pushInheritedAttributesToPageInternal( // Visit descendant nodes. QPDFObjectHandle kids = cur_pages.getKey("/Kids"); int n = kids.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { pushInheritedAttributesToPageInternal( - kids.getArrayItem(i), key_ancestors, pages, - allow_changes, warn_skipped_keys, visited); + kids.getArrayItem(i), + key_ancestors, + pages, + allow_changes, + warn_skipped_keys, + visited); } // For each inheritable key, pop the stack. If the stack @@ -309,61 +303,53 @@ QPDF::pushInheritedAttributesToPageInternal( // invariant that the list of keys in key_ancestors is exactly // those keys for which inheritable attributes are available. - if (! inheritable_keys.empty()) - { + if (!inheritable_keys.empty()) { QTC::TC("qpdf", "QPDF opt inheritable keys"); for (std::set::iterator iter = inheritable_keys.begin(); - iter != inheritable_keys.end(); ++iter) - { + iter != inheritable_keys.end(); + ++iter) { std::string const& key = (*iter); key_ancestors[key].pop_back(); - if (key_ancestors[key].empty()) - { + if (key_ancestors[key].empty()) { QTC::TC("qpdf", "QPDF opt erase empty key ancestor"); key_ancestors.erase(key); } } - } - else - { + } else { QTC::TC("qpdf", "QPDF opt no inheritable keys"); } - } - else if (type == "/Page") - { + } else if (type == "/Page") { // Add all available inheritable attributes not present in // this object to this object. - for (std::map >::iterator + for (std::map>::iterator iter = key_ancestors.begin(); - iter != key_ancestors.end(); ++iter) - { + iter != key_ancestors.end(); + ++iter) { std::string const& key = (*iter).first; - if (! cur_pages.hasKey(key)) - { + if (!cur_pages.hasKey(key)) { QTC::TC("qpdf", "QPDF opt resource inherited"); cur_pages.replaceKey(key, (*iter).second.back()); - } - else - { + } else { QTC::TC("qpdf", "QPDF opt page resource hides ancestor"); } } pages.push_back(cur_pages); - } - else - { - throw QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - this->m->last_object_description, - this->m->file->getLastOffset(), - "invalid Type " + type + " in page tree"); + } else { + throw QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + this->m->last_object_description, + this->m->file->getLastOffset(), + "invalid Type " + type + " in page tree"); } visited.erase(this_og); } void QPDF::updateObjectMaps( - ObjUser const& ou, QPDFObjectHandle oh, + ObjUser const& ou, + QPDFObjectHandle oh, std::function skip_stream_parameters) { std::set visited; @@ -372,9 +358,11 @@ QPDF::updateObjectMaps( void QPDF::updateObjectMapsInternal( - ObjUser const& ou, QPDFObjectHandle oh, + ObjUser const& ou, + QPDFObjectHandle oh, std::function skip_stream_parameters, - std::set& visited, bool top, + std::set& visited, + bool top, int depth) { // Traverse the object tree from this point taking care to avoid @@ -382,20 +370,16 @@ QPDF::updateObjectMapsInternal( bool is_page_node = false; - if (oh.isDictionaryOfType("/Page")) - { + if (oh.isDictionaryOfType("/Page")) { is_page_node = true; - if (! top) - { + if (!top) { return; } } - if (oh.isIndirect()) - { + if (oh.isIndirect()) { QPDFObjGen og(oh.getObjGen()); - if (visited.count(og)) - { + if (visited.count(og)) { QTC::TC("qpdf", "QPDF opt loop detected"); return; } @@ -404,60 +388,59 @@ QPDF::updateObjectMapsInternal( visited.insert(og); } - if (oh.isArray()) - { + if (oh.isArray()) { int n = oh.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { updateObjectMapsInternal( - ou, oh.getArrayItem(i), skip_stream_parameters, - visited, false, 1 + depth); + ou, + oh.getArrayItem(i), + skip_stream_parameters, + visited, + false, + 1 + depth); } - } - else if (oh.isDictionary() || oh.isStream()) - { + } else if (oh.isDictionary() || oh.isStream()) { QPDFObjectHandle dict = oh; bool is_stream = oh.isStream(); int ssp = 0; - if (is_stream) - { + if (is_stream) { dict = oh.getDict(); - if (skip_stream_parameters) - { + if (skip_stream_parameters) { ssp = skip_stream_parameters(oh); } } std::set keys = dict.getKeys(); for (std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + iter != keys.end(); + ++iter) { std::string const& key = *iter; - if (is_page_node && (key == "/Thumb")) - { + if (is_page_node && (key == "/Thumb")) { // Traverse page thumbnail dictionaries as a special // case. updateObjectMapsInternal( ObjUser(ObjUser::ou_thumb, ou.pageno), - dict.getKey(key), skip_stream_parameters, - visited, false, 1 + depth); - } - else if (is_page_node && (key == "/Parent")) - { + dict.getKey(key), + skip_stream_parameters, + visited, + false, + 1 + depth); + } else if (is_page_node && (key == "/Parent")) { // Don't traverse back up the page tree - } - else if (((ssp >= 1) && (key == "/Length")) || - ((ssp >= 2) && ((key == "/Filter") || - (key == "/DecodeParms")))) - { + } else if ( + ((ssp >= 1) && (key == "/Length")) || + ((ssp >= 2) && + ((key == "/Filter") || (key == "/DecodeParms")))) { // Don't traverse into stream parameters that we are // not going to write. - } - else - { + } else { updateObjectMapsInternal( - ou, dict.getKey(key), skip_stream_parameters, - visited, false, 1 + depth); + ou, + dict.getKey(key), + skip_stream_parameters, + visited, + false, + 1 + depth); } } } @@ -466,8 +449,7 @@ QPDF::updateObjectMapsInternal( void QPDF::filterCompressedObjects(std::map const& object_stream_data) { - if (object_stream_data.empty()) - { + if (object_stream_data.empty()) { return; } @@ -476,50 +458,44 @@ QPDF::filterCompressedObjects(std::map const& object_stream_data) // user of a compressed object, then it is really a user of the // object stream that contains it. - std::map > t_obj_user_to_objects; - std::map > t_object_to_obj_users; + std::map> t_obj_user_to_objects; + std::map> t_object_to_obj_users; - for (std::map >::iterator i1 = + for (std::map>::iterator i1 = this->m->obj_user_to_objects.begin(); - i1 != this->m->obj_user_to_objects.end(); ++i1) - { + i1 != this->m->obj_user_to_objects.end(); + ++i1) { ObjUser const& ou = (*i1).first; std::set const& objects = (*i1).second; for (std::set::const_iterator i2 = objects.begin(); - i2 != objects.end(); ++i2) - { + i2 != objects.end(); + ++i2) { QPDFObjGen const& og = (*i2); std::map::const_iterator i3 = object_stream_data.find(og.getObj()); - if (i3 == object_stream_data.end()) - { + if (i3 == object_stream_data.end()) { t_obj_user_to_objects[ou].insert(og); - } - else - { + } else { t_obj_user_to_objects[ou].insert(QPDFObjGen((*i3).second, 0)); } } } - for (std::map >::iterator i1 = + for (std::map>::iterator i1 = this->m->object_to_obj_users.begin(); - i1 != this->m->object_to_obj_users.end(); ++i1) - { + i1 != this->m->object_to_obj_users.end(); + ++i1) { QPDFObjGen const& og = (*i1).first; std::set const& objusers = (*i1).second; for (std::set::const_iterator i2 = objusers.begin(); - i2 != objusers.end(); ++i2) - { + i2 != objusers.end(); + ++i2) { ObjUser const& ou = (*i2); std::map::const_iterator i3 = object_stream_data.find(og.getObj()); - if (i3 == object_stream_data.end()) - { + if (i3 == object_stream_data.end()) { t_object_to_obj_users[og].insert(ou); - } - else - { + } else { t_object_to_obj_users[QPDFObjGen((*i3).second, 0)].insert(ou); } } diff --git a/libqpdf/QPDF_pages.cc b/libqpdf/QPDF_pages.cc index 032809e2..065be7e7 100644 --- a/libqpdf/QPDF_pages.cc +++ b/libqpdf/QPDF_pages.cc @@ -2,9 +2,9 @@ #include +#include #include #include -#include // In support of page manipulation APIs, these methods internally // maintain state about pages in a pair of data structures: all_pages, @@ -53,25 +53,21 @@ QPDF::getAllPages() { // Note that pushInheritedAttributesToPage may also be used to // initialize this->m->all_pages. - if (this->m->all_pages.empty()) - { + if (this->m->all_pages.empty()) { std::set visited; std::set seen; QPDFObjectHandle pages = getRoot().getKey("/Pages"); bool warned = false; bool changed_pages = false; - while (pages.isDictionary() && pages.hasKey("/Parent")) - { - if (seen.count(pages.getObjGen())) - { + while (pages.isDictionary() && pages.hasKey("/Parent")) { + if (seen.count(pages.getObjGen())) { // loop -- will be detected again and reported later break; } // Files have been found in the wild where /Pages in the // catalog points to the first page. Try to work around // this and similar cases with this heuristic. - if (! warned) - { + if (!warned) { getRoot().warnIfPossible( "document page tree root (root -> /Pages) doesn't point" " to the root of the page tree; attempting to correct"); @@ -81,8 +77,7 @@ QPDF::getAllPages() changed_pages = true; pages = pages.getKey("/Parent"); } - if (changed_pages) - { + if (changed_pages) { getRoot().replaceKey("/Pages", pages); } seen.clear(); @@ -92,37 +87,34 @@ QPDF::getAllPages() } void -QPDF::getAllPagesInternal(QPDFObjectHandle cur_node, - std::vector& result, - std::set& visited, - std::set& seen) +QPDF::getAllPagesInternal( + QPDFObjectHandle cur_node, + std::vector& result, + std::set& visited, + std::set& seen) { QPDFObjGen this_og = cur_node.getObjGen(); - if (visited.count(this_og) > 0) - { + if (visited.count(this_og) > 0) { throw QPDFExc( - qpdf_e_pages, this->m->file->getName(), - this->m->last_object_description, 0, + qpdf_e_pages, + this->m->file->getName(), + this->m->last_object_description, + 0, "Loop detected in /Pages structure (getAllPages)"); } visited.insert(this_og); std::string wanted_type; - if (cur_node.hasKey("/Kids")) - { + if (cur_node.hasKey("/Kids")) { wanted_type = "/Pages"; QPDFObjectHandle kids = cur_node.getKey("/Kids"); int n = kids.getArrayNItems(); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { QPDFObjectHandle kid = kids.getArrayItem(i); - if (! kid.isIndirect()) - { + if (!kid.isIndirect()) { QTC::TC("qpdf", "QPDF handle direct page object"); kid = makeIndirectObject(kid); kids.setArrayItem(i, kid); - } - else if (seen.count(kid.getObjGen())) - { + } else if (seen.count(kid.getObjGen())) { // Make a copy of the page. This does the same as // shallowCopyPage in QPDFPageObjectHelper. QTC::TC("qpdf", "QPDF resolve duplicated page object"); @@ -131,21 +123,19 @@ QPDF::getAllPagesInternal(QPDFObjectHandle cur_node, } getAllPagesInternal(kid, result, visited, seen); } - } - else - { + } else { wanted_type = "/Page"; seen.insert(this_og); result.push_back(cur_node); } - if (! cur_node.isDictionaryOfType(wanted_type)) - { - warn(QPDFExc(qpdf_e_damaged_pdf, this->m->file->getName(), - "page tree node", - this->m->file->getLastOffset(), - "/Type key should be " + wanted_type + - " but is not; overriding")); + if (!cur_node.isDictionaryOfType(wanted_type)) { + warn(QPDFExc( + qpdf_e_damaged_pdf, + this->m->file->getName(), + "page tree node", + this->m->file->getLastOffset(), + "/Type key should be " + wanted_type + " but is not; overriding")); cur_node.replaceKey("/Type", QPDFObjectHandle::newName(wanted_type)); } visited.erase(this_og); @@ -171,8 +161,7 @@ QPDF::flattenPagesTree() // If not already done, flatten the /Pages structure and // initialize pageobj_to_pages_pos. - if (! this->m->pageobj_to_pages_pos.empty()) - { + if (!this->m->pageobj_to_pages_pos.empty()) { return; } @@ -183,8 +172,7 @@ QPDF::flattenPagesTree() QPDFObjectHandle pages = getRoot().getKey("/Pages"); size_t const len = this->m->all_pages.size(); - for (size_t pos = 0; pos < len; ++pos) - { + for (size_t pos = 0; pos < len; ++pos) { // Populate pageobj_to_pages_pos and fix parent pointer. There // should be no duplicates at this point because // pushInheritedAttributesToPage calls getAllPages which @@ -195,35 +183,34 @@ QPDF::flattenPagesTree() pages.replaceKey("/Kids", QPDFObjectHandle::newArray(this->m->all_pages)); // /Count has not changed - if (pages.getKey("/Count").getUIntValue() != len) - { + if (pages.getKey("/Count").getUIntValue() != len) { throw std::runtime_error("/Count is wrong after flattening pages tree"); } } void -QPDF::insertPageobjToPage(QPDFObjectHandle const& obj, int pos, - bool check_duplicate) +QPDF::insertPageobjToPage( + QPDFObjectHandle const& obj, int pos, bool check_duplicate) { QPDFObjGen og(obj.getObjGen()); - if (check_duplicate) - { - if (! this->m->pageobj_to_pages_pos.insert( - std::make_pair(og, pos)).second) - { + if (check_duplicate) { + if (!this->m->pageobj_to_pages_pos.insert(std::make_pair(og, pos)) + .second) { // The library never calls insertPageobjToPage in a way // that causes this to happen. - setLastObjectDescription("page " + QUtil::int_to_string(pos) + - " (numbered from zero)", - og.getObj(), og.getGen()); - throw QPDFExc(qpdf_e_pages, this->m->file->getName(), - this->m->last_object_description, 0, - "duplicate page reference found;" - " this would cause loss of data"); + setLastObjectDescription( + "page " + QUtil::int_to_string(pos) + " (numbered from zero)", + og.getObj(), + og.getGen()); + throw QPDFExc( + qpdf_e_pages, + this->m->file->getName(), + this->m->last_object_description, + 0, + "duplicate page reference found;" + " this would cause loss of data"); } - } - else - { + } else { this->m->pageobj_to_pages_pos[og] = pos; } } @@ -236,45 +223,41 @@ QPDF::insertPage(QPDFObjectHandle newpage, int pos) flattenPagesTree(); - if (! newpage.isIndirect()) - { + if (!newpage.isIndirect()) { QTC::TC("qpdf", "QPDF insert non-indirect page"); newpage = makeIndirectObject(newpage); - } - else if (newpage.getOwningQPDF() != this) - { + } else if (newpage.getOwningQPDF() != this) { QTC::TC("qpdf", "QPDF insert foreign page"); newpage.getOwningQPDF()->pushInheritedAttributesToPage(); newpage = copyForeignObject(newpage); - } - else - { + } else { QTC::TC("qpdf", "QPDF insert indirect page"); } - QTC::TC("qpdf", "QPDF insert page", - (pos == 0) ? 0 : // insert at beginning - (pos == QIntC::to_int(this->m->all_pages.size())) ? 1 : // at end - 2); // insert in middle + QTC::TC( + "qpdf", + "QPDF insert page", + (pos == 0) ? 0 : // insert at beginning + (pos == QIntC::to_int(this->m->all_pages.size())) ? 1 + : // at end + 2); // insert in middle auto og = newpage.getObjGen(); - if (this->m->pageobj_to_pages_pos.count(og)) - { + if (this->m->pageobj_to_pages_pos.count(og)) { QTC::TC("qpdf", "QPDF resolve duplicated page in insert"); newpage = makeIndirectObject(QPDFObjectHandle(newpage).shallowCopy()); } QPDFObjectHandle pages = getRoot().getKey("/Pages"); QPDFObjectHandle kids = pages.getKey("/Kids"); - assert ((pos >= 0) && (QIntC::to_size(pos) <= this->m->all_pages.size())); + assert((pos >= 0) && (QIntC::to_size(pos) <= this->m->all_pages.size())); newpage.replaceKey("/Parent", pages); kids.insertItem(pos, newpage); int npages = kids.getArrayNItems(); pages.replaceKey("/Count", QPDFObjectHandle::newInteger(npages)); this->m->all_pages.insert(this->m->all_pages.begin() + pos, newpage); - for (int i = pos + 1; i < npages; ++i) - { + for (int i = pos + 1; i < npages; ++i) { insertPageobjToPage(this->m->all_pages.at(toS(i)), i, false); } insertPageobjToPage(newpage, pos, true); @@ -284,10 +267,13 @@ void QPDF::removePage(QPDFObjectHandle page) { int pos = findPage(page); // also ensures flat /Pages - QTC::TC("qpdf", "QPDF remove page", - (pos == 0) ? 0 : // remove at beginning - (pos == QIntC::to_int(this->m->all_pages.size() - 1)) ? 1 : // end - 2); // remove in middle + QTC::TC( + "qpdf", + "QPDF remove page", + (pos == 0) ? 0 : // remove at beginning + (pos == QIntC::to_int(this->m->all_pages.size() - 1)) ? 1 + : // end + 2); // remove in middle QPDFObjectHandle pages = getRoot().getKey("/Pages"); QPDFObjectHandle kids = pages.getKey("/Kids"); @@ -297,19 +283,16 @@ QPDF::removePage(QPDFObjectHandle page) pages.replaceKey("/Count", QPDFObjectHandle::newInteger(npages)); this->m->all_pages.erase(this->m->all_pages.begin() + pos); this->m->pageobj_to_pages_pos.erase(page.getObjGen()); - for (int i = pos; i < npages; ++i) - { + for (int i = pos; i < npages; ++i) { insertPageobjToPage(this->m->all_pages.at(toS(i)), i, false); } } void -QPDF::addPageAt(QPDFObjectHandle newpage, bool before, - QPDFObjectHandle refpage) +QPDF::addPageAt(QPDFObjectHandle newpage, bool before, QPDFObjectHandle refpage) { int refpos = findPage(refpage); - if (! before) - { + if (!before) { ++refpos; } insertPage(newpage, refpos); @@ -318,12 +301,9 @@ QPDF::addPageAt(QPDFObjectHandle newpage, bool before, void QPDF::addPage(QPDFObjectHandle newpage, bool first) { - if (first) - { + if (first) { insertPage(newpage, 0); - } - else - { + } else { insertPage( newpage, getRoot().getKey("/Pages").getKey("/Count").getIntValueAsInt()); @@ -342,13 +322,15 @@ QPDF::findPage(QPDFObjGen const& og) flattenPagesTree(); std::map::iterator it = this->m->pageobj_to_pages_pos.find(og); - if (it == this->m->pageobj_to_pages_pos.end()) - { + if (it == this->m->pageobj_to_pages_pos.end()) { QTC::TC("qpdf", "QPDF_pages findPage not found"); setLastObjectDescription("page object", og.getObj(), og.getGen()); - throw QPDFExc(qpdf_e_pages, this->m->file->getName(), - this->m->last_object_description, 0, - "page object not referenced in /Pages tree"); + throw QPDFExc( + qpdf_e_pages, + this->m->file->getName(), + this->m->last_object_description, + 0, + "page object not referenced in /Pages tree"); } return (*it).second; } diff --git a/libqpdf/QTC.cc b/libqpdf/QTC.cc index 53e57ce2..d27bfa8b 100644 --- a/libqpdf/QTC.cc +++ b/libqpdf/QTC.cc @@ -1,21 +1,22 @@ #include +#include #include #include -#include -static bool tc_active(char const* const scope) +static bool +tc_active(char const* const scope) { std::string value; return (QUtil::get_env("TC_SCOPE", &value) && (value == scope)); } -void QTC::TC(char const* const scope, char const* const ccase, int n) +void +QTC::TC(char const* const scope, char const* const ccase, int n) { - static std::set > cache; + static std::set> cache; - if (! tc_active(scope)) - { + if (!tc_active(scope)) { return; } @@ -25,14 +26,12 @@ void QTC::TC(char const* const scope, char const* const ccase, int n) #else # define TC_ENV "TC_FILENAME" #endif - if (! QUtil::get_env(TC_ENV, &filename)) - { + if (!QUtil::get_env(TC_ENV, &filename)) { return; } #undef TC_ENV - if (cache.count(std::make_pair(ccase, n))) - { + if (cache.count(std::make_pair(ccase, n))) { return; } cache.insert(std::make_pair(ccase, n)); diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index d56dd14f..11ced38d 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -3,253 +3,253 @@ #include -#include #include +#include +#include +#include #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #ifndef QPDF_NO_WCHAR_T # include #endif #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN -# include # include # include +# include #else -# include # include +# include #endif // First element is 24 static unsigned short pdf_doc_low_to_unicode[] = { - 0x02d8, // 0x18 BREVE - 0x02c7, // 0x19 CARON - 0x02c6, // 0x1a MODIFIER LETTER CIRCUMFLEX ACCENT - 0x02d9, // 0x1b DOT ABOVE - 0x02dd, // 0x1c DOUBLE ACUTE ACCENT - 0x02db, // 0x1d OGONEK - 0x02da, // 0x1e RING ABOVE - 0x02dc, // 0x1f SMALL TILDE + 0x02d8, // 0x18 BREVE + 0x02c7, // 0x19 CARON + 0x02c6, // 0x1a MODIFIER LETTER CIRCUMFLEX ACCENT + 0x02d9, // 0x1b DOT ABOVE + 0x02dd, // 0x1c DOUBLE ACUTE ACCENT + 0x02db, // 0x1d OGONEK + 0x02da, // 0x1e RING ABOVE + 0x02dc, // 0x1f SMALL TILDE }; // First element is 127 static unsigned short pdf_doc_to_unicode[] = { - 0xfffd, // 0x7f UNDEFINED - 0x2022, // 0x80 BULLET - 0x2020, // 0x81 DAGGER - 0x2021, // 0x82 DOUBLE DAGGER - 0x2026, // 0x83 HORIZONTAL ELLIPSIS - 0x2014, // 0x84 EM DASH - 0x2013, // 0x85 EN DASH - 0x0192, // 0x86 SMALL LETTER F WITH HOOK - 0x2044, // 0x87 FRACTION SLASH (solidus) - 0x2039, // 0x88 SINGLE LEFT-POINTING ANGLE QUOTATION MARK - 0x203a, // 0x89 SINGLE RIGHT-POINTING ANGLE QUOTATION MARK - 0x2212, // 0x8a MINUS SIGN - 0x2030, // 0x8b PER MILLE SIGN - 0x201e, // 0x8c DOUBLE LOW-9 QUOTATION MARK (quotedblbase) - 0x201c, // 0x8d LEFT DOUBLE QUOTATION MARK (double quote left) - 0x201d, // 0x8e RIGHT DOUBLE QUOTATION MARK (quotedblright) - 0x2018, // 0x8f LEFT SINGLE QUOTATION MARK (quoteleft) - 0x2019, // 0x90 RIGHT SINGLE QUOTATION MARK (quoteright) - 0x201a, // 0x91 SINGLE LOW-9 QUOTATION MARK (quotesinglbase) - 0x2122, // 0x92 TRADE MARK SIGN - 0xfb01, // 0x93 LATIN SMALL LIGATURE FI - 0xfb02, // 0x94 LATIN SMALL LIGATURE FL - 0x0141, // 0x95 LATIN CAPITAL LETTER L WITH STROKE - 0x0152, // 0x96 LATIN CAPITAL LIGATURE OE - 0x0160, // 0x97 LATIN CAPITAL LETTER S WITH CARON - 0x0178, // 0x98 LATIN CAPITAL LETTER Y WITH DIAERESIS - 0x017d, // 0x99 LATIN CAPITAL LETTER Z WITH CARON - 0x0131, // 0x9a LATIN SMALL LETTER DOTLESS I - 0x0142, // 0x9b LATIN SMALL LETTER L WITH STROKE - 0x0153, // 0x9c LATIN SMALL LIGATURE OE - 0x0161, // 0x9d LATIN SMALL LETTER S WITH CARON - 0x017e, // 0x9e LATIN SMALL LETTER Z WITH CARON - 0xfffd, // 0x9f UNDEFINED - 0x20ac, // 0xa0 EURO SIGN + 0xfffd, // 0x7f UNDEFINED + 0x2022, // 0x80 BULLET + 0x2020, // 0x81 DAGGER + 0x2021, // 0x82 DOUBLE DAGGER + 0x2026, // 0x83 HORIZONTAL ELLIPSIS + 0x2014, // 0x84 EM DASH + 0x2013, // 0x85 EN DASH + 0x0192, // 0x86 SMALL LETTER F WITH HOOK + 0x2044, // 0x87 FRACTION SLASH (solidus) + 0x2039, // 0x88 SINGLE LEFT-POINTING ANGLE QUOTATION MARK + 0x203a, // 0x89 SINGLE RIGHT-POINTING ANGLE QUOTATION MARK + 0x2212, // 0x8a MINUS SIGN + 0x2030, // 0x8b PER MILLE SIGN + 0x201e, // 0x8c DOUBLE LOW-9 QUOTATION MARK (quotedblbase) + 0x201c, // 0x8d LEFT DOUBLE QUOTATION MARK (double quote left) + 0x201d, // 0x8e RIGHT DOUBLE QUOTATION MARK (quotedblright) + 0x2018, // 0x8f LEFT SINGLE QUOTATION MARK (quoteleft) + 0x2019, // 0x90 RIGHT SINGLE QUOTATION MARK (quoteright) + 0x201a, // 0x91 SINGLE LOW-9 QUOTATION MARK (quotesinglbase) + 0x2122, // 0x92 TRADE MARK SIGN + 0xfb01, // 0x93 LATIN SMALL LIGATURE FI + 0xfb02, // 0x94 LATIN SMALL LIGATURE FL + 0x0141, // 0x95 LATIN CAPITAL LETTER L WITH STROKE + 0x0152, // 0x96 LATIN CAPITAL LIGATURE OE + 0x0160, // 0x97 LATIN CAPITAL LETTER S WITH CARON + 0x0178, // 0x98 LATIN CAPITAL LETTER Y WITH DIAERESIS + 0x017d, // 0x99 LATIN CAPITAL LETTER Z WITH CARON + 0x0131, // 0x9a LATIN SMALL LETTER DOTLESS I + 0x0142, // 0x9b LATIN SMALL LETTER L WITH STROKE + 0x0153, // 0x9c LATIN SMALL LIGATURE OE + 0x0161, // 0x9d LATIN SMALL LETTER S WITH CARON + 0x017e, // 0x9e LATIN SMALL LETTER Z WITH CARON + 0xfffd, // 0x9f UNDEFINED + 0x20ac, // 0xa0 EURO SIGN }; static unsigned short win_ansi_to_unicode[] = { - 0x20ac, // 0x80 - 0xfffd, // 0x81 - 0x201a, // 0x82 - 0x0192, // 0x83 - 0x201e, // 0x84 - 0x2026, // 0x85 - 0x2020, // 0x86 - 0x2021, // 0x87 - 0x02c6, // 0x88 - 0x2030, // 0x89 - 0x0160, // 0x8a - 0x2039, // 0x8b - 0x0152, // 0x8c - 0xfffd, // 0x8d - 0x017d, // 0x8e - 0xfffd, // 0x8f - 0xfffd, // 0x90 - 0x2018, // 0x91 - 0x2019, // 0x92 - 0x201c, // 0x93 - 0x201d, // 0x94 - 0x2022, // 0x95 - 0x2013, // 0x96 - 0x2014, // 0x97 - 0x0303, // 0x98 - 0x2122, // 0x99 - 0x0161, // 0x9a - 0x203a, // 0x9b - 0x0153, // 0x9c - 0xfffd, // 0x9d - 0x017e, // 0x9e - 0x0178, // 0x9f - 0x00a0, // 0xa0 + 0x20ac, // 0x80 + 0xfffd, // 0x81 + 0x201a, // 0x82 + 0x0192, // 0x83 + 0x201e, // 0x84 + 0x2026, // 0x85 + 0x2020, // 0x86 + 0x2021, // 0x87 + 0x02c6, // 0x88 + 0x2030, // 0x89 + 0x0160, // 0x8a + 0x2039, // 0x8b + 0x0152, // 0x8c + 0xfffd, // 0x8d + 0x017d, // 0x8e + 0xfffd, // 0x8f + 0xfffd, // 0x90 + 0x2018, // 0x91 + 0x2019, // 0x92 + 0x201c, // 0x93 + 0x201d, // 0x94 + 0x2022, // 0x95 + 0x2013, // 0x96 + 0x2014, // 0x97 + 0x0303, // 0x98 + 0x2122, // 0x99 + 0x0161, // 0x9a + 0x203a, // 0x9b + 0x0153, // 0x9c + 0xfffd, // 0x9d + 0x017e, // 0x9e + 0x0178, // 0x9f + 0x00a0, // 0xa0 }; static unsigned short mac_roman_to_unicode[] = { - 0x00c4, // 0x80 - 0x00c5, // 0x81 - 0x00c7, // 0x82 - 0x00c9, // 0x83 - 0x00d1, // 0x84 - 0x00d6, // 0x85 - 0x00dc, // 0x86 - 0x00e1, // 0x87 - 0x00e0, // 0x88 - 0x00e2, // 0x89 - 0x00e4, // 0x8a - 0x00e3, // 0x8b - 0x00e5, // 0x8c - 0x00e7, // 0x8d - 0x00e9, // 0x8e - 0x00e8, // 0x8f - 0x00ea, // 0x90 - 0x00eb, // 0x91 - 0x00ed, // 0x92 - 0x00ec, // 0x93 - 0x00ee, // 0x94 - 0x00ef, // 0x95 - 0x00f1, // 0x96 - 0x00f3, // 0x97 - 0x00f2, // 0x98 - 0x00f4, // 0x99 - 0x00f6, // 0x9a - 0x00f5, // 0x9b - 0x00fa, // 0x9c - 0x00f9, // 0x9d - 0x00fb, // 0x9e - 0x00fc, // 0x9f - 0x2020, // 0xa0 - 0x00b0, // 0xa1 - 0x00a2, // 0xa2 - 0x00a3, // 0xa3 - 0x00a7, // 0xa4 - 0x2022, // 0xa5 - 0x00b6, // 0xa6 - 0x00df, // 0xa7 - 0x00ae, // 0xa8 - 0x00a9, // 0xa9 - 0x2122, // 0xaa - 0x0301, // 0xab - 0x0308, // 0xac - 0xfffd, // 0xad - 0x00c6, // 0xae - 0x00d8, // 0xaf - 0xfffd, // 0xb0 - 0x00b1, // 0xb1 - 0xfffd, // 0xb2 - 0xfffd, // 0xb3 - 0x00a5, // 0xb4 - 0x03bc, // 0xb5 - 0xfffd, // 0xb6 - 0xfffd, // 0xb7 - 0xfffd, // 0xb8 - 0xfffd, // 0xb9 - 0xfffd, // 0xba - 0x1d43, // 0xbb - 0x1d52, // 0xbc - 0xfffd, // 0xbd - 0x00e6, // 0xbe - 0x00f8, // 0xbf - 0x00bf, // 0xc0 - 0x00a1, // 0xc1 - 0x00ac, // 0xc2 - 0xfffd, // 0xc3 - 0x0192, // 0xc4 - 0xfffd, // 0xc5 - 0xfffd, // 0xc6 - 0x00ab, // 0xc7 - 0x00bb, // 0xc8 - 0x2026, // 0xc9 - 0xfffd, // 0xca - 0x00c0, // 0xcb - 0x00c3, // 0xcc - 0x00d5, // 0xcd - 0x0152, // 0xce - 0x0153, // 0xcf - 0x2013, // 0xd0 - 0x2014, // 0xd1 - 0x201c, // 0xd2 - 0x201d, // 0xd3 - 0x2018, // 0xd4 - 0x2019, // 0xd5 - 0x00f7, // 0xd6 - 0xfffd, // 0xd7 - 0x00ff, // 0xd8 - 0x0178, // 0xd9 - 0x2044, // 0xda - 0x00a4, // 0xdb - 0x2039, // 0xdc - 0x203a, // 0xdd - 0xfb01, // 0xde - 0xfb02, // 0xdf - 0x2021, // 0xe0 - 0x00b7, // 0xe1 - 0x201a, // 0xe2 - 0x201e, // 0xe3 - 0x2030, // 0xe4 - 0x00c2, // 0xe5 - 0x00ca, // 0xe6 - 0x00c1, // 0xe7 - 0x00cb, // 0xe8 - 0x00c8, // 0xe9 - 0x00cd, // 0xea - 0x00ce, // 0xeb - 0x00cf, // 0xec - 0x00cc, // 0xed - 0x00d3, // 0xee - 0x00d4, // 0xef - 0xfffd, // 0xf0 - 0x00d2, // 0xf1 - 0x00da, // 0xf2 - 0x00db, // 0xf3 - 0x00d9, // 0xf4 - 0x0131, // 0xf5 - 0x02c6, // 0xf6 - 0x0303, // 0xf7 - 0x0304, // 0xf8 - 0x0306, // 0xf9 - 0x0307, // 0xfa - 0x030a, // 0xfb - 0x0327, // 0xfc - 0x030b, // 0xfd - 0x0328, // 0xfe - 0x02c7, // 0xff + 0x00c4, // 0x80 + 0x00c5, // 0x81 + 0x00c7, // 0x82 + 0x00c9, // 0x83 + 0x00d1, // 0x84 + 0x00d6, // 0x85 + 0x00dc, // 0x86 + 0x00e1, // 0x87 + 0x00e0, // 0x88 + 0x00e2, // 0x89 + 0x00e4, // 0x8a + 0x00e3, // 0x8b + 0x00e5, // 0x8c + 0x00e7, // 0x8d + 0x00e9, // 0x8e + 0x00e8, // 0x8f + 0x00ea, // 0x90 + 0x00eb, // 0x91 + 0x00ed, // 0x92 + 0x00ec, // 0x93 + 0x00ee, // 0x94 + 0x00ef, // 0x95 + 0x00f1, // 0x96 + 0x00f3, // 0x97 + 0x00f2, // 0x98 + 0x00f4, // 0x99 + 0x00f6, // 0x9a + 0x00f5, // 0x9b + 0x00fa, // 0x9c + 0x00f9, // 0x9d + 0x00fb, // 0x9e + 0x00fc, // 0x9f + 0x2020, // 0xa0 + 0x00b0, // 0xa1 + 0x00a2, // 0xa2 + 0x00a3, // 0xa3 + 0x00a7, // 0xa4 + 0x2022, // 0xa5 + 0x00b6, // 0xa6 + 0x00df, // 0xa7 + 0x00ae, // 0xa8 + 0x00a9, // 0xa9 + 0x2122, // 0xaa + 0x0301, // 0xab + 0x0308, // 0xac + 0xfffd, // 0xad + 0x00c6, // 0xae + 0x00d8, // 0xaf + 0xfffd, // 0xb0 + 0x00b1, // 0xb1 + 0xfffd, // 0xb2 + 0xfffd, // 0xb3 + 0x00a5, // 0xb4 + 0x03bc, // 0xb5 + 0xfffd, // 0xb6 + 0xfffd, // 0xb7 + 0xfffd, // 0xb8 + 0xfffd, // 0xb9 + 0xfffd, // 0xba + 0x1d43, // 0xbb + 0x1d52, // 0xbc + 0xfffd, // 0xbd + 0x00e6, // 0xbe + 0x00f8, // 0xbf + 0x00bf, // 0xc0 + 0x00a1, // 0xc1 + 0x00ac, // 0xc2 + 0xfffd, // 0xc3 + 0x0192, // 0xc4 + 0xfffd, // 0xc5 + 0xfffd, // 0xc6 + 0x00ab, // 0xc7 + 0x00bb, // 0xc8 + 0x2026, // 0xc9 + 0xfffd, // 0xca + 0x00c0, // 0xcb + 0x00c3, // 0xcc + 0x00d5, // 0xcd + 0x0152, // 0xce + 0x0153, // 0xcf + 0x2013, // 0xd0 + 0x2014, // 0xd1 + 0x201c, // 0xd2 + 0x201d, // 0xd3 + 0x2018, // 0xd4 + 0x2019, // 0xd5 + 0x00f7, // 0xd6 + 0xfffd, // 0xd7 + 0x00ff, // 0xd8 + 0x0178, // 0xd9 + 0x2044, // 0xda + 0x00a4, // 0xdb + 0x2039, // 0xdc + 0x203a, // 0xdd + 0xfb01, // 0xde + 0xfb02, // 0xdf + 0x2021, // 0xe0 + 0x00b7, // 0xe1 + 0x201a, // 0xe2 + 0x201e, // 0xe3 + 0x2030, // 0xe4 + 0x00c2, // 0xe5 + 0x00ca, // 0xe6 + 0x00c1, // 0xe7 + 0x00cb, // 0xe8 + 0x00c8, // 0xe9 + 0x00cd, // 0xea + 0x00ce, // 0xeb + 0x00cf, // 0xec + 0x00cc, // 0xed + 0x00d3, // 0xee + 0x00d4, // 0xef + 0xfffd, // 0xf0 + 0x00d2, // 0xf1 + 0x00da, // 0xf2 + 0x00db, // 0xf3 + 0x00d9, // 0xf4 + 0x0131, // 0xf5 + 0x02c6, // 0xf6 + 0x0303, // 0xf7 + 0x0304, // 0xf8 + 0x0306, // 0xf9 + 0x0307, // 0xfa + 0x030a, // 0xfb + 0x0327, // 0xfc + 0x030b, // 0xfd + 0x0328, // 0xfe + 0x02c7, // 0xff }; class FileCloser @@ -270,27 +270,22 @@ class FileCloser }; template -static -std::string +static std::string int_to_string_base_internal(T num, int base, int length) { // Backward compatibility -- int_to_string, which calls this // function, used to use sprintf with %0*d, so we interpret length // such that a negative value appends spaces and a positive value // prepends zeroes. - if (! ((base == 8) || (base == 10) || (base == 16))) - { + if (!((base == 8) || (base == 10) || (base == 16))) { throw std::logic_error( "int_to_string_base called with unsupported base"); } std::string cvt; - if (base == 10) - { + if (base == 10) { // Use the more efficient std::to_string when possible cvt = std::to_string(num); - } - else - { + } else { std::ostringstream buf; buf.imbue(std::locale::classic()); buf << std::setbase(base) << std::nouppercase << num; @@ -298,13 +293,11 @@ int_to_string_base_internal(T num, int base, int length) } std::string result; int str_length = QIntC::to_int(cvt.length()); - if ((length > 0) && (str_length < length)) - { + if ((length > 0) && (str_length < length)) { result.append(QIntC::to_size(length - str_length), '0'); } result += cvt; - if ((length < 0) && (str_length < -length)) - { + if ((length < 0) && (str_length < -length)) { result.append(QIntC::to_size(-length - str_length), ' '); } return result; @@ -341,29 +334,25 @@ QUtil::double_to_string(double num, int decimal_places) } std::string -QUtil::double_to_string(double num, int decimal_places, - bool trim_trailing_zeroes) +QUtil::double_to_string( + double num, int decimal_places, bool trim_trailing_zeroes) { // Backward compatibility -- this code used to use sprintf and // treated decimal_places <= 0 to mean to use the default, which // was six decimal places. Starting in 10.2, we trim trailing // zeroes by default. - if (decimal_places <= 0) - { + if (decimal_places <= 0) { decimal_places = 6; } std::ostringstream buf; buf.imbue(std::locale::classic()); buf << std::setprecision(decimal_places) << std::fixed << num; std::string result = buf.str(); - if (trim_trailing_zeroes) - { - while ((result.length() > 1) && (result.back() == '0')) - { + if (trim_trailing_zeroes) { + while ((result.length() > 1) && (result.back() == '0')) { result.pop_back(); } - if ((result.length() > 1) && (result.back() == '.')) - { + if ((result.length() > 1) && (result.back() == '.')) { result.pop_back(); } } @@ -379,11 +368,10 @@ QUtil::string_to_ll(char const* str) #else long long result = strtoll(str, 0, 10); #endif - if (errno == ERANGE) - { + if (errno == ERANGE) { throw std::range_error( - std::string("overflow/underflow converting ") + str - + " to 64-bit integer"); + std::string("overflow/underflow converting ") + str + + " to 64-bit integer"); } return result; } @@ -399,15 +387,13 @@ unsigned long long QUtil::string_to_ull(char const* str) { char const* p = str; - while (*p && is_space(*p)) - { + while (*p && is_space(*p)) { ++p; } - if (*p == '-') - { + if (*p == '-') { throw std::runtime_error( - std::string("underflow converting ") + str - + " to 64-bit unsigned integer"); + std::string("underflow converting ") + str + + " to 64-bit unsigned integer"); } errno = 0; @@ -416,11 +402,10 @@ QUtil::string_to_ull(char const* str) #else unsigned long long result = strtoull(str, 0, 10); #endif - if (errno == ERANGE) - { + if (errno == ERANGE) { throw std::runtime_error( - std::string("overflow converting ") + str - + " to 64-bit unsigned integer"); + std::string("overflow converting ") + str + + " to 64-bit unsigned integer"); } return result; } @@ -453,8 +438,7 @@ QUtil::throw_system_error(std::string const& description) int QUtil::os_wrapper(std::string const& description, int status) { - if (status == -1) - { + if (status == -1) { throw_system_error(description); } return status; @@ -473,12 +457,10 @@ win_convert_filename(char const* filename) PointerHolder wfilenamep(true, new wchar_t[wlen + 1]); wchar_t* wfilename = wfilenamep.get(); wfilename[wlen] = 0; - for (unsigned int i = 2; i < len; i += 2) - { - wfilename[(i/2) - 1] = - static_cast( - (static_cast(u16.at(i)) << 8) + - static_cast(u16.at(i+1))); + for (unsigned int i = 2; i < len; i += 2) { + wfilename[(i / 2) - 1] = static_cast( + (static_cast(u16.at(i)) << 8) + + static_cast(u16.at(i + 1))); } return wfilenamep; } @@ -494,22 +476,19 @@ QUtil::safe_fopen(char const* filename, char const* mode) PointerHolder wmodep(true, new wchar_t[strlen(mode) + 1]); wchar_t* wmode = wmodep.get(); wmode[strlen(mode)] = 0; - for (size_t i = 0; i < strlen(mode); ++i) - { + for (size_t i = 0; i < strlen(mode); ++i) { wmode[i] = static_cast(mode[i]); } -#ifdef _MSC_VER +# ifdef _MSC_VER errno_t err = _wfopen_s(&f, wfilename, wmode); - if (err != 0) - { + if (err != 0) { errno = err; } -#else +# else f = _wfopen(wfilename, wmode); -#endif - if (f == 0) - { +# endif + if (f == 0) { throw_system_error(std::string("open ") + filename); } #else @@ -521,8 +500,7 @@ QUtil::safe_fopen(char const* filename, char const* mode) FILE* QUtil::fopen_wrapper(std::string const& description, FILE* f) { - if (f == 0) - { + if (f == 0) { throw_system_error(description); } return f; @@ -531,13 +509,10 @@ QUtil::fopen_wrapper(std::string const& description, FILE* f) bool QUtil::file_can_be_opened(char const* filename) { - try - { + try { fclose(safe_fopen(filename, "rb")); return true; - } - catch (std::runtime_error&) - { + } catch (std::runtime_error&) { // can't open the file } return false; @@ -547,9 +522,10 @@ int QUtil::seek(FILE* stream, qpdf_offset_t offset, int whence) { #if HAVE_FSEEKO - return fseeko(stream, - QIntC::IntConverter::convert(offset), - whence); + return fseeko( + stream, + QIntC::IntConverter::convert(offset), + whence); #elif HAVE_FSEEKO64 return fseeko64(stream, offset, whence); #else @@ -580,36 +556,43 @@ QUtil::tell(FILE* stream) bool QUtil::same_file(char const* name1, char const* name2) { - if ((name1 == 0) || (strlen(name1) == 0) || - (name2 == 0) || (strlen(name2) == 0)) - { + if ((name1 == 0) || (strlen(name1) == 0) || (name2 == 0) || + (strlen(name2) == 0)) { return false; } #ifdef _WIN32 bool same = false; # ifndef AVOID_WINDOWS_HANDLE - HANDLE fh1 = CreateFile(name1, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - HANDLE fh2 = CreateFile(name2, GENERIC_READ, FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE fh1 = CreateFile( + name1, + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + HANDLE fh2 = CreateFile( + name2, + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); BY_HANDLE_FILE_INFORMATION fi1; BY_HANDLE_FILE_INFORMATION fi2; - if ((fh1 != INVALID_HANDLE_VALUE) && - (fh2 != INVALID_HANDLE_VALUE) && + if ((fh1 != INVALID_HANDLE_VALUE) && (fh2 != INVALID_HANDLE_VALUE) && GetFileInformationByHandle(fh1, &fi1) && GetFileInformationByHandle(fh2, &fi2) && (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber) && (fi1.nFileIndexLow == fi2.nFileIndexLow) && - (fi1.nFileIndexHigh == fi2.nFileIndexHigh)) - { + (fi1.nFileIndexHigh == fi2.nFileIndexHigh)) { same = true; } - if (fh1 != INVALID_HANDLE_VALUE) - { + if (fh1 != INVALID_HANDLE_VALUE) { CloseHandle(fh1); } - if (fh2 != INVALID_HANDLE_VALUE) - { + if (fh2 != INVALID_HANDLE_VALUE) { CloseHandle(fh2); } # endif @@ -617,18 +600,14 @@ QUtil::same_file(char const* name1, char const* name2) #else struct stat st1; struct stat st2; - if ((stat(name1, &st1) == 0) && - (stat(name2, &st2) == 0) && - (st1.st_ino == st2.st_ino) && - (st1.st_dev == st2.st_dev)) - { + if ((stat(name1, &st1) == 0) && (stat(name2, &st2) == 0) && + (st1.st_ino == st2.st_ino) && (st1.st_dev == st2.st_dev)) { return true; } #endif return false; } - void QUtil::remove_file(char const* path) { @@ -644,21 +623,20 @@ void QUtil::rename_file(char const* oldname, char const* newname) { #ifdef _WIN32 - try - { + try { remove_file(newname); - } - catch (QPDFSystemError&) - { + } catch (QPDFSystemError&) { // ignore } PointerHolder wold = win_convert_filename(oldname); PointerHolder wnew = win_convert_filename(newname); - os_wrapper(std::string("rename ") + oldname + " " + newname, - _wrename(wold.get(), wnew.get())); + os_wrapper( + std::string("rename ") + oldname + " " + newname, + _wrename(wold.get(), wnew.get())); #else - os_wrapper(std::string("rename ") + oldname + " " + newname, - rename(oldname, newname)); + os_wrapper( + std::string("rename ") + oldname + " " + newname, + rename(oldname, newname)); #endif } @@ -671,13 +649,11 @@ QUtil::pipe_file(char const* filename, Pipeline* p) size_t len = 0; int constexpr size = 8192; unsigned char buf[size]; - while ((len = fread(buf, 1, size, f)) > 0) - { + while ((len = fread(buf, 1, size, f)) > 0) { p->write(buf, len); } p->finish(); - if (ferror(f)) - { + if (ferror(f)) { throw std::runtime_error( std::string("failure reading file ") + filename); } @@ -686,9 +662,7 @@ QUtil::pipe_file(char const* filename, Pipeline* p) std::function QUtil::file_provider(std::string const& filename) { - return [filename](Pipeline* p) { - pipe_file(filename.c_str(), p); - }; + return [filename](Pipeline* p) { pipe_file(filename.c_str(), p); }; } std::string @@ -701,20 +675,14 @@ QUtil::path_basename(std::string const& filename) #endif std::string last = filename; auto len = last.length(); - while (len > 1) - { + while (len > 1) { auto pos = last.find_last_of(pathsep); - if (pos == len - 1) - { + if (pos == len - 1) { last.pop_back(); --len; - } - else if (pos == std::string::npos) - { + } else if (pos == std::string::npos) { break; - } - else - { + } else { last = last.substr(pos + 1); break; } @@ -756,8 +724,7 @@ std::string QUtil::hex_encode(std::string const& input) { std::string result; - for (unsigned int i = 0; i < input.length(); ++i) - { + for (unsigned int i = 0; i < input.length(); ++i) { result += QUtil::int_to_string_base( QIntC::to_int(static_cast(input.at(i))), 16, 2); } @@ -769,36 +736,24 @@ QUtil::hex_decode(std::string const& input) { std::string result; size_t pos = 0; - for (std::string::const_iterator p = input.begin(); p != input.end(); ++p) - { + for (std::string::const_iterator p = input.begin(); p != input.end(); ++p) { char ch = *p; bool skip = false; - if ((*p >= 'A') && (*p <= 'F')) - { + if ((*p >= 'A') && (*p <= 'F')) { ch = QIntC::to_char(ch - 'A' + 10); - } - else if ((*p >= 'a') && (*p <= 'f')) - { + } else if ((*p >= 'a') && (*p <= 'f')) { ch = QIntC::to_char(ch - 'a' + 10); - } - else if ((*p >= '0') && (*p <= '9')) - { + } else if ((*p >= '0') && (*p <= '9')) { ch = QIntC::to_char(ch - '0'); - } - else - { + } else { skip = true; } - if (! skip) - { - if (pos == 0) - { + if (!skip) { + if (pos == 0) { result.push_back(static_cast(ch << 4)); pos = 1; - } - else - { - result[result.length()-1] |= ch; + } else { + result[result.length() - 1] |= ch; pos = 0; } } @@ -810,7 +765,7 @@ void QUtil::binary_stdout() { #if defined(_WIN32) && defined(__BORLANDC__) - setmode(_fileno(stdout), _O_BINARY); + setmode(_fileno(stdout), _O_BINARY); #elif defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); #endif @@ -820,7 +775,7 @@ void QUtil::binary_stdin() { #if defined(_WIN32) && defined(__BORLANDC__) - setmode(_fileno(stdin), _O_BINARY); + setmode(_fileno(stdin), _O_BINARY); #elif defined(_WIN32) _setmode(_fileno(stdin), _O_BINARY); #endif @@ -830,7 +785,7 @@ void QUtil::setLineBuf(FILE* f) { #ifndef _WIN32 - setvbuf(f, reinterpret_cast(0), _IOLBF, 0); + setvbuf(f, reinterpret_cast(0), _IOLBF, 0); #endif } @@ -839,18 +794,14 @@ QUtil::getWhoami(char* argv0) { char* whoami = 0; if (((whoami = strrchr(argv0, '/')) == NULL) && - ((whoami = strrchr(argv0, '\\')) == NULL)) - { + ((whoami = strrchr(argv0, '\\')) == NULL)) { whoami = argv0; - } - else - { + } else { ++whoami; } if ((strlen(whoami) > 4) && - (strcmp(whoami + strlen(whoami) - 4, ".exe") == 0)) - { + (strcmp(whoami + strlen(whoami) - 4, ".exe") == 0)) { whoami[strlen(whoami) - 4] = '\0'; } @@ -867,14 +818,12 @@ QUtil::get_env(std::string const& var, std::string* value) # else // first get the size of the buffer DWORD len = ::GetEnvironmentVariable(var.c_str(), NULL, 0); - if (len == 0) - { + if (len == 0) { // this means that there is no such variable return false; } - if (value) - { + if (value) { PointerHolder t = PointerHolder(true, new char[len + 1]); ::GetEnvironmentVariable(var.c_str(), t.get(), len); *value = t.get(); @@ -884,12 +833,10 @@ QUtil::get_env(std::string const& var, std::string* value) # endif #else char* p = getenv(var.c_str()); - if (p == 0) - { + if (p == 0) { return false; } - if (value) - { + if (value) { *value = p; } @@ -931,40 +878,42 @@ QUtil::get_current_qpdf_time() GetLocalTime(<ime); TIME_ZONE_INFORMATION tzinfo; GetTimeZoneInformation(&tzinfo); - return QPDFTime(static_cast(ltime.wYear), - static_cast(ltime.wMonth), - static_cast(ltime.wDay), - static_cast(ltime.wHour), - static_cast(ltime.wMinute), - static_cast(ltime.wSecond), - // tzinfo.Bias is minutes before UTC - static_cast(tzinfo.Bias)); + return QPDFTime( + static_cast(ltime.wYear), + static_cast(ltime.wMonth), + static_cast(ltime.wDay), + static_cast(ltime.wHour), + static_cast(ltime.wMinute), + static_cast(ltime.wSecond), + // tzinfo.Bias is minutes before UTC + static_cast(tzinfo.Bias)); #else struct tm ltime; time_t now = time(0); tzset(); -#ifdef HAVE_LOCALTIME_R +# ifdef HAVE_LOCALTIME_R localtime_r(&now, <ime); -#else +# else ltime = *localtime(&now); -#endif -#if HAVE_TM_GMTOFF +# endif +# if HAVE_TM_GMTOFF // tm_gmtoff is seconds after UTC int tzoff = -static_cast(ltime.tm_gmtoff / 60); -#elif HAVE_EXTERN_LONG_TIMEZONE +# elif HAVE_EXTERN_LONG_TIMEZONE // timezone is seconds before UTC, not adjusted for daylight saving time int tzoff = static_cast(timezone / 60); -#else +# else // Don't know how to get timezone on this platform int tzoff = 0; -#endif - return QPDFTime(static_cast(ltime.tm_year + 1900), - static_cast(ltime.tm_mon + 1), - static_cast(ltime.tm_mday), - static_cast(ltime.tm_hour), - static_cast(ltime.tm_min), - static_cast(ltime.tm_sec), - tzoff); +# endif + return QPDFTime( + static_cast(ltime.tm_year + 1900), + static_cast(ltime.tm_mon + 1), + static_cast(ltime.tm_mday), + static_cast(ltime.tm_hour), + static_cast(ltime.tm_min), + static_cast(ltime.tm_sec), + tzoff); #endif } @@ -973,33 +922,24 @@ QUtil::qpdf_time_to_pdf_time(QPDFTime const& qtm) { std::string tz_offset; int t = qtm.tz_delta; - if (t == 0) - { + if (t == 0) { tz_offset = "Z"; - } - else - { - if (t < 0) - { + } else { + if (t < 0) { t = -t; tz_offset += "+"; - } - else - { + } else { tz_offset += "-"; } - tz_offset += - QUtil::int_to_string(t / 60, 2) + "'" + + tz_offset += QUtil::int_to_string(t / 60, 2) + "'" + QUtil::int_to_string(t % 60, 2) + "'"; } - return ("D:" + - QUtil::int_to_string(qtm.year, 4) + - QUtil::int_to_string(qtm.month, 2) + - QUtil::int_to_string(qtm.day, 2) + - QUtil::int_to_string(qtm.hour, 2) + - QUtil::int_to_string(qtm.minute, 2) + - QUtil::int_to_string(qtm.second, 2) + - tz_offset); + return ( + "D:" + QUtil::int_to_string(qtm.year, 4) + + QUtil::int_to_string(qtm.month, 2) + QUtil::int_to_string(qtm.day, 2) + + QUtil::int_to_string(qtm.hour, 2) + + QUtil::int_to_string(qtm.minute, 2) + + QUtil::int_to_string(qtm.second, 2) + tz_offset); } bool @@ -1009,8 +949,7 @@ QUtil::pdf_time_to_qpdf_time(std::string const& str, QPDFTime* qtm) "([0-9]{2})([0-9]{2})([0-9]{2})" "(?:(Z?)|([\\+\\-])([0-9]{2})'([0-9]{2})')$"); std::smatch m; - if (! std::regex_match(str, m, pdf_date)) - { + if (!std::regex_match(str, m, pdf_date)) { return false; } int tz_delta = 0; @@ -1018,24 +957,21 @@ QUtil::pdf_time_to_qpdf_time(std::string const& str, QPDFTime* qtm) return QUtil::string_to_int(s.c_str()); }; - if (m[8] != "") - { - tz_delta = ((to_i(m[9]) * 60) + - to_i(m[10])); - if (m[8] == "+") - { + if (m[8] != "") { + tz_delta = ((to_i(m[9]) * 60) + to_i(m[10])); + if (m[8] == "+") { tz_delta = -tz_delta; } } - if (qtm) - { - *qtm = QPDFTime(to_i(m[1]), - to_i(m[2]), - to_i(m[3]), - to_i(m[4]), - to_i(m[5]), - to_i(m[6]), - tz_delta); + if (qtm) { + *qtm = QPDFTime( + to_i(m[1]), + to_i(m[2]), + to_i(m[3]), + to_i(m[4]), + to_i(m[5]), + to_i(m[6]), + tz_delta); } return true; } @@ -1055,16 +991,11 @@ QUtil::toUTF8(unsigned long uval) // 110zzzzz, the second is 10zzzzzz, and the z's represent the // remaining bits. - if (uval > 0x7fffffff) - { + if (uval > 0x7fffffff) { throw std::runtime_error("bounds error in QUtil::toUTF8"); - } - else if (uval < 128) - { + } else if (uval < 128) { result += static_cast(uval); - } - else - { + } else { unsigned char bytes[7]; bytes[6] = '\0'; unsigned char* cur_byte = &bytes[5]; @@ -1072,8 +1003,7 @@ QUtil::toUTF8(unsigned long uval) // maximum value that will fit in the current number of bytes unsigned char maxval = 0x3f; // six bits - while (uval > QIntC::to_ulong(maxval)) - { + while (uval > QIntC::to_ulong(maxval)) { // Assign low six bits plus 10000000 to lowest unused // byte position, then shift *cur_byte = static_cast(0x80 + (uval & 0x3f)); @@ -1081,8 +1011,7 @@ QUtil::toUTF8(unsigned long uval) // Maximum that will fit in high byte now shrinks by one bit maxval = static_cast(maxval >> 1); // Slide to the left one byte - if (cur_byte <= bytes) - { + if (cur_byte <= bytes) { throw std::logic_error("QUtil::toUTF8: overflow error"); } --cur_byte; @@ -1102,19 +1031,14 @@ std::string QUtil::toUTF16(unsigned long uval) { std::string result; - if ((uval >= 0xd800) && (uval <= 0xdfff)) - { + if ((uval >= 0xd800) && (uval <= 0xdfff)) { result = "\xff\xfd"; - } - else if (uval <= 0xffff) - { + } else if (uval <= 0xffff) { char out[2]; out[0] = static_cast((uval & 0xff00) >> 8); out[1] = static_cast(uval & 0xff); result = std::string(out, 2); - } - else if (uval <= 0x10ffff) - { + } else if (uval <= 0x10ffff) { char out[4]; uval -= 0x10000; unsigned short high = @@ -1126,9 +1050,7 @@ QUtil::toUTF16(unsigned long uval) out[2] = static_cast((low & 0xff00) >> 8); out[3] = static_cast(low & 0xff); result = std::string(out, 4); - } - else - { + } else { result = "\xff\xfd"; } @@ -1199,8 +1121,7 @@ QUtil::random() { long result = 0L; initializeWithRandomBytes( - reinterpret_cast(&result), - sizeof(result)); + reinterpret_cast(&result), sizeof(result)); return result; } @@ -1226,33 +1147,24 @@ bool QUtil::is_number(char const* p) { // ^[\+\-]?(\.\d*|\d+(\.\d*)?)$ - if (! *p) - { + if (!*p) { return false; } - if ((*p == '-') || (*p == '+')) - { + if ((*p == '-') || (*p == '+')) { ++p; } bool found_dot = false; bool found_digit = false; - for (; *p; ++p) - { - if (*p == '.') - { - if (found_dot) - { + for (; *p; ++p) { + if (*p == '.') { + if (found_dot) { // only one dot return false; } found_dot = true; - } - else if (QUtil::is_digit(*p)) - { + } else if (QUtil::is_digit(*p)) { found_digit = true; - } - else - { + } else { return false; } } @@ -1261,8 +1173,7 @@ QUtil::is_number(char const* p) void QUtil::read_file_into_memory( - char const* filename, - PointerHolder& file_buf, size_t& size) + char const* filename, PointerHolder& file_buf, size_t& size) { FILE* f = safe_fopen(filename, "rb"); FileCloser fc(f); @@ -1273,38 +1184,30 @@ QUtil::read_file_into_memory( char* buf_p = file_buf.get(); size_t bytes_read = 0; size_t len = 0; - while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) - { + while ((len = fread(buf_p + bytes_read, 1, size - bytes_read, f)) > 0) { bytes_read += len; } - if (bytes_read != size) - { - if (ferror(f)) - { + if (bytes_read != size) { + if (ferror(f)) { throw std::runtime_error( std::string("failure reading file ") + filename + - " into memory: read " + - uint_to_string(bytes_read) + "; wanted " + - uint_to_string(size)); - } - else - { + " into memory: read " + uint_to_string(bytes_read) + + "; wanted " + uint_to_string(size)); + } else { throw std::runtime_error( std::string("premature eof reading file ") + filename + - " into memory: read " + - uint_to_string(bytes_read) + "; wanted " + - uint_to_string(size)); + " into memory: read " + uint_to_string(bytes_read) + + "; wanted " + uint_to_string(size)); } } } -static bool read_char_from_FILE(char& ch, FILE* f) +static bool +read_char_from_FILE(char& ch, FILE* f) { auto len = fread(&ch, 1, 1, f); - if (len == 0) - { - if (ferror(f)) - { + if (len == 0) { + if (ferror(f)) { throw std::runtime_error("failure reading character from file"); } return false; @@ -1327,7 +1230,7 @@ std::list QUtil::read_lines_from_file(std::istream& in, bool preserve_eol) { std::list lines; - auto next_char = [&in](char& ch) { return (in.get(ch)) ? true: false; }; + auto next_char = [&in](char& ch) { return (in.get(ch)) ? true : false; }; read_lines_from_file(next_char, lines, preserve_eol); return lines; } @@ -1342,51 +1245,42 @@ QUtil::read_lines_from_file(FILE* f, bool preserve_eol) } void -QUtil::read_lines_from_file(std::function next_char, - std::list& lines, - bool preserve_eol) +QUtil::read_lines_from_file( + std::function next_char, + std::list& lines, + bool preserve_eol) { std::string* buf = 0; char c; - while (next_char(c)) - { - if (buf == 0) - { + while (next_char(c)) { + if (buf == 0) { lines.push_back(""); buf = &(lines.back()); buf->reserve(80); } - if (buf->capacity() == buf->size()) - { + if (buf->capacity() == buf->size()) { buf->reserve(buf->capacity() * 2); } - if (c == '\n') - { - if (preserve_eol) - { + if (c == '\n') { + if (preserve_eol) { buf->append(1, c); - } - else - { + } else { // Remove any carriage return that preceded the // newline and discard the newline - if ((! buf->empty()) && ((*(buf->rbegin())) == '\r')) - { + if ((!buf->empty()) && ((*(buf->rbegin())) == '\r')) { buf->erase(buf->length() - 1); } } buf = 0; - } - else - { + } else { buf->append(1, c); } } } int -QUtil::str_compare_nocase(char const *s1, char const *s2) +QUtil::str_compare_nocase(char const* s1, char const* s2) { #if defined(_WIN32) && defined(__BORLANDC__) return stricmp(s1, s2); @@ -1397,16 +1291,13 @@ QUtil::str_compare_nocase(char const *s1, char const *s2) #endif } -static int maybe_from_end(int num, bool from_end, int max) +static int +maybe_from_end(int num, bool from_end, int max) { - if (from_end) - { - if (num > max) - { + if (from_end) { + if (num > max) { num = 0; - } - else - { + } else { num = max + 1 - num; } } @@ -1418,189 +1309,134 @@ QUtil::parse_numrange(char const* range, int max) { std::vector result; char const* p = range; - try - { + try { std::vector work; static int const comma = -1; static int const dash = -2; size_t start_idx = 0; size_t skip = 1; - enum { st_top, - st_in_number, - st_after_number } state = st_top; + enum { st_top, st_in_number, st_after_number } state = st_top; bool last_separator_was_dash = false; int cur_number = 0; bool from_end = false; - while (*p) - { + while (*p) { char ch = *p; - if (isdigit(ch)) - { - if (! ((state == st_top) || (state == st_in_number))) - { + if (isdigit(ch)) { + if (!((state == st_top) || (state == st_in_number))) { throw std::runtime_error("digit not expected"); } state = st_in_number; cur_number *= 10; cur_number += (ch - '0'); - } - else if (ch == 'z') - { + } else if (ch == 'z') { // z represents max - if (! (state == st_top)) - { + if (!(state == st_top)) { throw std::runtime_error("z not expected"); } state = st_after_number; cur_number = max; - } - else if (ch == 'r') - { - if (! (state == st_top)) - { + } else if (ch == 'r') { + if (!(state == st_top)) { throw std::runtime_error("r not expected"); } state = st_in_number; from_end = true; - } - else if ((ch == ',') || (ch == '-')) - { - if (! ((state == st_in_number) || (state == st_after_number))) - { + } else if ((ch == ',') || (ch == '-')) { + if (!((state == st_in_number) || (state == st_after_number))) { throw std::runtime_error("unexpected separator"); } cur_number = maybe_from_end(cur_number, from_end, max); work.push_back(cur_number); cur_number = 0; from_end = false; - if (ch == ',') - { + if (ch == ',') { state = st_top; last_separator_was_dash = false; work.push_back(comma); - } - else if (ch == '-') - { - if (last_separator_was_dash) - { + } else if (ch == '-') { + if (last_separator_was_dash) { throw std::runtime_error("unexpected dash"); } state = st_top; last_separator_was_dash = true; work.push_back(dash); } - } - else if (ch == ':') - { - if (! ((state == st_in_number) || (state == st_after_number))) - { + } else if (ch == ':') { + if (!((state == st_in_number) || (state == st_after_number))) { throw std::runtime_error("unexpected colon"); } break; - } - else - { + } else { throw std::runtime_error("unexpected character"); } ++p; } - if ((state == st_in_number) || (state == st_after_number)) - { + if ((state == st_in_number) || (state == st_after_number)) { cur_number = maybe_from_end(cur_number, from_end, max); work.push_back(cur_number); - } - else - { + } else { throw std::runtime_error("number expected"); } - if (*p == ':') - { - if (strcmp(p, ":odd") == 0) - { + if (*p == ':') { + if (strcmp(p, ":odd") == 0) { skip = 2; - } - else if (strcmp(p, ":even") == 0) - { + } else if (strcmp(p, ":even") == 0) { skip = 2; start_idx = 1; - } - else - { + } else { throw std::runtime_error("unexpected even/odd modifier"); } } p = 0; - for (size_t i = 0; i < work.size(); i += 2) - { + for (size_t i = 0; i < work.size(); i += 2) { int num = work.at(i); // max == 0 means we don't know the max and are just // testing for valid syntax. - if ((max > 0) && ((num < 1) || (num > max))) - { + if ((max > 0) && ((num < 1) || (num > max))) { throw std::runtime_error( "number " + QUtil::int_to_string(num) + " out of range"); } - if (i == 0) - { + if (i == 0) { result.push_back(work.at(i)); - } - else - { - int separator = work.at(i-1); - if (separator == comma) - { + } else { + int separator = work.at(i - 1); + if (separator == comma) { result.push_back(num); - } - else if (separator == dash) - { + } else if (separator == dash) { int lastnum = result.back(); - if (num > lastnum) - { - for (int j = lastnum + 1; j <= num; ++j) - { + if (num > lastnum) { + for (int j = lastnum + 1; j <= num; ++j) { + result.push_back(j); + } + } else { + for (int j = lastnum - 1; j >= num; --j) { result.push_back(j); } } - else - { - for (int j = lastnum - 1; j >= num; --j) - { - result.push_back(j); - } - } - } - else - { + } else { throw std::logic_error( "INTERNAL ERROR parsing numeric range"); } } } - if ((start_idx > 0) || (skip != 1)) - { + if ((start_idx > 0) || (skip != 1)) { auto t = result; result.clear(); - for (size_t i = start_idx; i < t.size(); i += skip) - { + for (size_t i = start_idx; i < t.size(); i += skip) { result.push_back(t.at(i)); } } - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { std::string message; - if (p) - { + if (p) { message = "error at * in numeric range " + - std::string(range, QIntC::to_size(p - range)) + - "*" + p + ": " + e.what(); - } - else - { - message = "error in numeric range " + - std::string(range) + ": " + e.what(); + std::string(range, QIntC::to_size(p - range)) + "*" + p + ": " + + e.what(); + } else { + message = "error in numeric range " + std::string(range) + ": " + + e.what(); } throw std::runtime_error(message); } @@ -1615,93 +1451,92 @@ encode_winansi(unsigned long codepoint) // Use this ugly switch statement to avoid a static, which is not // thread-safe. unsigned char ch = '\0'; - switch (codepoint) - { - case 0x20ac: + switch (codepoint) { + case 0x20ac: ch = 0x80; break; - case 0x201a: + case 0x201a: ch = 0x82; break; - case 0x192: + case 0x192: ch = 0x83; break; - case 0x201e: + case 0x201e: ch = 0x84; break; - case 0x2026: + case 0x2026: ch = 0x85; break; - case 0x2020: + case 0x2020: ch = 0x86; break; - case 0x2021: + case 0x2021: ch = 0x87; break; - case 0x2c6: + case 0x2c6: ch = 0x88; break; - case 0x2030: + case 0x2030: ch = 0x89; break; - case 0x160: + case 0x160: ch = 0x8a; break; - case 0x2039: + case 0x2039: ch = 0x8b; break; - case 0x152: + case 0x152: ch = 0x8c; break; - case 0x17d: + case 0x17d: ch = 0x8e; break; - case 0x2018: + case 0x2018: ch = 0x91; break; - case 0x2019: + case 0x2019: ch = 0x92; break; - case 0x201c: + case 0x201c: ch = 0x93; break; - case 0x201d: + case 0x201d: ch = 0x94; break; - case 0x2022: + case 0x2022: ch = 0x95; break; - case 0x2013: + case 0x2013: ch = 0x96; break; - case 0x2014: + case 0x2014: ch = 0x97; break; - case 0x303: + case 0x303: ch = 0x98; break; - case 0x2122: + case 0x2122: ch = 0x99; break; - case 0x161: + case 0x161: ch = 0x9a; break; - case 0x203a: + case 0x203a: ch = 0x9b; break; - case 0x153: + case 0x153: ch = 0x9c; break; - case 0x17e: + case 0x17e: ch = 0x9e; break; - case 0x178: + case 0x178: ch = 0x9f; break; - case 0xa0: + case 0xa0: ch = 0xa0; break; - default: + default: break; } return ch; @@ -1713,345 +1548,344 @@ encode_macroman(unsigned long codepoint) // Use this ugly switch statement to avoid a static, which is not // thread-safe. unsigned char ch = '\0'; - switch (codepoint) - { - case 0xc4: + switch (codepoint) { + case 0xc4: ch = 0x80; break; - case 0xc5: + case 0xc5: ch = 0x81; break; - case 0xc7: + case 0xc7: ch = 0x82; break; - case 0xc9: + case 0xc9: ch = 0x83; break; - case 0xd1: + case 0xd1: ch = 0x84; break; - case 0xd6: + case 0xd6: ch = 0x85; break; - case 0xdc: + case 0xdc: ch = 0x86; break; - case 0xe1: + case 0xe1: ch = 0x87; break; - case 0xe0: + case 0xe0: ch = 0x88; break; - case 0xe2: + case 0xe2: ch = 0x89; break; - case 0xe4: + case 0xe4: ch = 0x8a; break; - case 0xe3: + case 0xe3: ch = 0x8b; break; - case 0xe5: + case 0xe5: ch = 0x8c; break; - case 0xe7: + case 0xe7: ch = 0x8d; break; - case 0xe9: + case 0xe9: ch = 0x8e; break; - case 0xe8: + case 0xe8: ch = 0x8f; break; - case 0xea: + case 0xea: ch = 0x90; break; - case 0xeb: + case 0xeb: ch = 0x91; break; - case 0xed: + case 0xed: ch = 0x92; break; - case 0xec: + case 0xec: ch = 0x93; break; - case 0xee: + case 0xee: ch = 0x94; break; - case 0xef: + case 0xef: ch = 0x95; break; - case 0xf1: + case 0xf1: ch = 0x96; break; - case 0xf3: + case 0xf3: ch = 0x97; break; - case 0xf2: + case 0xf2: ch = 0x98; break; - case 0xf4: + case 0xf4: ch = 0x99; break; - case 0xf6: + case 0xf6: ch = 0x9a; break; - case 0xf5: + case 0xf5: ch = 0x9b; break; - case 0xfa: + case 0xfa: ch = 0x9c; break; - case 0xf9: + case 0xf9: ch = 0x9d; break; - case 0xfb: + case 0xfb: ch = 0x9e; break; - case 0xfc: + case 0xfc: ch = 0x9f; break; - case 0x2020: + case 0x2020: ch = 0xa0; break; - case 0xb0: + case 0xb0: ch = 0xa1; break; - case 0xa2: + case 0xa2: ch = 0xa2; break; - case 0xa3: + case 0xa3: ch = 0xa3; break; - case 0xa7: + case 0xa7: ch = 0xa4; break; - case 0x2022: + case 0x2022: ch = 0xa5; break; - case 0xb6: + case 0xb6: ch = 0xa6; break; - case 0xdf: + case 0xdf: ch = 0xa7; break; - case 0xae: + case 0xae: ch = 0xa8; break; - case 0xa9: + case 0xa9: ch = 0xa9; break; - case 0x2122: + case 0x2122: ch = 0xaa; break; - case 0x301: + case 0x301: ch = 0xab; break; - case 0x308: + case 0x308: ch = 0xac; break; - case 0xc6: + case 0xc6: ch = 0xae; break; - case 0xd8: + case 0xd8: ch = 0xaf; break; - case 0xb1: + case 0xb1: ch = 0xb1; break; - case 0xa5: + case 0xa5: ch = 0xb4; break; - case 0x3bc: + case 0x3bc: ch = 0xb5; break; - case 0x1d43: + case 0x1d43: ch = 0xbb; break; - case 0x1d52: + case 0x1d52: ch = 0xbc; break; - case 0xe6: + case 0xe6: ch = 0xbe; break; - case 0xf8: + case 0xf8: ch = 0xbf; break; - case 0xbf: + case 0xbf: ch = 0xc0; break; - case 0xa1: + case 0xa1: ch = 0xc1; break; - case 0xac: + case 0xac: ch = 0xc2; break; - case 0x192: + case 0x192: ch = 0xc4; break; - case 0xab: + case 0xab: ch = 0xc7; break; - case 0xbb: + case 0xbb: ch = 0xc8; break; - case 0x2026: + case 0x2026: ch = 0xc9; break; - case 0xc0: + case 0xc0: ch = 0xcb; break; - case 0xc3: + case 0xc3: ch = 0xcc; break; - case 0xd5: + case 0xd5: ch = 0xcd; break; - case 0x152: + case 0x152: ch = 0xce; break; - case 0x153: + case 0x153: ch = 0xcf; break; - case 0x2013: + case 0x2013: ch = 0xd0; break; - case 0x2014: + case 0x2014: ch = 0xd1; break; - case 0x201c: + case 0x201c: ch = 0xd2; break; - case 0x201d: + case 0x201d: ch = 0xd3; break; - case 0x2018: + case 0x2018: ch = 0xd4; break; - case 0x2019: + case 0x2019: ch = 0xd5; break; - case 0xf7: + case 0xf7: ch = 0xd6; break; - case 0xff: + case 0xff: ch = 0xd8; break; - case 0x178: + case 0x178: ch = 0xd9; break; - case 0x2044: + case 0x2044: ch = 0xda; break; - case 0xa4: + case 0xa4: ch = 0xdb; break; - case 0x2039: + case 0x2039: ch = 0xdc; break; - case 0x203a: + case 0x203a: ch = 0xdd; break; - case 0xfb01: + case 0xfb01: ch = 0xde; break; - case 0xfb02: + case 0xfb02: ch = 0xdf; break; - case 0x2021: + case 0x2021: ch = 0xe0; break; - case 0xb7: + case 0xb7: ch = 0xe1; break; - case 0x201a: + case 0x201a: ch = 0xe2; break; - case 0x201e: + case 0x201e: ch = 0xe3; break; - case 0x2030: + case 0x2030: ch = 0xe4; break; - case 0xc2: + case 0xc2: ch = 0xe5; break; - case 0xca: + case 0xca: ch = 0xe6; break; - case 0xc1: + case 0xc1: ch = 0xe7; break; - case 0xcb: + case 0xcb: ch = 0xe8; break; - case 0xc8: + case 0xc8: ch = 0xe9; break; - case 0xcd: + case 0xcd: ch = 0xea; break; - case 0xce: + case 0xce: ch = 0xeb; break; - case 0xcf: + case 0xcf: ch = 0xec; break; - case 0xcc: + case 0xcc: ch = 0xed; break; - case 0xd3: + case 0xd3: ch = 0xee; break; - case 0xd4: + case 0xd4: ch = 0xef; break; - case 0xd2: + case 0xd2: ch = 0xf1; break; - case 0xda: + case 0xda: ch = 0xf2; break; - case 0xdb: + case 0xdb: ch = 0xf3; break; - case 0xd9: + case 0xd9: ch = 0xf4; break; - case 0x131: + case 0x131: ch = 0xf5; break; - case 0x2c6: + case 0x2c6: ch = 0xf6; break; - case 0x303: + case 0x303: ch = 0xf7; break; - case 0x304: + case 0x304: ch = 0xf8; break; - case 0x306: + case 0x306: ch = 0xf9; break; - case 0x307: + case 0x307: ch = 0xfa; break; - case 0x30a: + case 0x30a: ch = 0xfb; break; - case 0x327: + case 0x327: ch = 0xfc; break; - case 0x30b: + case 0x30b: ch = 0xfd; break; - case 0x328: + case 0x328: ch = 0xfe; break; - case 0x2c7: + case 0x2c7: ch = 0xff; break; - default: + default: break; } return ch; @@ -2063,171 +1897,165 @@ encode_pdfdoc(unsigned long codepoint) // Use this ugly switch statement to avoid a static, which is not // thread-safe. unsigned char ch = '\0'; - switch (codepoint) - { - case 0x02d8: + switch (codepoint) { + case 0x02d8: ch = 0x18; break; - case 0x02c7: + case 0x02c7: ch = 0x19; break; - case 0x02c6: + case 0x02c6: ch = 0x1a; break; - case 0x02d9: + case 0x02d9: ch = 0x1b; break; - case 0x02dd: + case 0x02dd: ch = 0x1c; break; - case 0x02db: + case 0x02db: ch = 0x1d; break; - case 0x02da: + case 0x02da: ch = 0x1e; break; - case 0x02dc: + case 0x02dc: ch = 0x1f; break; - case 0x2022: + case 0x2022: ch = 0x80; break; - case 0x2020: + case 0x2020: ch = 0x81; break; - case 0x2021: + case 0x2021: ch = 0x82; break; - case 0x2026: + case 0x2026: ch = 0x83; break; - case 0x2014: + case 0x2014: ch = 0x84; break; - case 0x2013: + case 0x2013: ch = 0x85; break; - case 0x0192: + case 0x0192: ch = 0x86; break; - case 0x2044: + case 0x2044: ch = 0x87; break; - case 0x2039: + case 0x2039: ch = 0x88; break; - case 0x203a: + case 0x203a: ch = 0x89; break; - case 0x2212: + case 0x2212: ch = 0x8a; break; - case 0x2030: + case 0x2030: ch = 0x8b; break; - case 0x201e: + case 0x201e: ch = 0x8c; break; - case 0x201c: + case 0x201c: ch = 0x8d; break; - case 0x201d: + case 0x201d: ch = 0x8e; break; - case 0x2018: + case 0x2018: ch = 0x8f; break; - case 0x2019: + case 0x2019: ch = 0x90; break; - case 0x201a: + case 0x201a: ch = 0x91; break; - case 0x2122: + case 0x2122: ch = 0x92; break; - case 0xfb01: + case 0xfb01: ch = 0x93; break; - case 0xfb02: + case 0xfb02: ch = 0x94; break; - case 0x0141: + case 0x0141: ch = 0x95; break; - case 0x0152: + case 0x0152: ch = 0x96; break; - case 0x0160: + case 0x0160: ch = 0x97; break; - case 0x0178: + case 0x0178: ch = 0x98; break; - case 0x017d: + case 0x017d: ch = 0x99; break; - case 0x0131: + case 0x0131: ch = 0x9a; break; - case 0x0142: + case 0x0142: ch = 0x9b; break; - case 0x0153: + case 0x0153: ch = 0x9c; break; - case 0x0161: + case 0x0161: ch = 0x9d; break; - case 0x017e: + case 0x017e: ch = 0x9e; break; - case 0xfffd: + case 0xfffd: ch = 0x9f; break; - case 0x20ac: + case 0x20ac: ch = 0xa0; break; - default: + default: break; } return ch; } -unsigned long get_next_utf8_codepoint( - std::string const& utf8_val, size_t& pos, bool& error) +unsigned long +get_next_utf8_codepoint(std::string const& utf8_val, size_t& pos, bool& error) { size_t len = utf8_val.length(); unsigned char ch = static_cast(utf8_val.at(pos)); error = false; - if (ch < 128) - { + if (ch < 128) { return static_cast(ch); } size_t bytes_needed = 0; unsigned bit_check = 0x40; unsigned char to_clear = 0x80; - while (ch & bit_check) - { + while (ch & bit_check) { ++bytes_needed; to_clear = static_cast(to_clear | bit_check); bit_check >>= 1; } if (((bytes_needed > 5) || (bytes_needed < 1)) || - ((pos + bytes_needed) >= len)) - { + ((pos + bytes_needed) >= len)) { error = true; return 0xfffd; } unsigned long codepoint = static_cast(ch & ~to_clear); - while (bytes_needed > 0) - { + while (bytes_needed > 0) { --bytes_needed; ch = static_cast(utf8_val.at(++pos)); - if ((ch & 0xc0) != 0x80) - { + if ((ch & 0xc0) != 0x80) { --pos; codepoint = 0xfffd; break; @@ -2239,86 +2067,64 @@ unsigned long get_next_utf8_codepoint( } static bool -transcode_utf8(std::string const& utf8_val, std::string& result, - encoding_e encoding, char unknown) +transcode_utf8( + std::string const& utf8_val, + std::string& result, + encoding_e encoding, + char unknown) { bool okay = true; result.clear(); - if (encoding == e_utf16) - { + if (encoding == e_utf16) { result += "\xfe\xff"; } size_t len = utf8_val.length(); - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { bool error = false; unsigned long codepoint = get_next_utf8_codepoint(utf8_val, i, error); - if (error) - { + if (error) { okay = false; - if (encoding == e_utf16) - { + if (encoding == e_utf16) { result += "\xff\xfd"; - } - else - { + } else { result.append(1, unknown); } - } - else if (codepoint < 128) - { + } else if (codepoint < 128) { char ch = static_cast(codepoint); - if (encoding == e_utf16) - { + if (encoding == e_utf16) { result += QUtil::toUTF16(QIntC::to_ulong(ch)); - } - else if ((encoding == e_pdfdoc) && - (((ch >= 0x18) && (ch <= 0x1f)) || (ch == 127))) - { + } else if ( + (encoding == e_pdfdoc) && + (((ch >= 0x18) && (ch <= 0x1f)) || (ch == 127))) { // PDFDocEncoding maps some low characters to Unicode, // so if we encounter those invalid UTF-8 code points, // map them to unknown so reversing the mapping // doesn't change them into other characters. okay = false; result.append(1, unknown); - } - else - { + } else { result.append(1, ch); } - } - else if (encoding == e_utf16) - { + } else if (encoding == e_utf16) { result += QUtil::toUTF16(codepoint); - } - else if ((codepoint == 0xad) && (encoding == e_pdfdoc)) - { + } else if ((codepoint == 0xad) && (encoding == e_pdfdoc)) { // PDFDocEncoding omits 0x00ad (soft hyphen). okay = false; result.append(1, unknown); - } - else if ((codepoint > 160) && (codepoint < 256) && - ((encoding == e_winansi) || (encoding == e_pdfdoc))) - { + } else if ( + (codepoint > 160) && (codepoint < 256) && + ((encoding == e_winansi) || (encoding == e_pdfdoc))) { result.append(1, static_cast(codepoint & 0xff)); - } - else - { + } else { unsigned char ch = '\0'; - if (encoding == e_winansi) - { + if (encoding == e_winansi) { ch = encode_winansi(codepoint); - } - else if (encoding == e_macroman) - { + } else if (encoding == e_macroman) { ch = encode_macroman(codepoint); - } - else if (encoding == e_pdfdoc) - { + } else if (encoding == e_pdfdoc) { ch = encode_pdfdoc(codepoint); } - if (ch == '\0') - { + if (ch == '\0') { okay = false; ch = static_cast(unknown); } @@ -2329,8 +2135,7 @@ transcode_utf8(std::string const& utf8_val, std::string& result, } static std::string -transcode_utf8(std::string const& utf8_val, encoding_e encoding, - char unknown) +transcode_utf8(std::string const& utf8_val, encoding_e encoding, char unknown) { std::string result; transcode_utf8(utf8_val, result, encoding, unknown); @@ -2368,29 +2173,29 @@ QUtil::utf8_to_pdf_doc(std::string const& utf8, char unknown_char) } bool -QUtil::utf8_to_ascii(std::string const& utf8, std::string& ascii, - char unknown_char) +QUtil::utf8_to_ascii( + std::string const& utf8, std::string& ascii, char unknown_char) { return transcode_utf8(utf8, ascii, e_ascii, unknown_char); } bool -QUtil::utf8_to_win_ansi(std::string const& utf8, std::string& win, - char unknown_char) +QUtil::utf8_to_win_ansi( + std::string const& utf8, std::string& win, char unknown_char) { return transcode_utf8(utf8, win, e_winansi, unknown_char); } bool -QUtil::utf8_to_mac_roman(std::string const& utf8, std::string& mac, - char unknown_char) +QUtil::utf8_to_mac_roman( + std::string const& utf8, std::string& mac, char unknown_char) { return transcode_utf8(utf8, mac, e_macroman, unknown_char); } bool -QUtil::utf8_to_pdf_doc(std::string const& utf8, std::string& pdfdoc, - char unknown_char) +QUtil::utf8_to_pdf_doc( + std::string const& utf8, std::string& pdfdoc, char unknown_char) { return transcode_utf8(utf8, pdfdoc, e_pdfdoc, unknown_char); } @@ -2398,9 +2203,10 @@ QUtil::utf8_to_pdf_doc(std::string const& utf8, std::string& pdfdoc, bool QUtil::is_utf16(std::string const& val) { - return ((val.length() >= 2) && - (((val.at(0) == '\xfe') && (val.at(1) == '\xff')) || - ((val.at(0) == '\xff') && (val.at(1) == '\xfe')))); + return ( + (val.length() >= 2) && + (((val.at(0) == '\xfe') && (val.at(1) == '\xff')) || + ((val.at(0) == '\xff') && (val.at(1) == '\xfe')))); } std::string @@ -2415,45 +2221,35 @@ QUtil::utf16_to_utf8(std::string const& val) size_t len = val.length(); size_t start = 0; bool is_le = false; - if (is_utf16(val)) - { - if (static_cast(val.at(0)) == 0xff) - { + if (is_utf16(val)) { + if (static_cast(val.at(0)) == 0xff) { is_le = true; } start += 2; } // If the string has an odd number of bytes, the last byte is // ignored. - for (size_t i = start; i + 1 < len; i += 2) - { + for (size_t i = start; i + 1 < len; i += 2) { // Convert from UTF16-BE. If we get a malformed // codepoint, this code will generate incorrect output // without giving a warning. Specifically, a high // codepoint not followed by a low codepoint will be // discarded, and a low codepoint not preceded by a high // codepoint will just get its low 10 bits output. - auto msb = is_le ? i+1 : i; - auto lsb = is_le ? i : i+1; - unsigned short bits = - QIntC::to_ushort( - (static_cast(val.at(msb)) << 8) + - static_cast(val.at(lsb))); - if ((bits & 0xFC00) == 0xD800) - { + auto msb = is_le ? i + 1 : i; + auto lsb = is_le ? i : i + 1; + unsigned short bits = QIntC::to_ushort( + (static_cast(val.at(msb)) << 8) + + static_cast(val.at(lsb))); + if ((bits & 0xFC00) == 0xD800) { codepoint = 0x10000U + ((bits & 0x3FFU) << 10U); continue; - } - else if ((bits & 0xFC00) == 0xDC00) - { - if (codepoint != 0) - { + } else if ((bits & 0xFC00) == 0xDC00) { + if (codepoint != 0) { QTC::TC("qpdf", "QUtil non-trivial UTF-16"); } codepoint += bits & 0x3FF; - } - else - { + } else { codepoint = bits; } @@ -2468,12 +2264,10 @@ QUtil::win_ansi_to_utf8(std::string const& val) { std::string result; size_t len = val.length(); - for (unsigned int i = 0; i < len; ++i) - { + for (unsigned int i = 0; i < len; ++i) { unsigned char ch = static_cast(val.at(i)); unsigned short ch_short = ch; - if ((ch >= 128) && (ch <= 160)) - { + if ((ch >= 128) && (ch <= 160)) { ch_short = win_ansi_to_unicode[ch - 128]; } result += QUtil::toUTF8(ch_short); @@ -2486,12 +2280,10 @@ QUtil::mac_roman_to_utf8(std::string const& val) { std::string result; size_t len = val.length(); - for (unsigned int i = 0; i < len; ++i) - { + for (unsigned int i = 0; i < len; ++i) { unsigned char ch = static_cast(val.at(i)); unsigned short ch_short = ch; - if (ch >= 128) - { + if (ch >= 128) { ch_short = mac_roman_to_unicode[ch - 128]; } result += QUtil::toUTF8(ch_short); @@ -2504,20 +2296,14 @@ QUtil::pdf_doc_to_utf8(std::string const& val) { std::string result; size_t len = val.length(); - for (unsigned int i = 0; i < len; ++i) - { + for (unsigned int i = 0; i < len; ++i) { unsigned char ch = static_cast(val.at(i)); unsigned short ch_short = ch; - if ((ch >= 127) && (ch <= 160)) - { + if ((ch >= 127) && (ch <= 160)) { ch_short = pdf_doc_to_unicode[ch - 127]; - } - else if ((ch >= 24) && (ch <= 31)) - { + } else if ((ch >= 24) && (ch <= 31)) { ch_short = pdf_doc_low_to_unicode[ch - 24]; - } - else if (ch == 173) - { + } else if (ch == 173) { ch_short = 0xfffd; } result += QUtil::toUTF8(ch_short); @@ -2526,35 +2312,31 @@ QUtil::pdf_doc_to_utf8(std::string const& val) } void -QUtil::analyze_encoding(std::string const& val, - bool& has_8bit_chars, - bool& is_valid_utf8, - bool& is_utf16) +QUtil::analyze_encoding( + std::string const& val, + bool& has_8bit_chars, + bool& is_valid_utf8, + bool& is_utf16) { has_8bit_chars = is_utf16 = is_valid_utf8 = false; - if (QUtil::is_utf16(val)) - { + if (QUtil::is_utf16(val)) { has_8bit_chars = true; is_utf16 = true; return; } size_t len = val.length(); bool any_errors = false; - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { bool error = false; unsigned long codepoint = get_next_utf8_codepoint(val, i, error); - if (error) - { + if (error) { any_errors = true; } - if (codepoint >= 128) - { + if (codepoint >= 128) { has_8bit_chars = true; } } - if (has_8bit_chars && (! any_errors)) - { + if (has_8bit_chars && (!any_errors)) { is_valid_utf8 = true; } } @@ -2569,37 +2351,29 @@ QUtil::possible_repaired_encodings(std::string supplied) bool is_valid_utf8 = false; bool is_utf16 = false; analyze_encoding(supplied, has_8bit_chars, is_valid_utf8, is_utf16); - if (! has_8bit_chars) - { + if (!has_8bit_chars) { return result; } - if (is_utf16) - { + if (is_utf16) { // Convert to UTF-8 and pretend we got a UTF-8 string. is_utf16 = false; is_valid_utf8 = true; supplied = utf16_to_utf8(supplied); } std::string output; - if (is_valid_utf8) - { + if (is_valid_utf8) { // Maybe we were given UTF-8 but wanted one of the single-byte // encodings. - if (utf8_to_pdf_doc(supplied, output)) - { + if (utf8_to_pdf_doc(supplied, output)) { result.push_back(output); } - if (utf8_to_win_ansi(supplied, output)) - { + if (utf8_to_win_ansi(supplied, output)) { result.push_back(output); } - if (utf8_to_mac_roman(supplied, output)) - { + if (utf8_to_mac_roman(supplied, output)) { result.push_back(output); } - } - else - { + } else { // Maybe we were given one of the single-byte encodings but // wanted UTF-8. std::string from_pdf_doc(pdf_doc_to_utf8(supplied)); @@ -2611,28 +2385,22 @@ QUtil::possible_repaired_encodings(std::string supplied) // Maybe we were given one of the other single-byte encodings // but wanted one of the other ones. - if (utf8_to_win_ansi(from_pdf_doc, output)) - { + if (utf8_to_win_ansi(from_pdf_doc, output)) { result.push_back(output); } - if (utf8_to_mac_roman(from_pdf_doc, output)) - { + if (utf8_to_mac_roman(from_pdf_doc, output)) { result.push_back(output); } - if (utf8_to_pdf_doc(from_win_ansi, output)) - { + if (utf8_to_pdf_doc(from_win_ansi, output)) { result.push_back(output); } - if (utf8_to_mac_roman(from_win_ansi, output)) - { + if (utf8_to_mac_roman(from_win_ansi, output)) { result.push_back(output); } - if (utf8_to_pdf_doc(from_mac_roman, output)) - { + if (utf8_to_pdf_doc(from_mac_roman, output)) { result.push_back(output); } - if (utf8_to_win_ansi(from_mac_roman, output)) - { + if (utf8_to_win_ansi(from_mac_roman, output)) { result.push_back(output); } } @@ -2640,10 +2408,9 @@ QUtil::possible_repaired_encodings(std::string supplied) std::vector t; std::set seen; for (std::vector::iterator iter = result.begin(); - iter != result.end(); ++iter) - { - if (! seen.count(*iter)) - { + iter != result.end(); + ++iter) { + if (!seen.count(*iter)) { seen.insert(*iter); t.push_back(*iter); } @@ -2653,8 +2420,11 @@ QUtil::possible_repaired_encodings(std::string supplied) #ifndef QPDF_NO_WCHAR_T static int -call_main_from_wmain(bool, int argc, wchar_t const* const argv[], - std::function realmain) +call_main_from_wmain( + bool, + int argc, + wchar_t const* const argv[], + std::function realmain) { // argv contains UTF-16-encoded strings with a 16-bit wchar_t. // Convert this to UTF-8-encoded strings for compatibility with @@ -2662,24 +2432,20 @@ call_main_from_wmain(bool, int argc, wchar_t const* const argv[], // arguments are UTF-8. std::vector> utf8_argv; - for (int i = 0; i < argc; ++i) - { + for (int i = 0; i < argc; ++i) { std::string utf16; - for (size_t j = 0; j < std::wcslen(argv[i]); ++j) - { + for (size_t j = 0; j < std::wcslen(argv[i]); ++j) { unsigned short codepoint = static_cast(argv[i][j]); - utf16.append(1, static_cast( - QIntC::to_uchar(codepoint >> 8))); - utf16.append(1, static_cast( - QIntC::to_uchar(codepoint & 0xff))); + utf16.append(1, static_cast(QIntC::to_uchar(codepoint >> 8))); + utf16.append( + 1, static_cast(QIntC::to_uchar(codepoint & 0xff))); } std::string utf8 = QUtil::utf16_to_utf8(utf16); utf8_argv.push_back(QUtil::make_unique_cstr(utf8)); } - auto utf8_argv_sp = std::make_unique(1+utf8_argv.size()); + auto utf8_argv_sp = std::make_unique(1 + utf8_argv.size()); char** new_argv = utf8_argv_sp.get(); - for (size_t i = 0; i < utf8_argv.size(); ++i) - { + for (size_t i = 0; i < utf8_argv.size(); ++i) { new_argv[i] = utf8_argv.at(i).get(); } argc = QIntC::to_int(utf8_argv.size()); @@ -2688,15 +2454,16 @@ call_main_from_wmain(bool, int argc, wchar_t const* const argv[], } int -QUtil::call_main_from_wmain(int argc, wchar_t* argv[], - std::function realmain) +QUtil::call_main_from_wmain( + int argc, wchar_t* argv[], std::function realmain) { return ::call_main_from_wmain(true, argc, argv, realmain); } int QUtil::call_main_from_wmain( - int argc, wchar_t const* const argv[], + int argc, + wchar_t const* const argv[], std::function realmain) { return ::call_main_from_wmain( diff --git a/libqpdf/RC4.cc b/libqpdf/RC4.cc index 64c08091..4859c878 100644 --- a/libqpdf/RC4.cc +++ b/libqpdf/RC4.cc @@ -11,7 +11,7 @@ RC4::RC4(unsigned char const* key_data, int key_len) : } void -RC4::process(unsigned char *in_data, size_t len, unsigned char* out_data) +RC4::process(unsigned char* in_data, size_t len, unsigned char* out_data) { this->crypto->RC4_process(in_data, len, out_data); } diff --git a/libqpdf/RC4_native.cc b/libqpdf/RC4_native.cc index bb0b9013..e2d36554 100644 --- a/libqpdf/RC4_native.cc +++ b/libqpdf/RC4_native.cc @@ -4,7 +4,8 @@ #include -static void swap_byte(unsigned char &a, unsigned char &b) +static void +swap_byte(unsigned char& a, unsigned char& b) { unsigned char t; @@ -15,14 +16,12 @@ static void swap_byte(unsigned char &a, unsigned char &b) RC4_native::RC4_native(unsigned char const* key_data, int key_len) { - if (key_len == -1) - { - key_len = QIntC::to_int( - strlen(reinterpret_cast(key_data))); + if (key_len == -1) { + key_len = + QIntC::to_int(strlen(reinterpret_cast(key_data))); } - for (int i = 0; i < 256; ++i) - { + for (int i = 0; i < 256; ++i) { key.state[i] = static_cast(i); } key.x = 0; @@ -30,8 +29,7 @@ RC4_native::RC4_native(unsigned char const* key_data, int key_len) int i1 = 0; int i2 = 0; - for (int i = 0; i < 256; ++i) - { + for (int i = 0; i < 256; ++i) { i2 = (key_data[i1] + key.state[i] + i2) % 256; swap_byte(key.state[i], key.state[i2]); i1 = (i1 + 1) % key_len; @@ -39,16 +37,14 @@ RC4_native::RC4_native(unsigned char const* key_data, int key_len) } void -RC4_native::process(unsigned char *in_data, size_t len, unsigned char* out_data) +RC4_native::process(unsigned char* in_data, size_t len, unsigned char* out_data) { - if (out_data == 0) - { + if (out_data == 0) { // Convert in place out_data = in_data; } - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { key.x = static_cast((key.x + 1) % 256); key.y = static_cast((key.state[key.x] + key.y) % 256); swap_byte(key.state[key.x], key.state[key.y]); diff --git a/libqpdf/ResourceFinder.cc b/libqpdf/ResourceFinder.cc index 8d430be5..798fe67f 100644 --- a/libqpdf/ResourceFinder.cc +++ b/libqpdf/ResourceFinder.cc @@ -8,8 +8,7 @@ ResourceFinder::ResourceFinder() : void ResourceFinder::handleObject(QPDFObjectHandle obj, size_t offset, size_t) { - if (obj.isOperator() && (! this->last_name.empty())) - { + if (obj.isOperator() && (!this->last_name.empty())) { static std::map op_to_rtype = { {"CS", "/ColorSpace"}, {"cs", "/ColorSpace"}, @@ -25,19 +24,15 @@ ResourceFinder::handleObject(QPDFObjectHandle obj, size_t offset, size_t) std::string op = obj.getOperatorValue(); std::string resource_type; auto iter = op_to_rtype.find(op); - if (iter != op_to_rtype.end()) - { + if (iter != op_to_rtype.end()) { resource_type = iter->second; } - if (! resource_type.empty()) - { + if (!resource_type.empty()) { this->names.insert(this->last_name); - this->names_by_resource_type[ - resource_type][this->last_name].insert(this->last_name_offset); + this->names_by_resource_type[resource_type][this->last_name].insert( + this->last_name_offset); } - } - else if (obj.isName()) - { + } else if (obj.isName()) { this->last_name = obj.getName(); this->last_name_offset = offset; } diff --git a/libqpdf/SF_FlateLzwDecode.cc b/libqpdf/SF_FlateLzwDecode.cc index 196cbded..f753ffd8 100644 --- a/libqpdf/SF_FlateLzwDecode.cc +++ b/libqpdf/SF_FlateLzwDecode.cc @@ -1,11 +1,11 @@ #include -#include -#include #include #include -#include +#include +#include #include +#include SF_FlateLzwDecode::SF_FlateLzwDecode(bool lzw) : lzw(lzw), @@ -21,105 +21,80 @@ SF_FlateLzwDecode::SF_FlateLzwDecode(bool lzw) : bool SF_FlateLzwDecode::setDecodeParms(QPDFObjectHandle decode_parms) { - if (decode_parms.isNull()) - { + if (decode_parms.isNull()) { return true; } bool filterable = true; std::set keys = decode_parms.getKeys(); - for (auto const& key: keys) - { + for (auto const& key : keys) { QPDFObjectHandle value = decode_parms.getKey(key); - if (key == "/Predictor") - { - if (value.isInteger()) - { + if (key == "/Predictor") { + if (value.isInteger()) { this->predictor = value.getIntValueAsInt(); - if (! ((this->predictor == 1) || (this->predictor == 2) || - ((this->predictor >= 10) && (this->predictor <= 15)))) - { + if (!((this->predictor == 1) || (this->predictor == 2) || + ((this->predictor >= 10) && (this->predictor <= 15)))) { filterable = false; } - } - else - { + } else { filterable = false; } - } - else if ((key == "/Columns") || - (key == "/Colors") || - (key == "/BitsPerComponent")) - { - if (value.isInteger()) - { + } else if ( + (key == "/Columns") || (key == "/Colors") || + (key == "/BitsPerComponent")) { + if (value.isInteger()) { int val = value.getIntValueAsInt(); - if (key == "/Columns") - { + if (key == "/Columns") { this->columns = val; - } - else if (key == "/Colors") - { + } else if (key == "/Colors") { this->colors = val; - } - else if (key == "/BitsPerComponent") - { + } else if (key == "/BitsPerComponent") { this->bits_per_component = val; } - } - else - { + } else { filterable = false; } - } - else if (lzw && (key == "/EarlyChange")) - { - if (value.isInteger()) - { + } else if (lzw && (key == "/EarlyChange")) { + if (value.isInteger()) { int earlychange = value.getIntValueAsInt(); this->early_code_change = (earlychange == 1); - if (! ((earlychange == 0) || (earlychange == 1))) - { + if (!((earlychange == 0) || (earlychange == 1))) { filterable = false; } - } - else - { + } else { filterable = false; } } } - if ((this->predictor > 1) && (this->columns == 0)) - { + if ((this->predictor > 1) && (this->columns == 0)) { filterable = false; } return filterable; } - - Pipeline* SF_FlateLzwDecode::getDecodePipeline(Pipeline* next) { std::shared_ptr pipeline; - if ((this->predictor >= 10) && (this->predictor <= 15)) - { + if ((this->predictor >= 10) && (this->predictor <= 15)) { QTC::TC("qpdf", "SF_FlateLzwDecode PNG filter"); pipeline = std::make_shared( - "png decode", next, Pl_PNGFilter::a_decode, + "png decode", + next, + Pl_PNGFilter::a_decode, QIntC::to_uint(this->columns), QIntC::to_uint(this->colors), QIntC::to_uint(this->bits_per_component)); this->pipelines.push_back(pipeline); next = pipeline.get(); - } - else if (this->predictor == 2) - { + } else if (this->predictor == 2) { QTC::TC("qpdf", "SF_FlateLzwDecode TIFF predictor"); pipeline = std::make_shared( - "tiff decode", next, Pl_TIFFPredictor::a_decode, + "tiff decode", + next, + Pl_TIFFPredictor::a_decode, QIntC::to_uint(this->columns), QIntC::to_uint(this->colors), QIntC::to_uint(this->bits_per_component)); @@ -127,13 +102,10 @@ SF_FlateLzwDecode::getDecodePipeline(Pipeline* next) next = pipeline.get(); } - if (lzw) - { + if (lzw) { pipeline = std::make_shared( "lzw decode", next, early_code_change); - } - else - { + } else { pipeline = std::make_shared( "stream inflate", next, Pl_Flate::a_inflate); } diff --git a/libqpdf/SHA2_native.cc b/libqpdf/SHA2_native.cc index c40b48b4..949d5634 100644 --- a/libqpdf/SHA2_native.cc +++ b/libqpdf/SHA2_native.cc @@ -1,26 +1,24 @@ #include -#include -#include #include #include - +#include +#include SHA2_native::SHA2_native(int bits) : bits(bits) { - switch (bits) - { - case 256: + switch (bits) { + case 256: sph_sha256_init(&this->ctx256); break; - case 384: + case 384: sph_sha384_init(&this->ctx384); break; - case 512: + case 512: sph_sha512_init(&this->ctx512); break; - default: + default: badBits(); break; } @@ -35,18 +33,17 @@ SHA2_native::badBits() void SHA2_native::update(unsigned char const* buf, size_t len) { - switch (bits) - { - case 256: + switch (bits) { + case 256: sph_sha256(&this->ctx256, buf, len); break; - case 384: + case 384: sph_sha384(&this->ctx384, buf, len); break; - case 512: + case 512: sph_sha512(&this->ctx512, buf, len); break; - default: + default: badBits(); break; } @@ -55,18 +52,17 @@ SHA2_native::update(unsigned char const* buf, size_t len) void SHA2_native::finalize() { - switch (bits) - { - case 256: + switch (bits) { + case 256: sph_sha256_close(&this->ctx256, sha256sum); break; - case 384: + case 384: sph_sha384_close(&this->ctx384, sha384sum); break; - case 512: + case 512: sph_sha512_close(&this->ctx512, sha512sum); break; - default: + default: badBits(); break; } @@ -76,21 +72,20 @@ std::string SHA2_native::getRawDigest() { std::string result; - switch (bits) - { - case 256: - result = std::string(reinterpret_cast(this->sha256sum), - sizeof(this->sha256sum)); + switch (bits) { + case 256: + result = std::string( + reinterpret_cast(this->sha256sum), sizeof(this->sha256sum)); break; - case 384: - result = std::string(reinterpret_cast(this->sha384sum), - sizeof(this->sha384sum)); + case 384: + result = std::string( + reinterpret_cast(this->sha384sum), sizeof(this->sha384sum)); break; - case 512: - result = std::string(reinterpret_cast(this->sha512sum), - sizeof(this->sha512sum)); + case 512: + result = std::string( + reinterpret_cast(this->sha512sum), sizeof(this->sha512sum)); break; - default: + default: badBits(); break; } diff --git a/libqpdf/SecureRandomDataProvider.cc b/libqpdf/SecureRandomDataProvider.cc index 705046c6..17af08ba 100644 --- a/libqpdf/SecureRandomDataProvider.cc +++ b/libqpdf/SecureRandomDataProvider.cc @@ -1,12 +1,12 @@ #include -#include #include +#include #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN -# include # include # include +# include # ifndef SKIP_OS_SECURE_RANDOM # include # endif @@ -25,7 +25,8 @@ SecureRandomDataProvider::~SecureRandomDataProvider() void SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) { - throw std::logic_error("SecureRandomDataProvider::provideRandomData called when support was not compiled in"); + throw std::logic_error("SecureRandomDataProvider::provideRandomData called " + "when support was not compiled in"); } RandomDataProvider* @@ -36,22 +37,17 @@ SecureRandomDataProvider::getInstance() #else -#ifdef _WIN32 +# ifdef _WIN32 class WindowsCryptProvider { public: WindowsCryptProvider() { - if (!CryptAcquireContextW(&crypt_prov, - NULL, - NULL, - PROV_RSA_FULL, - CRYPT_VERIFYCONTEXT)) - { - throw std::runtime_error( - "unable to acquire crypt context: " + - getErrorMessage()); + if (!CryptAcquireContextW( + &crypt_prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + throw std::runtime_error( + "unable to acquire crypt context: " + getErrorMessage()); } } ~WindowsCryptProvider() @@ -63,40 +59,45 @@ class WindowsCryptProvider HCRYPTPROV crypt_prov; private: - std::string getErrorMessage() + std::string + getErrorMessage() { DWORD errorMessageID = ::GetLastError(); LPSTR messageBuffer = nullptr; size_t size = FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - reinterpret_cast(&messageBuffer), 0, NULL); + reinterpret_cast(&messageBuffer), + 0, + NULL); std::string message(messageBuffer, size); LocalFree(messageBuffer); - return ("error number " + - QUtil::int_to_string_base(errorMessageID, 16) + - ": " + message); + return ( + "error number " + QUtil::int_to_string_base(errorMessageID, 16) + + ": " + message); } }; -#endif +# endif void SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) { -#if defined(_WIN32) +# if defined(_WIN32) // Optimization: make the WindowsCryptProvider static as long as // it can be done in a thread-safe fashion. WindowsCryptProvider c; - if (! CryptGenRandom(c.crypt_prov, static_cast(len), - reinterpret_cast(data))) - { + if (!CryptGenRandom( + c.crypt_prov, + static_cast(len), + reinterpret_cast(data))) { throw std::runtime_error("unable to generate secure random data"); } -#elif defined(RANDOM_DEVICE) +# elif defined(RANDOM_DEVICE) // Optimization: wrap the file open and close in a class so that // the file is closed in a destructor, then make this static to @@ -105,19 +106,18 @@ SecureRandomDataProvider::provideRandomData(unsigned char* data, size_t len) FILE* f = QUtil::safe_fopen(RANDOM_DEVICE, "rb"); size_t fr = fread(data, 1, len, f); fclose(f); - if (fr != len) - { + if (fr != len) { throw std::runtime_error( - "unable to read " + - QUtil::uint_to_string(len) + - " bytes from " + std::string(RANDOM_DEVICE)); + "unable to read " + QUtil::uint_to_string(len) + " bytes from " + + std::string(RANDOM_DEVICE)); } -#else +# else -# error "Don't know how to generate secure random numbers on this platform. See random number generation in the top-level README.md" +# error \ + "Don't know how to generate secure random numbers on this platform. See random number generation in the top-level README.md" -#endif +# endif } RandomDataProvider* diff --git a/libqpdf/SparseOHArray.cc b/libqpdf/SparseOHArray.cc index 1bcf8309..738ab44d 100644 --- a/libqpdf/SparseOHArray.cc +++ b/libqpdf/SparseOHArray.cc @@ -16,8 +16,7 @@ SparseOHArray::size() const void SparseOHArray::append(QPDFObjectHandle oh) { - if (! oh.isDirectNull()) - { + if (!oh.isDirectNull()) { this->elements[this->n_elements] = oh; } ++this->n_elements; @@ -26,18 +25,14 @@ SparseOHArray::append(QPDFObjectHandle oh) QPDFObjectHandle SparseOHArray::at(size_t idx) const { - if (idx >= this->n_elements) - { + if (idx >= this->n_elements) { throw std::logic_error( "INTERNAL ERROR: bounds error accessing SparseOHArray element"); } auto const& iter = this->elements.find(idx); - if (iter == this->elements.end()) - { + if (iter == this->elements.end()) { return QPDFObjectHandle::newNull(); - } - else - { + } else { return (*iter).second; } } @@ -45,11 +40,9 @@ SparseOHArray::at(size_t idx) const void SparseOHArray::remove_last() { - if (this->n_elements == 0) - { - throw std::logic_error( - "INTERNAL ERROR: attempt to remove" - " last item from empty SparseOHArray"); + if (this->n_elements == 0) { + throw std::logic_error("INTERNAL ERROR: attempt to remove" + " last item from empty SparseOHArray"); } --this->n_elements; this->elements.erase(this->n_elements); @@ -58,8 +51,7 @@ SparseOHArray::remove_last() void SparseOHArray::releaseResolved() { - for (auto& iter: this->elements) - { + for (auto& iter : this->elements) { QPDFObjectHandle::ReleaseResolver::releaseResolved(iter.second); } } @@ -67,16 +59,12 @@ SparseOHArray::releaseResolved() void SparseOHArray::setAt(size_t idx, QPDFObjectHandle oh) { - if (idx >= this->n_elements) - { + if (idx >= this->n_elements) { throw std::logic_error("bounds error setting item in SparseOHArray"); } - if (oh.isDirectNull()) - { + if (oh.isDirectNull()) { this->elements.erase(idx); - } - else - { + } else { this->elements[idx] = oh; } } @@ -84,19 +72,14 @@ SparseOHArray::setAt(size_t idx, QPDFObjectHandle oh) void SparseOHArray::erase(size_t idx) { - if (idx >= this->n_elements) - { + if (idx >= this->n_elements) { throw std::logic_error("bounds error erasing item from SparseOHArray"); } decltype(this->elements) dest; - for (auto const& iter: this->elements) - { - if (iter.first < idx) - { + for (auto const& iter : this->elements) { + if (iter.first < idx) { dest.insert(iter); - } - else if (iter.first > idx) - { + } else if (iter.first > idx) { dest[iter.first - 1] = iter.second; } } @@ -107,26 +90,17 @@ SparseOHArray::erase(size_t idx) void SparseOHArray::insert(size_t idx, QPDFObjectHandle oh) { - if (idx > this->n_elements) - { + if (idx > this->n_elements) { throw std::logic_error("bounds error inserting item to SparseOHArray"); - } - else if (idx == this->n_elements) - { + } else if (idx == this->n_elements) { // Allow inserting to the last position append(oh); - } - else - { + } else { decltype(this->elements) dest; - for (auto const& iter: this->elements) - { - if (iter.first < idx) - { + for (auto const& iter : this->elements) { + if (iter.first < idx) { dest.insert(iter); - } - else - { + } else { dest[iter.first + 1] = iter.second; } } diff --git a/libqpdf/qpdf-c.cc b/libqpdf/qpdf-c.cc index 01c2a7ca..c8d92a75 100644 --- a/libqpdf/qpdf-c.cc +++ b/libqpdf/qpdf-c.cc @@ -2,19 +2,19 @@ #include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include -#include -#include -#include #include #include +#include +#include +#include struct _qpdf_error { @@ -35,7 +35,7 @@ struct _qpdf_data std::string tmp_string; // Parameters for functions we call - char const* filename; // or description + char const* filename; // or description char const* buffer; unsigned long long size; char const* password; @@ -89,37 +89,46 @@ ProgressReporter::reportProgress(int progress) } // must set qpdf->filename and qpdf->password -static void call_read(qpdf_data qpdf) +static void +call_read(qpdf_data qpdf) { qpdf->qpdf->processFile(qpdf->filename, qpdf->password); } // must set qpdf->filename, qpdf->buffer, qpdf->size, and qpdf->password -static void call_read_memory(qpdf_data qpdf) +static void +call_read_memory(qpdf_data qpdf) { - qpdf->qpdf->processMemoryFile(qpdf->filename, qpdf->buffer, - QIntC::to_size(qpdf->size), qpdf->password); + qpdf->qpdf->processMemoryFile( + qpdf->filename, + qpdf->buffer, + QIntC::to_size(qpdf->size), + qpdf->password); } // must set qpdf->filename -static void call_init_write(qpdf_data qpdf) +static void +call_init_write(qpdf_data qpdf) { - qpdf->qpdf_writer = make_pointer_holder( - *(qpdf->qpdf), qpdf->filename); + qpdf->qpdf_writer = + make_pointer_holder(*(qpdf->qpdf), qpdf->filename); } -static void call_init_write_memory(qpdf_data qpdf) +static void +call_init_write_memory(qpdf_data qpdf) { qpdf->qpdf_writer = make_pointer_holder(*(qpdf->qpdf)); qpdf->qpdf_writer->setOutputMemory(); } -static void call_write(qpdf_data qpdf) +static void +call_write(qpdf_data qpdf) { qpdf->qpdf_writer->write(); } -static void call_check(qpdf_data qpdf) +static void +call_check(qpdf_data qpdf) { QPDFWriter w(*qpdf->qpdf); Pl_Discard discard; @@ -128,47 +137,41 @@ static void call_check(qpdf_data qpdf) w.write(); } -static QPDF_ERROR_CODE trap_errors( - qpdf_data qpdf, std::function fn) +static QPDF_ERROR_CODE +trap_errors(qpdf_data qpdf, std::function fn) { QPDF_ERROR_CODE status = QPDF_SUCCESS; - try - { + try { fn(qpdf); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { qpdf->error = make_pointer_holder(e); status |= QPDF_ERRORS; - } - catch (std::runtime_error& e) - { - qpdf->error = make_pointer_holder( - qpdf_e_system, "", "", 0, e.what()); + } catch (std::runtime_error& e) { + qpdf->error = + make_pointer_holder(qpdf_e_system, "", "", 0, e.what()); status |= QPDF_ERRORS; - } - catch (std::exception& e) - { - qpdf->error = make_pointer_holder( - qpdf_e_internal, "", "", 0, e.what()); + } catch (std::exception& e) { + qpdf->error = + make_pointer_holder(qpdf_e_internal, "", "", 0, e.what()); status |= QPDF_ERRORS; } - if (qpdf_more_warnings(qpdf)) - { + if (qpdf_more_warnings(qpdf)) { status |= QPDF_WARNINGS; } return status; } -char const* qpdf_get_qpdf_version() +char const* +qpdf_get_qpdf_version() { QTC::TC("qpdf", "qpdf-c called qpdf_get_qpdf_version"); // The API guarantees that this is a static value. return QPDF::QPDFVersion().c_str(); } -qpdf_data qpdf_init() +qpdf_data +qpdf_init() { QTC::TC("qpdf", "qpdf-c called qpdf_init"); qpdf_data qpdf = new _qpdf_data(); @@ -176,157 +179,154 @@ qpdf_data qpdf_init() return qpdf; } -void qpdf_cleanup(qpdf_data* qpdf) +void +qpdf_cleanup(qpdf_data* qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_cleanup"); qpdf_oh_release_all(*qpdf); - if ((*qpdf)->error.get()) - { + if ((*qpdf)->error.get()) { QTC::TC("qpdf", "qpdf-c cleanup warned about unhandled error"); std::cerr << "WARNING: application did not handle error: " - << (*qpdf)->error->what() << std::endl; - + << (*qpdf)->error->what() << std::endl; } delete *qpdf; *qpdf = 0; } -size_t qpdf_get_last_string_length(qpdf_data qpdf) +size_t +qpdf_get_last_string_length(qpdf_data qpdf) { return qpdf->tmp_string.length(); } -QPDF_BOOL qpdf_more_warnings(qpdf_data qpdf) +QPDF_BOOL +qpdf_more_warnings(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_more_warnings"); - if (qpdf->warnings.empty()) - { + if (qpdf->warnings.empty()) { std::vector w = qpdf->qpdf->getWarnings(); - if (! w.empty()) - { + if (!w.empty()) { qpdf->warnings.assign(w.begin(), w.end()); } } - if (qpdf->warnings.empty()) - { + if (qpdf->warnings.empty()) { return QPDF_FALSE; - } - else - { + } else { return QPDF_TRUE; } } -QPDF_BOOL qpdf_has_error(qpdf_data qpdf) +QPDF_BOOL +qpdf_has_error(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_has_error"); return (qpdf->error.get() ? QPDF_TRUE : QPDF_FALSE); } -qpdf_error qpdf_get_error(qpdf_data qpdf) +qpdf_error +qpdf_get_error(qpdf_data qpdf) { - if (qpdf->error.get()) - { + if (qpdf->error.get()) { qpdf->tmp_error.exc = qpdf->error; qpdf->error = 0; QTC::TC("qpdf", "qpdf-c qpdf_get_error returned error"); return &qpdf->tmp_error; - } - else - { + } else { return 0; } } -qpdf_error qpdf_next_warning(qpdf_data qpdf) +qpdf_error +qpdf_next_warning(qpdf_data qpdf) { - if (qpdf_more_warnings(qpdf)) - { - qpdf->tmp_error.exc = make_pointer_holder( - qpdf->warnings.front()); + if (qpdf_more_warnings(qpdf)) { + qpdf->tmp_error.exc = + make_pointer_holder(qpdf->warnings.front()); qpdf->warnings.pop_front(); QTC::TC("qpdf", "qpdf-c qpdf_next_warning returned warning"); return &qpdf->tmp_error; - } - else - { + } else { return 0; } } -char const* qpdf_get_error_full_text(qpdf_data qpdf, qpdf_error e) +char const* +qpdf_get_error_full_text(qpdf_data qpdf, qpdf_error e) { - if (e == 0) - { + if (e == 0) { return ""; } return e->exc->what(); } -enum qpdf_error_code_e qpdf_get_error_code(qpdf_data qpdf, qpdf_error e) +enum qpdf_error_code_e +qpdf_get_error_code(qpdf_data qpdf, qpdf_error e) { - if (e == 0) - { + if (e == 0) { return qpdf_e_success; } return e->exc->getErrorCode(); } -char const* qpdf_get_error_filename(qpdf_data qpdf, qpdf_error e) +char const* +qpdf_get_error_filename(qpdf_data qpdf, qpdf_error e) { - if (e == 0) - { + if (e == 0) { return ""; } return e->exc->getFilename().c_str(); } -unsigned long long qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e) +unsigned long long +qpdf_get_error_file_position(qpdf_data qpdf, qpdf_error e) { - if (e == 0) - { + if (e == 0) { return 0; } return QIntC::to_ulonglong(e->exc->getFilePosition()); } -char const* qpdf_get_error_message_detail(qpdf_data qpdf, qpdf_error e) +char const* +qpdf_get_error_message_detail(qpdf_data qpdf, qpdf_error e) { - if (e == 0) - { + if (e == 0) { return ""; } return e->exc->getMessageDetail().c_str(); } -QPDF_ERROR_CODE qpdf_check_pdf(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_check_pdf(qpdf_data qpdf) { QPDF_ERROR_CODE status = trap_errors(qpdf, &call_check); QTC::TC("qpdf", "qpdf-c called qpdf_check_pdf"); return status; } -void qpdf_set_suppress_warnings(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_suppress_warnings(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_suppress_warnings"); qpdf->qpdf->setSuppressWarnings(value != QPDF_FALSE); } -void qpdf_set_ignore_xref_streams(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_ignore_xref_streams(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_ignore_xref_streams"); qpdf->qpdf->setIgnoreXRefStreams(value != QPDF_FALSE); } -void qpdf_set_attempt_recovery(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_attempt_recovery(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_attempt_recovery"); qpdf->qpdf->setAttemptRecovery(value != QPDF_FALSE); } -QPDF_ERROR_CODE qpdf_read(qpdf_data qpdf, char const* filename, - char const* password) +QPDF_ERROR_CODE +qpdf_read(qpdf_data qpdf, char const* filename, char const* password) { QPDF_ERROR_CODE status = QPDF_SUCCESS; qpdf->filename = filename; @@ -335,20 +335,23 @@ QPDF_ERROR_CODE qpdf_read(qpdf_data qpdf, char const* filename, // We no longer have a good way to exercise a file with both // warnings and errors because qpdf is getting much better at // recovering. - QTC::TC("qpdf", "qpdf-c called qpdf_read", - (status == 0) ? 0 + QTC::TC( + "qpdf", + "qpdf-c called qpdf_read", + (status == 0) ? 0 : (status & QPDF_WARNINGS) ? 1 - : (status & QPDF_ERRORS) ? 2 : - -1 - ); + : (status & QPDF_ERRORS) ? 2 + : -1); return status; } -QPDF_ERROR_CODE qpdf_read_memory(qpdf_data qpdf, - char const* description, - char const* buffer, - unsigned long long size, - char const* password) +QPDF_ERROR_CODE +qpdf_read_memory( + qpdf_data qpdf, + char const* description, + char const* buffer, + unsigned long long size, + char const* password) { QPDF_ERROR_CODE status = QPDF_SUCCESS; qpdf->filename = description; @@ -360,7 +363,8 @@ QPDF_ERROR_CODE qpdf_read_memory(qpdf_data qpdf, return status; } -QPDF_ERROR_CODE qpdf_empty_pdf(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_empty_pdf(qpdf_data qpdf) { qpdf->filename = "empty PDF"; qpdf->qpdf->emptyPDF(); @@ -368,38 +372,39 @@ QPDF_ERROR_CODE qpdf_empty_pdf(qpdf_data qpdf) return QPDF_SUCCESS; } -char const* qpdf_get_pdf_version(qpdf_data qpdf) +char const* +qpdf_get_pdf_version(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_get_pdf_version"); qpdf->tmp_string = qpdf->qpdf->getPDFVersion(); return qpdf->tmp_string.c_str(); } -int qpdf_get_pdf_extension_level(qpdf_data qpdf) +int +qpdf_get_pdf_extension_level(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_get_pdf_extension_level"); return qpdf->qpdf->getExtensionLevel(); } -char const* qpdf_get_user_password(qpdf_data qpdf) +char const* +qpdf_get_user_password(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_get_user_password"); qpdf->tmp_string = qpdf->qpdf->getTrimmedUserPassword(); return qpdf->tmp_string.c_str(); } -char const* qpdf_get_info_key(qpdf_data qpdf, char const* key) +char const* +qpdf_get_info_key(qpdf_data qpdf, char const* key) { char const* result = 0; QPDFObjectHandle trailer = qpdf->qpdf->getTrailer(); - if (trailer.hasKey("/Info")) - { + if (trailer.hasKey("/Info")) { QPDFObjectHandle info = trailer.getKey("/Info"); - if (info.hasKey(key)) - { + if (info.hasKey(key)) { QPDFObjectHandle value = info.getKey(key); - if (value.isString()) - { + if (value.isString()) { qpdf->tmp_string = value.getStringValue(); result = qpdf->tmp_string.c_str(); } @@ -409,34 +414,28 @@ char const* qpdf_get_info_key(qpdf_data qpdf, char const* key) return result; } -void qpdf_set_info_key(qpdf_data qpdf, char const* key, char const* value) +void +qpdf_set_info_key(qpdf_data qpdf, char const* key, char const* value) { - if ((key == 0) || (std::strlen(key) == 0) || (key[0] != '/')) - { + if ((key == 0) || (std::strlen(key) == 0) || (key[0] != '/')) { return; } QPDFObjectHandle value_object; - if (value) - { + if (value) { QTC::TC("qpdf", "qpdf-c set_info_key to value"); value_object = QPDFObjectHandle::newString(value); - } - else - { + } else { QTC::TC("qpdf", "qpdf-c set_info_key to null"); value_object = QPDFObjectHandle::newNull(); } QPDFObjectHandle trailer = qpdf->qpdf->getTrailer(); - if (! trailer.hasKey("/Info")) - { + if (!trailer.hasKey("/Info")) { QTC::TC("qpdf", "qpdf-c add info to trailer"); trailer.replaceKey( "/Info", qpdf->qpdf->makeIndirectObject(QPDFObjectHandle::newDictionary())); - } - else - { + } else { QTC::TC("qpdf", "qpdf-c set-info-key use existing info"); } @@ -444,80 +443,90 @@ void qpdf_set_info_key(qpdf_data qpdf, char const* key, char const* value) info.replaceOrRemoveKey(key, value_object); } -QPDF_BOOL qpdf_is_linearized(qpdf_data qpdf) +QPDF_BOOL +qpdf_is_linearized(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_is_linearized"); return (qpdf->qpdf->isLinearized() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_is_encrypted(qpdf_data qpdf) +QPDF_BOOL +qpdf_is_encrypted(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_is_encrypted"); return (qpdf->qpdf->isEncrypted() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_accessibility(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_accessibility(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_accessibility"); return (qpdf->qpdf->allowAccessibility() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_extract_all(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_extract_all(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_extract_all"); return (qpdf->qpdf->allowExtractAll() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_print_low_res(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_print_low_res(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_print_low_res"); return (qpdf->qpdf->allowPrintLowRes() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_print_high_res(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_print_high_res(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_print_high_res"); return (qpdf->qpdf->allowPrintHighRes() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_modify_assembly(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_modify_assembly(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_modify_assembly"); return (qpdf->qpdf->allowModifyAssembly() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_modify_form(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_modify_form(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_modify_form"); return (qpdf->qpdf->allowModifyForm() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_modify_annotation(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_modify_annotation(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_modify_annotation"); return (qpdf->qpdf->allowModifyAnnotation() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_modify_other(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_modify_other(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_modify_other"); return (qpdf->qpdf->allowModifyOther() ? QPDF_TRUE : QPDF_FALSE); } -QPDF_BOOL qpdf_allow_modify_all(qpdf_data qpdf) +QPDF_BOOL +qpdf_allow_modify_all(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_allow_modify_all"); return (qpdf->qpdf->allowModifyAll() ? QPDF_TRUE : QPDF_FALSE); } -static void qpdf_init_write_internal(qpdf_data qpdf) +static void +qpdf_init_write_internal(qpdf_data qpdf) { - if (qpdf->qpdf_writer.get()) - { + if (qpdf->qpdf_writer.get()) { QTC::TC("qpdf", "qpdf-c called qpdf_init_write multiple times"); qpdf->qpdf_writer = 0; - if (qpdf->output_buffer.get()) - { + if (qpdf->output_buffer.get()) { qpdf->output_buffer = 0; qpdf->write_memory = false; qpdf->filename = 0; @@ -525,7 +534,8 @@ static void qpdf_init_write_internal(qpdf_data qpdf) } } -QPDF_ERROR_CODE qpdf_init_write(qpdf_data qpdf, char const* filename) +QPDF_ERROR_CODE +qpdf_init_write(qpdf_data qpdf, char const* filename) { qpdf_init_write_internal(qpdf); qpdf->filename = filename; @@ -534,7 +544,8 @@ QPDF_ERROR_CODE qpdf_init_write(qpdf_data qpdf, char const* filename) return status; } -QPDF_ERROR_CODE qpdf_init_write_memory(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_init_write_memory(qpdf_data qpdf) { qpdf_init_write_internal(qpdf); QPDF_ERROR_CODE status = trap_errors(qpdf, &call_init_write_memory); @@ -543,313 +554,420 @@ QPDF_ERROR_CODE qpdf_init_write_memory(qpdf_data qpdf) return status; } -static void qpdf_get_buffer_internal(qpdf_data qpdf) +static void +qpdf_get_buffer_internal(qpdf_data qpdf) { - if (qpdf->write_memory && (qpdf->output_buffer == 0)) - { + if (qpdf->write_memory && (qpdf->output_buffer == 0)) { qpdf->output_buffer = qpdf->qpdf_writer->getBufferSharedPointer(); } } -size_t qpdf_get_buffer_length(qpdf_data qpdf) +size_t +qpdf_get_buffer_length(qpdf_data qpdf) { qpdf_get_buffer_internal(qpdf); size_t result = 0; - if (qpdf->output_buffer.get()) - { + if (qpdf->output_buffer.get()) { result = qpdf->output_buffer->getSize(); } return result; } -unsigned char const* qpdf_get_buffer(qpdf_data qpdf) +unsigned char const* +qpdf_get_buffer(qpdf_data qpdf) { unsigned char const* result = 0; qpdf_get_buffer_internal(qpdf); - if (qpdf->output_buffer.get()) - { + if (qpdf->output_buffer.get()) { result = qpdf->output_buffer->getBuffer(); } return result; } -void qpdf_set_object_stream_mode(qpdf_data qpdf, qpdf_object_stream_e mode) +void +qpdf_set_object_stream_mode(qpdf_data qpdf, qpdf_object_stream_e mode) { QTC::TC("qpdf", "qpdf-c called qpdf_set_object_stream_mode"); qpdf->qpdf_writer->setObjectStreamMode(mode); } -void qpdf_set_compress_streams(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_compress_streams(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_compress_streams"); qpdf->qpdf_writer->setCompressStreams(value != QPDF_FALSE); } -void qpdf_set_decode_level(qpdf_data qpdf, qpdf_stream_decode_level_e level) +void +qpdf_set_decode_level(qpdf_data qpdf, qpdf_stream_decode_level_e level) { QTC::TC("qpdf", "qpdf-c called qpdf_set_decode_level"); qpdf->qpdf_writer->setDecodeLevel(level); } -void qpdf_set_preserve_unreferenced_objects(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_preserve_unreferenced_objects(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_preserve_unreferenced_objects"); qpdf->qpdf_writer->setPreserveUnreferencedObjects(value != QPDF_FALSE); } -void qpdf_set_newline_before_endstream(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_newline_before_endstream(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_newline_before_endstream"); qpdf->qpdf_writer->setNewlineBeforeEndstream(value != QPDF_FALSE); } -void qpdf_set_stream_data_mode(qpdf_data qpdf, qpdf_stream_data_e mode) +void +qpdf_set_stream_data_mode(qpdf_data qpdf, qpdf_stream_data_e mode) { QTC::TC("qpdf", "qpdf-c called qpdf_set_stream_data_mode"); qpdf->qpdf_writer->setStreamDataMode(mode); } -void qpdf_set_content_normalization(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_content_normalization(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_content_normalization"); qpdf->qpdf_writer->setContentNormalization(value != QPDF_FALSE); } -void qpdf_set_qdf_mode(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_qdf_mode(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_qdf_mode"); qpdf->qpdf_writer->setQDFMode(value != QPDF_FALSE); } -void qpdf_set_deterministic_ID(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_deterministic_ID(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_deterministic_ID"); qpdf->qpdf_writer->setDeterministicID(value != QPDF_FALSE); } -void qpdf_set_static_ID(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_static_ID(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_static_ID"); qpdf->qpdf_writer->setStaticID(value != QPDF_FALSE); } -void qpdf_set_static_aes_IV(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_static_aes_IV(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_static_aes_IV"); qpdf->qpdf_writer->setStaticAesIV(value != QPDF_FALSE); } -void qpdf_set_suppress_original_object_IDs( - qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_suppress_original_object_IDs(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_suppress_original_object_IDs"); qpdf->qpdf_writer->setSuppressOriginalObjectIDs(value != QPDF_FALSE); } -void qpdf_set_preserve_encryption(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_preserve_encryption(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_preserve_encryption"); qpdf->qpdf_writer->setPreserveEncryption(value != QPDF_FALSE); } -void qpdf_set_r2_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_print, QPDF_BOOL allow_modify, - QPDF_BOOL allow_extract, QPDF_BOOL allow_annotate) +void +qpdf_set_r2_encryption_parameters( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_print, + QPDF_BOOL allow_modify, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_annotate) { QTC::TC("qpdf", "qpdf-c called qpdf_set_r2_encryption_parameters"); qpdf->qpdf_writer->setR2EncryptionParameters( - user_password, owner_password, - allow_print != QPDF_FALSE, allow_modify != QPDF_FALSE, - allow_extract != QPDF_FALSE, allow_annotate != QPDF_FALSE); + user_password, + owner_password, + allow_print != QPDF_FALSE, + allow_modify != QPDF_FALSE, + allow_extract != QPDF_FALSE, + allow_annotate != QPDF_FALSE); } -void qpdf_set_r3_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, +void +qpdf_set_r3_encryption_parameters2( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, enum qpdf_r3_print_e print) { QTC::TC("qpdf", "qpdf-c called qpdf_set_r3_encryption_parameters"); qpdf->qpdf_writer->setR3EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - allow_assemble != QPDF_FALSE, allow_annotate_and_form != QPDF_FALSE, - allow_form_filling != QPDF_FALSE, allow_modify_other != QPDF_FALSE, + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + allow_assemble != QPDF_FALSE, + allow_annotate_and_form != QPDF_FALSE, + allow_form_filling != QPDF_FALSE, + allow_modify_other != QPDF_FALSE, print); } -void qpdf_set_r4_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, +void +qpdf_set_r4_encryption_parameters2( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, enum qpdf_r3_print_e print, - QPDF_BOOL encrypt_metadata, QPDF_BOOL use_aes) + QPDF_BOOL encrypt_metadata, + QPDF_BOOL use_aes) { QTC::TC("qpdf", "qpdf-c called qpdf_set_r4_encryption_parameters"); qpdf->qpdf_writer->setR4EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - allow_assemble != QPDF_FALSE, allow_annotate_and_form != QPDF_FALSE, - allow_form_filling != QPDF_FALSE, allow_modify_other != QPDF_FALSE, - print, encrypt_metadata != QPDF_FALSE, use_aes != QPDF_FALSE); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + allow_assemble != QPDF_FALSE, + allow_annotate_and_form != QPDF_FALSE, + allow_form_filling != QPDF_FALSE, + allow_modify_other != QPDF_FALSE, + print, + encrypt_metadata != QPDF_FALSE, + use_aes != QPDF_FALSE); } - -void qpdf_set_r5_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, - enum qpdf_r3_print_e print, QPDF_BOOL encrypt_metadata) +void +qpdf_set_r5_encryption_parameters2( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, + enum qpdf_r3_print_e print, + QPDF_BOOL encrypt_metadata) { QTC::TC("qpdf", "qpdf-c called qpdf_set_r5_encryption_parameters"); qpdf->qpdf_writer->setR5EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - allow_assemble != QPDF_FALSE, allow_annotate_and_form != QPDF_FALSE, - allow_form_filling != QPDF_FALSE, allow_modify_other != QPDF_FALSE, - print, encrypt_metadata != QPDF_FALSE); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + allow_assemble != QPDF_FALSE, + allow_annotate_and_form != QPDF_FALSE, + allow_form_filling != QPDF_FALSE, + allow_modify_other != QPDF_FALSE, + print, + encrypt_metadata != QPDF_FALSE); } -void qpdf_set_r6_encryption_parameters2( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - QPDF_BOOL allow_assemble, QPDF_BOOL allow_annotate_and_form, - QPDF_BOOL allow_form_filling, QPDF_BOOL allow_modify_other, - enum qpdf_r3_print_e print, QPDF_BOOL encrypt_metadata) +void +qpdf_set_r6_encryption_parameters2( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + QPDF_BOOL allow_assemble, + QPDF_BOOL allow_annotate_and_form, + QPDF_BOOL allow_form_filling, + QPDF_BOOL allow_modify_other, + enum qpdf_r3_print_e print, + QPDF_BOOL encrypt_metadata) { QTC::TC("qpdf", "qpdf-c called qpdf_set_r6_encryption_parameters"); qpdf->qpdf_writer->setR6EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - allow_assemble != QPDF_FALSE, allow_annotate_and_form != QPDF_FALSE, - allow_form_filling != QPDF_FALSE, allow_modify_other != QPDF_FALSE, - print, encrypt_metadata != QPDF_FALSE); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + allow_assemble != QPDF_FALSE, + allow_annotate_and_form != QPDF_FALSE, + allow_form_filling != QPDF_FALSE, + allow_modify_other != QPDF_FALSE, + print, + encrypt_metadata != QPDF_FALSE); } -void qpdf_set_r3_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify) +void +qpdf_set_r3_encryption_parameters( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify) { #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR3EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - print, modify); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + print, + modify); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif } -void qpdf_set_r4_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, - QPDF_BOOL encrypt_metadata, QPDF_BOOL use_aes) +void +qpdf_set_r4_encryption_parameters( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, + QPDF_BOOL encrypt_metadata, + QPDF_BOOL use_aes) { #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR4EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - print, modify, - encrypt_metadata != QPDF_FALSE, use_aes != QPDF_FALSE); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + print, + modify, + encrypt_metadata != QPDF_FALSE, + use_aes != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif } -void qpdf_set_r5_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, +void +qpdf_set_r5_encryption_parameters( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, QPDF_BOOL encrypt_metadata) { #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR5EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - print, modify, + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + print, + modify, encrypt_metadata != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif } -void qpdf_set_r6_encryption_parameters( - qpdf_data qpdf, char const* user_password, char const* owner_password, - QPDF_BOOL allow_accessibility, QPDF_BOOL allow_extract, - qpdf_r3_print_e print, qpdf_r3_modify_e modify, +void +qpdf_set_r6_encryption_parameters( + qpdf_data qpdf, + char const* user_password, + char const* owner_password, + QPDF_BOOL allow_accessibility, + QPDF_BOOL allow_extract, + qpdf_r3_print_e print, + qpdf_r3_modify_e modify, QPDF_BOOL encrypt_metadata) { #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif qpdf->qpdf_writer->setR6EncryptionParameters( - user_password, owner_password, - allow_accessibility != QPDF_FALSE, allow_extract != QPDF_FALSE, - print, modify, encrypt_metadata != QPDF_FALSE); + user_password, + owner_password, + allow_accessibility != QPDF_FALSE, + allow_extract != QPDF_FALSE, + print, + modify, + encrypt_metadata != QPDF_FALSE); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif } -void qpdf_set_linearization(qpdf_data qpdf, QPDF_BOOL value) +void +qpdf_set_linearization(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_set_linearization"); qpdf->qpdf_writer->setLinearization(value != QPDF_FALSE); } -void qpdf_set_minimum_pdf_version(qpdf_data qpdf, char const* version) +void +qpdf_set_minimum_pdf_version(qpdf_data qpdf, char const* version) { qpdf_set_minimum_pdf_version_and_extension(qpdf, version, 0); } -void qpdf_set_minimum_pdf_version_and_extension( +void +qpdf_set_minimum_pdf_version_and_extension( qpdf_data qpdf, char const* version, int extension_level) { QTC::TC("qpdf", "qpdf-c called qpdf_set_minimum_pdf_version"); qpdf->qpdf_writer->setMinimumPDFVersion(version, extension_level); } -void qpdf_force_pdf_version(qpdf_data qpdf, char const* version) +void +qpdf_force_pdf_version(qpdf_data qpdf, char const* version) { qpdf_force_pdf_version_and_extension(qpdf, version, 0); } -void qpdf_force_pdf_version_and_extension( +void +qpdf_force_pdf_version_and_extension( qpdf_data qpdf, char const* version, int extension_level) { QTC::TC("qpdf", "qpdf-c called qpdf_force_pdf_version"); qpdf->qpdf_writer->forcePDFVersion(version, extension_level); } -void qpdf_register_progress_reporter( +void +qpdf_register_progress_reporter( qpdf_data qpdf, void (*report_progress)(int percent, void* data), void* data) @@ -860,7 +978,8 @@ void qpdf_register_progress_reporter( new ProgressReporter(report_progress, data))); } -QPDF_ERROR_CODE qpdf_write(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_write(qpdf_data qpdf) { QPDF_ERROR_CODE status = QPDF_SUCCESS; status = trap_errors(qpdf, &call_write); @@ -868,14 +987,16 @@ QPDF_ERROR_CODE qpdf_write(qpdf_data qpdf) return status; } -void qpdf_silence_errors(qpdf_data qpdf) +void +qpdf_silence_errors(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c silence oh errors"); qpdf->silence_errors = true; } -template -static RET trap_oh_errors( +template +static RET +trap_oh_errors( qpdf_data qpdf, std::function fallback, std::function fn) @@ -884,25 +1005,23 @@ static RET trap_oh_errors( // unless needed. This is important because sometimes the fallback // creates an object. RET ret; - QPDF_ERROR_CODE status = trap_errors(qpdf, [&ret, fn] (qpdf_data q) { - ret = fn(q); - }); - if (status & QPDF_ERRORS) - { - if (! qpdf->silence_errors) - { - QTC::TC("qpdf", "qpdf-c warn about oh error", - qpdf->oh_error_occurred ? 0 : 1); - if (! qpdf->oh_error_occurred) - { - qpdf->warnings.push_back( - QPDFExc( - qpdf_e_internal, - qpdf->qpdf->getFilename(), - "", 0, - "C API function caught an exception that it isn't" - " returning; please point the application developer" - " to ERROR HANDLING in qpdf-c.h")); + QPDF_ERROR_CODE status = + trap_errors(qpdf, [&ret, fn](qpdf_data q) { ret = fn(q); }); + if (status & QPDF_ERRORS) { + if (!qpdf->silence_errors) { + QTC::TC( + "qpdf", + "qpdf-c warn about oh error", + qpdf->oh_error_occurred ? 0 : 1); + if (!qpdf->oh_error_occurred) { + qpdf->warnings.push_back(QPDFExc( + qpdf_e_internal, + qpdf->qpdf->getFilename(), + "", + 0, + "C API function caught an exception that it isn't" + " returning; please point the application developer" + " to ERROR HANDLING in qpdf-c.h")); qpdf->oh_error_occurred = true; } std::cerr << qpdf->error->what() << std::endl; @@ -920,97 +1039,106 @@ new_object(qpdf_data qpdf, QPDFObjectHandle const& qoh) return oh; } -qpdf_oh qpdf_oh_new_object(qpdf_data qpdf, qpdf_oh oh) +qpdf_oh +qpdf_oh_new_object(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_new_object"); return new_object(qpdf, *(qpdf->oh_cache[oh])); } -void qpdf_oh_release(qpdf_data qpdf, qpdf_oh oh) +void +qpdf_oh_release(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_release"); qpdf->oh_cache.erase(oh); } -void qpdf_oh_release_all(qpdf_data qpdf) +void +qpdf_oh_release_all(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_release_all"); qpdf->oh_cache.clear(); } template -static std::function return_T(T const& r) +static std::function +return_T(T const& r) { return [&r]() { return r; }; } -static QPDF_BOOL return_false() +static QPDF_BOOL +return_false() { return QPDF_FALSE; } -static std::function return_uninitialized(qpdf_data qpdf) +static std::function +return_uninitialized(qpdf_data qpdf) { return [qpdf]() { return qpdf_oh_new_uninitialized(qpdf); }; } -static std::function return_null(qpdf_data qpdf) +static std::function +return_null(qpdf_data qpdf) { return [qpdf]() { return qpdf_oh_new_null(qpdf); }; } -qpdf_oh qpdf_get_trailer(qpdf_data qpdf) +qpdf_oh +qpdf_get_trailer(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_get_trailer"); return trap_oh_errors( - qpdf, return_uninitialized(qpdf), [] (qpdf_data q) { + qpdf, return_uninitialized(qpdf), [](qpdf_data q) { return new_object(q, q->qpdf->getTrailer()); }); } -qpdf_oh qpdf_get_root(qpdf_data qpdf) +qpdf_oh +qpdf_get_root(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_get_root"); return trap_oh_errors( - qpdf, return_uninitialized(qpdf), [] (qpdf_data q) { + qpdf, return_uninitialized(qpdf), [](qpdf_data q) { return new_object(q, q->qpdf->getRoot()); }); } -qpdf_oh qpdf_get_object_by_id(qpdf_data qpdf, int objid, int generation) +qpdf_oh +qpdf_get_object_by_id(qpdf_data qpdf, int objid, int generation) { QTC::TC("qpdf", "qpdf-c called qpdf_get_object_by_id"); return new_object(qpdf, qpdf->qpdf->getObjectByID(objid, generation)); } -template -static RET do_with_oh( - qpdf_data qpdf, qpdf_oh oh, +template +static RET +do_with_oh( + qpdf_data qpdf, + qpdf_oh oh, std::function fallback, std::function fn) { - return trap_oh_errors( - qpdf, fallback, [fn, oh](qpdf_data q) { - auto i = q->oh_cache.find(oh); - bool result = ((i != q->oh_cache.end()) && - (i->second).get()); - if (! result) - { - QTC::TC("qpdf", "qpdf-c invalid object handle"); - throw QPDFExc( - qpdf_e_internal, - q->qpdf->getFilename(), - std::string("C API object handle ") + - QUtil::uint_to_string(oh), - 0, "attempted access to unknown object handle"); - } - return fn(*(q->oh_cache[oh])); - }); + return trap_oh_errors(qpdf, fallback, [fn, oh](qpdf_data q) { + auto i = q->oh_cache.find(oh); + bool result = ((i != q->oh_cache.end()) && (i->second).get()); + if (!result) { + QTC::TC("qpdf", "qpdf-c invalid object handle"); + throw QPDFExc( + qpdf_e_internal, + q->qpdf->getFilename(), + std::string("C API object handle ") + QUtil::uint_to_string(oh), + 0, + "attempted access to unknown object handle"); + } + return fn(*(q->oh_cache[oh])); + }); } -static void do_with_oh_void( - qpdf_data qpdf, qpdf_oh oh, - std::function fn) +static void +do_with_oh_void( + qpdf_data qpdf, qpdf_oh oh, std::function fn) { do_with_oh( qpdf, oh, return_T(false), [fn](QPDFObjectHandle& o) { @@ -1019,16 +1147,17 @@ static void do_with_oh_void( }); } -void qpdf_replace_object(qpdf_data qpdf, int objid, int generation, qpdf_oh oh) +void +qpdf_replace_object(qpdf_data qpdf, int objid, int generation, qpdf_oh oh) { - do_with_oh_void( - qpdf, oh, [qpdf, objid, generation](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_replace_object"); - qpdf->qpdf->replaceObject(objid, generation, o); - }); + do_with_oh_void(qpdf, oh, [qpdf, objid, generation](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_replace_object"); + qpdf->qpdf->replaceObject(objid, generation, o); + }); } -QPDF_BOOL qpdf_oh_is_initialized(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_initialized(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_initialized"); return do_with_oh( @@ -1037,25 +1166,24 @@ QPDF_BOOL qpdf_oh_is_initialized(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_bool(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_bool(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_bool"); return do_with_oh( - qpdf, oh, return_false, [](QPDFObjectHandle& o) { - return o.isBool(); - }); + qpdf, oh, return_false, [](QPDFObjectHandle& o) { return o.isBool(); }); } -QPDF_BOOL qpdf_oh_is_null(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_null(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_null"); return do_with_oh( - qpdf, oh, return_false, [](QPDFObjectHandle& o) { - return o.isNull(); - }); + qpdf, oh, return_false, [](QPDFObjectHandle& o) { return o.isNull(); }); } -QPDF_BOOL qpdf_oh_is_integer(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_integer(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_integer"); return do_with_oh( @@ -1064,25 +1192,24 @@ QPDF_BOOL qpdf_oh_is_integer(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_real(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_real(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_real"); return do_with_oh( - qpdf, oh, return_false, [](QPDFObjectHandle& o) { - return o.isReal(); - }); + qpdf, oh, return_false, [](QPDFObjectHandle& o) { return o.isReal(); }); } -QPDF_BOOL qpdf_oh_is_name(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_name(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_name"); return do_with_oh( - qpdf, oh, return_false, [](QPDFObjectHandle& o) { - return o.isName(); - }); + qpdf, oh, return_false, [](QPDFObjectHandle& o) { return o.isName(); }); } -QPDF_BOOL qpdf_oh_is_string(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_string(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_string"); return do_with_oh( @@ -1091,7 +1218,8 @@ QPDF_BOOL qpdf_oh_is_string(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_operator(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_operator(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_operator"); return do_with_oh( @@ -1100,7 +1228,8 @@ QPDF_BOOL qpdf_oh_is_operator(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_inline_image(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_inline_image(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_inline_image"); return do_with_oh( @@ -1109,7 +1238,8 @@ QPDF_BOOL qpdf_oh_is_inline_image(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_array(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_array(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_array"); return do_with_oh( @@ -1118,7 +1248,8 @@ QPDF_BOOL qpdf_oh_is_array(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_dictionary(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_dictionary(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_dictionary"); return do_with_oh( @@ -1127,7 +1258,8 @@ QPDF_BOOL qpdf_oh_is_dictionary(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_stream(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_stream(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_stream"); return do_with_oh( @@ -1136,7 +1268,8 @@ QPDF_BOOL qpdf_oh_is_stream(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_indirect(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_indirect(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_indirect"); return do_with_oh( @@ -1145,7 +1278,8 @@ QPDF_BOOL qpdf_oh_is_indirect(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_scalar(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_scalar(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_is_scalar"); return do_with_oh( @@ -1154,7 +1288,8 @@ QPDF_BOOL qpdf_oh_is_scalar(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_number(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_is_number(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_false, [](QPDFObjectHandle& o) { @@ -1163,8 +1298,8 @@ QPDF_BOOL qpdf_oh_is_number(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_is_name_and_equals( - qpdf_data qpdf, qpdf_oh oh, char const* name) +QPDF_BOOL +qpdf_oh_is_name_and_equals(qpdf_data qpdf, qpdf_oh oh, char const* name) { return do_with_oh( qpdf, oh, return_false, [name](QPDFObjectHandle& o) { @@ -1173,7 +1308,8 @@ QPDF_BOOL qpdf_oh_is_name_and_equals( }); } -QPDF_BOOL qpdf_oh_is_dictionary_of_type( +QPDF_BOOL +qpdf_oh_is_dictionary_of_type( qpdf_data qpdf, qpdf_oh oh, char const* type, char const* subtype) { auto stype = (subtype == nullptr) ? "" : subtype; @@ -1184,17 +1320,21 @@ QPDF_BOOL qpdf_oh_is_dictionary_of_type( }); } -qpdf_object_type_e qpdf_oh_get_type_code(qpdf_data qpdf, qpdf_oh oh) +qpdf_object_type_e +qpdf_oh_get_type_code(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( - qpdf, oh, return_T(ot_uninitialized), + qpdf, + oh, + return_T(ot_uninitialized), [](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_type_code"); return o.getTypeCode(); }); } -char const* qpdf_oh_get_type_name(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_get_type_name(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1204,37 +1344,39 @@ char const* qpdf_oh_get_type_name(qpdf_data qpdf, qpdf_oh oh) }); } -qpdf_oh qpdf_oh_wrap_in_array(qpdf_data qpdf, qpdf_oh oh) +qpdf_oh +qpdf_oh_wrap_in_array(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( - qpdf, oh, - [qpdf](){ return qpdf_oh_new_array(qpdf); }, + qpdf, + oh, + [qpdf]() { return qpdf_oh_new_array(qpdf); }, [qpdf](QPDFObjectHandle& qoh) { - if (qoh.isArray()) - { + if (qoh.isArray()) { QTC::TC("qpdf", "qpdf-c array to wrap_in_array"); return new_object(qpdf, qoh); - } - else - { + } else { QTC::TC("qpdf", "qpdf-c non-array to wrap_in_array"); - return new_object(qpdf, - QPDFObjectHandle::newArray( - std::vector{qoh})); + return new_object( + qpdf, + QPDFObjectHandle::newArray( + std::vector{qoh})); } - }); + }); } -qpdf_oh qpdf_oh_parse(qpdf_data qpdf, char const* object_str) +qpdf_oh +qpdf_oh_parse(qpdf_data qpdf, char const* object_str) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_parse"); return trap_oh_errors( - qpdf, return_uninitialized(qpdf), [object_str] (qpdf_data q) { + qpdf, return_uninitialized(qpdf), [object_str](qpdf_data q) { return new_object(q, QPDFObjectHandle::parse(object_str)); }); } -QPDF_BOOL qpdf_oh_get_bool_value(qpdf_data qpdf, qpdf_oh oh) +QPDF_BOOL +qpdf_oh_get_bool_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_false, [](QPDFObjectHandle& o) { @@ -1243,23 +1385,23 @@ QPDF_BOOL qpdf_oh_get_bool_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_bool( - qpdf_data qpdf, qpdf_oh oh, QPDF_BOOL* value) +QPDF_BOOL +qpdf_oh_get_value_as_bool(qpdf_data qpdf, qpdf_oh oh, QPDF_BOOL* value) { return do_with_oh( qpdf, oh, return_false, [value](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_value_as_bool"); bool v = *value; QPDF_BOOL result = o.getValueAsBool(v); - if (result) - { + if (result) { *value = v; } return result; }); } -long long qpdf_oh_get_int_value(qpdf_data qpdf, qpdf_oh oh) +long long +qpdf_oh_get_int_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(0LL), [](QPDFObjectHandle& o) { @@ -1268,8 +1410,8 @@ long long qpdf_oh_get_int_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_longlong( - qpdf_data qpdf, qpdf_oh oh, long long* value) +QPDF_BOOL +qpdf_oh_get_value_as_longlong(qpdf_data qpdf, qpdf_oh oh, long long* value) { return do_with_oh( qpdf, oh, return_false, [value](QPDFObjectHandle& o) { @@ -1278,17 +1420,17 @@ QPDF_BOOL qpdf_oh_get_value_as_longlong( }); } -int qpdf_oh_get_int_value_as_int(qpdf_data qpdf, qpdf_oh oh) +int +qpdf_oh_get_int_value_as_int(qpdf_data qpdf, qpdf_oh oh) { - return do_with_oh( - qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_int_value_as_int"); - return o.getIntValueAsInt(); - }); + return do_with_oh(qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_int_value_as_int"); + return o.getIntValueAsInt(); + }); } -QPDF_BOOL qpdf_oh_get_value_as_int( - qpdf_data qpdf, qpdf_oh oh, int* value) +QPDF_BOOL +qpdf_oh_get_value_as_int(qpdf_data qpdf, qpdf_oh oh, int* value) { return do_with_oh( qpdf, oh, return_false, [value](QPDFObjectHandle& o) { @@ -1297,7 +1439,8 @@ QPDF_BOOL qpdf_oh_get_value_as_int( }); } -unsigned long long qpdf_oh_get_uint_value(qpdf_data qpdf, qpdf_oh oh) +unsigned long long +qpdf_oh_get_uint_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(0ULL), [](QPDFObjectHandle& o) { @@ -1306,7 +1449,8 @@ unsigned long long qpdf_oh_get_uint_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_ulonglong( +QPDF_BOOL +qpdf_oh_get_value_as_ulonglong( qpdf_data qpdf, qpdf_oh oh, unsigned long long* value) { return do_with_oh( @@ -1316,7 +1460,8 @@ QPDF_BOOL qpdf_oh_get_value_as_ulonglong( }); } -unsigned int qpdf_oh_get_uint_value_as_uint(qpdf_data qpdf, qpdf_oh oh) +unsigned int +qpdf_oh_get_uint_value_as_uint(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(0U), [](QPDFObjectHandle& o) { @@ -1325,8 +1470,8 @@ unsigned int qpdf_oh_get_uint_value_as_uint(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_uint( - qpdf_data qpdf, qpdf_oh oh, unsigned int* value) +QPDF_BOOL +qpdf_oh_get_value_as_uint(qpdf_data qpdf, qpdf_oh oh, unsigned int* value) { return do_with_oh( qpdf, oh, return_false, [value](QPDFObjectHandle& o) { @@ -1335,7 +1480,8 @@ QPDF_BOOL qpdf_oh_get_value_as_uint( }); } -char const* qpdf_oh_get_real_value(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_get_real_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1345,15 +1491,15 @@ char const* qpdf_oh_get_real_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_real( +QPDF_BOOL +qpdf_oh_get_value_as_real( qpdf_data qpdf, qpdf_oh oh, char const** value, size_t* length) { return do_with_oh( qpdf, oh, return_false, [qpdf, value, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_value_as_real"); auto result = o.getValueAsReal(qpdf->tmp_string); - if (result) - { + if (result) { *value = qpdf->tmp_string.c_str(); *length = qpdf->tmp_string.length(); } @@ -1361,7 +1507,8 @@ QPDF_BOOL qpdf_oh_get_value_as_real( }); } -double qpdf_oh_get_numeric_value(qpdf_data qpdf, qpdf_oh oh) +double +qpdf_oh_get_numeric_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(0.0), [](QPDFObjectHandle& o) { @@ -1370,8 +1517,8 @@ double qpdf_oh_get_numeric_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_number( - qpdf_data qpdf, qpdf_oh oh, double* value) +QPDF_BOOL +qpdf_oh_get_value_as_number(qpdf_data qpdf, qpdf_oh oh, double* value) { return do_with_oh( qpdf, oh, return_false, [value](QPDFObjectHandle& o) { @@ -1380,7 +1527,8 @@ QPDF_BOOL qpdf_oh_get_value_as_number( }); } -char const* qpdf_oh_get_name(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_get_name(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1390,15 +1538,15 @@ char const* qpdf_oh_get_name(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_name( +QPDF_BOOL +qpdf_oh_get_value_as_name( qpdf_data qpdf, qpdf_oh oh, char const** value, size_t* length) { return do_with_oh( qpdf, oh, return_false, [qpdf, value, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_value_as_name"); auto result = o.getValueAsName(qpdf->tmp_string); - if (result) - { + if (result) { *value = qpdf->tmp_string.c_str(); *length = qpdf->tmp_string.length(); } @@ -1406,7 +1554,8 @@ QPDF_BOOL qpdf_oh_get_value_as_name( }); } -char const* qpdf_oh_get_string_value(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_get_string_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1416,15 +1565,15 @@ char const* qpdf_oh_get_string_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_string( +QPDF_BOOL +qpdf_oh_get_value_as_string( qpdf_data qpdf, qpdf_oh oh, char const** value, size_t* length) { return do_with_oh( qpdf, oh, return_false, [qpdf, value, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_value_as_string"); auto result = o.getValueAsString(qpdf->tmp_string); - if (result) - { + if (result) { *value = qpdf->tmp_string.c_str(); *length = qpdf->tmp_string.length(); } @@ -1432,7 +1581,8 @@ QPDF_BOOL qpdf_oh_get_value_as_string( }); } -char const* qpdf_oh_get_utf8_value(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_get_utf8_value(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1442,15 +1592,15 @@ char const* qpdf_oh_get_utf8_value(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_BOOL qpdf_oh_get_value_as_utf8( +QPDF_BOOL +qpdf_oh_get_value_as_utf8( qpdf_data qpdf, qpdf_oh oh, char const** value, size_t* length) { return do_with_oh( qpdf, oh, return_false, [qpdf, value, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_value_as_utf8"); auto result = o.getValueAsUTF8(qpdf->tmp_string); - if (result) - { + if (result) { *value = qpdf->tmp_string.c_str(); *length = qpdf->tmp_string.length(); } @@ -1458,11 +1608,12 @@ QPDF_BOOL qpdf_oh_get_value_as_utf8( }); } -char const* qpdf_oh_get_binary_string_value( - qpdf_data qpdf, qpdf_oh oh, size_t* length) +char const* +qpdf_oh_get_binary_string_value(qpdf_data qpdf, qpdf_oh oh, size_t* length) { return do_with_oh( - qpdf, oh, + qpdf, + oh, return_T(""), [qpdf, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_binary_string_value"); @@ -1472,11 +1623,12 @@ char const* qpdf_oh_get_binary_string_value( }); } -char const* qpdf_oh_get_binary_utf8_value( - qpdf_data qpdf, qpdf_oh oh, size_t* length) +char const* +qpdf_oh_get_binary_utf8_value(qpdf_data qpdf, qpdf_oh oh, size_t* length) { return do_with_oh( - qpdf, oh, + qpdf, + oh, return_T(""), [qpdf, length](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_binary_utf8_value"); @@ -1486,16 +1638,17 @@ char const* qpdf_oh_get_binary_utf8_value( }); } -int qpdf_oh_get_array_n_items(qpdf_data qpdf, qpdf_oh oh) +int +qpdf_oh_get_array_n_items(qpdf_data qpdf, qpdf_oh oh) { - return do_with_oh( - qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_array_n_items"); - return o.getArrayNItems(); - }); + return do_with_oh(qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_array_n_items"); + return o.getArrayNItems(); + }); } -qpdf_oh qpdf_oh_get_array_item(qpdf_data qpdf, qpdf_oh oh, int n) +qpdf_oh +qpdf_oh_get_array_item(qpdf_data qpdf, qpdf_oh oh, int n) { return do_with_oh( qpdf, oh, return_null(qpdf), [qpdf, n](QPDFObjectHandle& o) { @@ -1504,11 +1657,13 @@ qpdf_oh qpdf_oh_get_array_item(qpdf_data qpdf, qpdf_oh oh, int n) }); } -void qpdf_oh_begin_dict_key_iter(qpdf_data qpdf, qpdf_oh oh) +void +qpdf_oh_begin_dict_key_iter(qpdf_data qpdf, qpdf_oh oh) { qpdf->cur_iter_dict_keys = do_with_oh>( - qpdf, oh, - [](){ return std::set(); }, + qpdf, + oh, + []() { return std::set(); }, [](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_begin_dict_key_iter"); return o.getKeys(); @@ -1516,28 +1671,28 @@ void qpdf_oh_begin_dict_key_iter(qpdf_data qpdf, qpdf_oh oh) qpdf->dict_iter = qpdf->cur_iter_dict_keys.begin(); } -QPDF_BOOL qpdf_oh_dict_more_keys(qpdf_data qpdf) +QPDF_BOOL +qpdf_oh_dict_more_keys(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_dict_more_keys"); return qpdf->dict_iter != qpdf->cur_iter_dict_keys.end(); } -char const* qpdf_oh_dict_next_key(qpdf_data qpdf) +char const* +qpdf_oh_dict_next_key(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_dict_next_key"); - if (qpdf_oh_dict_more_keys(qpdf)) - { + if (qpdf_oh_dict_more_keys(qpdf)) { qpdf->cur_dict_key = *qpdf->dict_iter; ++qpdf->dict_iter; return qpdf->cur_dict_key.c_str(); - } - else - { + } else { return nullptr; } } -QPDF_BOOL qpdf_oh_has_key(qpdf_data qpdf, qpdf_oh oh, char const* key) +QPDF_BOOL +qpdf_oh_has_key(qpdf_data qpdf, qpdf_oh oh, char const* key) { return do_with_oh( qpdf, oh, return_false, [key](QPDFObjectHandle& o) { @@ -1546,7 +1701,8 @@ QPDF_BOOL qpdf_oh_has_key(qpdf_data qpdf, qpdf_oh oh, char const* key) }); } -qpdf_oh qpdf_oh_get_key(qpdf_data qpdf, qpdf_oh oh, char const* key) +qpdf_oh +qpdf_oh_get_key(qpdf_data qpdf, qpdf_oh oh, char const* key) { return do_with_oh( qpdf, oh, return_null(qpdf), [qpdf, key](QPDFObjectHandle& o) { @@ -1555,7 +1711,8 @@ qpdf_oh qpdf_oh_get_key(qpdf_data qpdf, qpdf_oh oh, char const* key) }); } -qpdf_oh qpdf_oh_get_key_if_dict(qpdf_data qpdf, qpdf_oh oh, char const* key) +qpdf_oh +qpdf_oh_get_key_if_dict(qpdf_data qpdf, qpdf_oh oh, char const* key) { return do_with_oh( qpdf, oh, return_null(qpdf), [qpdf, key](QPDFObjectHandle& o) { @@ -1564,7 +1721,8 @@ qpdf_oh qpdf_oh_get_key_if_dict(qpdf_data qpdf, qpdf_oh oh, char const* key) }); } -QPDF_BOOL qpdf_oh_is_or_has_name(qpdf_data qpdf, qpdf_oh oh, char const* key) +QPDF_BOOL +qpdf_oh_is_or_has_name(qpdf_data qpdf, qpdf_oh oh, char const* key) { return do_with_oh( qpdf, oh, return_false, [key](QPDFObjectHandle& o) { @@ -1573,111 +1731,122 @@ QPDF_BOOL qpdf_oh_is_or_has_name(qpdf_data qpdf, qpdf_oh oh, char const* key) }); } -qpdf_oh qpdf_oh_new_uninitialized(qpdf_data qpdf) +qpdf_oh +qpdf_oh_new_uninitialized(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_uninitialized"); return new_object(qpdf, QPDFObjectHandle()); } -qpdf_oh qpdf_oh_new_null(qpdf_data qpdf) +qpdf_oh +qpdf_oh_new_null(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_null"); return new_object(qpdf, QPDFObjectHandle::newNull()); } -qpdf_oh qpdf_oh_new_bool(qpdf_data qpdf, QPDF_BOOL value) +qpdf_oh +qpdf_oh_new_bool(qpdf_data qpdf, QPDF_BOOL value) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_bool"); return new_object(qpdf, QPDFObjectHandle::newBool(value)); } -qpdf_oh qpdf_oh_new_integer(qpdf_data qpdf, long long value) +qpdf_oh +qpdf_oh_new_integer(qpdf_data qpdf, long long value) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_integer"); return new_object(qpdf, QPDFObjectHandle::newInteger(value)); } -qpdf_oh qpdf_oh_new_real_from_string(qpdf_data qpdf, char const* value) +qpdf_oh +qpdf_oh_new_real_from_string(qpdf_data qpdf, char const* value) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_real_from_string"); return new_object(qpdf, QPDFObjectHandle::newReal(value)); } -qpdf_oh qpdf_oh_new_real_from_double(qpdf_data qpdf, - double value, int decimal_places) +qpdf_oh +qpdf_oh_new_real_from_double(qpdf_data qpdf, double value, int decimal_places) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_real_from_double"); return new_object(qpdf, QPDFObjectHandle::newReal(value, decimal_places)); } -qpdf_oh qpdf_oh_new_name(qpdf_data qpdf, char const* name) +qpdf_oh +qpdf_oh_new_name(qpdf_data qpdf, char const* name) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_name"); return new_object(qpdf, QPDFObjectHandle::newName(name)); } -qpdf_oh qpdf_oh_new_string(qpdf_data qpdf, char const* str) +qpdf_oh +qpdf_oh_new_string(qpdf_data qpdf, char const* str) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_string"); return new_object(qpdf, QPDFObjectHandle::newString(str)); } -qpdf_oh qpdf_oh_new_unicode_string(qpdf_data qpdf, char const* utf8_str) +qpdf_oh +qpdf_oh_new_unicode_string(qpdf_data qpdf, char const* utf8_str) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_unicode_string"); return new_object(qpdf, QPDFObjectHandle::newUnicodeString(utf8_str)); } -qpdf_oh qpdf_oh_new_binary_string( - qpdf_data qpdf, char const* str, size_t length) +qpdf_oh +qpdf_oh_new_binary_string(qpdf_data qpdf, char const* str, size_t length) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_binary_string"); return new_object( qpdf, QPDFObjectHandle::newString(std::string(str, length))); } -qpdf_oh qpdf_oh_new_binary_unicode_string( +qpdf_oh +qpdf_oh_new_binary_unicode_string( qpdf_data qpdf, char const* utf8_str, size_t length) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_binary_unicode_string"); return new_object( - qpdf, QPDFObjectHandle::newUnicodeString(std::string(utf8_str, length))); + qpdf, + QPDFObjectHandle::newUnicodeString(std::string(utf8_str, length))); } -qpdf_oh qpdf_oh_new_array(qpdf_data qpdf) +qpdf_oh +qpdf_oh_new_array(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_array"); return new_object(qpdf, QPDFObjectHandle::newArray()); } -qpdf_oh qpdf_oh_new_dictionary(qpdf_data qpdf) +qpdf_oh +qpdf_oh_new_dictionary(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_dictionary"); return new_object(qpdf, QPDFObjectHandle::newDictionary()); } -qpdf_oh qpdf_oh_new_stream(qpdf_data qpdf) +qpdf_oh +qpdf_oh_new_stream(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_new_stream"); - return new_object( - qpdf, QPDFObjectHandle::newStream(qpdf->qpdf.get())); + return new_object(qpdf, QPDFObjectHandle::newStream(qpdf->qpdf.get())); } -void qpdf_oh_make_direct(qpdf_data qpdf, qpdf_oh oh) +void +qpdf_oh_make_direct(qpdf_data qpdf, qpdf_oh oh) { - do_with_oh_void( - qpdf, oh, [](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_make_direct"); - o.makeDirect(); - }); + do_with_oh_void(qpdf, oh, [](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_make_direct"); + o.makeDirect(); + }); } -qpdf_oh qpdf_make_indirect_object(qpdf_data qpdf, qpdf_oh oh) +qpdf_oh +qpdf_make_indirect_object(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( - qpdf, oh, - return_uninitialized(qpdf), - [qpdf](QPDFObjectHandle& o) { + qpdf, oh, return_uninitialized(qpdf), [qpdf](QPDFObjectHandle& o) { return new_object(qpdf, qpdf->qpdf->makeIndirectObject(o)); }); } @@ -1686,80 +1855,78 @@ static QPDFObjectHandle qpdf_oh_item_internal(qpdf_data qpdf, qpdf_oh item) { return do_with_oh( - qpdf, item, - [](){return QPDFObjectHandle::newNull();}, - [](QPDFObjectHandle& o) { - return o; - }); + qpdf, + item, + []() { return QPDFObjectHandle::newNull(); }, + [](QPDFObjectHandle& o) { return o; }); } -void qpdf_oh_set_array_item(qpdf_data qpdf, qpdf_oh oh, - int at, qpdf_oh item) +void +qpdf_oh_set_array_item(qpdf_data qpdf, qpdf_oh oh, int at, qpdf_oh item) { - do_with_oh_void( - qpdf, oh, [qpdf, at, item](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_set_array_item"); - o.setArrayItem(at, qpdf_oh_item_internal(qpdf, item)); - }); + do_with_oh_void(qpdf, oh, [qpdf, at, item](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_set_array_item"); + o.setArrayItem(at, qpdf_oh_item_internal(qpdf, item)); + }); } -void qpdf_oh_insert_item(qpdf_data qpdf, qpdf_oh oh, int at, qpdf_oh item) +void +qpdf_oh_insert_item(qpdf_data qpdf, qpdf_oh oh, int at, qpdf_oh item) { - do_with_oh_void( - qpdf, oh, [qpdf, at, item](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_insert_item"); - o.insertItem(at, qpdf_oh_item_internal(qpdf, item)); - }); + do_with_oh_void(qpdf, oh, [qpdf, at, item](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_insert_item"); + o.insertItem(at, qpdf_oh_item_internal(qpdf, item)); + }); } -void qpdf_oh_append_item(qpdf_data qpdf, qpdf_oh oh, qpdf_oh item) +void +qpdf_oh_append_item(qpdf_data qpdf, qpdf_oh oh, qpdf_oh item) { - do_with_oh_void( - qpdf, oh, [qpdf, item](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_append_item"); - o.appendItem(qpdf_oh_item_internal(qpdf, item)); - }); + do_with_oh_void(qpdf, oh, [qpdf, item](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_append_item"); + o.appendItem(qpdf_oh_item_internal(qpdf, item)); + }); } -void qpdf_oh_erase_item(qpdf_data qpdf, qpdf_oh oh, int at) +void +qpdf_oh_erase_item(qpdf_data qpdf, qpdf_oh oh, int at) { - do_with_oh_void( - qpdf, oh, [at](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_erase_item"); - o.eraseItem(at); - }); + do_with_oh_void(qpdf, oh, [at](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_erase_item"); + o.eraseItem(at); + }); } -void qpdf_oh_replace_key(qpdf_data qpdf, qpdf_oh oh, - char const* key, qpdf_oh item) +void +qpdf_oh_replace_key(qpdf_data qpdf, qpdf_oh oh, char const* key, qpdf_oh item) { - do_with_oh_void( - qpdf, oh, [qpdf, key, item](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_key"); - o.replaceKey(key, qpdf_oh_item_internal(qpdf, item)); - }); + do_with_oh_void(qpdf, oh, [qpdf, key, item](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_key"); + o.replaceKey(key, qpdf_oh_item_internal(qpdf, item)); + }); } -void qpdf_oh_remove_key(qpdf_data qpdf, qpdf_oh oh, char const* key) +void +qpdf_oh_remove_key(qpdf_data qpdf, qpdf_oh oh, char const* key) { - do_with_oh_void( - qpdf, oh, [key](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_remove_key"); - o.removeKey(key); - }); + do_with_oh_void(qpdf, oh, [key](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_remove_key"); + o.removeKey(key); + }); } -void qpdf_oh_replace_or_remove_key(qpdf_data qpdf, qpdf_oh oh, - char const* key, qpdf_oh item) +void +qpdf_oh_replace_or_remove_key( + qpdf_data qpdf, qpdf_oh oh, char const* key, qpdf_oh item) { - do_with_oh_void( - qpdf, oh, [qpdf, key, item](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_or_remove_key"); - o.replaceOrRemoveKey(key, qpdf_oh_item_internal(qpdf, item)); - }); + do_with_oh_void(qpdf, oh, [qpdf, key, item](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_or_remove_key"); + o.replaceOrRemoveKey(key, qpdf_oh_item_internal(qpdf, item)); + }); } -qpdf_oh qpdf_oh_get_dict(qpdf_data qpdf, qpdf_oh oh) +qpdf_oh +qpdf_oh_get_dict(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_null(qpdf), [qpdf](QPDFObjectHandle& o) { @@ -1768,25 +1935,26 @@ qpdf_oh qpdf_oh_get_dict(qpdf_data qpdf, qpdf_oh oh) }); } -int qpdf_oh_get_object_id(qpdf_data qpdf, qpdf_oh oh) +int +qpdf_oh_get_object_id(qpdf_data qpdf, qpdf_oh oh) { - return do_with_oh( - qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_object_id"); - return o.getObjectID(); - }); + return do_with_oh(qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_object_id"); + return o.getObjectID(); + }); } -int qpdf_oh_get_generation(qpdf_data qpdf, qpdf_oh oh) +int +qpdf_oh_get_generation(qpdf_data qpdf, qpdf_oh oh) { - return do_with_oh( - qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_generation"); - return o.getGeneration(); - }); + return do_with_oh(qpdf, oh, return_T(0), [](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_generation"); + return o.getGeneration(); + }); } -char const* qpdf_oh_unparse(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_unparse(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1796,7 +1964,8 @@ char const* qpdf_oh_unparse(qpdf_data qpdf, qpdf_oh oh) }); } -char const* qpdf_oh_unparse_resolved(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_unparse_resolved(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1806,7 +1975,8 @@ char const* qpdf_oh_unparse_resolved(qpdf_data qpdf, qpdf_oh oh) }); } -char const* qpdf_oh_unparse_binary(qpdf_data qpdf, qpdf_oh oh) +char const* +qpdf_oh_unparse_binary(qpdf_data qpdf, qpdf_oh oh) { return do_with_oh( qpdf, oh, return_T(""), [qpdf](QPDFObjectHandle& o) { @@ -1816,11 +1986,13 @@ char const* qpdf_oh_unparse_binary(qpdf_data qpdf, qpdf_oh oh) }); } -qpdf_oh qpdf_oh_copy_foreign_object( +qpdf_oh +qpdf_oh_copy_foreign_object( qpdf_data qpdf, qpdf_data other_qpdf, qpdf_oh foreign_oh) { return do_with_oh( - other_qpdf, foreign_oh, + other_qpdf, + foreign_oh, return_uninitialized(qpdf), [qpdf](QPDFObjectHandle& o) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_copy_foreign_object"); @@ -1828,50 +2000,50 @@ qpdf_oh qpdf_oh_copy_foreign_object( }); } -QPDF_ERROR_CODE qpdf_oh_get_stream_data( - qpdf_data qpdf, qpdf_oh stream_oh, - qpdf_stream_decode_level_e decode_level, QPDF_BOOL* filtered, - unsigned char** bufp, size_t* len) +QPDF_ERROR_CODE +qpdf_oh_get_stream_data( + qpdf_data qpdf, + qpdf_oh stream_oh, + qpdf_stream_decode_level_e decode_level, + QPDF_BOOL* filtered, + unsigned char** bufp, + size_t* len) { - return trap_errors(qpdf, [stream_oh, decode_level, - filtered, bufp, len] (qpdf_data q) { - auto stream = qpdf_oh_item_internal(q, stream_oh); - Pipeline* p = nullptr; - Pl_Buffer buf("stream data"); - if (bufp) - { - p = &buf; - } - bool was_filtered = false; - if (stream.pipeStreamData( - p, &was_filtered, 0, decode_level, false, false)) - { - QTC::TC("qpdf", "qpdf-c stream data buf set", - bufp ? 0 : 1); - if (p && bufp && len) - { - buf.getMallocBuffer(bufp, len); + return trap_errors( + qpdf, [stream_oh, decode_level, filtered, bufp, len](qpdf_data q) { + auto stream = qpdf_oh_item_internal(q, stream_oh); + Pipeline* p = nullptr; + Pl_Buffer buf("stream data"); + if (bufp) { + p = &buf; } - QTC::TC("qpdf", "qpdf-c stream data filtered set", + bool was_filtered = false; + if (stream.pipeStreamData( + p, &was_filtered, 0, decode_level, false, false)) { + QTC::TC("qpdf", "qpdf-c stream data buf set", bufp ? 0 : 1); + if (p && bufp && len) { + buf.getMallocBuffer(bufp, len); + } + QTC::TC( + "qpdf", + "qpdf-c stream data filtered set", filtered ? 0 : 1); - if (filtered) - { - *filtered = was_filtered ? QPDF_TRUE : QPDF_FALSE; + if (filtered) { + *filtered = was_filtered ? QPDF_TRUE : QPDF_FALSE; + } + } else { + throw std::runtime_error( + "unable to access stream data for stream " + + stream.unparse()); } - } - else - { - throw std::runtime_error( - "unable to access stream data for stream " + stream.unparse()); - } - }); + }); } -QPDF_ERROR_CODE qpdf_oh_get_page_content_data( - qpdf_data qpdf, qpdf_oh page_oh, - unsigned char** bufp, size_t* len) +QPDF_ERROR_CODE +qpdf_oh_get_page_content_data( + qpdf_data qpdf, qpdf_oh page_oh, unsigned char** bufp, size_t* len) { - return trap_errors(qpdf, [page_oh, bufp, len] (qpdf_data q) { + return trap_errors(qpdf, [page_oh, bufp, len](qpdf_data q) { QTC::TC("qpdf", "qpdf-c called qpdf_oh_get_page_content_data"); auto o = qpdf_oh_item_internal(q, page_oh); Pl_Buffer buf("page contents"); @@ -1880,61 +2052,68 @@ QPDF_ERROR_CODE qpdf_oh_get_page_content_data( }); } -void qpdf_oh_replace_stream_data( - qpdf_data qpdf, qpdf_oh stream_oh, - unsigned char const* buf, size_t len, - qpdf_oh filter_oh, qpdf_oh decode_parms_oh) +void +qpdf_oh_replace_stream_data( + qpdf_data qpdf, + qpdf_oh stream_oh, + unsigned char const* buf, + size_t len, + qpdf_oh filter_oh, + qpdf_oh decode_parms_oh) { - do_with_oh_void(qpdf, stream_oh, [ - qpdf, buf, len, filter_oh, - decode_parms_oh](QPDFObjectHandle& o) { - QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_stream_data"); - auto filter = qpdf_oh_item_internal(qpdf, filter_oh); - auto decode_parms = qpdf_oh_item_internal(qpdf, decode_parms_oh); - // XXX test with binary data with null - o.replaceStreamData( - std::string(reinterpret_cast(buf), len), - filter, decode_parms); - }); + do_with_oh_void( + qpdf, + stream_oh, + [qpdf, buf, len, filter_oh, decode_parms_oh](QPDFObjectHandle& o) { + QTC::TC("qpdf", "qpdf-c called qpdf_oh_replace_stream_data"); + auto filter = qpdf_oh_item_internal(qpdf, filter_oh); + auto decode_parms = qpdf_oh_item_internal(qpdf, decode_parms_oh); + // XXX test with binary data with null + o.replaceStreamData( + std::string(reinterpret_cast(buf), len), + filter, + decode_parms); + }); } -int qpdf_get_num_pages(qpdf_data qpdf) +int +qpdf_get_num_pages(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_num_pages"); int n = -1; QPDF_ERROR_CODE code = trap_errors(qpdf, [&n](qpdf_data q) { n = QIntC::to_int(q->qpdf->getAllPages().size()); }); - if (code & QPDF_ERRORS) - { + if (code & QPDF_ERRORS) { return -1; } return n; } -qpdf_oh qpdf_get_page_n(qpdf_data qpdf, size_t i) +qpdf_oh +qpdf_get_page_n(qpdf_data qpdf, size_t i) { QTC::TC("qpdf", "qpdf-c called qpdf_get_page_n"); qpdf_oh result = 0; QPDF_ERROR_CODE code = trap_errors(qpdf, [&result, i](qpdf_data q) { result = new_object(q, q->qpdf->getAllPages().at(i)); }); - if ((code & QPDF_ERRORS) || (result == 0)) - { + if ((code & QPDF_ERRORS) || (result == 0)) { return qpdf_oh_new_uninitialized(qpdf); } return result; } -QPDF_ERROR_CODE qpdf_update_all_pages_cache(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_update_all_pages_cache(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_update_all_pages_cache"); - return trap_errors(qpdf, [](qpdf_data q) { - q->qpdf->updateAllPagesCache(); - }); + return trap_errors( + qpdf, [](qpdf_data q) { q->qpdf->updateAllPagesCache(); }); } -int qpdf_find_page_by_id(qpdf_data qpdf, int objid, int generation) +int +qpdf_find_page_by_id(qpdf_data qpdf, int objid, int generation) { QTC::TC("qpdf", "qpdf-c called qpdf_find_page_by_id"); int n = -1; @@ -1942,14 +2121,14 @@ int qpdf_find_page_by_id(qpdf_data qpdf, int objid, int generation) QPDF_ERROR_CODE code = trap_errors(qpdf, [&n, &og](qpdf_data q) { n = QIntC::to_int(q->qpdf->findPage(og)); }); - if (code & QPDF_ERRORS) - { + if (code & QPDF_ERRORS) { return -1; } return n; } -int qpdf_find_page_by_oh(qpdf_data qpdf, qpdf_oh oh) +int +qpdf_find_page_by_oh(qpdf_data qpdf, qpdf_oh oh) { QTC::TC("qpdf", "qpdf-c called qpdf_find_page_by_oh"); return do_with_oh( @@ -1958,27 +2137,31 @@ int qpdf_find_page_by_oh(qpdf_data qpdf, qpdf_oh oh) }); } -QPDF_ERROR_CODE qpdf_push_inherited_attributes_to_page(qpdf_data qpdf) +QPDF_ERROR_CODE +qpdf_push_inherited_attributes_to_page(qpdf_data qpdf) { QTC::TC("qpdf", "qpdf-c called qpdf_push_inherited_attributes_to_page"); - return trap_errors(qpdf, [](qpdf_data q) { - q->qpdf->pushInheritedAttributesToPage(); - }); + return trap_errors( + qpdf, [](qpdf_data q) { q->qpdf->pushInheritedAttributesToPage(); }); } -QPDF_ERROR_CODE qpdf_add_page( +QPDF_ERROR_CODE +qpdf_add_page( qpdf_data qpdf, qpdf_data newpage_qpdf, qpdf_oh newpage, QPDF_BOOL first) { QTC::TC("qpdf", "qpdf-c called qpdf_add_page"); auto page = qpdf_oh_item_internal(newpage_qpdf, newpage); - return trap_errors(qpdf, [&page, first](qpdf_data q) { - q->qpdf->addPage(page, first); - }); + return trap_errors( + qpdf, [&page, first](qpdf_data q) { q->qpdf->addPage(page, first); }); } -QPDF_ERROR_CODE qpdf_add_page_at( - qpdf_data qpdf, qpdf_data newpage_qpdf, qpdf_oh newpage, - QPDF_BOOL before, qpdf_oh refpage) +QPDF_ERROR_CODE +qpdf_add_page_at( + qpdf_data qpdf, + qpdf_data newpage_qpdf, + qpdf_oh newpage, + QPDF_BOOL before, + qpdf_oh refpage) { QTC::TC("qpdf", "qpdf-c called qpdf_add_page_at"); auto page = qpdf_oh_item_internal(newpage_qpdf, newpage); @@ -1988,11 +2171,10 @@ QPDF_ERROR_CODE qpdf_add_page_at( }); } -QPDF_ERROR_CODE qpdf_remove_page(qpdf_data qpdf, qpdf_oh page) +QPDF_ERROR_CODE +qpdf_remove_page(qpdf_data qpdf, qpdf_oh page) { QTC::TC("qpdf", "qpdf-c called qpdf_remove_page"); auto p = qpdf_oh_item_internal(qpdf, page); - return trap_errors(qpdf, [&p](qpdf_data q) { - q->qpdf->removePage(p); - }); + return trap_errors(qpdf, [&p](qpdf_data q) { q->qpdf->removePage(p); }); } diff --git a/libqpdf/qpdf/AES_PDF_native.hh b/libqpdf/qpdf/AES_PDF_native.hh index d1f08631..186ebbae 100644 --- a/libqpdf/qpdf/AES_PDF_native.hh +++ b/libqpdf/qpdf/AES_PDF_native.hh @@ -9,8 +9,12 @@ class AES_PDF_native { public: // key should be a pointer to key_bytes bytes of data - AES_PDF_native(bool encrypt, unsigned char const* key, - size_t key_bytes, bool cbc_mode, unsigned char* cbc_block); + AES_PDF_native( + bool encrypt, + unsigned char const* key, + size_t key_bytes, + bool cbc_mode, + unsigned char* cbc_block); ~AES_PDF_native(); void update(unsigned char* in_data, unsigned char* out_data); diff --git a/libqpdf/qpdf/CryptoRandomDataProvider.hh b/libqpdf/qpdf/CryptoRandomDataProvider.hh index 581fd511..5bea502e 100644 --- a/libqpdf/qpdf/CryptoRandomDataProvider.hh +++ b/libqpdf/qpdf/CryptoRandomDataProvider.hh @@ -1,8 +1,8 @@ #ifndef CRYPTORANDOMDATAPROVIDER_HH #define CRYPTORANDOMDATAPROVIDER_HH -#include #include +#include class CryptoRandomDataProvider: public RandomDataProvider { diff --git a/libqpdf/qpdf/InsecureRandomDataProvider.hh b/libqpdf/qpdf/InsecureRandomDataProvider.hh index 76f2703a..2504c673 100644 --- a/libqpdf/qpdf/InsecureRandomDataProvider.hh +++ b/libqpdf/qpdf/InsecureRandomDataProvider.hh @@ -1,8 +1,8 @@ #ifndef INSECURERANDOMDATAPROVIDER_HH #define INSECURERANDOMDATAPROVIDER_HH -#include #include +#include class InsecureRandomDataProvider: public RandomDataProvider { diff --git a/libqpdf/qpdf/JSONHandler.hh b/libqpdf/qpdf/JSONHandler.hh index d7f08ead..a77d2b53 100644 --- a/libqpdf/qpdf/JSONHandler.hh +++ b/libqpdf/qpdf/JSONHandler.hh @@ -2,12 +2,12 @@ #define JSONHANDLER_HH #include -#include #include -#include -#include +#include #include +#include #include +#include // This class allows a sax-like walk through a JSON object with // functionality that mostly mirrors QPDFArgParser. It is primarily @@ -32,14 +32,14 @@ class JSONHandler // called. There is no "final" handler -- if the top-level is a // dictionary or array, just use its end handler. + typedef std::function + json_handler_t; + typedef std::function void_handler_t; typedef std::function json_handler_t; - typedef std::function void_handler_t; - typedef std::function string_handler_t; - typedef std::function bool_handler_t; + std::string const& path, std::string const& value)> + string_handler_t; + typedef std::function + bool_handler_t; // If an any handler is added, it will be called for any value // including null, and no other handler will be called. @@ -60,15 +60,16 @@ class JSONHandler QPDF_DLL void addDictHandlers(json_handler_t start_fn, void_handler_t end_fn); QPDF_DLL - void addDictKeyHandler( - std::string const& key, std::shared_ptr); + void + addDictKeyHandler(std::string const& key, std::shared_ptr); QPDF_DLL void addFallbackDictHandler(std::shared_ptr); QPDF_DLL - void addArrayHandlers(json_handler_t start_fn, - void_handler_t end_fn, - std::shared_ptr item_handlers); + void addArrayHandlers( + json_handler_t start_fn, + void_handler_t end_fn, + std::shared_ptr item_handlers); // Apply handlers recursively to a JSON object. QPDF_DLL diff --git a/libqpdf/qpdf/MD5.hh b/libqpdf/qpdf/MD5.hh index bbea5707..8a2f60fa 100644 --- a/libqpdf/qpdf/MD5.hh +++ b/libqpdf/qpdf/MD5.hh @@ -2,10 +2,10 @@ #define MD5_HH #include -#include #include -#include +#include #include +#include class MD5 { @@ -50,15 +50,16 @@ class MD5 QPDF_DLL static std::string getDataChecksum(char const* buf, size_t len); QPDF_DLL - static std::string getFileChecksum(char const* filename, - qpdf_offset_t up_to_offset = -1); + static std::string + getFileChecksum(char const* filename, qpdf_offset_t up_to_offset = -1); QPDF_DLL - static bool checkDataChecksum(char const* const checksum, - char const* buf, size_t len); + static bool + checkDataChecksum(char const* const checksum, char const* buf, size_t len); QPDF_DLL - static bool checkFileChecksum(char const* const checksum, - char const* filename, - qpdf_offset_t up_to_offset = -1); + static bool checkFileChecksum( + char const* const checksum, + char const* filename, + qpdf_offset_t up_to_offset = -1); private: void init(); diff --git a/libqpdf/qpdf/MD5_native.hh b/libqpdf/qpdf/MD5_native.hh index 47486589..2832a9c5 100644 --- a/libqpdf/qpdf/MD5_native.hh +++ b/libqpdf/qpdf/MD5_native.hh @@ -12,18 +12,18 @@ class MD5_native MD5_native(); void init(); - void update(unsigned char *, size_t); + void update(unsigned char*, size_t); void finalize(); void digest(Digest); private: static void transform(uint32_t[4], unsigned char[64]); - static void encode(unsigned char *, uint32_t *, size_t); - static void decode(uint32_t *, unsigned char *, size_t); + static void encode(unsigned char*, uint32_t*, size_t); + static void decode(uint32_t*, unsigned char*, size_t); - uint32_t state[4]; // state (ABCD) - uint32_t count[2]; // number of bits, modulo 2^64 (lsb first) - unsigned char buffer[64]; // input buffer + uint32_t state[4]; // state (ABCD) + uint32_t count[2]; // number of bits, modulo 2^64 (lsb first) + unsigned char buffer[64]; // input buffer bool finalized; Digest digest_val; diff --git a/libqpdf/qpdf/NNTree.hh b/libqpdf/qpdf/NNTree.hh index f9acc0d1..6ee2ee07 100644 --- a/libqpdf/qpdf/NNTree.hh +++ b/libqpdf/qpdf/NNTree.hh @@ -20,6 +20,7 @@ class NNTreeImpl; class NNTreeIterator { friend class NNTreeImpl; + public: typedef std::pair T; using iterator_category = std::bidirectional_iterator_tag; @@ -31,14 +32,16 @@ class NNTreeIterator virtual ~NNTreeIterator() = default; bool valid() const; NNTreeIterator& operator++(); - NNTreeIterator operator++(int) + NNTreeIterator + operator++(int) { NNTreeIterator t = *this; ++(*this); return t; } NNTreeIterator& operator--(); - NNTreeIterator operator--(int) + NNTreeIterator + operator--(int) { NNTreeIterator t = *this; --(*this); @@ -47,13 +50,13 @@ class NNTreeIterator reference operator*(); pointer operator->(); bool operator==(NNTreeIterator const& other) const; - bool operator!=(NNTreeIterator const& other) const + bool + operator!=(NNTreeIterator const& other) const { - return ! operator==(other); + return !operator==(other); } - void insertAfter( - QPDFObjectHandle key, QPDFObjectHandle value); + void insertAfter(QPDFObjectHandle key, QPDFObjectHandle value); void remove(); private: @@ -73,11 +76,11 @@ class NNTreeIterator void addPathElement(QPDFObjectHandle const& node, int kid_number); QPDFObjectHandle getNextKid(PathElement& element, bool backward); void increment(bool backward); - void resetLimits(QPDFObjectHandle node, - std::list::iterator parent); + void + resetLimits(QPDFObjectHandle node, std::list::iterator parent); - void split(QPDFObjectHandle to_split, - std::list::iterator parent); + void + split(QPDFObjectHandle to_split, std::list::iterator parent); std::list::iterator lastPathElement(); NNTreeImpl& impl; @@ -90,12 +93,16 @@ class NNTreeIterator class NNTreeImpl { friend class NNTreeIterator; + public: typedef NNTreeIterator iterator; // ABI: for qpdf 11, make qpdf a reference - NNTreeImpl(NNTreeDetails const&, QPDF*, QPDFObjectHandle&, - bool auto_repair = true); + NNTreeImpl( + NNTreeDetails const&, + QPDF*, + QPDFObjectHandle&, + bool auto_repair = true); iterator begin(); iterator end(); iterator last(); @@ -111,19 +118,18 @@ class NNTreeImpl private: void repair(); - iterator findInternal( - QPDFObjectHandle key, bool return_prev_if_not_found = false); + iterator + findInternal(QPDFObjectHandle key, bool return_prev_if_not_found = false); int withinLimits(QPDFObjectHandle key, QPDFObjectHandle node); int binarySearch( - QPDFObjectHandle key, QPDFObjectHandle items, - int num_items, bool return_prev_if_not_found, - int (NNTreeImpl::*compare)(QPDFObjectHandle& key, - QPDFObjectHandle& arr, - int item)); - int compareKeyItem( - QPDFObjectHandle& key, QPDFObjectHandle& items, int idx); - int compareKeyKid( - QPDFObjectHandle& key, QPDFObjectHandle& items, int idx); + QPDFObjectHandle key, + QPDFObjectHandle items, + int num_items, + bool return_prev_if_not_found, + int (NNTreeImpl::*compare)( + QPDFObjectHandle& key, QPDFObjectHandle& arr, int item)); + int compareKeyItem(QPDFObjectHandle& key, QPDFObjectHandle& items, int idx); + int compareKeyKid(QPDFObjectHandle& key, QPDFObjectHandle& items, int idx); NNTreeDetails const& details; QPDF* qpdf; diff --git a/libqpdf/qpdf/Pl_AES_PDF.hh b/libqpdf/qpdf/Pl_AES_PDF.hh index 87e4de55..880d7d32 100644 --- a/libqpdf/qpdf/Pl_AES_PDF.hh +++ b/libqpdf/qpdf/Pl_AES_PDF.hh @@ -13,9 +13,12 @@ class Pl_AES_PDF: public Pipeline public: QPDF_DLL // key should be a pointer to key_bytes bytes of data - Pl_AES_PDF(char const* identifier, Pipeline* next, - bool encrypt, unsigned char const* key, - size_t key_bytes); + Pl_AES_PDF( + char const* identifier, + Pipeline* next, + bool encrypt, + unsigned char const* key, + size_t key_bytes); QPDF_DLL virtual ~Pl_AES_PDF(); @@ -53,7 +56,7 @@ class Pl_AES_PDF: public Pipeline bool encrypt; bool cbc_mode; bool first; - size_t offset; // offset into memory buffer + size_t offset; // offset into memory buffer std::unique_ptr key; size_t key_bytes; unsigned char inbuf[buf_size]; diff --git a/libqpdf/qpdf/Pl_LZWDecoder.hh b/libqpdf/qpdf/Pl_LZWDecoder.hh index e034da05..5a9c9097 100644 --- a/libqpdf/qpdf/Pl_LZWDecoder.hh +++ b/libqpdf/qpdf/Pl_LZWDecoder.hh @@ -10,8 +10,8 @@ class Pl_LZWDecoder: public Pipeline { public: QPDF_DLL - Pl_LZWDecoder(char const* identifier, Pipeline* next, - bool early_code_change); + Pl_LZWDecoder( + char const* identifier, Pipeline* next, bool early_code_change); QPDF_DLL virtual ~Pl_LZWDecoder(); QPDF_DLL @@ -30,7 +30,7 @@ class Pl_LZWDecoder: public Pipeline unsigned int code_size; unsigned int next; unsigned int byte_pos; - unsigned int bit_pos; // left to right: 01234567 + unsigned int bit_pos; // left to right: 01234567 unsigned int bits_available; // members used for handle LZW decompression diff --git a/libqpdf/qpdf/Pl_MD5.hh b/libqpdf/qpdf/Pl_MD5.hh index 08a93706..269e84a8 100644 --- a/libqpdf/qpdf/Pl_MD5.hh +++ b/libqpdf/qpdf/Pl_MD5.hh @@ -9,8 +9,8 @@ // calling finish(). The first call to write() after a call to // finish() initializes a new MD5 object. -#include #include +#include class Pl_MD5: public Pipeline { diff --git a/libqpdf/qpdf/Pl_PNGFilter.hh b/libqpdf/qpdf/Pl_PNGFilter.hh index ebf87aa3..21750842 100644 --- a/libqpdf/qpdf/Pl_PNGFilter.hh +++ b/libqpdf/qpdf/Pl_PNGFilter.hh @@ -16,10 +16,13 @@ class Pl_PNGFilter: public Pipeline enum action_e { a_encode, a_decode }; QPDF_DLL - Pl_PNGFilter(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, - unsigned int samples_per_pixel = 1, - unsigned int bits_per_sample = 8); + Pl_PNGFilter( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int columns, + unsigned int samples_per_pixel = 1, + unsigned int bits_per_sample = 8); QPDF_DLL virtual ~Pl_PNGFilter(); @@ -41,8 +44,8 @@ class Pl_PNGFilter: public Pipeline action_e action; unsigned int bytes_per_row; unsigned int bytes_per_pixel; - unsigned char* cur_row; // points to buf1 or buf2 - unsigned char* prev_row; // points to buf1 or buf2 + unsigned char* cur_row; // points to buf1 or buf2 + unsigned char* prev_row; // points to buf1 or buf2 PointerHolder buf1; PointerHolder buf2; size_t pos; diff --git a/libqpdf/qpdf/Pl_RC4.hh b/libqpdf/qpdf/Pl_RC4.hh index 33e35d58..4154c18c 100644 --- a/libqpdf/qpdf/Pl_RC4.hh +++ b/libqpdf/qpdf/Pl_RC4.hh @@ -12,9 +12,12 @@ class Pl_RC4: public Pipeline // key_len of -1 means treat key_data as a null-terminated string QPDF_DLL - Pl_RC4(char const* identifier, Pipeline* next, - unsigned char const* key_data, int key_len = -1, - size_t out_bufsize = def_bufsize); + Pl_RC4( + char const* identifier, + Pipeline* next, + unsigned char const* key_data, + int key_len = -1, + size_t out_bufsize = def_bufsize); QPDF_DLL virtual ~Pl_RC4(); diff --git a/libqpdf/qpdf/Pl_TIFFPredictor.hh b/libqpdf/qpdf/Pl_TIFFPredictor.hh index 484f4df4..90c9ac05 100644 --- a/libqpdf/qpdf/Pl_TIFFPredictor.hh +++ b/libqpdf/qpdf/Pl_TIFFPredictor.hh @@ -12,10 +12,13 @@ class Pl_TIFFPredictor: public Pipeline enum action_e { a_encode, a_decode }; QPDF_DLL - Pl_TIFFPredictor(char const* identifier, Pipeline* next, - action_e action, unsigned int columns, - unsigned int samples_per_pixel = 1, - unsigned int bits_per_sample = 8); + Pl_TIFFPredictor( + char const* identifier, + Pipeline* next, + action_e action, + unsigned int columns, + unsigned int samples_per_pixel = 1, + unsigned int bits_per_sample = 8); QPDF_DLL virtual ~Pl_TIFFPredictor(); diff --git a/libqpdf/qpdf/QPDFArgParser.hh b/libqpdf/qpdf/QPDFArgParser.hh index cdc850f7..b73146fc 100644 --- a/libqpdf/qpdf/QPDFArgParser.hh +++ b/libqpdf/qpdf/QPDFArgParser.hh @@ -2,13 +2,13 @@ #define QPDFARGPARSER_HH #include -#include -#include -#include -#include -#include #include +#include +#include +#include #include +#include +#include // This is not a general-purpose argument parser. It is tightly // crafted to work with qpdf. qpdf's command-line syntax is very @@ -79,8 +79,10 @@ class QPDFArgParser void addOptionalParameter(std::string const& arg, param_arg_handler_t); QPDF_DLL void addChoices( - std::string const& arg, param_arg_handler_t, - bool required, char const** choices); + std::string const& arg, + param_arg_handler_t, + bool required, + char const** choices); // The default behavior when an invalid choice is specified with // an option that takes choices is to list all the choices. This @@ -137,16 +139,18 @@ class QPDFArgParser // Add a help topic along with the text for that topic QPDF_DLL - void addHelpTopic(std::string const& topic, - std::string const& short_text, - std::string const& long_text); + void addHelpTopic( + std::string const& topic, + std::string const& short_text, + std::string const& long_text); // Add help for an option, and associate it with a topic. QPDF_DLL - void addOptionHelp(std::string const& option_name, - std::string const& topic, - std::string const& short_text, - std::string const& long_text); + void addOptionHelp( + std::string const& option_name, + std::string const& topic, + std::string const& short_text, + std::string const& long_text); // Return the help text for a topic or option. Passing a null // pointer returns the top-level help information. Passing an @@ -158,12 +162,14 @@ class QPDFArgParser // Convenience methods for adding member functions of a class as // handlers. template - static bare_arg_handler_t bindBare(void (T::*f)(), T* o) + static bare_arg_handler_t + bindBare(void (T::*f)(), T* o) { return std::bind(std::mem_fn(f), o); } template - static param_arg_handler_t bindParam(void (T::*f)(std::string const&), T* o) + static param_arg_handler_t + bindParam(void (T::*f)(std::string const&), T* o) { return std::bind(std::mem_fn(f), o, std::placeholders::_1); } @@ -239,8 +245,8 @@ class QPDFArgParser void addOptionsToCompletions(option_table_t&); void addChoicesToCompletions( option_table_t&, std::string const&, std::string const&); - void insertCompletions( - option_table_t&, std::string const&, std::string const&); + void + insertCompletions(option_table_t&, std::string const&, std::string const&); void handleCompletion(); void getTopHelp(std::ostringstream&); diff --git a/libqpdf/qpdf/QPDFCrypto_gnutls.hh b/libqpdf/qpdf/QPDFCrypto_gnutls.hh index 18945cb8..73d5a199 100644 --- a/libqpdf/qpdf/QPDFCrypto_gnutls.hh +++ b/libqpdf/qpdf/QPDFCrypto_gnutls.hh @@ -27,8 +27,8 @@ class QPDFCrypto_gnutls: public QPDFCryptoImpl virtual void MD5_digest(MD5_Digest); virtual void RC4_init(unsigned char const* key_data, int key_len = -1); - virtual void RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0); + virtual void RC4_process( + unsigned char* in_data, size_t len, unsigned char* out_data = 0); virtual void RC4_finalize(); virtual void SHA2_init(int bits); @@ -37,10 +37,13 @@ class QPDFCrypto_gnutls: public QPDFCryptoImpl virtual std::string SHA2_digest(); virtual void rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block); - virtual void rijndael_process( - unsigned char* in_data, unsigned char* out_data); + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block); + virtual void + rijndael_process(unsigned char* in_data, unsigned char* out_data); virtual void rijndael_finalize(); private: diff --git a/libqpdf/qpdf/QPDFCrypto_native.hh b/libqpdf/qpdf/QPDFCrypto_native.hh index cd1909cc..9f5c7765 100644 --- a/libqpdf/qpdf/QPDFCrypto_native.hh +++ b/libqpdf/qpdf/QPDFCrypto_native.hh @@ -1,12 +1,12 @@ #ifndef QPDFCRYPTO_NATIVE_HH #define QPDFCRYPTO_NATIVE_HH +#include #include -#include #include +#include #include #include -#include #include class QPDFCrypto_native: public QPDFCryptoImpl @@ -25,8 +25,8 @@ class QPDFCrypto_native: public QPDFCryptoImpl virtual void MD5_digest(MD5_Digest); virtual void RC4_init(unsigned char const* key_data, int key_len = -1); - virtual void RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0); + virtual void RC4_process( + unsigned char* in_data, size_t len, unsigned char* out_data = 0); virtual void RC4_finalize(); virtual void SHA2_init(int bits); @@ -35,10 +35,13 @@ class QPDFCrypto_native: public QPDFCryptoImpl virtual std::string SHA2_digest(); virtual void rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block); - virtual void rijndael_process( - unsigned char* in_data, unsigned char* out_data); + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block); + virtual void + rijndael_process(unsigned char* in_data, unsigned char* out_data); virtual void rijndael_finalize(); private: diff --git a/libqpdf/qpdf/QPDFCrypto_openssl.hh b/libqpdf/qpdf/QPDFCrypto_openssl.hh index eb369c8a..a8fad041 100644 --- a/libqpdf/qpdf/QPDFCrypto_openssl.hh +++ b/libqpdf/qpdf/QPDFCrypto_openssl.hh @@ -13,10 +13,10 @@ #endif #include #ifdef OPENSSL_IS_BORINGSSL -#include -#include +# include +# include #else -#include +# include #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop @@ -38,8 +38,10 @@ class QPDFCrypto_openssl: public QPDFCryptoImpl void MD5_digest(MD5_Digest) override; void RC4_init(unsigned char const* key_data, int key_len = -1) override; - void RC4_process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0) override; + void RC4_process( + unsigned char* in_data, + size_t len, + unsigned char* out_data = 0) override; void RC4_finalize() override; void SHA2_init(int bits) override; @@ -48,10 +50,13 @@ class QPDFCrypto_openssl: public QPDFCryptoImpl std::string SHA2_digest() override; void rijndael_init( - bool encrypt, unsigned char const* key_data, size_t key_len, - bool cbc_mode, unsigned char* cbc_block) override; - void rijndael_process( - unsigned char* in_data, unsigned char* out_data) override; + bool encrypt, + unsigned char const* key_data, + size_t key_len, + bool cbc_mode, + unsigned char* cbc_block) override; + void + rijndael_process(unsigned char* in_data, unsigned char* out_data) override; void rijndael_finalize() override; private: diff --git a/libqpdf/qpdf/QPDF_Array.hh b/libqpdf/qpdf/QPDF_Array.hh index 7ea111a9..78e268fa 100644 --- a/libqpdf/qpdf/QPDF_Array.hh +++ b/libqpdf/qpdf/QPDF_Array.hh @@ -3,9 +3,9 @@ #include -#include -#include #include +#include +#include class QPDF_Array: public QPDFObject { diff --git a/libqpdf/qpdf/QPDF_Dictionary.hh b/libqpdf/qpdf/QPDF_Dictionary.hh index c4e236d3..4b8047df 100644 --- a/libqpdf/qpdf/QPDF_Dictionary.hh +++ b/libqpdf/qpdf/QPDF_Dictionary.hh @@ -3,8 +3,8 @@ #include -#include #include +#include #include diff --git a/libqpdf/qpdf/QPDF_Stream.hh b/libqpdf/qpdf/QPDF_Stream.hh index 3d70ea4e..d9d4e752 100644 --- a/libqpdf/qpdf/QPDF_Stream.hh +++ b/libqpdf/qpdf/QPDF_Stream.hh @@ -16,9 +16,13 @@ class QPDF; class QPDF_Stream: public QPDFObject { public: - QPDF_Stream(QPDF*, int objid, int generation, - QPDFObjectHandle stream_dict, - qpdf_offset_t offset, size_t length); + QPDF_Stream( + QPDF*, + int objid, + int generation, + QPDFObjectHandle stream_dict, + qpdf_offset_t offset, + size_t length); virtual ~QPDF_Stream(); virtual std::string unparse(); virtual JSON getJSON(); @@ -34,24 +38,29 @@ class QPDF_Stream: public QPDFObject qpdf_offset_t getOffset() const; size_t getLength() const; PointerHolder getStreamDataBuffer() const; - PointerHolder getStreamDataProvider() const; + PointerHolder + getStreamDataProvider() const; // See comments in QPDFObjectHandle.hh for these methods. - bool pipeStreamData(Pipeline*, bool* tried_filtering, - int encode_flags, - qpdf_stream_decode_level_e decode_level, - bool suppress_warnings, bool will_retry); + bool pipeStreamData( + Pipeline*, + bool* tried_filtering, + int encode_flags, + qpdf_stream_decode_level_e decode_level, + bool suppress_warnings, + bool will_retry); PointerHolder getStreamData(qpdf_stream_decode_level_e); PointerHolder getRawStreamData(); - void replaceStreamData(PointerHolder data, - QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms); + void replaceStreamData( + PointerHolder data, + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms); void replaceStreamData( PointerHolder provider, QPDFObjectHandle const& filter, QPDFObjectHandle const& decode_parms); - void addTokenFilter( - PointerHolder token_filter); + void + addTokenFilter(PointerHolder token_filter); void replaceDict(QPDFObjectHandle new_dict); @@ -69,15 +78,18 @@ class QPDF_Stream: public QPDFObject private: static std::map filter_abbreviations; - static std::map< - std::string, - std::function()>> filter_factories; + static std:: + map()>> + filter_factories; - void replaceFilterData(QPDFObjectHandle const& filter, - QPDFObjectHandle const& decode_parms, - size_t length); - bool filterable(std::vector>& filters, - bool& specialized_compression, bool& lossy_compression); + void replaceFilterData( + QPDFObjectHandle const& filter, + QPDFObjectHandle const& decode_parms, + size_t length); + bool filterable( + std::vector>& filters, + bool& specialized_compression, + bool& lossy_compression); void warn(QPDFExc const& e); void setDictDescription(); void setStreamDescription(); @@ -91,8 +103,7 @@ class QPDF_Stream: public QPDFObject size_t length; PointerHolder stream_data; PointerHolder stream_provider; - std::vector< - PointerHolder > token_filters; + std::vector> token_filters; }; #endif // QPDF_STREAM_HH diff --git a/libqpdf/qpdf/RC4.hh b/libqpdf/qpdf/RC4.hh index 22c43b36..58e12e2f 100644 --- a/libqpdf/qpdf/RC4.hh +++ b/libqpdf/qpdf/RC4.hh @@ -2,8 +2,8 @@ #define RC4_HH #include -#include #include +#include class RC4 { @@ -14,8 +14,8 @@ class RC4 // out_data = 0 means to encrypt/decrypt in place QPDF_DLL - void process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0); + void + process(unsigned char* in_data, size_t len, unsigned char* out_data = 0); private: std::shared_ptr crypto; diff --git a/libqpdf/qpdf/RC4_native.hh b/libqpdf/qpdf/RC4_native.hh index 08b3fc68..4693ff9f 100644 --- a/libqpdf/qpdf/RC4_native.hh +++ b/libqpdf/qpdf/RC4_native.hh @@ -10,8 +10,8 @@ class RC4_native RC4_native(unsigned char const* key_data, int key_len = -1); // out_data = 0 means to encrypt/decrypt in place - void process(unsigned char* in_data, size_t len, - unsigned char* out_data = 0); + void + process(unsigned char* in_data, size_t len, unsigned char* out_data = 0); private: class RC4Key diff --git a/libqpdf/qpdf/ResourceFinder.hh b/libqpdf/qpdf/ResourceFinder.hh index 8d3c6782..d037e600 100644 --- a/libqpdf/qpdf/ResourceFinder.hh +++ b/libqpdf/qpdf/ResourceFinder.hh @@ -11,17 +11,15 @@ class ResourceFinder: public QPDFObjectHandle::ParserCallbacks virtual void handleObject(QPDFObjectHandle, size_t, size_t) override; virtual void handleEOF() override; std::set const& getNames() const; - std::map>> const& getNamesByResourceType() const; + std::map>> const& + getNamesByResourceType() const; private: std::string last_name; size_t last_name_offset; std::set names; - std::map>> names_by_resource_type; + std::map>> + names_by_resource_type; }; #endif // RESOURCEFINDER_HH diff --git a/libqpdf/qpdf/SF_ASCII85Decode.hh b/libqpdf/qpdf/SF_ASCII85Decode.hh index b0b2f2e3..0b77d2e4 100644 --- a/libqpdf/qpdf/SF_ASCII85Decode.hh +++ b/libqpdf/qpdf/SF_ASCII85Decode.hh @@ -1,9 +1,9 @@ -#include #include +#include #include #ifndef SF_ASCII85DECODE_HH -#define SF_ASCII85DECODE_HH +# define SF_ASCII85DECODE_HH class SF_ASCII85Decode: public QPDFStreamFilter { @@ -11,14 +11,16 @@ class SF_ASCII85Decode: public QPDFStreamFilter SF_ASCII85Decode() = default; virtual ~SF_ASCII85Decode() = default; - virtual Pipeline* getDecodePipeline(Pipeline* next) override + virtual Pipeline* + getDecodePipeline(Pipeline* next) override { - this->pipeline = std::make_shared( - "ascii85 decode", next); + this->pipeline = + std::make_shared("ascii85 decode", next); return this->pipeline.get(); } - static std::shared_ptr factory() + static std::shared_ptr + factory() { return std::make_shared(); } diff --git a/libqpdf/qpdf/SF_ASCIIHexDecode.hh b/libqpdf/qpdf/SF_ASCIIHexDecode.hh index 869d0722..6454ce44 100644 --- a/libqpdf/qpdf/SF_ASCIIHexDecode.hh +++ b/libqpdf/qpdf/SF_ASCIIHexDecode.hh @@ -1,9 +1,9 @@ -#include #include +#include #include #ifndef SF_ASCIIHEXDECODE_HH -#define SF_ASCIIHEXDECODE_HH +# define SF_ASCIIHEXDECODE_HH class SF_ASCIIHexDecode: public QPDFStreamFilter { @@ -11,14 +11,16 @@ class SF_ASCIIHexDecode: public QPDFStreamFilter SF_ASCIIHexDecode() = default; virtual ~SF_ASCIIHexDecode() = default; - virtual Pipeline* getDecodePipeline(Pipeline* next) override + virtual Pipeline* + getDecodePipeline(Pipeline* next) override { - this->pipeline = std::make_shared( - "asciiHex decode", next); + this->pipeline = + std::make_shared("asciiHex decode", next); return this->pipeline.get(); } - static std::shared_ptr factory() + static std::shared_ptr + factory() { return std::make_shared(); } diff --git a/libqpdf/qpdf/SF_DCTDecode.hh b/libqpdf/qpdf/SF_DCTDecode.hh index 28aa42c1..f9b1af3a 100644 --- a/libqpdf/qpdf/SF_DCTDecode.hh +++ b/libqpdf/qpdf/SF_DCTDecode.hh @@ -1,9 +1,9 @@ -#include #include +#include #include #ifndef SF_DCTDECODE_HH -#define SF_DCTDECODE_HH +# define SF_DCTDECODE_HH class SF_DCTDecode: public QPDFStreamFilter { @@ -11,23 +11,27 @@ class SF_DCTDecode: public QPDFStreamFilter SF_DCTDecode() = default; virtual ~SF_DCTDecode() = default; - virtual Pipeline* getDecodePipeline(Pipeline* next) override + virtual Pipeline* + getDecodePipeline(Pipeline* next) override { this->pipeline = std::make_shared("DCT decode", next); return this->pipeline.get(); } - static std::shared_ptr factory() + static std::shared_ptr + factory() { return std::make_shared(); } - virtual bool isSpecializedCompression() override + virtual bool + isSpecializedCompression() override { return true; } - virtual bool isLossyCompression() override + virtual bool + isLossyCompression() override { return true; } diff --git a/libqpdf/qpdf/SF_FlateLzwDecode.hh b/libqpdf/qpdf/SF_FlateLzwDecode.hh index 9c72eff9..2230ec58 100644 --- a/libqpdf/qpdf/SF_FlateLzwDecode.hh +++ b/libqpdf/qpdf/SF_FlateLzwDecode.hh @@ -3,7 +3,7 @@ #include #ifndef SF_FLATELZWDECODE_HH -#define SF_FLATELZWDECODE_HH +# define SF_FLATELZWDECODE_HH class SF_FlateLzwDecode: public QPDFStreamFilter { diff --git a/libqpdf/qpdf/SF_RunLengthDecode.hh b/libqpdf/qpdf/SF_RunLengthDecode.hh index 1bdfb4c0..a1c8c80a 100644 --- a/libqpdf/qpdf/SF_RunLengthDecode.hh +++ b/libqpdf/qpdf/SF_RunLengthDecode.hh @@ -1,9 +1,9 @@ -#include #include +#include #include #ifndef SF_RUNLENGTHDECODE_HH -#define SF_RUNLENGTHDECODE_HH +# define SF_RUNLENGTHDECODE_HH class SF_RunLengthDecode: public QPDFStreamFilter { @@ -11,19 +11,22 @@ class SF_RunLengthDecode: public QPDFStreamFilter SF_RunLengthDecode() = default; virtual ~SF_RunLengthDecode() = default; - virtual Pipeline* getDecodePipeline(Pipeline* next) override + virtual Pipeline* + getDecodePipeline(Pipeline* next) override { this->pipeline = std::make_shared( "runlength decode", next, Pl_RunLength::a_decode); return this->pipeline.get(); } - static std::shared_ptr factory() + static std::shared_ptr + factory() { return std::make_shared(); } - virtual bool isSpecializedCompression() override + virtual bool + isSpecializedCompression() override { return true; } diff --git a/libqpdf/qpdf/SecureRandomDataProvider.hh b/libqpdf/qpdf/SecureRandomDataProvider.hh index 3f5ed19f..3e7893ed 100644 --- a/libqpdf/qpdf/SecureRandomDataProvider.hh +++ b/libqpdf/qpdf/SecureRandomDataProvider.hh @@ -1,8 +1,8 @@ #ifndef SECURERANDOMDATAPROVIDER_HH #define SECURERANDOMDATAPROVIDER_HH -#include #include +#include class SecureRandomDataProvider: public RandomDataProvider { diff --git a/libqpdf/qpdf/SparseOHArray.hh b/libqpdf/qpdf/SparseOHArray.hh index f23a871b..894cf7a1 100644 --- a/libqpdf/qpdf/SparseOHArray.hh +++ b/libqpdf/qpdf/SparseOHArray.hh @@ -26,7 +26,8 @@ class SparseOHArray QPDF_DLL void insert(size_t idx, QPDFObjectHandle oh); - typedef std::unordered_map::const_iterator const_iterator; + typedef std::unordered_map::const_iterator + const_iterator; QPDF_DLL const_iterator begin() const; QPDF_DLL diff --git a/libqpdf/qpdf/bits_functions.hh b/libqpdf/qpdf/bits_functions.hh index c00a0bcb..f6e385f6 100644 --- a/libqpdf/qpdf/bits_functions.hh +++ b/libqpdf/qpdf/bits_functions.hh @@ -1,11 +1,11 @@ #ifndef __BITS_FUNCTIONS_HH__ #define __BITS_FUNCTIONS_HH__ +#include +#include +#include #include #include -#include -#include -#include // This file is #included by specific source files, which must define // certain preprocessor symbols. These functions may be run at places @@ -17,8 +17,11 @@ #ifdef BITS_READ static unsigned long long -read_bits(unsigned char const*& p, size_t& bit_offset, - size_t& bits_available, size_t bits_wanted) +read_bits( + unsigned char const*& p, + size_t& bit_offset, + size_t& bits_available, + size_t bits_wanted) { // View p as a stream of bits: @@ -27,43 +30,41 @@ read_bits(unsigned char const*& p, size_t& bit_offset, // bit_offset is the bit number within the first byte that marks // the first bit that we would read. - if (bits_wanted > bits_available) - { + if (bits_wanted > bits_available) { throw std::runtime_error( "overflow reading bit stream: wanted = " + - QUtil::uint_to_string(bits_wanted) + "; available = " + - QUtil::uint_to_string(bits_available)); + QUtil::uint_to_string(bits_wanted) + + "; available = " + QUtil::uint_to_string(bits_available)); } - if (bits_wanted > 32) - { + if (bits_wanted > 32) { throw std::out_of_range("read_bits: too many bits requested"); } unsigned long result = 0; -#ifdef BITS_TESTING - if (bits_wanted == 0) - { +# ifdef BITS_TESTING + if (bits_wanted == 0) { QTC::TC("libtests", "bits zero bits wanted"); } -#endif - while (bits_wanted > 0) - { +# endif + while (bits_wanted > 0) { // Grab bits from the first byte clearing anything before // bit_offset. - unsigned char byte = static_cast( - *p & ((1U << (bit_offset + 1U)) - 1U)); + unsigned char byte = + static_cast(*p & ((1U << (bit_offset + 1U)) - 1U)); // There are bit_offset + 1 bits available in the first byte. size_t to_copy = std::min(bits_wanted, bit_offset + 1); size_t leftover = (bit_offset + 1) - to_copy; -#ifdef BITS_TESTING - QTC::TC("libtests", "bits bit_offset", - ((bit_offset == 0) ? 0 : - (bit_offset == 7) ? 1 : - 2)); +# ifdef BITS_TESTING + QTC::TC( + "libtests", + "bits bit_offset", + ((bit_offset == 0) ? 0 + : (bit_offset == 7) ? 1 + : 2)); QTC::TC("libtests", "bits leftover", (leftover > 0) ? 1 : 0); -#endif +# endif // Right shift so that all the bits we want are right justified. byte = static_cast(byte >> leftover); @@ -73,24 +74,23 @@ read_bits(unsigned char const*& p, size_t& bit_offset, result |= byte; // Update pointers - if (leftover) - { + if (leftover) { bit_offset = leftover - 1; - } - else - { + } else { bit_offset = 7; ++p; } bits_wanted -= to_copy; bits_available -= to_copy; -#ifdef BITS_TESTING - QTC::TC("libtests", "bits iterations", - ((bits_wanted > 8) ? 0 : - (bits_wanted > 0) ? 1 : - 2)); -#endif +# ifdef BITS_TESTING + QTC::TC( + "libtests", + "bits iterations", + ((bits_wanted > 8) ? 0 + : (bits_wanted > 0) ? 1 + : 2)); +# endif } return result; @@ -99,54 +99,53 @@ read_bits(unsigned char const*& p, size_t& bit_offset, #ifdef BITS_WRITE static void -write_bits(unsigned char& ch, size_t& bit_offset, - unsigned long long val, size_t bits, Pipeline* pipeline) +write_bits( + unsigned char& ch, + size_t& bit_offset, + unsigned long long val, + size_t bits, + Pipeline* pipeline) { - if (bits > 32) - { + if (bits > 32) { throw std::out_of_range("write_bits: too many bits requested"); } // bit_offset + 1 is the number of bits left in ch -#ifdef BITS_TESTING - if (bits == 0) - { +# ifdef BITS_TESTING + if (bits == 0) { QTC::TC("libtests", "bits write zero bits"); } -#endif - while (bits > 0) - { +# endif + while (bits > 0) { size_t bits_to_write = std::min(bits, bit_offset + 1); unsigned char newval = static_cast( (val >> (bits - bits_to_write)) & ((1U << bits_to_write) - 1)); size_t bits_left_in_ch = bit_offset + 1 - bits_to_write; newval = static_cast(newval << bits_left_in_ch); ch |= newval; - if (bits_left_in_ch == 0) - { -#ifdef BITS_TESTING + if (bits_left_in_ch == 0) { +# ifdef BITS_TESTING QTC::TC("libtests", "bits write pipeline"); -#endif +# endif pipeline->write(&ch, 1); bit_offset = 7; ch = 0; - } - else - { -#ifdef BITS_TESTING + } else { +# ifdef BITS_TESTING QTC::TC("libtests", "bits write leftover"); -#endif +# endif bit_offset -= bits_to_write; } bits -= bits_to_write; -#ifdef BITS_TESTING - QTC::TC("libtests", "bits write iterations", - ((bits > 8) ? 0 : - (bits > 0) ? 1 : - 2)); -#endif +# ifdef BITS_TESTING + QTC::TC( + "libtests", + "bits write iterations", + ((bits > 8) ? 0 + : (bits > 0) ? 1 + : 2)); +# endif } - } #endif diff --git a/libqpdf/qpdf/rijndael.h b/libqpdf/qpdf/rijndael.h index fa838fd9..5e059491 100644 --- a/libqpdf/qpdf/rijndael.h +++ b/libqpdf/qpdf/rijndael.h @@ -10,17 +10,23 @@ #endif #include -unsigned int rijndaelSetupEncrypt(uint32_t *rk, const unsigned char *key, - size_t keybits); -unsigned int rijndaelSetupDecrypt(uint32_t *rk, const unsigned char *key, - size_t keybits); -void rijndaelEncrypt(const uint32_t *rk, unsigned int nrounds, - const unsigned char plaintext[16], unsigned char ciphertext[16]); -void rijndaelDecrypt(const uint32_t *rk, unsigned int nrounds, - const unsigned char ciphertext[16], unsigned char plaintext[16]); +unsigned int +rijndaelSetupEncrypt(uint32_t* rk, const unsigned char* key, size_t keybits); +unsigned int +rijndaelSetupDecrypt(uint32_t* rk, const unsigned char* key, size_t keybits); +void rijndaelEncrypt( + const uint32_t* rk, + unsigned int nrounds, + const unsigned char plaintext[16], + unsigned char ciphertext[16]); +void rijndaelDecrypt( + const uint32_t* rk, + unsigned int nrounds, + const unsigned char ciphertext[16], + unsigned char plaintext[16]); -#define KEYLENGTH(keybits) ((keybits)/8) -#define RKLENGTH(keybits) ((keybits)/8+28) -#define NROUNDS(keybits) ((keybits)/32+6) +#define KEYLENGTH(keybits) ((keybits) / 8) +#define RKLENGTH(keybits) ((keybits) / 8 + 28) +#define NROUNDS(keybits) ((keybits) / 32 + 6) #endif diff --git a/libqpdf/qpdfjob-c.cc b/libqpdf/qpdfjob-c.cc index 8d8b9d7c..0e8ded02 100644 --- a/libqpdf/qpdfjob-c.cc +++ b/libqpdf/qpdfjob-c.cc @@ -1,26 +1,24 @@ #include #include -#include #include +#include #include #include -int qpdfjob_run_from_argv(char const* const argv[]) +int +qpdfjob_run_from_argv(char const* const argv[]) { auto whoami_p = QUtil::make_unique_cstr(argv[0]); auto whoami = QUtil::getWhoami(whoami_p.get()); QUtil::setLineBuf(stdout); QPDFJob j; - try - { + try { j.initializeFromArgv(argv); j.run(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; return QPDFJob::EXIT_ERROR; } @@ -28,11 +26,11 @@ int qpdfjob_run_from_argv(char const* const argv[]) } #ifndef QPDF_NO_WCHAR_T -int qpdfjob_run_from_wide_argv(wchar_t const* const argv[]) +int +qpdfjob_run_from_wide_argv(wchar_t const* const argv[]) { int argc = 0; - for (auto k = argv; *k; ++k) - { + for (auto k = argv; *k; ++k) { ++argc; } return QUtil::call_main_from_wmain( @@ -42,16 +40,14 @@ int qpdfjob_run_from_wide_argv(wchar_t const* const argv[]) } #endif // QPDF_NO_WCHAR_T -int qpdfjob_run_from_json(char const* json) +int +qpdfjob_run_from_json(char const* json) { QPDFJob j; - try - { + try { j.initializeFromJson(json); j.run(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "qpdfjob json: " << e.what() << std::endl; return QPDFJob::EXIT_ERROR; } diff --git a/libtests/aes.cc b/libtests/aes.cc index 71348744..3ad491cc 100644 --- a/libtests/aes.cc +++ b/libtests/aes.cc @@ -1,14 +1,15 @@ #include #include -#include #include +#include -#include -#include #include +#include #include +#include -static void usage() +static void +usage() { std::cerr << "Usage: aes options hex-key infile outfile" << std::endl << " -cbc -- disable CBC mode" << std::endl @@ -16,13 +17,15 @@ static void usage() << " -encrypt -- encrypt" << std::endl << " -decrypt -- decrypt CBC mode" << std::endl << " -zero-iv -- use zero initialization vector" << std::endl - << " -static-iv -- use static initialization vector" << std::endl + << " -static-iv -- use static initialization vector" + << std::endl << " -no-padding -- disable padding" << std::endl << "Options must precede key and file names." << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { bool encrypt = true; bool cbc_mode = true; @@ -33,58 +36,36 @@ int main(int argc, char* argv[]) bool static_iv = false; bool disable_padding = false; - for (int i = 1; i < argc; ++i) - { + for (int i = 1; i < argc; ++i) { char* arg = argv[i]; - if ((arg[0] == '-') || (arg[0] == '+')) - { - if (strcmp(arg, "-cbc") == 0) - { + if ((arg[0] == '-') || (arg[0] == '+')) { + if (strcmp(arg, "-cbc") == 0) { cbc_mode = false; - } - else if (strcmp(arg, "+cbc") == 0) - { + } else if (strcmp(arg, "+cbc") == 0) { cbc_mode = true; - } - else if (strcmp(arg, "-decrypt") == 0) - { + } else if (strcmp(arg, "-decrypt") == 0) { encrypt = false; - } - else if (strcmp(arg, "-encrypt") == 0) - { + } else if (strcmp(arg, "-encrypt") == 0) { encrypt = true; - } - else if (strcmp(arg, "-zero-iv") == 0) - { + } else if (strcmp(arg, "-zero-iv") == 0) { zero_iv = true; - } - else if (strcmp(arg, "-static-iv") == 0) - { + } else if (strcmp(arg, "-static-iv") == 0) { static_iv = true; - } - else if (strcmp(arg, "-no-padding") == 0) - { + } else if (strcmp(arg, "-no-padding") == 0) { disable_padding = true; - } - else - { + } else { usage(); } - } - else if (argc == i + 3) - { + } else if (argc == i + 3) { hexkey = argv[i]; - infilename = argv[i+1]; - outfilename = argv[i+2]; + infilename = argv[i + 1]; + outfilename = argv[i + 2]; break; - } - else - { + } else { usage(); } } - if (outfilename == 0) - { + if (outfilename == 0) { usage(); } @@ -94,50 +75,40 @@ int main(int argc, char* argv[]) FILE* infile = QUtil::safe_fopen(infilename, "rb"); FILE* outfile = QUtil::safe_fopen(outfilename, "wb"); unsigned char* key = new unsigned char[keylen]; - for (unsigned int i = 0; i < strlen(hexkey); i += 2) - { + for (unsigned int i = 0; i < strlen(hexkey); i += 2) { char t[3]; t[0] = hexkey[i]; t[1] = hexkey[i + 1]; t[2] = '\0'; long val = strtol(t, 0, 16); - key[i/2] = static_cast(val); + key[i / 2] = static_cast(val); } Pl_StdioFile* out = new Pl_StdioFile("stdout", outfile); Pl_AES_PDF* aes = new Pl_AES_PDF("aes_128_cbc", out, encrypt, key, keylen); - delete [] key; + delete[] key; key = 0; - if (! cbc_mode) - { + if (!cbc_mode) { aes->disableCBC(); } - if (zero_iv) - { + if (zero_iv) { aes->useZeroIV(); - } - else if (static_iv) - { + } else if (static_iv) { aes->useStaticIV(); } - if (disable_padding) - { + if (disable_padding) { aes->disablePadding(); } // 16 < buffer size, buffer_size is not a multiple of 8 for testing unsigned char buf[83]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { aes->write(buf, len); } } diff --git a/libtests/arg_parser.cc b/libtests/arg_parser.cc index 4b10709e..8b4d556a 100644 --- a/libtests/arg_parser.cc +++ b/libtests/arg_parser.cc @@ -1,8 +1,8 @@ #include -#include #include -#include +#include #include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -59,39 +59,39 @@ ArgParser::initOptions() char const* choices[] = {"pig", "boar", "sow", 0}; ap.addChoices("oink", p(&ArgParser::handleOink), true, choices); ap.selectHelpOptionTable(); - ap.addBare("version", [this](){ output("3.14159"); }); + ap.addBare("version", [this]() { output("3.14159"); }); ap.selectMainOptionTable(); ap.addBare("quack", b(&ArgParser::startQuack)); ap.registerOptionTable("quack", b(&ArgParser::endQuack)); ap.addPositional(p(&ArgParser::getQuack)); ap.addFinalCheck(b(&ArgParser::finalChecks)); ap.selectMainOptionTable(); - ap.addBare("baaa", [this](){ this->ap.selectOptionTable("baaa"); }); + ap.addBare("baaa", [this]() { this->ap.selectOptionTable("baaa"); }); ap.registerOptionTable("baaa", nullptr); - ap.addBare("ewe", [this](){ output("you"); }); - ap.addBare("ram", [this](){ output("ram"); }); + ap.addBare("ewe", [this]() { output("you"); }); + ap.addBare("ram", [this]() { output("ram"); }); ap.selectMainOptionTable(); - ap.addBare("sheep", [this](){ this->ap.selectOptionTable("sheep"); }); + ap.addBare("sheep", [this]() { this->ap.selectOptionTable("sheep"); }); ap.registerOptionTable("sheep", nullptr); ap.addHelpFooter("For more help, read the manual.\n"); ap.addHelpTopic( - "quack", "Quack Options", + "quack", + "Quack Options", "Just put stuff after quack to get a count at the end.\n"); ap.addHelpTopic( - "baaa", "Baaa Options", + "baaa", + "Baaa Options", "Ewe can do sheepish things.\n" "For example, ewe can add more ram to your computer.\n"); - ap.addOptionHelp("--ewe", "baaa", - "just for ewe", "You are not a ewe.\n"); + ap.addOptionHelp("--ewe", "baaa", "just for ewe", "You are not a ewe.\n"); ap.addOptionHelp("--ram", "baaa", "curly horns", ""); } void ArgParser::output(std::string const& msg) { - if (! this->ap.isCompleting()) - { + if (!this->ap.isCompleting()) { std::cout << msg << std::endl; } } @@ -130,10 +130,8 @@ void ArgParser::startQuack() { this->ap.selectOptionTable("quack"); - if (this->ap.isCompleting()) - { - if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) - { + if (this->ap.isCompleting()) { + if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) { this->ap.insertCompletion("something"); this->ap.insertCompletion("anything"); } @@ -145,8 +143,7 @@ void ArgParser::getQuack(std::string const& p) { ++this->quacks; - if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) - { + if (this->ap.isCompleting() && (this->ap.argsLeft() == 0)) { this->ap.insertCompletion( std::string("thing-") + QUtil::int_to_string(this->quacks)); return; @@ -170,74 +167,56 @@ void ArgParser::test_exceptions() { auto err = [](char const* msg, std::function fn) { - try - { + try { fn(); assert(msg == nullptr); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << msg << ": " << e.what() << std::endl; } }; err("duplicate handler", [this]() { ap.selectMainOptionTable(); - ap.addBare("potato", [](){}); + ap.addBare("potato", []() {}); }); err("duplicate handler", [this]() { ap.selectOptionTable("baaa"); - ap.addBare("ram", [](){}); - }); - err("duplicate table", [this]() { - ap.registerOptionTable("baaa", nullptr); - }); - err("unknown table", [this]() { - ap.selectOptionTable("aardvark"); - }); - err("add existing help topic", [this]() { - ap.addHelpTopic("baaa", "potato", "salad"); - }); - err("add reserved help topic", [this]() { - ap.addHelpTopic("all", "potato", "salad"); - }); - err("add to unknown topic", [this]() { - ap.addOptionHelp("--new", "oops", "potato", "salad"); - }); - err("bad option for help", [this]() { - ap.addOptionHelp("nodash", "baaa", "potato", "salad"); - }); - err("bad topic for help", [this]() { - ap.addHelpTopic("--dashes", "potato", "salad"); - }); - err("duplicate option help", [this]() { - ap.addOptionHelp("--ewe", "baaa", "potato", "salad"); + ap.addBare("ram", []() {}); }); + err("duplicate table", + [this]() { ap.registerOptionTable("baaa", nullptr); }); + err("unknown table", [this]() { ap.selectOptionTable("aardvark"); }); + err("add existing help topic", + [this]() { ap.addHelpTopic("baaa", "potato", "salad"); }); + err("add reserved help topic", + [this]() { ap.addHelpTopic("all", "potato", "salad"); }); + err("add to unknown topic", + [this]() { ap.addOptionHelp("--new", "oops", "potato", "salad"); }); + err("bad option for help", + [this]() { ap.addOptionHelp("nodash", "baaa", "potato", "salad"); }); + err("bad topic for help", + [this]() { ap.addHelpTopic("--dashes", "potato", "salad"); }); + err("duplicate option help", + [this]() { ap.addOptionHelp("--ewe", "baaa", "potato", "salad"); }); err("invalid choice handler to unknown", [this]() { - ap.addInvalidChoiceHandler( - "elephant", [](std::string const&){}); + ap.addInvalidChoiceHandler("elephant", [](std::string const&) {}); }); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { ArgParser ap(argc, argv); - if ((argc == 2) && (strcmp(argv[1], "exceptions") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "exceptions") == 0)) { ap.test_exceptions(); return 0; } - try - { + try { ap.parseArgs(); - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { std::cerr << "usage: " << e.what() << std::endl; exit(2); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; exit(3); } diff --git a/libtests/ascii85.cc b/libtests/ascii85.cc index 91f3b7f5..2acc56ba 100644 --- a/libtests/ascii85.cc +++ b/libtests/ascii85.cc @@ -4,31 +4,25 @@ #include #include -int main() +int +main() { Pl_StdioFile out("stdout", stdout); Pl_ASCII85Decoder decode("decode", &out); - try - { + try { unsigned char buf[10000]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), stdin); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { decode.write(buf, len); } } decode.finish(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/libtests/bits.cc b/libtests/bits.cc index 2c3dc349..07870eb7 100644 --- a/libtests/bits.cc +++ b/libtests/bits.cc @@ -1,8 +1,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -14,8 +14,7 @@ #include static void -print_values(long long byte_offset, size_t bit_offset, - size_t bits_available) +print_values(long long byte_offset, size_t bit_offset, size_t bits_available) { std::cout << "byte offset = " << byte_offset << ", " << "bit offset = " << bit_offset << ", " @@ -23,9 +22,12 @@ print_values(long long byte_offset, size_t bit_offset, } static void -test_read_bits(unsigned char const* buf, - unsigned char const*& p, size_t& bit_offset, - size_t& bits_available, size_t bits_wanted) +test_read_bits( + unsigned char const* buf, + unsigned char const*& p, + size_t& bit_offset, + size_t& bits_available, + size_t bits_wanted) { unsigned long result = QIntC::to_ulong(read_bits(p, bit_offset, bits_available, bits_wanted)); @@ -36,8 +38,12 @@ test_read_bits(unsigned char const* buf, } static void -test_write_bits(unsigned char& ch, size_t& bit_offset, unsigned long val, - size_t bits, Pl_Buffer* bp) +test_write_bits( + unsigned char& ch, + size_t& bit_offset, + unsigned long val, + size_t bits, + Pl_Buffer* bp) { write_bits(ch, bit_offset, val, bits, bp); std::cout << "ch = " << QUtil::uint_to_string_base(ch, 16, 2) @@ -51,8 +57,7 @@ print_buffer(Pl_Buffer* bp) Buffer* b = bp->getBuffer(); unsigned char const* p = b->getBuffer(); size_t l = b->getSize(); - for (unsigned long i = 0; i < l; ++i) - { + for (unsigned long i = 0; i < l; ++i) { std::cout << QUtil::uint_to_string_base(p[i], 16, 2) << ((i == l - 1) ? "\n" : " "); } @@ -69,8 +74,7 @@ test() // Read tests static unsigned char const buf[] = { - 0xF5, 0x15, 0x65, 0x79, 0x12, 0x89, 0x75, 0x4B - }; + 0xF5, 0x15, 0x65, 0x79, 0x12, 0x89, 0x75, 0x4B}; unsigned char const* p = buf; size_t bit_offset = 7; @@ -89,12 +93,9 @@ test() test_read_bits(buf, p, bit_offset, bits_available, 0); test_read_bits(buf, p, bit_offset, bits_available, 25); - try - { + try { test_read_bits(buf, p, bit_offset, bits_available, 4); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << "exception: " << e.what() << std::endl; print_values(p - buf, bit_offset, bits_available); } @@ -179,14 +180,12 @@ test() delete bp; } -int main() +int +main() { - try - { + try { test(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << "unexpected exception: " << e.what() << std::endl; exit(2); } diff --git a/libtests/buffer.cc b/libtests/buffer.cc index 5dfe55f8..a24c0f99 100644 --- a/libtests/buffer.cc +++ b/libtests/buffer.cc @@ -2,10 +2,10 @@ #include #include #include -#include -#include -#include #include +#include +#include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -13,12 +13,14 @@ #endif #include -static unsigned char* uc(char const* s) +static unsigned char* +uc(char const* s) { return QUtil::unsigned_char_pointer(s); } -int main() +int +main() { { // Test that buffers can be copied by value. @@ -39,8 +41,7 @@ int main() assert(bc2p[1] == 'W'); } - try - { + try { Pl_Discard discard; Pl_Count count("count", &discard); Pl_Buffer bp1("bp1", &count); @@ -68,12 +69,9 @@ int main() Pl_Buffer bp2("bp2"); bp2.write(uc("moo"), 3); bp2.write(uc("quack"), 6); - try - { + try { delete bp2.getBuffer(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << e.what() << std::endl; } bp2.finish(); @@ -84,9 +82,7 @@ int main() unsigned char lbuf[10]; Buffer b1(lbuf, 10); - if (! ((b1.getBuffer() == lbuf) && - (b1.getSize() == 10))) - { + if (!((b1.getBuffer() == lbuf) && (b1.getSize() == 10))) { throw std::logic_error("hand-created buffer is not as expected"); } @@ -110,13 +106,10 @@ int main() bp4.write(uc("asdf"), 4); unsigned char* mbuf; size_t len; - try - { + try { bp4.getMallocBuffer(&mbuf, &len); assert(false); - } - catch (std::logic_error& e) - { + } catch (std::logic_error& e) { std::cout << "malloc buffer logic error: " << e.what() << std::endl; } bp4.finish(); @@ -129,9 +122,7 @@ int main() bp4.getMallocBuffer(&mbuf, &len); assert(mbuf == nullptr); assert(len == 0); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << "unexpected exception: " << e.what() << std::endl; exit(2); } diff --git a/libtests/closed_file_input_source.cc b/libtests/closed_file_input_source.cc index f3e4f2ac..ff5354fb 100644 --- a/libtests/closed_file_input_source.cc +++ b/libtests/closed_file_input_source.cc @@ -1,20 +1,21 @@ #include #include -#include -#include #include +#include #include +#include -void check(std::string const& what, bool result) +void +check(std::string const& what, bool result) { - if (! result) - { + if (!result) { std::cout << "FAIL: " << what << std::endl; } } -void do_tests(InputSource* is) +void +do_tests(InputSource* is) { check("get name", "input" == is->getName()); check("initial tell", 0 == is->tell()); @@ -59,7 +60,8 @@ void do_tests(InputSource* is) check("last offset after read 0", 0 == is->getLastOffset()); } -int main() +int +main() { // This test is designed to work with a specified input file. std::cout << "testing with ClosedFileInputSource\n"; diff --git a/libtests/concatenate.cc b/libtests/concatenate.cc index 84fee2bb..10902adf 100644 --- a/libtests/concatenate.cc +++ b/libtests/concatenate.cc @@ -1,6 +1,6 @@ +#include #include #include -#include #include #include @@ -10,13 +10,15 @@ #endif #include -static void pipeStringAndFinish(Pipeline* p, std::string const& str) +static void +pipeStringAndFinish(Pipeline* p, std::string const& str) { p->write(QUtil::unsigned_char_pointer(str), str.length()); p->finish(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { Pl_Buffer b1("compressed"); Pl_Flate deflate("compress", &b1, Pl_Flate::a_deflate); @@ -31,14 +33,11 @@ int main(int argc, char* argv[]) inflate.write(b1_buf->getBuffer(), b1_buf->getSize()); inflate.finish(); auto b2_buf = b2.getBufferSharedPointer(); - std::string result(reinterpret_cast(b2_buf->getBuffer()), - b2_buf->getSize()); - if (result == "-one--two-") - { + std::string result( + reinterpret_cast(b2_buf->getBuffer()), b2_buf->getSize()); + if (result == "-one--two-") { std::cout << "concatenate test passed" << std::endl; - } - else - { + } else { std::cout << "concatenate test failed: " << result << std::endl; } return 0; diff --git a/libtests/cxx11.cc b/libtests/cxx11.cc index 5ad3e6ed..fbf3cc38 100644 --- a/libtests/cxx11.cc +++ b/libtests/cxx11.cc @@ -1,13 +1,13 @@ -#include -#include -#include -#include -#include #include -#include +#include +#include +#include +#include #include #include #include +#include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -18,29 +18,31 @@ // Functional programming // Function that returns a callable in the form of a lambda -std::function make_adder(int x) +std::function +make_adder(int x) { - return ([=](int a) -> int{ return x + a; }); + return ([=](int a) -> int { return x + a; }); } -void do_functional() +void +do_functional() { // Lambda with no capture - auto simple_lambda = [](int a){ return a + 3; }; + auto simple_lambda = [](int a) { return a + 3; }; assert(simple_lambda(5) == 8); // Capture by value int x = 5; - auto by_value = [x](int a){ return a + x; }; + auto by_value = [x](int a) { return a + x; }; assert(by_value(1) == 6); x = 7; // change not seen by lambda assert(by_value(1) == 6); // Also >> at end of template - assert((std::is_convertible>::value)); + assert((std::is_convertible>:: + value)); // Capture by reference - auto by_reference = [&x](int a){ return a + x; }; + auto by_reference = [&x](int a) { return a + x; }; assert(by_reference(1) == 8); x = 8; // change seen my lambda assert(by_reference(1) == 9); @@ -49,29 +51,29 @@ void do_functional() auto add3 = make_adder(3); assert(add3(5) == 8); - auto make_addr_lambda = [](int a) { - return [a](int b) { return a + b; }; - }; + auto make_addr_lambda = [](int a) { return [a](int b) { return a + b; }; }; assert(make_addr_lambda(6)(8) == 14); // nullptr and {} are empty functions std::function f1 = {}; - assert(! f1); + assert(!f1); std::function f2 = nullptr; - assert(! f2); + assert(!f2); } // Integer types, type traits template -void check_size(size_t size, bool is_signed) +void +check_size(size_t size, bool is_signed) { assert(sizeof(T) == size); assert(std::is_signed::value == is_signed); } -void do_inttypes() +void +do_inttypes() { // static_assert is a compile-time check static_assert(1 == sizeof(int8_t), "int8_t check"); @@ -99,10 +101,12 @@ class A { } // Constructor delegation - A() : A(def_value) + A() : + A(def_value) { } - int getX() const + int + getX() const { return x; } @@ -111,66 +115,71 @@ class A int x; }; -void do_iteration() +void +do_iteration() { // Initializers, foreach syntax, auto for iterators - std::vector v = { 1, 2, 3, 4 }; + std::vector v = {1, 2, 3, 4}; assert(v.size() == 4); int sum = 0; - for (auto& i: v) - { + for (auto& i : v) { sum += i; } assert(10 == sum); - for (auto i = v.begin(); i != v.end(); ++i) - { + for (auto i = v.begin(); i != v.end(); ++i) { sum += *i; } assert(20 == sum); - std::vector v2 = { A(), A(3) }; + std::vector v2 = {A(), A(3)}; assert(5 == v2.at(0).getX()); assert(3 == v2.at(1).getX()); } // Variadic template -template -void variadic1(A1 const& a1) +template +void +variadic1(A1 const& a1) { assert(a1 == 12); } -template -void variadic1(A1 const& a1, A2 const& a2) +template +void +variadic1(A1 const& a1, A2 const& a2) { assert(a1 == a2); } -template -void variadic(Args... args) +template +void +variadic(Args... args) { variadic1(args...); } -template -bool pairwise_equal(A const& a, A const& b) +template +bool +pairwise_equal(A const& a, A const& b) { return (a == b); } -template -bool pairwise_equal(T const& a, T const& b, Rest... rest) +template +bool +pairwise_equal(T const& a, T const& b, Rest... rest) { return pairwise_equal(a, b) && pairwise_equal(rest...); } -void do_variadic() +void +do_variadic() { variadic(15, 15); variadic(12); assert(pairwise_equal(5, 5, 2.0, 2.0, std::string("a"), std::string("a"))); - assert(! pairwise_equal(5, 5, 2.0, 3.0)); + assert(!pairwise_equal(5, 5, 2.0, 3.0)); } // deleted, default @@ -182,10 +191,12 @@ class B x(x) { } - B() : B(5) + B() : + B(5) { } - int getX() const + int + getX() const { return x; } @@ -198,12 +209,13 @@ class B int x; }; -void do_default_deleted() +void +do_default_deleted() { B b1; assert(5 == b1.getX()); assert(std::is_copy_constructible::value); - assert(! std::is_copy_constructible::value); + assert(!std::is_copy_constructible::value); } // smart pointers @@ -220,38 +232,40 @@ class C { decr(id); } - C(C const& rhs) : C(rhs.id) + C(C const& rhs) : + C(rhs.id) { } - C& operator=(C const& rhs) + C& + operator=(C const& rhs) { - if (&rhs != this) - { + if (&rhs != this) { decr(id); id = rhs.id; incr(id); } return *this; } - static void check(size_t size, int v, int count) + static void + check(size_t size, int v, int count) { assert(m.size() == size); auto p = m.find(v); - if (p != m.end()) - { + if (p != m.end()) { assert(p->second == count); } } private: - void incr(int i) + void + incr(int i) { ++m[i]; } - void decr(int i) + void + decr(int i) { - if (--m[i] == 0) - { + if (--m[i] == 0) { m.erase(i); } } @@ -262,29 +276,30 @@ class C std::map C::m; -std::shared_ptr make_c(int id) +std::shared_ptr +make_c(int id) { return std::make_shared(id); } -std::shared_ptr make_c_array(std::vector const& is) +std::shared_ptr +make_c_array(std::vector const& is) { auto p = std::shared_ptr(new C[is.size()], std::default_delete()); C* pp = p.get(); - for (size_t i = 0; i < is.size(); ++i) - { + for (size_t i = 0; i < is.size(); ++i) { pp[i] = C(is.at(i)); } return p; } -void do_smart_pointers() +void +do_smart_pointers() { auto p1 = make_c(1); C::check(1, 1, 1); auto p2 = make_c_array({2, 3, 4, 5}); - for (auto i: {1, 2, 3, 4, 5}) - { + for (auto i : {1, 2, 3, 4, 5}) { C::check(5, i, 1); } { @@ -306,7 +321,8 @@ void do_smart_pointers() // Regular expressions -void do_regex() +void +do_regex() { // Basic match/search. Match matches whole string; search searches // within string. Use std::smatch for matching std::string and @@ -320,9 +336,9 @@ void do_regex() std::string str4("234"); std::string str5("234 five 678"); std::smatch match1; - assert(! std::regex_match(str1, match1, expr1)); - assert(! std::regex_match(str2, match1, expr1)); - assert(! std::regex_match(str3, match1, expr1)); + assert(!std::regex_match(str1, match1, expr1)); + assert(!std::regex_match(str2, match1, expr1)); + assert(!std::regex_match(str3, match1, expr1)); assert(std::regex_match(str4, match1, expr1)); assert(match1[0].first == match1[1].first); assert(match1[0].second == match1[1].second); @@ -347,8 +363,7 @@ void do_regex() std::sregex_iterator m1(str6.begin(), str6.end(), expr3); std::sregex_iterator m2; s.clear(); - for (std::sregex_iterator iter = m1; iter != m2; ++iter) - { + for (std::sregex_iterator iter = m1; iter != m2; ++iter) { std::smatch const& match2 = *iter; s += match2[0].str() + "|"; } @@ -360,24 +375,25 @@ void do_regex() std::cregex_iterator m3(str7, str7 + std::strlen(str7), expr4); assert("asdf" == (*m3)[0].str()); assert((*m3)[1].matched); - assert(! (*m3)[2].matched); + assert(!(*m3)[2].matched); ++m3; assert("qwer" == (*m3)[0].str()); - assert(! (*m3)[1].matched); + assert(!(*m3)[1].matched); assert((*m3)[2].matched); } -static long operator ""_x(char const* v) +static long operator""_x(char const* v) { return strtol(v, nullptr, 16); } -static std::string operator ""_y(char const* v, size_t len) +static std::string operator""_y(char const* v, size_t len) { return "y" + std::string(v, len) + "y"; } -void do_user_defined_literals() +void +do_user_defined_literals() { assert(10_x == 16); // operator""_x("10") assert("abc"_y == "yabcy"); // operator""_y("abc", 3) @@ -390,7 +406,8 @@ void do_user_defined_literals() // assert(R"x(a)"bc)x"_y == "ya)\"bcy"); } -int main() +int +main() { do_functional(); do_inttypes(); diff --git a/libtests/dct_compress.cc b/libtests/dct_compress.cc index 2a583ffd..446d4d0a 100644 --- a/libtests/dct_compress.cc +++ b/libtests/dct_compress.cc @@ -2,12 +2,13 @@ #include #include -#include -#include #include +#include #include +#include -static void usage() +static void +usage() { std::cerr << "Usage: dct_compress infile outfile width height" << " {rgb|cmyk|gray}" << std::endl; @@ -28,15 +29,16 @@ class Callback: public Pl_DCT::CompressConfig bool called; }; -void Callback::apply(jpeg_compress_struct*) +void +Callback::apply(jpeg_compress_struct*) { this->called = true; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 6) - { + if (argc != 6) { usage(); } @@ -46,23 +48,22 @@ int main(int argc, char* argv[]) JDIMENSION height = QUtil::string_to_uint(argv[4]); char* colorspace = argv[5]; J_COLOR_SPACE cs = - ((strcmp(colorspace, "rgb") == 0) ? JCS_RGB : - (strcmp(colorspace, "cmyk") == 0) ? JCS_CMYK : - (strcmp(colorspace, "gray") == 0) ? JCS_GRAYSCALE : - JCS_UNKNOWN); + ((strcmp(colorspace, "rgb") == 0) ? JCS_RGB + : (strcmp(colorspace, "cmyk") == 0) ? JCS_CMYK + : (strcmp(colorspace, "gray") == 0) ? JCS_GRAYSCALE + : JCS_UNKNOWN); int components = 0; - switch (cs) - { - case JCS_RGB: + switch (cs) { + case JCS_RGB: components = 3; break; - case JCS_CMYK: + case JCS_CMYK: components = 4; break; - case JCS_GRAYSCALE: + case JCS_GRAYSCALE: components = 1; break; - default: + default: usage(); break; } @@ -74,21 +75,16 @@ int main(int argc, char* argv[]) bool done = false; Callback callback; Pl_DCT dct("dct", &out, width, height, components, cs, &callback); - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { dct.write(buf, len); } } dct.finish(); - if (! callback.called) - { + if (!callback.called) { std::cout << "Callback was not called" << std::endl; } fclose(infile); diff --git a/libtests/dct_uncompress.cc b/libtests/dct_uncompress.cc index dd366852..1ab22e97 100644 --- a/libtests/dct_uncompress.cc +++ b/libtests/dct_uncompress.cc @@ -2,17 +2,16 @@ #include #include -#include -#include #include +#include #include +#include -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 3) - { - std::cerr << "Usage: dct_uncompress infile outfile" - << std::endl; + if (argc != 3) { + std::cerr << "Usage: dct_uncompress infile outfile" << std::endl; exit(2); } @@ -25,15 +24,11 @@ int main(int argc, char* argv[]) unsigned char buf[100]; bool done = false; Pl_DCT dct("dct", &out); - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { dct.write(buf, len); } } diff --git a/libtests/flate.cc b/libtests/flate.cc index 058b956e..77fb440e 100644 --- a/libtests/flate.cc +++ b/libtests/flate.cc @@ -1,15 +1,16 @@ +#include #include #include -#include #include -#include #include -#include +#include #include +#include -void run(char const* filename) +void +run(char const* filename) { std::string n1 = std::string(filename) + ".1"; std::string n2 = std::string(filename) + ".2"; @@ -38,8 +39,7 @@ void run(char const* filename) FILE* in1 = QUtil::safe_fopen(filename, "rb"); unsigned char buf[1024]; size_t len; - while ((len = fread(buf, 1, sizeof(buf), in1)) > 0) - { + while ((len = fread(buf, 1, sizeof(buf), in1)) > 0) { // Write to the compression pipeline def1->write(buf, len); @@ -57,7 +57,6 @@ void run(char const* filename) std::cout << "bytes written to o3: " << count3->getCount() << std::endl; - delete def3; delete inf3; delete count3; @@ -66,8 +65,7 @@ void run(char const* filename) // Now read the compressed data and write to the output uncompress pipeline FILE* in2 = QUtil::safe_fopen(n1.c_str(), "rb"); - while ((len = fread(buf, 1, sizeof(buf), in2)) > 0) - { + while ((len = fread(buf, 1, sizeof(buf), in2)) > 0) { inf2->write(buf, len); } fclose(in2); @@ -83,21 +81,18 @@ void run(char const* filename) std::cout << "done" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 2) - { + if (argc != 2) { std::cerr << "Usage: pipeline filename" << std::endl; exit(2); } char* filename = argv[1]; - try - { + try { run(filename); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << e.what() << std::endl; } return 0; diff --git a/libtests/hex.cc b/libtests/hex.cc index 0480c7ea..9e708204 100644 --- a/libtests/hex.cc +++ b/libtests/hex.cc @@ -4,33 +4,27 @@ #include #include -int main() +int +main() { Pl_StdioFile out("stdout", stdout); Pl_ASCIIHexDecoder decode("decode", &out); - try - { + try { unsigned char buf[10000]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), stdin); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { decode.write(buf, len); } } decode.finish(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; - exit(2); + exit(2); } return 0; diff --git a/libtests/input_source.cc b/libtests/input_source.cc index 9e72bbf6..cb62daea 100644 --- a/libtests/input_source.cc +++ b/libtests/input_source.cc @@ -1,9 +1,9 @@ +#include #include #include -#include #include -#include #include +#include static PointerHolder get_buffer() @@ -11,8 +11,7 @@ get_buffer() size_t size = 3172; PointerHolder b(new Buffer(size)); unsigned char* p = b->getBuffer(); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { p[i] = static_cast(i & 0xff); } return b; @@ -41,22 +40,22 @@ Finder::check() { QPDFTokenizer tokenizer; QPDFTokenizer::Token t = tokenizer.readToken(is, "finder", true); - if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "potato")) - { + if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "potato")) { t = tokenizer.readToken(is, "finder", true); return (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, after)); } return false; } -void check(char const* description, bool expected, bool actual) +void +check(char const* description, bool expected, bool actual) { - std::cout << description << ": " - << ((actual == expected) ? "PASS" : "FAIL") + std::cout << description << ": " << ((actual == expected) ? "PASS" : "FAIL") << std::endl; } -int main() +int +main() { PointerHolder b1 = get_buffer(); unsigned char* b = b1->getBuffer(); @@ -68,42 +67,46 @@ int main() auto is = PointerHolder( new BufferInputSource("test buffer input source", b1.get())); Finder f1(is, "salad"); - check("find potato salad", true, - is->findFirst("potato", 0, 0, f1)); - check("barely find potato salad", true, - is->findFirst("potato", 1100, 945, f1)); - check("barely find potato salad", true, - is->findFirst("potato", 2000, 45, f1)); - check("potato salad is too late", false, - is->findFirst("potato", 1100, 944, f1)); - check("potato salad is too late", false, - is->findFirst("potato", 2000, 44, f1)); - check("potato salad not found", false, - is->findFirst("potato", 2045, 0, f1)); - check("potato salad not found", false, - is->findFirst("potato", 0, 1, f1)); + check("find potato salad", true, is->findFirst("potato", 0, 0, f1)); + check( + "barely find potato salad", + true, + is->findFirst("potato", 1100, 945, f1)); + check( + "barely find potato salad", + true, + is->findFirst("potato", 2000, 45, f1)); + check( + "potato salad is too late", + false, + is->findFirst("potato", 1100, 944, f1)); + check( + "potato salad is too late", + false, + is->findFirst("potato", 2000, 44, f1)); + check( + "potato salad not found", false, is->findFirst("potato", 2045, 0, f1)); + check("potato salad not found", false, is->findFirst("potato", 0, 1, f1)); // Put one more right at EOF memcpy(b + b1->getSize() - 12, "potato salad", 12); - check("potato salad at EOF", true, - is->findFirst("potato", 3000, 0, f1)); + check("potato salad at EOF", true, is->findFirst("potato", 3000, 0, f1)); is->findFirst("potato", 0, 0, f1); - check("findFirst found first", true, - is->tell() == 2056); - check("findLast found potato salad", true, - is->findLast("potato", 0, 0, f1)); - check("findLast found at EOF", true, - is->tell() == 3172); + check("findFirst found first", true, is->tell() == 2056); + check( + "findLast found potato salad", true, is->findLast("potato", 0, 0, f1)); + check("findLast found at EOF", true, is->tell() == 3172); // Make check() bump into EOF memcpy(b + b1->getSize() - 6, "potato", 6); - check("potato but not salad salad at EOF", false, - is->findFirst("potato", 3000, 0, f1)); - check("findLast found potato salad", true, - is->findLast("potato", 0, 0, f1)); - check("findLast found first one", true, - is->tell() == 2056); + check( + "potato but not salad salad at EOF", + false, + is->findFirst("potato", 3000, 0, f1)); + check( + "findLast found potato salad", true, is->findLast("potato", 0, 0, f1)); + check("findLast found first one", true, is->tell() == 2056); return 0; } diff --git a/libtests/json.cc b/libtests/json.cc index a8c72a3b..17a5d574 100644 --- a/libtests/json.cc +++ b/libtests/json.cc @@ -8,32 +8,34 @@ #endif #include -static void check(JSON const& j, std::string const& exp) +static void +check(JSON const& j, std::string const& exp) { - if (exp != j.unparse()) - { + if (exp != j.unparse()) { std::cout << "Got " << j.unparse() << "; wanted " << exp << "\n"; } } -static void test_main() +static void +test_main() { JSON jstr = JSON::makeString( "<1>\xcf\x80<2>\xf0\x9f\xa5\x94\\\"<3>\x03\t\b\r\n<4>"); - check(jstr, - "\"<1>\xcf\x80<2>\xf0\x9f\xa5\x94\\\\\\\"<3>" - "\\u0003\\t\\b\\r\\n<4>\""); + check( + jstr, + "\"<1>\xcf\x80<2>\xf0\x9f\xa5\x94\\\\\\\"<3>" + "\\u0003\\t\\b\\r\\n<4>\""); JSON jnull = JSON::makeNull(); check(jnull, "null"); assert(jnull.isNull()); std::string value; - assert(! jnull.getNumber(value)); + assert(!jnull.getNumber(value)); JSON jarr = JSON::makeArray(); check(jarr, "[]"); JSON jstr2 = JSON::makeString("a\tb"); assert(jstr2.getString(value)); assert(value == "a\tb"); - assert(! jstr2.getNumber(value)); + assert(!jstr2.getNumber(value)); /* cSpell: ignore jbool xavalue dvalue xdvalue */ JSON jint = JSON::makeInt(16059); JSON jdouble = JSON::makeReal(3.14159); @@ -44,24 +46,24 @@ static void test_main() assert(jbool1.getBool(bvalue)); assert(bvalue); assert(jbool2.getBool(bvalue)); - assert(! bvalue); + assert(!bvalue); jarr.addArrayElement(jstr2); jarr.addArrayElement(jnull); jarr.addArrayElement(jint); jarr.addArrayElement(jdouble); jarr.addArrayElement(jexp); - check(jarr, - "[\n" - " \"a\\tb\",\n" - " null,\n" - " 16059,\n" - " 3.14159,\n" - " 2.1e5\n" - "]"); + check( + jarr, + "[\n" + " \"a\\tb\",\n" + " null,\n" + " 16059,\n" + " 3.14159,\n" + " 2.1e5\n" + "]"); std::vector avalue; - assert(jarr.forEachArrayItem([&avalue](JSON j) { - avalue.push_back(j.unparse()); - })); + assert(jarr.forEachArrayItem( + [&avalue](JSON j) { avalue.push_back(j.unparse()); })); std::vector xavalue = { "\"a\\tb\"", "null", @@ -79,37 +81,36 @@ static void test_main() jmap.addDictionaryMember("no", JSON::makeBool(true)); jmap.addDictionaryMember("empty_dict", JSON::makeDictionary()); jmap.addDictionaryMember("empty_list", JSON::makeArray()); - jmap.addDictionaryMember("single", JSON::makeArray()). - addArrayElement(JSON::makeInt(12)); - check(jmap, - "{\n" - " \"a\": [\n" - " \"a\\tb\",\n" - " null,\n" - " 16059,\n" - " 3.14159,\n" - " 2.1e5\n" - " ],\n" - " \"b\": \"a\\tb\",\n" - " \"c\\r\\nd\": null,\n" - " \"empty_dict\": {},\n" - " \"empty_list\": [],\n" - " \"no\": true,\n" - " \"single\": [\n" - " 12\n" - " ],\n" - " \"yes\": false\n" - "}"); + jmap.addDictionaryMember("single", JSON::makeArray()) + .addArrayElement(JSON::makeInt(12)); + check( + jmap, + "{\n" + " \"a\": [\n" + " \"a\\tb\",\n" + " null,\n" + " 16059,\n" + " 3.14159,\n" + " 2.1e5\n" + " ],\n" + " \"b\": \"a\\tb\",\n" + " \"c\\r\\nd\": null,\n" + " \"empty_dict\": {},\n" + " \"empty_list\": [],\n" + " \"no\": true,\n" + " \"single\": [\n" + " 12\n" + " ],\n" + " \"yes\": false\n" + "}"); check(QPDFObjectHandle::newReal("0.12").getJSON(), "0.12"); check(QPDFObjectHandle::newReal(".34").getJSON(), "0.34"); check(QPDFObjectHandle::newReal("-0.56").getJSON(), "-0.56"); check(QPDFObjectHandle::newReal("-.78").getJSON(), "-0.78"); JSON jmap2 = JSON::parse(R"({"a": 1, "b": "two", "c": [true]})"); std::map dvalue; - assert(jmap2.forEachDictItem([&dvalue] - (std::string const& k, JSON j) { - dvalue[k] = j.unparse(); - })); + assert(jmap2.forEachDictItem( + [&dvalue](std::string const& k, JSON j) { dvalue[k] = j.unparse(); })); std::map xdvalue = { {"a", "1"}, {"b", "\"two\""}, @@ -118,21 +119,27 @@ static void test_main() assert(dvalue == xdvalue); } -static void check_schema(JSON& obj, JSON& schema, unsigned long flags, - bool exp, std::string const& description) +static void +check_schema( + JSON& obj, + JSON& schema, + unsigned long flags, + bool exp, + std::string const& description) { std::list errors; std::cout << "--- " << description << std::endl; assert(exp == obj.checkSchema(schema, flags, errors)); for (std::list::iterator iter = errors.begin(); - iter != errors.end(); ++iter) - { + iter != errors.end(); + ++iter) { std::cout << *iter << std::endl; } std::cout << "---" << std::endl; } -static void test_schema() +static void +test_schema() { /* cSpell: ignore ptional ebra */ JSON schema = JSON::parse(R"( @@ -249,7 +256,8 @@ static void test_schema() check_schema(good, schema, JSON::f_optional, true, "pass"); } -int main() +int +main() { test_main(); test_schema(); diff --git a/libtests/json_handler.cc b/libtests/json_handler.cc index 6e894e11..567cde86 100644 --- a/libtests/json_handler.cc +++ b/libtests/json_handler.cc @@ -1,6 +1,6 @@ #include -#include #include +#include #include #ifdef NDEBUG @@ -9,39 +9,46 @@ #endif #include -static void print_null(std::string const& path) +static void +print_null(std::string const& path) { std::cout << path << ": null" << std::endl; } -static void print_string(std::string const& path, std::string const& value) +static void +print_string(std::string const& path, std::string const& value) { std::cout << path << ": string: " << value << std::endl; } -static void print_number(std::string const& path, std::string const& value) +static void +print_number(std::string const& path, std::string const& value) { std::cout << path << ": number: " << value << std::endl; } -static void print_bool(std::string const& path, bool value) +static void +print_bool(std::string const& path, bool value) { std::cout << path << ": bool: " << (value ? "true" : "false") << std::endl; } -static void print_json(std::string const& path, JSON value) +static void +print_json(std::string const& path, JSON value) { std::cout << path << ": json: " << value.unparse() << std::endl; } -static JSONHandler::void_handler_t make_print_message(std::string msg) +static JSONHandler::void_handler_t +make_print_message(std::string msg) { return [msg](std::string const& path) { std::cout << path << ": json: " << msg << std::endl; }; } -static void test_scalar() +static void +test_scalar() { std::cout << "-- scalar --" << std::endl; JSONHandler h; @@ -50,11 +57,11 @@ static void test_scalar() h.handle(".", j); } -static std::shared_ptr make_all_handler() +static std::shared_ptr +make_all_handler() { auto h = std::make_shared(); - h->addDictHandlers( - print_json, make_print_message("dict end")); + h->addDictHandlers(print_json, make_print_message("dict end")); auto h1 = std::make_shared(); h1->addStringHandler(print_string); h->addDictKeyHandler("one", h1); @@ -75,16 +82,12 @@ static std::shared_ptr make_all_handler() h5->addNullHandler(print_null); auto h5s = std::make_shared(); h->addDictKeyHandler("five", h5s); - h5s->addArrayHandlers( - print_json, make_print_message("array end"), - h5); + h5s->addArrayHandlers(print_json, make_print_message("array end"), h5); auto h6 = std::make_shared(); - h6->addDictHandlers( - print_json, make_print_message("dict end")); + h6->addDictHandlers(print_json, make_print_message("dict end")); auto h6a = std::make_shared(); h6->addDictKeyHandler("a", h6a); - h6a->addDictHandlers( - print_json, make_print_message("dict end")); + h6a->addDictHandlers(print_json, make_print_message("dict end")); auto h6ab = std::make_shared(); h6a->addDictKeyHandler("b", h6ab); auto h6ax = std::make_shared(); @@ -96,7 +99,8 @@ static std::shared_ptr make_all_handler() return h; } -static void test_all() +static void +test_all() { std::cout << "-- all --" << std::endl; auto h = make_all_handler(); @@ -113,32 +117,29 @@ static void test_all() h->handle(".", j); } -static void test_errors() +static void +test_errors() { std::cout << "-- errors --" << std::endl; auto h = make_all_handler(); auto t = [h](std::string const& msg, std::function fn) { - try - { + try { fn(); assert(false); - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { std::cout << msg << ": " << e.what() << std::endl; } }; - t("bad type at top", [&h](){ - h->handle(".", JSON::makeString("oops")); - }); - t("unexpected key", [&h](){ + t("bad type at top", [&h]() { h->handle(".", JSON::makeString("oops")); }); + t("unexpected key", [&h]() { JSON j = JSON::parse(R"({"x": "y"})"); h->handle(".", j); }); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { test_scalar(); test_all(); diff --git a/libtests/json_parse.cc b/libtests/json_parse.cc index a2f004f5..13d29b65 100644 --- a/libtests/json_parse.cc +++ b/libtests/json_parse.cc @@ -2,25 +2,22 @@ #include #include -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 2) - { + if (argc != 2) { std::cerr << "Usage: json_parse file" << std::endl; return 2; } char const* filename = argv[1]; - try - { + try { PointerHolder buf; size_t size; QUtil::read_file_into_memory(filename, buf, size); std::string s(buf.get(), size); std::cout << JSON::parse(s).unparse() << std::endl; - } - catch (std::exception& e) - { - std::cerr << "exception: " << filename<< ": " << e.what() << std::endl; + } catch (std::exception& e) { + std::cerr << "exception: " << filename << ": " << e.what() << std::endl; return 2; } return 0; diff --git a/libtests/lzw.cc b/libtests/lzw.cc index 1c87045b..788d3dfc 100644 --- a/libtests/lzw.cc +++ b/libtests/lzw.cc @@ -6,23 +6,21 @@ #include #include -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { bool early_code_change = true; - if ((argc == 4) && (strcmp(argv[3], "--no-early-code-change") == 0)) - { + if ((argc == 4) && (strcmp(argv[3], "--no-early-code-change") == 0)) { early_code_change = false; } - if (argc < 3) - { + if (argc < 3) { std::cerr << "Usage: lzw infile outfile [ --no-early-code-change ]" << std::endl; exit(2); } - try - { + try { char* infilename = argv[1]; char* outfilename = argv[2]; @@ -34,22 +32,16 @@ int main(int argc, char* argv[]) unsigned char buf[10000]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { decode.write(buf, len); } } decode.finish(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/libtests/main_from_wmain.cc b/libtests/main_from_wmain.cc index 842db52e..b2290b2e 100644 --- a/libtests/main_from_wmain.cc +++ b/libtests/main_from_wmain.cc @@ -2,13 +2,15 @@ #include #ifndef QPDF_NO_WCHAR_T -void wmain_test() +void +wmain_test() { // writable args and function args auto realmain = [](int argc, char* argv[]) { for (int i = 0; i < argc; ++i) { std::cout << argv[i] << std::endl; - } return 0; + } + return 0; }; wchar_t* argv[3]; // This works because call_main_from_wmain doesn't actually write @@ -20,13 +22,15 @@ void wmain_test() QUtil::call_main_from_wmain(3, argv, realmain); } -void cwmain_test() +void +cwmain_test() { // const args and function args auto realmain = [](int argc, char const* const argv[]) { for (int i = 0; i < argc; ++i) { std::cout << "const " << argv[i] << std::endl; - } return 0; + } + return 0; }; wchar_t const* argv[3] = { L"ascii", @@ -37,16 +41,14 @@ void cwmain_test() } #endif // QPDF_NO_WCHAR_T -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { #ifndef QPDF_NO_WCHAR_T - try - { + try { wmain_test(); cwmain_test(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << "unexpected exception: " << e.what() << std::endl; } #endif // QPDF_NO_WCHAR_T diff --git a/libtests/matrix.cc b/libtests/matrix.cc index 210c022f..7dc73390 100644 --- a/libtests/matrix.cc +++ b/libtests/matrix.cc @@ -8,45 +8,50 @@ #endif #include -static void check(QPDFMatrix const& m, std::string const& exp) +static void +check(QPDFMatrix const& m, std::string const& exp) { std::string u = m.unparse(); - if (u != exp) - { + if (u != exp) { std::cout << "got " << u << ", wanted " << exp << std::endl; } } -static void check_xy(double x, double y, std::string const& exp) +static void +check_xy(double x, double y, std::string const& exp) { - std::string u = (QUtil::double_to_string(x, 2) + " " + - QUtil::double_to_string(y, 2)); - if (u != exp) - { + std::string u = + (QUtil::double_to_string(x, 2) + " " + QUtil::double_to_string(y, 2)); + if (u != exp) { std::cout << "got " << u << ", wanted " << exp << std::endl; } } -static void check_rect(QPDFObjectHandle::Rectangle const& r, - double llx, double lly, double urx, double ury) +static void +check_rect( + QPDFObjectHandle::Rectangle const& r, + double llx, + double lly, + double urx, + double ury) { - std::string actual = ( - QUtil::double_to_string(r.llx, 2) + " " + - QUtil::double_to_string(r.lly, 2) + " " + - QUtil::double_to_string(r.urx, 2) + " " + - QUtil::double_to_string(r.ury, 2)); - std::string wanted = ( - QUtil::double_to_string(llx, 2) + " " + - QUtil::double_to_string(lly, 2) + " " + - QUtil::double_to_string(urx, 2) + " " + - QUtil::double_to_string(ury, 2)); - if (actual != wanted) - { + std::string actual = + (QUtil::double_to_string(r.llx, 2) + " " + + QUtil::double_to_string(r.lly, 2) + " " + + QUtil::double_to_string(r.urx, 2) + " " + + QUtil::double_to_string(r.ury, 2)); + std::string wanted = + (QUtil::double_to_string(llx, 2) + " " + + QUtil::double_to_string(lly, 2) + " " + + QUtil::double_to_string(urx, 2) + " " + + QUtil::double_to_string(ury, 2)); + if (actual != wanted) { std::cout << "got " << actual << ", wanted " << wanted << std::endl; } } -int main() +int +main() { QPDFMatrix m; check(m, "1 0 0 1 0 0"); @@ -78,17 +83,20 @@ int main() m.transform(240, 480, xp, yp); check_xy(xp, yp, "2582.5 4912"); - check(QPDFMatrix( - QPDFObjectHandle::parse( - "[3 1 4 1 5 9.26535]").getArrayAsMatrix()), - "3 1 4 1 5 9.26535"); + check( + QPDFMatrix( + QPDFObjectHandle::parse("[3 1 4 1 5 9.26535]").getArrayAsMatrix()), + "3 1 4 1 5 9.26535"); m = QPDFMatrix(); m.rotatex90(90); m.translate(200, -100); check_rect( m.transformRectangle(QPDFObjectHandle::Rectangle(10, 20, 30, 50)), - 50, 210, 80, 230); + 50, + 210, + 80, + 230); std::cout << "matrix tests done" << std::endl; return 0; diff --git a/libtests/md5.cc b/libtests/md5.cc index 04935804..0fe4205e 100644 --- a/libtests/md5.cc +++ b/libtests/md5.cc @@ -1,18 +1,20 @@ #include -#include #include +#include #include #include #include -static void test_string(char const* str) +static void +test_string(char const* str) { MD5 a; a.encodeString(str); a.print(); } -int main(int, char*[]) +int +main(int, char*[]) { test_string(""); test_string("a"); @@ -42,7 +44,6 @@ int main(int, char*[]) << MD5::checkFileChecksum("6f4b4321873433daae578f85c72f9e74", "glerbl") << std::endl; - Pl_Discard d; Pl_MD5 p("MD5", &d); // Create a second pipeline, protect against finish, and call @@ -52,25 +53,19 @@ int main(int, char*[]) // calling finalize. Pl_MD5 p2("MD5", &d); p2.persistAcrossFinish(true); - for (int i = 0; i < 2; ++i) - { + for (int i = 0; i < 2; ++i) { FILE* f = QUtil::safe_fopen("md5.in", "rb"); // buffer size < size of md5.in unsigned char buf[50]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), f); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { p.write(buf, len); p2.write(buf, len); - if (i == 1) - { + if (i == 1) { // Partial digest -- resets after each call to write std::cout << p.getHexDigest() << std::endl; } diff --git a/libtests/nntree.cc b/libtests/nntree.cc index 1579ab46..4a874578 100644 --- a/libtests/nntree.cc +++ b/libtests/nntree.cc @@ -1,12 +1,13 @@ -#include -#include #include +#include +#include #include #include static bool any_failures = false; -bool report(QPDF& q, QPDFObjectHandle oh, long long item, long long exp_item) +bool +report(QPDF& q, QPDFObjectHandle oh, long long item, long long exp_item) { QPDFNumberTreeObjectHelper nh(oh, q); QPDFObjectHandle o1; @@ -16,61 +17,54 @@ bool report(QPDF& q, QPDFObjectHandle oh, long long item, long long exp_item) bool f2 = nh.findObject(item, o2); bool failed = false; - auto show = [&failed, &oh, &item] () { - if (! failed) - { + auto show = [&failed, &oh, &item]() { + if (!failed) { failed = true; - std::cout << "key = " << item << ", oh = " - << oh.unparseResolved() << std::endl; + std::cout << "key = " << item << ", oh = " << oh.unparseResolved() + << std::endl; } }; auto mk_wanted = [](long long i) { - return ((i == -1) - ? "end" - : (QUtil::int_to_string(i) + - "/(-" + QUtil::int_to_string(i) + "-)")); + return ( + (i == -1) ? "end" + : (QUtil::int_to_string(i) + "/(-" + + QUtil::int_to_string(i) + "-)")); }; std::string i1_wanted = mk_wanted(exp_item); std::string i2_wanted = mk_wanted(item == exp_item ? item : -1); auto mk_actual = [](bool found, long long v, QPDFObjectHandle& o) { - return (found - ? QUtil::int_to_string(v) + "/" + o.unparse() - : "end"); + return (found ? QUtil::int_to_string(v) + "/" + o.unparse() : "end"); }; std::string i1_actual = mk_actual(f1, item - offset, o1); std::string i2_actual = mk_actual(f2, item, o2); - if (i1_wanted != i1_actual) - { + if (i1_wanted != i1_actual) { show(); - std::cout << "i1: wanted " << i1_wanted - << ", got " << i1_actual + std::cout << "i1: wanted " << i1_wanted << ", got " << i1_actual << std::endl; } - if (i2_wanted != i2_actual) - { + if (i2_wanted != i2_actual) { show(); - std::cout << "i2: wanted " << i2_wanted - << ", got " << i2_actual + std::cout << "i2: wanted " << i2_wanted << ", got " << i2_actual << std::endl; } return failed; } -void test_bsearch() +void +test_bsearch() { QPDF q; q.emptyPDF(); - auto mk = [&q] (std::vector const& v) { + auto mk = [&q](std::vector const& v) { auto nums = QPDFObjectHandle::newArray(); - for (auto i: v) - { + for (auto i : v) { nums.appendItem(QPDFObjectHandle::newInteger(i)); nums.appendItem(QPDFObjectHandle::newString( - "-" + QUtil::int_to_string(i) + "-")); + "-" + QUtil::int_to_string(i) + "-")); } auto limits = QPDFObjectHandle::newArray(); limits.appendItem(QPDFObjectHandle::newInteger(v.at(0))); @@ -82,8 +76,7 @@ void test_bsearch() }; auto r = [&q](QPDFObjectHandle& oh, int item, int exp) { - if (report(q, oh, item, exp)) - { + if (report(q, oh, item, exp)) { any_failures = true; } }; @@ -119,36 +112,37 @@ void test_bsearch() r(d, 20, 20); r(d, 25, 20); - if (! any_failures) - { + if (!any_failures) { std::cout << "bsearch tests passed" << std::endl; } } -QPDFObjectHandle new_node(QPDF& q, std::string const& key) +QPDFObjectHandle +new_node(QPDF& q, std::string const& key) { auto dict = QPDFObjectHandle::newDictionary(); dict.replaceKey(key, QPDFObjectHandle::newArray()); return q.makeIndirectObject(dict); } -static void check_find(QPDFNameTreeObjectHelper& nh, - std::string const& key, bool prev_if_not_found) +static void +check_find( + QPDFNameTreeObjectHelper& nh, + std::string const& key, + bool prev_if_not_found) { auto i = nh.find(key, prev_if_not_found); std::cout << "find " << key << " (" << prev_if_not_found << "): "; - if (i == nh.end()) - { + if (i == nh.end()) { std::cout << "not found"; - } - else - { + } else { std::cout << (*i).first << " -> " << (*i).second.unparse(); } std::cout << std::endl; } -void test_depth() +void +test_depth() { int constexpr NITEMS = 3; QPDF q; @@ -157,40 +151,29 @@ void test_depth() auto n0 = new_node(q, "/Kids"); root.replaceKey("/NT", n0); auto k0 = root.getKey("/NT").getKey("/Kids"); - for (int i1 = 0; i1 < NITEMS; ++i1) - { + for (int i1 = 0; i1 < NITEMS; ++i1) { auto n1 = new_node(q, "/Kids"); k0.appendItem(n1); auto k1 = n1.getKey("/Kids"); - for (int i2 = 0; i2 < NITEMS; ++i2) - { + for (int i2 = 0; i2 < NITEMS; ++i2) { auto n2 = new_node(q, "/Kids"); k1.appendItem(n2); auto k2 = n2.getKey("/Kids"); - for (int i3 = 0; i3 < NITEMS; ++i3) - { + for (int i3 = 0; i3 < NITEMS; ++i3) { auto n3 = new_node(q, "/Names"); k2.appendItem(n3); auto items = n3.getKey("/Names"); std::string first; std::string last; - for (int i4 = 0; i4 < NITEMS; ++i4) - { - int val = (((((i1 - * NITEMS) + i2) - * NITEMS) + i3) - * NITEMS) + i4; + for (int i4 = 0; i4 < NITEMS; ++i4) { + int val = + (((((i1 * NITEMS) + i2) * NITEMS) + i3) * NITEMS) + i4; std::string str = QUtil::int_to_string(10 * val, 6); - items.appendItem( - QPDFObjectHandle::newString(str)); - items.appendItem( - QPDFObjectHandle::newString("val " + str)); - if (i4 == 0) - { + items.appendItem(QPDFObjectHandle::newString(str)); + items.appendItem(QPDFObjectHandle::newString("val " + str)); + if (i4 == 0) { first = str; - } - else if (i4 == NITEMS - 1) - { + } else if (i4 == NITEMS - 1) { last = str; } } @@ -201,35 +184,26 @@ void test_depth() } auto limits = QPDFObjectHandle::newArray(); n2.replaceKey("/Limits", limits); - limits.appendItem(k2.getArrayItem(0) - .getKey("/Limits") - .getArrayItem(0)); - limits.appendItem(k2.getArrayItem(NITEMS - 1) - .getKey("/Limits") - .getArrayItem(1)); + limits.appendItem( + k2.getArrayItem(0).getKey("/Limits").getArrayItem(0)); + limits.appendItem( + k2.getArrayItem(NITEMS - 1).getKey("/Limits").getArrayItem(1)); } auto limits = QPDFObjectHandle::newArray(); n1.replaceKey("/Limits", limits); - limits.appendItem(k1.getArrayItem(0) - .getKey("/Limits") - .getArrayItem(0)); - limits.appendItem(k1.getArrayItem(NITEMS - 1) - .getKey("/Limits") - .getArrayItem(1)); + limits.appendItem(k1.getArrayItem(0).getKey("/Limits").getArrayItem(0)); + limits.appendItem( + k1.getArrayItem(NITEMS - 1).getKey("/Limits").getArrayItem(1)); } QPDFNameTreeObjectHelper nh(n0, q); std::cout << "--- forward ---" << std::endl; - for (auto i: nh) - { - std::cout << i.first << " -> " - << i.second.unparse() << std::endl; + for (auto i : nh) { + std::cout << i.first << " -> " << i.second.unparse() << std::endl; } std::cout << "--- backward ---" << std::endl; - for (auto i = nh.last(); i.valid(); --i) - { - std::cout << (*i).first << " -> " - << (*i).second.unparse() << std::endl; + for (auto i = nh.last(); i.valid(); --i) { + std::cout << (*i).first << " -> " << (*i).second.unparse() << std::endl; } // Find @@ -243,11 +217,11 @@ void test_depth() check_find(nh, "000805", true); } -int main() +int +main() { test_bsearch(); test_depth(); return 0; } - diff --git a/libtests/numrange.cc b/libtests/numrange.cc index bc3a4036..d1548fe9 100644 --- a/libtests/numrange.cc +++ b/libtests/numrange.cc @@ -1,33 +1,29 @@ #include #include -static void test_numrange(char const* range) +static void +test_numrange(char const* range) { - if (range == 0) - { + if (range == 0) { std::cout << "null" << std::endl; - } - else - { + } else { std::vector result = QUtil::parse_numrange(range, 15); std::cout << "numeric range " << range << " ->"; for (std::vector::iterator iter = result.begin(); - iter != result.end(); ++iter) - { + iter != result.end(); + ++iter) { std::cout << " " << *iter; } std::cout << std::endl; } } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - try - { + try { test_numrange(argv[1]); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << e.what() << std::endl; return 2; } diff --git a/libtests/pdf_version.cc b/libtests/pdf_version.cc index 2471cb0b..e9bfb00b 100644 --- a/libtests/pdf_version.cc +++ b/libtests/pdf_version.cc @@ -8,7 +8,8 @@ #endif #include -int main() +int +main() { PDFVersion v1; assert(v1.getMajor() == 0); @@ -32,8 +33,8 @@ int main() assert(v3 == v1); v1.updateIfGreater(v2); assert(v3 == v1); - assert(! (v3 == v2)); - assert(! (v2 == v1)); + assert(!(v3 == v2)); + assert(!(v2 == v1)); v2.updateIfGreater(v1); assert(v2 == v1); v2.getVersion(version, extension_level); @@ -42,12 +43,12 @@ int main() assert(PDFVersion(1, 2) < PDFVersion(1, 3)); assert(PDFVersion(1, 2) < PDFVersion(1, 2, 1)); assert(PDFVersion(1, 2, 1) < PDFVersion(1, 2, 2)); - assert(! (PDFVersion(1, 2, 2) < PDFVersion(1, 2, 2))); - assert(! (PDFVersion(1, 2, 3) < PDFVersion(1, 2, 2))); + assert(!(PDFVersion(1, 2, 2) < PDFVersion(1, 2, 2))); + assert(!(PDFVersion(1, 2, 3) < PDFVersion(1, 2, 2))); assert(PDFVersion(1, 1) < PDFVersion(1, 2, 2)); - assert(! (PDFVersion(1, 3) < PDFVersion(1, 2, 2))); - assert(! (PDFVersion(2, 0) < PDFVersion(1, 9, 9))); - assert(! (PDFVersion(2, 0) < PDFVersion(2, 0))); + assert(!(PDFVersion(1, 3) < PDFVersion(1, 2, 2))); + assert(!(PDFVersion(2, 0) < PDFVersion(1, 9, 9))); + assert(!(PDFVersion(2, 0) < PDFVersion(2, 0))); assert(PDFVersion(2, 0) == PDFVersion(2, 0)); assert(PDFVersion(2, 0, 1) == PDFVersion(2, 0, 1)); diff --git a/libtests/pointer_holder.cc b/libtests/pointer_holder.cc index 67c13d5a..70c83aeb 100644 --- a/libtests/pointer_holder.cc +++ b/libtests/pointer_holder.cc @@ -6,8 +6,8 @@ #include #include -#include #include +#include class Object { @@ -22,7 +22,6 @@ class Object int id; }; - int Object::next_id = 0; Object::Object() @@ -50,21 +49,24 @@ Object::hello() const typedef PointerHolder ObjectHolder; -void callHello(ObjectHolder& oh) +void +callHello(ObjectHolder& oh) { oh.getPointer()->hello(); oh->hello(); (*oh).hello(); } -void callHelloWithGet(ObjectHolder const& oh) +void +callHelloWithGet(ObjectHolder const& oh) { oh.get()->hello(); oh->hello(); (*oh).hello(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { std::list ol1; @@ -81,18 +83,15 @@ int main(int argc, char* argv[]) ObjectHolder oh4; ObjectHolder oh5; std::cout << "oh5 refcount = " << oh5.getRefcount() << std::endl; - if (oh4 == oh5) - { + if (oh4 == oh5) { std::cout << "nulls equal" << std::endl; } oh3 = oh1; oh4 = oh2; - if (oh3 == oh4) - { + if (oh3 == oh4) { std::cout << "equal okay" << std::endl; } - if ((! (oh3 < oh4)) && (! (oh4 < oh3))) - { + if ((!(oh3 < oh4)) && (!(oh4 < oh3))) { std::cout << "less than okay" << std::endl; } ol1.push_back(oh3); diff --git a/libtests/predictors.cc b/libtests/predictors.cc index f9fa759e..c024cbd6 100644 --- a/libtests/predictors.cc +++ b/libtests/predictors.cc @@ -1,13 +1,13 @@ #include -#include #include -#include +#include #include +#include -#include #include -#include +#include #include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -15,53 +15,54 @@ #endif #include -void run(char const* filename, char const* filter, - bool encode, unsigned int columns, - unsigned int bits_per_sample, unsigned int samples_per_pixel) +void +run(char const* filename, + char const* filter, + bool encode, + unsigned int columns, + unsigned int bits_per_sample, + unsigned int samples_per_pixel) { FILE* in = QUtil::safe_fopen(filename, "rb"); FILE* o1 = QUtil::safe_fopen("out", "wb"); Pipeline* out = new Pl_StdioFile("out", o1); Pipeline* pl = 0; - if (strcmp(filter, "png") == 0) - { + if (strcmp(filter, "png") == 0) { pl = new Pl_PNGFilter( - "png", out, + "png", + out, encode ? Pl_PNGFilter::a_encode : Pl_PNGFilter::a_decode, - columns, samples_per_pixel, bits_per_sample); - } - else if (strcmp(filter, "tiff") == 0) - { + columns, + samples_per_pixel, + bits_per_sample); + } else if (strcmp(filter, "tiff") == 0) { pl = new Pl_TIFFPredictor( - "png", out, + "png", + out, encode ? Pl_TIFFPredictor::a_encode : Pl_TIFFPredictor::a_decode, - columns, samples_per_pixel, bits_per_sample); - } - else - { + columns, + samples_per_pixel, + bits_per_sample); + } else { std::cerr << "unknown filter " << filter << std::endl; exit(2); } assert((2 * (columns + 1)) < 1024); unsigned char buf[1024]; size_t len; - while (true) - { + while (true) { len = fread(buf, 1, (2 * columns) + 1, in); - if (len == 0) - { + if (len == 0) { break; } pl->write(buf, len); len = fread(buf, 1, 1, in); - if (len == 0) - { + if (len == 0) { break; } pl->write(buf, len); len = fread(buf, 1, 1, in); - if (len == 0) - { + if (len == 0) { break; } pl->write(buf, len); @@ -76,13 +77,12 @@ void run(char const* filename, char const* filter, std::cout << "done" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 7) - { + if (argc != 7) { std::cerr << "Usage: predictor {png|tiff} {en,de}code filename" - << " columns samples-per-pixel bits-per-sample" - << std::endl; + << " columns samples-per-pixel bits-per-sample" << std::endl; exit(2); } char* filter = argv[1]; @@ -92,15 +92,14 @@ int main(int argc, char* argv[]) int samples_per_pixel = QUtil::string_to_int(argv[5]); int bits_per_sample = QUtil::string_to_int(argv[6]); - try - { - run(filename, filter, encode, + try { + run(filename, + filter, + encode, QIntC::to_uint(columns), QIntC::to_uint(bits_per_sample), QIntC::to_uint(samples_per_pixel)); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << e.what() << std::endl; } return 0; diff --git a/libtests/qintc.cc b/libtests/qintc.cc index 85806d1a..d3e19f5b 100644 --- a/libtests/qintc.cc +++ b/libtests/qintc.cc @@ -8,22 +8,22 @@ #include #define try_convert(exp_pass, fn, i) \ - try_convert_real(#fn "(" #i ")", exp_pass, fn, i) + try_convert_real(#fn "(" #i ")", exp_pass, fn, i) template -static void try_convert_real( - char const* description, bool exp_pass, - To (*fn)(From const&), From const& i) +static void +try_convert_real( + char const* description, + bool exp_pass, + To (*fn)(From const&), + From const& i) { bool passed = false; - try - { + try { To result = fn(i); passed = true; std::cout << description << ": " << i << " " << result; - } - catch (std::range_error& e) - { + } catch (std::range_error& e) { std::cout << description << ": " << e.what(); passed = false; } @@ -31,22 +31,19 @@ static void try_convert_real( } #define try_range_check(exp_pass, a, b) \ - try_range_check_real(#a " + " #b, exp_pass, a, b) + try_range_check_real(#a " + " #b, exp_pass, a, b) template -static void try_range_check_real( - char const* description, bool exp_pass, - T const& a, T const& b) +static void +try_range_check_real( + char const* description, bool exp_pass, T const& a, T const& b) { bool passed = false; - try - { + try { QIntC::range_check(a, b); std::cout << description << ": okay"; passed = true; - } - catch (std::range_error& e) - { + } catch (std::range_error& e) { std::cout << description << ": " << e.what(); passed = false; } @@ -54,29 +51,27 @@ static void try_range_check_real( } #define try_range_check_subtract(exp_pass, a, b) \ - try_range_check_subtract_real(#a " - " #b, exp_pass, a, b) + try_range_check_subtract_real(#a " - " #b, exp_pass, a, b) template -static void try_range_check_subtract_real( - char const* description, bool exp_pass, - T const& a, T const& b) +static void +try_range_check_subtract_real( + char const* description, bool exp_pass, T const& a, T const& b) { bool passed = false; - try - { + try { QIntC::range_check_substract(a, b); std::cout << description << ": okay"; passed = true; - } - catch (std::range_error& e) - { + } catch (std::range_error& e) { std::cout << description << ": " << e.what(); passed = false; } std::cout << ((passed == exp_pass) ? " PASSED" : " FAILED") << std::endl; } -int main() +int +main() { uint32_t u1 = 3141592653U; // Too big for signed type int32_t i1 = -1153374643; // Same bit pattern as u1 @@ -84,28 +79,28 @@ int main() uint64_t ul2 = 12345; // Fits into 32-bit int32_t i2 = 81; // Fits in char and uchar signed char c1 = static_cast('\xf7'); // Signed value when char - char c2 = 'W'; // char; may be signed or unsigned + char c2 = 'W'; // char; may be signed or unsigned // Verify i1 and u1 have same bit pattern assert(static_cast(i1) == u1); // Verify that we can unsafely convert between signed and unsigned char assert(c1 == static_cast(static_cast(c1))); - try_convert(true, QIntC::to_int, i1); - try_convert(true, QIntC::to_uint, u1); + try_convert(true, QIntC::to_int, i1); + try_convert(true, QIntC::to_uint, u1); try_convert(false, QIntC::to_int, u1); try_convert(false, QIntC::to_uint, i1); try_convert(false, QIntC::to_int, ul1); - try_convert(true, QIntC::to_int, ul2); - try_convert(true, QIntC::to_uint, ul2); - try_convert(true, QIntC::to_offset, u1); - try_convert(true, QIntC::to_offset, i1); + try_convert(true, QIntC::to_int, ul2); + try_convert(true, QIntC::to_uint, ul2); + try_convert(true, QIntC::to_offset, u1); + try_convert(true, QIntC::to_offset, i1); try_convert(false, QIntC::to_ulonglong, i1); - try_convert(true, QIntC::to_char, i2); - try_convert(true, QIntC::to_uchar, i2); + try_convert(true, QIntC::to_char, i2); + try_convert(true, QIntC::to_uchar, i2); try_convert(false, QIntC::to_uchar, c1); - try_convert(true, QIntC::to_uchar, c2); - try_convert(true, QIntC::to_char, c2); + try_convert(true, QIntC::to_uchar, c2); + try_convert(true, QIntC::to_char, c2); auto constexpr max_ll = std::numeric_limits::max(); auto constexpr max_ull = std::numeric_limits::max(); diff --git a/libtests/qutil.cc b/libtests/qutil.cc index c3a9b163..fea9fca1 100644 --- a/libtests/qutil.cc +++ b/libtests/qutil.cc @@ -1,16 +1,16 @@ -#include -#include -#include -#include -#include -#include +#include #include #include -#include -#include -#include +#include +#include #include +#include +#include #include +#include +#include +#include +#include #ifdef _WIN32 # include @@ -25,96 +25,86 @@ #include template -void test_to_number(char const* str, int_T wanted, bool error, - int_T (*fn)(char const*)) +void +test_to_number( + char const* str, int_T wanted, bool error, int_T (*fn)(char const*)) { bool threw = false; bool worked = false; int_T result = 0; std::string msg; - try - { + try { result = fn(str); worked = (wanted == result); - } - catch (std::runtime_error const& e) - { + } catch (std::runtime_error const& e) { threw = true; msg = e.what(); } - if (threw) - { - if (error) - { - std::cout << str << " to int threw (" << msg << "): PASSED" << std::endl; + if (threw) { + if (error) { + std::cout << str << " to int threw (" << msg << "): PASSED" + << std::endl; + } else { + std::cout << str << " to int threw but wanted " << wanted + << std::endl; } - else - { - std::cout << str << " to int threw but wanted " - << wanted << std::endl; - } - } - else - { - if (worked) - { + } else { + if (worked) { std::cout << str << " to int: PASSED" << std::endl; - } - else - { + } else { std::cout << str << " to int failed; got " << result << std::endl; } } } -void test_to_int(char const* str, int wanted, bool error) +void +test_to_int(char const* str, int wanted, bool error) { test_to_number(str, wanted, error, QUtil::string_to_int); } -void test_to_ll(char const* str, long long wanted, bool error) +void +test_to_ll(char const* str, long long wanted, bool error) { test_to_number(str, wanted, error, QUtil::string_to_ll); } -void test_to_uint(char const* str, unsigned int wanted, bool error) +void +test_to_uint(char const* str, unsigned int wanted, bool error) { test_to_number(str, wanted, error, QUtil::string_to_uint); } -void test_to_ull(char const* str, unsigned long long wanted, bool error) +void +test_to_ull(char const* str, unsigned long long wanted, bool error) { test_to_number(str, wanted, error, QUtil::string_to_ull); } -static void set_locale() +static void +set_locale() { - try - { + try { // First try a locale known to put commas in numbers. std::locale::global(std::locale("en_US.UTF-8")); - } - catch (std::runtime_error&) - { - try - { + } catch (std::runtime_error&) { + try { // If that fails, fall back to the user's default locale. std::locale::global(std::locale("")); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { // Ignore this error on Windows without MSVC. We get // enough test coverage on other platforms, and mingw // seems to have limited locale support (as of // 2020-10). -#if ! defined(_WIN32) || defined(_MSC_VER) +#if !defined(_WIN32) || defined(_MSC_VER) throw e; #endif } } } -void string_conversion_test() +void +string_conversion_test() { // Make sure the code produces consistent results even if we load // a non-C locale. @@ -146,32 +136,23 @@ void string_conversion_test() std::cout << embedded_null.c_str() << std::endl; std::cout << embedded_null.length() << std::endl; char* tmp = QUtil::copy_string(embedded_null); - if (memcmp(tmp, embedded_null.c_str(), 7) == 0) - { + if (memcmp(tmp, embedded_null.c_str(), 7) == 0) { std::cout << "compare okay" << std::endl; - } - else - { + } else { std::cout << "compare failed" << std::endl; } - delete [] tmp; + delete[] tmp; // Also test with make_shared_cstr and make_unique_cstr auto tmp2 = QUtil::make_shared_cstr(embedded_null); - if (memcmp(tmp2.get(), embedded_null.c_str(), 7) == 0) - { + if (memcmp(tmp2.get(), embedded_null.c_str(), 7) == 0) { std::cout << "compare okay" << std::endl; - } - else - { + } else { std::cout << "compare failed" << std::endl; } auto tmp3 = QUtil::make_unique_cstr(embedded_null); - if (memcmp(tmp3.get(), embedded_null.c_str(), 7) == 0) - { + if (memcmp(tmp3.get(), embedded_null.c_str(), 7) == 0) { std::cout << "compare okay" << std::endl; - } - else - { + } else { std::cout << "compare failed" << std::endl; } @@ -198,41 +179,37 @@ void string_conversion_test() test_to_ull(small_negative.c_str(), 0, true); } -void os_wrapper_test() +void +os_wrapper_test() { - try - { + try { std::cout << "before remove" << std::endl; - QUtil::os_wrapper("remove file", - remove("/this/file/does/not/exist")); + QUtil::os_wrapper("remove file", remove("/this/file/does/not/exist")); std::cout << "after remove" << std::endl; - } - catch (std::runtime_error& s) - { + } catch (std::runtime_error& s) { std::cout << "exception: " << s.what() << std::endl; } } -void fopen_wrapper_test() +void +fopen_wrapper_test() { - try - { + try { std::cout << "before fopen" << std::endl; FILE* f = QUtil::safe_fopen("/this/file/does/not/exist", "r"); std::cout << "after fopen" << std::endl; - (void) fclose(f); - } - catch (QPDFSystemError& s) - { + (void)fclose(f); + } catch (QPDFSystemError& s) { std::cout << "exception: " << s.what() << std::endl; assert(s.getErrno() != 0); } assert(QUtil::file_can_be_opened("qutil.out")); - assert(! QUtil::file_can_be_opened("/does/not/exist")); + assert(!QUtil::file_can_be_opened("/does/not/exist")); } -void getenv_test() +void +getenv_test() { std::string val; std::cout << "IN_TESTSUITE: " << QUtil::get_env("IN_TESTSUITE", &val) @@ -242,60 +219,63 @@ void getenv_test() << std::endl; } -static void print_utf8(unsigned long val) +static void +print_utf8(unsigned long val) { std::string result = QUtil::toUTF8(val); std::cout << "0x" << QUtil::uint_to_string_base(val, 16) << " ->"; - if (val < 0xfffe) - { + if (val < 0xfffe) { std::cout << " " << result; - } - else - { + } else { // Emacs has trouble with utf-8 encoding files with characters // outside the 16-bit portion, so just show the character // values. - for (std::string::iterator iter = result.begin(); - iter != result.end(); ++iter) - { - std::cout << " " << QUtil::int_to_string_base( - static_cast(static_cast(*iter)), 16, 2); + for (std::string::iterator iter = result.begin(); iter != result.end(); + ++iter) { + std::cout << " " + << QUtil::int_to_string_base( + static_cast( + static_cast(*iter)), + 16, + 2); } } std::cout << std::endl; } -void to_utf8_test() +void +to_utf8_test() { print_utf8(0x41UL); print_utf8(0xF7UL); print_utf8(0x3c0UL); print_utf8(0x16059UL); print_utf8(0x7fffffffUL); - try - { + try { print_utf8(0x80000000UL); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { std::cout << "0x80000000: " << e.what() << std::endl; } } -static void print_utf16(unsigned long val) +static void +print_utf16(unsigned long val) { std::string result = QUtil::toUTF16(val); std::cout << "0x" << QUtil::uint_to_string_base(val, 16) << " ->"; - for (std::string::iterator iter = result.begin(); - iter != result.end(); ++iter) - { - std::cout << " " << QUtil::int_to_string_base( - static_cast(static_cast(*iter)), 16, 2); + for (std::string::iterator iter = result.begin(); iter != result.end(); + ++iter) { + std::cout << " " + << QUtil::int_to_string_base( + static_cast(static_cast(*iter)), + 16, + 2); } std::cout << std::endl; } -void to_utf16_test() +void +to_utf16_test() { print_utf16(0x41UL); print_utf16(0xF7UL); @@ -308,88 +288,88 @@ void to_utf16_test() std::string s(QUtil::utf8_to_utf16("\xcf\x80")); std::cout << QUtil::utf16_to_utf8(s) << std::endl; std::cout << QUtil::utf16_to_utf8(s + ".") << std::endl; - std::cout << "LE: " << QUtil::utf16_to_utf8("\xff\xfe\xc0\x03") << std::endl; + std::cout << "LE: " << QUtil::utf16_to_utf8("\xff\xfe\xc0\x03") + << std::endl; } -void utf8_to_ascii_test() +void +utf8_to_ascii_test() { char const* input = "\302\277Does \317\200 have fingers?"; - std::cout << input - << std::endl - << QUtil::utf8_to_ascii(input) - << std::endl - << QUtil::utf8_to_ascii(input, '*') - << std::endl; + std::cout << input << std::endl + << QUtil::utf8_to_ascii(input) << std::endl + << QUtil::utf8_to_ascii(input, '*') << std::endl; std::string a = QUtil::utf8_to_win_ansi(input, '*'); std::string b = QUtil::utf8_to_mac_roman(input, '*'); std::cout - << "<" << QUtil::int_to_string_base( - static_cast(a.at(0)), 16, 2) + << "<" + << QUtil::int_to_string_base(static_cast(a.at(0)), 16, 2) << ">" << a.substr(1) << std::endl - << "<" << QUtil::int_to_string_base( - static_cast(b.at(0)), 16, 2) + << "<" + << QUtil::int_to_string_base(static_cast(b.at(0)), 16, 2) << ">" << b.substr(1) << std::endl; } -void transcoding_test(std::string (*to_utf8)(std::string const&), - std::string (*from_utf8)(std::string const&, char), - int first, int last, std::string unknown) +void +transcoding_test( + std::string (*to_utf8)(std::string const&), + std::string (*from_utf8)(std::string const&, char), + int first, + int last, + std::string unknown) { std::string in(" "); std::string out; std::string back; - for (int i = first; i <= last; ++i) - { + for (int i = first; i <= last; ++i) { in.at(0) = static_cast(static_cast(i)); out = (*to_utf8)(in); std::string wanted = (out == "\xef\xbf\xbd") ? unknown : in; back = (*from_utf8)(out, '?'); - if (back != wanted) - { - std::cout << i << ": " << in << " -> " << out - << " -> " << back << " (wanted " << wanted << ")" - << std::endl; + if (back != wanted) { + std::cout << i << ": " << in << " -> " << out << " -> " << back + << " (wanted " << wanted << ")" << std::endl; } } } -void check_analyze(std::string const& str, bool has8bit, bool utf8, bool utf16) +void +check_analyze(std::string const& str, bool has8bit, bool utf8, bool utf16) { bool has_8bit_chars = false; bool is_valid_utf8 = false; bool is_utf16 = false; QUtil::analyze_encoding(str, has_8bit_chars, is_valid_utf8, is_utf16); - if (! ((has_8bit_chars == has8bit) && - (is_valid_utf8 == utf8) && - (is_utf16 == utf16))) - { + if (!((has_8bit_chars == has8bit) && (is_valid_utf8 == utf8) && + (is_utf16 == utf16))) { std::cout << "analysis failed: " << str << std::endl; } } -void print_alternatives(std::string const& str) +void +print_alternatives(std::string const& str) { std::vector result = QUtil::possible_repaired_encodings(str); size_t n = result.size(); - for (size_t i = 0; i < n; ++i) - { + for (size_t i = 0; i < n; ++i) { std::cout << i << ": " << QUtil::hex_encode(result.at(i)) << std::endl; } } -void transcoding_test() +void +transcoding_test() { - transcoding_test(&QUtil::pdf_doc_to_utf8, - &QUtil::utf8_to_pdf_doc, 127, 160, "\x9f"); + transcoding_test( + &QUtil::pdf_doc_to_utf8, &QUtil::utf8_to_pdf_doc, 127, 160, "\x9f"); std::cout << "bidirectional pdf doc done" << std::endl; - transcoding_test(&QUtil::pdf_doc_to_utf8, - &QUtil::utf8_to_pdf_doc, 24, 31, "?"); + transcoding_test( + &QUtil::pdf_doc_to_utf8, &QUtil::utf8_to_pdf_doc, 24, 31, "?"); std::cout << "bidirectional pdf doc low done" << std::endl; - transcoding_test(&QUtil::win_ansi_to_utf8, - &QUtil::utf8_to_win_ansi, 128, 160, "?"); + transcoding_test( + &QUtil::win_ansi_to_utf8, &QUtil::utf8_to_win_ansi, 128, 160, "?"); std::cout << "bidirectional win ansi done" << std::endl; - transcoding_test(&QUtil::mac_roman_to_utf8, - &QUtil::utf8_to_mac_roman, 128, 255, "?"); + transcoding_test( + &QUtil::mac_roman_to_utf8, &QUtil::utf8_to_mac_roman, 128, 255, "?"); std::cout << "bidirectional mac roman done" << std::endl; check_analyze("pi = \317\200", true, true, false); check_analyze("pi != \317", true, false, false); @@ -401,17 +381,17 @@ void transcoding_test() std::string input2("a\317\200b"); std::string input3("ab"); std::string output; - assert(! QUtil::utf8_to_ascii(input1, output)); - assert(! QUtil::utf8_to_ascii(input2, output)); + assert(!QUtil::utf8_to_ascii(input1, output)); + assert(!QUtil::utf8_to_ascii(input2, output)); assert(QUtil::utf8_to_ascii(input3, output)); assert(QUtil::utf8_to_win_ansi(input1, output)); - assert(! QUtil::utf8_to_win_ansi(input2, output)); + assert(!QUtil::utf8_to_win_ansi(input2, output)); assert(QUtil::utf8_to_win_ansi(input3, output)); assert(QUtil::utf8_to_mac_roman(input1, output)); - assert(! QUtil::utf8_to_mac_roman(input2, output)); + assert(!QUtil::utf8_to_mac_roman(input2, output)); assert(QUtil::utf8_to_mac_roman(input3, output)); assert(QUtil::utf8_to_pdf_doc(input1, output)); - assert(! QUtil::utf8_to_pdf_doc(input2, output)); + assert(!QUtil::utf8_to_pdf_doc(input2, output)); assert(QUtil::utf8_to_pdf_doc(input3, output)); std::cout << "alternatives" << std::endl; // char name mac win pdf-doc @@ -434,18 +414,20 @@ void transcoding_test() std::string other_utf8 = other + QUtil::toUTF8(0x9f) + "w" + QUtil::toUTF8(0xad) + "w"; std::string other_to_utf8; - assert(! QUtil::utf8_to_pdf_doc(other_utf8, other_to_utf8)); + assert(!QUtil::utf8_to_pdf_doc(other_utf8, other_to_utf8)); std::cout << other_to_utf8 << std::endl; std::cout << "done other characters" << std::endl; } -void print_whoami(char const* str) +void +print_whoami(char const* str) { auto dup = QUtil::make_unique_cstr(str); std::cout << QUtil::getWhoami(dup.get()) << std::endl; } -void get_whoami_test() +void +get_whoami_test() { print_whoami("a/b/c/quack1"); print_whoami("a/b/c/quack2.exe"); @@ -453,26 +435,24 @@ void get_whoami_test() print_whoami("a\\b\\c\\quack4.exe"); } -void assert_same_file(char const* file1, char const* file2, bool expected) +void +assert_same_file(char const* file1, char const* file2, bool expected) { bool actual = QUtil::same_file(file1, file2); std::cout << "file1: -" << (file1 ? file1 : "(null)") << "-, file2: -" - << (file2 ? file2 : "(null)") << "-; same: " - << actual << ": " << ((actual == expected) ? "PASS" : "FAIL") - << std::endl; + << (file2 ? file2 : "(null)") << "-; same: " << actual << ": " + << ((actual == expected) ? "PASS" : "FAIL") << std::endl; } -void same_file_test() +void +same_file_test() { - try - { + try { fclose(QUtil::safe_fopen("qutil.out", "r")); fclose(QUtil::safe_fopen("other-file", "r")); - } - catch (std::exception const&) - { + } catch (std::exception const&) { std::cout << "same_file_test expects to have qutil.out and other-file" - " exist in the current directory\n"; + " exist in the current directory\n"; return; } assert_same_file("qutil.out", "./qutil.out", true); @@ -483,12 +463,12 @@ void same_file_test() assert_same_file("", "qutil.out", false); } -void path_test() +void +path_test() { auto check = [](bool print, std::string const& a, std::string const& b) { auto result = QUtil::path_basename(a); - if (print) - { + if (print) { std::cout << a << " -> " << result << std::endl; } assert(result == b); @@ -506,12 +486,13 @@ void path_test() check(true, "quack", "quack"); } -void read_from_file_test() +void +read_from_file_test() { std::list lines = QUtil::read_lines_from_file("other-file"); for (std::list::iterator iter = lines.begin(); - iter != lines.end(); ++iter) - { + iter != lines.end(); + ++iter) { std::cout << *iter << std::endl; } // Test the other versions and make sure we get the same results @@ -565,36 +546,34 @@ void read_from_file_test() assert(memcmp(buf2->getBuffer(), p, size) == 0); } -void assert_hex_encode(std::string const& input, std::string const& expected) +void +assert_hex_encode(std::string const& input, std::string const& expected) { std::string actual = QUtil::hex_encode(input); - if (expected != actual) - { - std::cout << "hex encode " << input - << ": expected = " << expected - << "; actual = " << actual - << std::endl; + if (expected != actual) { + std::cout << "hex encode " << input << ": expected = " << expected + << "; actual = " << actual << std::endl; } } -void assert_hex_decode(std::string const& input, std::string const& expected) +void +assert_hex_decode(std::string const& input, std::string const& expected) { std::string actual = QUtil::hex_decode(input); - if (expected != actual) - { - std::cout << "hex encode " << input - << ": expected = " << expected - << "; actual = " << actual - << std::endl; + if (expected != actual) { + std::cout << "hex encode " << input << ": expected = " << expected + << "; actual = " << actual << std::endl; } } -void hex_encode_decode_test() +void +hex_encode_decode_test() { std::cout << "begin hex encode/decode\n"; assert_hex_encode("", ""); assert_hex_encode("Potato", "506f7461746f"); - std::string with_null("a\367" "00w"); + std::string with_null("a\367" + "00w"); with_null[3] = '\0'; assert_hex_encode(with_null, "61f7300077"); assert_hex_decode("", ""); @@ -603,58 +582,60 @@ void hex_encode_decode_test() std::cout << "end hex encode/decode\n"; } -static void assert_no_file(char const* filename) +static void +assert_no_file(char const* filename) { - try - { + try { fclose(QUtil::safe_fopen(filename, "r")); assert(false); - } - catch (QPDFSystemError&) - { + } catch (QPDFSystemError&) { } } -void rename_delete_test() +void +rename_delete_test() { PointerHolder buf; size_t size = 0; - try - { + try { QUtil::remove_file("old\xcf\x80"); - } - catch (QPDFSystemError&) - { + } catch (QPDFSystemError&) { } assert_no_file("old\xcf\x80"); - std::cout << "create file" << std::endl;; + std::cout << "create file" << std::endl; + ; FILE* f1 = QUtil::safe_fopen("old\xcf\x80", "w"); fprintf(f1, "one"); fclose(f1); QUtil::read_file_into_memory("old\xcf\x80", buf, size); assert(memcmp(buf.get(), "one", 3) == 0); - std::cout << "rename file" << std::endl;; + std::cout << "rename file" << std::endl; + ; QUtil::rename_file("old\xcf\x80", "old\xcf\x80.~tmp"); QUtil::read_file_into_memory("old\xcf\x80.~tmp", buf, size); assert(memcmp(buf.get(), "one", 3) == 0); assert_no_file("old\xcf\x80"); - std::cout << "create file" << std::endl;; + std::cout << "create file" << std::endl; + ; f1 = QUtil::safe_fopen("old\xcf\x80", "w"); fprintf(f1, "two"); fclose(f1); - std::cout << "rename over existing" << std::endl;; + std::cout << "rename over existing" << std::endl; + ; QUtil::rename_file("old\xcf\x80", "old\xcf\x80.~tmp"); QUtil::read_file_into_memory("old\xcf\x80.~tmp", buf, size); assert(memcmp(buf.get(), "two", 3) == 0); assert_no_file("old\xcf\x80"); - std::cout << "delete file" << std::endl;; + std::cout << "delete file" << std::endl; + ; QUtil::remove_file("old\xcf\x80.~tmp"); assert_no_file("old\xcf\x80"); assert_no_file("old\xcf\x80.~tmp"); } -void timestamp_test() +void +timestamp_test() { auto check = [](QUtil::QPDFTime const& t) { std::string pdf = QUtil::qpdf_time_to_pdf_time(t); @@ -666,7 +647,7 @@ void timestamp_test() check(QUtil::QPDFTime(2021, 2, 9, 14, 49, 25, 300)); check(QUtil::QPDFTime(2021, 2, 10, 1, 19, 25, -330)); check(QUtil::QPDFTime(2021, 2, 9, 19, 19, 25, 0)); - assert(! QUtil::pdf_time_to_qpdf_time("potato")); + assert(!QUtil::pdf_time_to_qpdf_time("potato")); assert(QUtil::pdf_time_to_qpdf_time("D:20210211064743Z")); assert(QUtil::pdf_time_to_qpdf_time("D:20210211064743-05'00'")); assert(QUtil::pdf_time_to_qpdf_time("D:20210211064743+05'30'")); @@ -675,14 +656,13 @@ void timestamp_test() // Manual testing was done to ensure that we are actually getting // back the current time in various time zones. assert(QUtil::pdf_time_to_qpdf_time( - QUtil::qpdf_time_to_pdf_time( - QUtil::get_current_qpdf_time()))); + QUtil::qpdf_time_to_pdf_time(QUtil::get_current_qpdf_time()))); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - try - { + try { std::cout << "---- string conversion" << std::endl; string_conversion_test(); std::cout << "---- os wrapper" << std::endl; @@ -713,9 +693,7 @@ int main(int argc, char* argv[]) rename_delete_test(); std::cout << "---- timestamp" << std::endl; timestamp_test(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cout << "unexpected exception: " << e.what() << std::endl; } diff --git a/libtests/random.cc b/libtests/random.cc index 70e5135e..2148111c 100644 --- a/libtests/random.cc +++ b/libtests/random.cc @@ -1,7 +1,7 @@ -#include -#include #include +#include #include +#include #include class BogusRandomDataProvider: public RandomDataProvider @@ -13,67 +13,58 @@ class BogusRandomDataProvider: public RandomDataProvider BogusRandomDataProvider() { } - virtual void provideRandomData(unsigned char* data, size_t len) + virtual void + provideRandomData(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { data[i] = static_cast(i & 0xff); } } }; -int main() +int +main() { RandomDataProvider* orig_rdp = QUtil::getRandomDataProvider(); long r1 = QUtil::random(); long r2 = QUtil::random(); - if (r1 == r2) - { + if (r1 == r2) { std::cout << "fail: two randoms were the same\n"; } InsecureRandomDataProvider irdp; irdp.provideRandomData(reinterpret_cast(&r1), 4); irdp.provideRandomData(reinterpret_cast(&r2), 4); - if (r1 == r2) - { + if (r1 == r2) { std::cout << "fail: two insecure randoms were the same\n"; } #ifndef SKIP_OS_SECURE_RANDOM SecureRandomDataProvider srdp; srdp.provideRandomData(reinterpret_cast(&r1), 4); srdp.provideRandomData(reinterpret_cast(&r2), 4); - if (r1 == r2) - { + if (r1 == r2) { std::cout << "fail: two secure randoms were the same\n"; } #endif BogusRandomDataProvider brdp; QUtil::setRandomDataProvider(&brdp); - if (QUtil::getRandomDataProvider() != &brdp) - { + if (QUtil::getRandomDataProvider() != &brdp) { std::cout << "fail: getRandomDataProvider didn't" - " return our provider\n"; + " return our provider\n"; } r1 = QUtil::random(); r2 = QUtil::random(); - if (r1 != r2) - { + if (r1 != r2) { std::cout << "fail: two bogus randoms were different\n"; } unsigned char buf[4]; QUtil::initializeWithRandomBytes(buf, 4); - if (! ((buf[0] == 0) && - (buf[1] == 1) && - (buf[2] == 2) && - (buf[3] == 3))) - { + if (!((buf[0] == 0) && (buf[1] == 1) && (buf[2] == 2) && (buf[3] == 3))) { std::cout << "fail: bogus random didn't provide correct bytes\n"; } QUtil::setRandomDataProvider(0); - if (QUtil::getRandomDataProvider() != orig_rdp) - { + if (QUtil::getRandomDataProvider() != orig_rdp) { std::cout << "fail: passing null to setRandomDataProvider " - "didn't reset the random data provider\n"; + "didn't reset the random data provider\n"; } std::cout << "random: end of tests\n"; return 0; diff --git a/libtests/rc4.cc b/libtests/rc4.cc index b7aecd4b..7245ef86 100644 --- a/libtests/rc4.cc +++ b/libtests/rc4.cc @@ -1,12 +1,12 @@ #include #include -#include #include +#include -#include -#include #include +#include #include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -14,7 +14,8 @@ #endif #include -static void other_tests() +static void +other_tests() { // Test cases not covered by the pipeline: string as key, convert // in place @@ -26,16 +27,15 @@ static void other_tests() std::cout << "passed" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if ((argc == 2) && (strcmp(argv[1], "other") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "other") == 0)) { other_tests(); return 0; } - if (argc != 4) - { + if (argc != 4) { std::cerr << "Usage: rc4 hex-key infile outfile" << std::endl; exit(2); } @@ -49,35 +49,30 @@ int main(int argc, char* argv[]) key[keylen] = '\0'; FILE* infile = QUtil::safe_fopen(infilename, "rb"); - for (unsigned int i = 0; i < strlen(hexkey); i += 2) - { + for (unsigned int i = 0; i < strlen(hexkey); i += 2) { char t[3]; t[0] = hexkey[i]; t[1] = hexkey[i + 1]; t[2] = '\0'; long val = strtol(t, 0, 16); - key[i/2] = static_cast(val); + key[i / 2] = static_cast(val); } FILE* outfile = QUtil::safe_fopen(outfilename, "wb"); Pl_StdioFile* out = new Pl_StdioFile("stdout", outfile); // Use a small buffer size (64) for testing Pl_RC4* rc4 = new Pl_RC4("rc4", out, key, QIntC::to_int(keylen), 64U); - delete [] key; + delete[] key; // 64 < buffer size < 512, buffer_size is not a power of 2 for testing unsigned char buf[100]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { rc4->write(buf, len); } } diff --git a/libtests/runlength.cc b/libtests/runlength.cc index f54e7300..456e33a2 100644 --- a/libtests/runlength.cc +++ b/libtests/runlength.cc @@ -2,15 +2,15 @@ #include #include -#include -#include #include +#include #include +#include -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if (argc != 4) - { + if (argc != 4) { std::cerr << "Usage: runlength {-encode|-decode} infile outfile" << std::endl; exit(2); @@ -26,17 +26,14 @@ int main(int argc, char* argv[]) unsigned char buf[100]; bool done = false; Pl_RunLength rl( - "runlength", &out, + "runlength", + &out, (encode ? Pl_RunLength::a_encode : Pl_RunLength::a_decode)); - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), infile); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { rl.write(buf, len); } } diff --git a/libtests/sha2.cc b/libtests/sha2.cc index 5110b89f..57bc0c12 100644 --- a/libtests/sha2.cc +++ b/libtests/sha2.cc @@ -1,69 +1,99 @@ #include +#include #include #include #include -#include -static void test(Pl_SHA2& sha2, char const* description, int bits, - char const* input, std::string const& output) +static void +test( + Pl_SHA2& sha2, + char const* description, + int bits, + char const* input, + std::string const& output) { sha2.resetBits(bits); sha2.write(QUtil::unsigned_char_pointer(input), strlen(input)); sha2.finish(); std::cout << description << ": "; - if (output == sha2.getHexDigest()) - { + if (output == sha2.getHexDigest()) { std::cout << "passed\n"; - } - else - { + } else { std::cout << "failed\n" << " expected: " << output << "\n" << " actual: " << sha2.getHexDigest() << "\n"; } } -int main( int argc, char *argv[] ) +int +main(int argc, char* argv[]) { Pl_SHA2 sha2; char million_a[1000001]; memset(million_a, 'a', 1000000); million_a[1000000] = '\0'; - test(sha2, "256 short", 256, - "abc", - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); - test(sha2, "256 long", 256, - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); - test(sha2, "256 million", 256, - million_a, - "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); - test(sha2, "384 short", 384, - "abc", - "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163" - "1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"); - test(sha2, "384 long", 384, - "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "09330c33f71147e83d192fc782cd1b4753111b173b3b05d2" - "2fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039"); - test(sha2, "384 million", 384, - million_a, - "9d0e1809716474cb086e834e310a4a1ced149e9c00f24852" - "7972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"); - test(sha2, "512 short", 512, - "abc", - "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" - "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); - test(sha2, "512 long", 512, - "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" - "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", - "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" - "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"); - test(sha2, "512 million", 512, - million_a, - "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" - "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"); + test( + sha2, + "256 short", + 256, + "abc", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + test( + sha2, + "256 long", + 256, + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); + test( + sha2, + "256 million", + 256, + million_a, + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); + test( + sha2, + "384 short", + 384, + "abc", + "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded163" + "1a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"); + test( + sha2, + "384 long", + 384, + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "09330c33f71147e83d192fc782cd1b4753111b173b3b05d2" + "2fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039"); + test( + sha2, + "384 million", + 384, + million_a, + "9d0e1809716474cb086e834e310a4a1ced149e9c00f24852" + "7972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"); + test( + sha2, + "512 short", + 512, + "abc", + "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" + "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); + test( + sha2, + "512 long", + 512, + "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmn" + "hijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" + "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"); + test( + sha2, + "512 million", + 512, + million_a, + "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" + "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"); return 0; } diff --git a/libtests/sparse_array.cc b/libtests/sparse_array.cc index 5636abd1..8d37bc2f 100644 --- a/libtests/sparse_array.cc +++ b/libtests/sparse_array.cc @@ -7,7 +7,8 @@ #endif #include -int main() +int +main() { SparseOHArray a; assert(a.size() == 0); diff --git a/pkg-test/qpdf-version.cc b/pkg-test/qpdf-version.cc index 63fd3308..ab78cede 100644 --- a/pkg-test/qpdf-version.cc +++ b/pkg-test/qpdf-version.cc @@ -1,7 +1,9 @@ #include #include -int main() { +int +main() +{ std::cout << QPDF::QPDFVersion() << std::endl; return 0; } diff --git a/qpdf/fix-qdf.cc b/qpdf/fix-qdf.cc index 291eeed0..4fd5bf93 100644 --- a/qpdf/fix-qdf.cc +++ b/qpdf/fix-qdf.cc @@ -1,15 +1,16 @@ -#include +#include #include #include -#include +#include #include -#include #include +#include #include static char const* whoami = 0; -static void usage() +static void +usage() { std::cerr << "Usage: " << whoami << " [filename]" << std::endl; exit(2); @@ -20,6 +21,7 @@ class QdfFixer public: QdfFixer(std::string const& filename); void processLines(std::list& lines); + private: void fatal(std::string const&); void checkObjId(std::string const& obj_id); @@ -110,52 +112,38 @@ QdfFixer::processLines(std::list& lines) static std::regex re_dict_end("^>>\n$"); lineno = 0; - for (auto const& line: lines) - { + for (auto const& line : lines) { ++lineno; last_offset = offset; offset += QIntC::to_offset(line.length()); std::smatch m; - auto matches = [&m, &line](std::regex& r){ - return std::regex_search(line, m, r); }; - if (state == st_top) - { - if (matches(re_n_0_obj)) - { + auto matches = [&m, &line](std::regex& r) { + return std::regex_search(line, m, r); + }; + if (state == st_top) { + if (matches(re_n_0_obj)) { checkObjId(m[1].str()); state = st_in_obj; - } - else if (matches(re_xref)) - { + } else if (matches(re_xref)) { xref_offset = last_offset; state = st_at_xref; } std::cout << line; - } - else if (state == st_in_obj) - { + } else if (state == st_in_obj) { std::cout << line; - if (matches(re_stream)) - { + if (matches(re_stream)) { state = st_in_stream; stream_start = offset; - } - else if (matches(re_endobj)) - { + } else if (matches(re_endobj)) { state = st_top; - } - else if (matches(re_type_objstm)) - { + } else if (matches(re_type_objstm)) { state = st_in_ostream_dict; ostream_id = last_obj; - } - else if (matches(re_type_xref)) - { + } else if (matches(re_type_xref)) { xref_offset = xref.back().getOffset(); xref_f1_nbytes = 0; auto t = xref_offset; - while (t) - { + while (t) { t >>= 8; ++xref_f1_nbytes; } @@ -163,17 +151,14 @@ QdfFixer::processLines(std::list& lines) // index. Make sure we get at least 1 byte even if // there are no object streams. int max_objects = 1; - for (auto const& e: xref) - { + for (auto const& e : xref) { if ((e.getType() == 2) && - (e.getObjStreamIndex() > max_objects)) - { + (e.getObjStreamIndex() > max_objects)) { max_objects = e.getObjStreamIndex(); } } - while (max_objects) - { - max_objects >>=8; + while (max_objects) { + max_objects >>= 8; ++xref_f2_nbytes; } auto esize = 1 + xref_f1_nbytes + xref_f2_nbytes; @@ -181,94 +166,65 @@ QdfFixer::processLines(std::list& lines) auto length = xref_size * esize; std::cout << " /Length " << length << "\n" << " /W [ 1 " << xref_f1_nbytes << " " - << xref_f2_nbytes << " ]" << "\n"; + << xref_f2_nbytes << " ]" + << "\n"; state = st_in_xref_stream_dict; } - } - else if (state == st_in_ostream_dict) - { - if (matches(re_stream)) - { + } else if (state == st_in_ostream_dict) { + if (matches(re_stream)) { state = st_in_ostream_offsets; - } - else - { + } else { ostream_discarded.push_back(line); - if (matches(re_extends)) - { + if (matches(re_extends)) { ostream_extends = m[1].str(); } } // discard line - } - else if (state == st_in_ostream_offsets) - { - if (matches(re_ostream_obj)) - { + } else if (state == st_in_ostream_offsets) { + if (matches(re_ostream_obj)) { checkObjId(m[1].str()); stream_start = last_offset; state = st_in_ostream_outer; ostream.push_back(line); - } - else - { + } else { ostream_discarded.push_back(line); } // discard line - } - else if (state == st_in_ostream_outer) - { + } else if (state == st_in_ostream_outer) { adjustOstreamXref(); ostream_offsets.push_back(last_offset - stream_start); state = st_in_ostream_obj; ostream.push_back(line); - } - else if (state == st_in_ostream_obj) - { + } else if (state == st_in_ostream_obj) { ostream.push_back(line); - if (matches(re_ostream_obj)) - { + if (matches(re_ostream_obj)) { checkObjId(m[1].str()); state = st_in_ostream_outer; - } - else if (matches(re_endstream)) - { + } else if (matches(re_endstream)) { stream_length = QIntC::to_size(last_offset - stream_start); writeOstream(); state = st_in_obj; } - } - else if (state == st_in_xref_stream_dict) - { - if (matches(re_length_or_w)) - { + } else if (state == st_in_xref_stream_dict) { + if (matches(re_length_or_w)) { // already printed - } - else if (matches(re_size)) - { + } else if (matches(re_size)) { auto xref_size = 1 + xref.size(); std::cout << " /Size " << xref_size << "\n"; - } - else - { + } else { std::cout << line; } - if (matches(re_stream)) - { + if (matches(re_stream)) { writeBinary(0, 1); writeBinary(0, xref_f1_nbytes); writeBinary(0, xref_f2_nbytes); - for (auto const& x: xref) - { + for (auto const& x : xref) { unsigned long long f1 = 0; unsigned long long f2 = 0; unsigned int type = QIntC::to_uint(x.getType()); - if (1 == type) - { + if (1 == type) { f1 = QIntC::to_ulonglong(x.getOffset()); - } - else - { + } else { f1 = QIntC::to_ulonglong(x.getObjStreamNumber()); f2 = QIntC::to_ulonglong(x.getObjStreamIndex()); } @@ -277,41 +233,31 @@ QdfFixer::processLines(std::list& lines) writeBinary(f2, xref_f2_nbytes); } std::cout << "\nendstream\nendobj\n\n" - << "startxref\n" << xref_offset << "\n%%EOF\n"; + << "startxref\n" + << xref_offset << "\n%%EOF\n"; state = st_done; } - } - else if (state == st_in_stream) - { - if (matches(re_endstream)) - { + } else if (state == st_in_stream) { + if (matches(re_endstream)) { stream_length = QIntC::to_size(last_offset - stream_start); state = st_after_stream; } std::cout << line; - } - else if (state == st_after_stream) - { - if (matches(re_ignore_newline)) - { - if (stream_length > 0) - { + } else if (state == st_after_stream) { + if (matches(re_ignore_newline)) { + if (stream_length > 0) { --stream_length; } - } - else if (matches(re_n_0_obj)) - { + } else if (matches(re_n_0_obj)) { checkObjId(m[1].str()); state = st_in_length; } std::cout << line; - } - else if (state == st_in_length) - { - if (! matches(re_num)) - { - fatal(filename + ":" + QUtil::uint_to_string(lineno) + - ": expected integer"); + } else if (state == st_in_length) { + if (!matches(re_num)) { + fatal( + filename + ":" + QUtil::uint_to_string(lineno) + + ": expected integer"); } std::string new_length = QUtil::uint_to_string(stream_length) + "\n"; @@ -319,45 +265,31 @@ QdfFixer::processLines(std::list& lines) offset += QIntC::to_offset(new_length.length()); std::cout << new_length; state = st_top; - } - else if (state == st_at_xref) - { + } else if (state == st_at_xref) { auto n = xref.size(); std::cout << "0 " << 1 + n << "\n0000000000 65535 f \n"; - for (auto const& e: xref) - { + for (auto const& e : xref) { std::cout << QUtil::int_to_string(e.getOffset(), 10) << " 00000 n \n"; } state = st_before_trailer; - } - else if (state == st_before_trailer) - { - if (matches(re_trailer)) - { + } else if (state == st_before_trailer) { + if (matches(re_trailer)) { std::cout << line; state = st_in_trailer; } // no output - } - else if (state == st_in_trailer) - { - if (matches(re_size_n)) - { + } else if (state == st_in_trailer) { + if (matches(re_size_n)) { std::cout << " /Size " << 1 + xref.size() << "\n"; - } - else - { + } else { std::cout << line; } - if (matches(re_dict_end)) - { - std::cout << "startxref\n" << xref_offset<< "\n%%EOF\n"; + if (matches(re_dict_end)) { + std::cout << "startxref\n" << xref_offset << "\n%%EOF\n"; state = st_done; } - } - else if (state == st_done) - { + } else if (state == st_done) { // ignore } } @@ -367,10 +299,10 @@ void QdfFixer::checkObjId(std::string const& cur_obj_str) { int cur_obj = QUtil::string_to_int(cur_obj_str.c_str()); - if (cur_obj != last_obj + 1) - { - fatal(filename + ":" + QUtil::uint_to_string(lineno) + - ": expected object " + QUtil::int_to_string(last_obj + 1)); + if (cur_obj != last_obj + 1) { + fatal( + filename + ":" + QUtil::uint_to_string(lineno) + + ": expected object " + QUtil::int_to_string(last_obj + 1)); } last_obj = cur_obj; xref.push_back(QPDFXRefEntry(1, QIntC::to_offset(last_offset), 0)); @@ -390,8 +322,7 @@ QdfFixer::writeOstream() auto onum = ostream_id; std::string offsets; auto n = ostream_offsets.size(); - for (auto iter: ostream_offsets) - { + for (auto iter : ostream_offsets) { iter -= QIntC::to_offset(first); ++onum; offsets += QUtil::int_to_string(onum) + " " + @@ -404,22 +335,17 @@ QdfFixer::writeOstream() dict_data += " /Length " + QUtil::uint_to_string(stream_length) + "\n"; dict_data += " /N " + QUtil::uint_to_string(n) + "\n"; dict_data += " /First " + QUtil::int_to_string(first) + "\n"; - if (! ostream_extends.empty()) - { + if (!ostream_extends.empty()) { dict_data += " /Extends " + ostream_extends + "\n"; } dict_data += ">>\n"; offset_adjust += QIntC::to_offset(dict_data.length()); - std::cout << dict_data - << "stream\n" - << offsets; - for (auto const& o: ostream) - { + std::cout << dict_data << "stream\n" << offsets; + for (auto const& o : ostream) { std::cout << o; } - for (auto const& o: ostream_discarded) - { + for (auto const& o : ostream_discarded) { offset -= QIntC::to_offset(o.length()); } offset += offset_adjust; @@ -435,58 +361,45 @@ QdfFixer::writeOstream() void QdfFixer::writeBinary(unsigned long long val, size_t bytes) { - if (bytes > sizeof(unsigned long long)) - { + if (bytes > sizeof(unsigned long long)) { throw std::logic_error( "fix-qdf::writeBinary called with too many bytes"); } std::string data; data.reserve(bytes); - for (size_t i = 0; i < bytes; ++i) - { + for (size_t i = 0; i < bytes; ++i) { data.append(1, '\0'); } - for (size_t i = 0; i < bytes; ++i) - { - data.at(bytes - i - 1) = - static_cast(QIntC::to_uchar(val & 0xff)); + for (size_t i = 0; i < bytes; ++i) { + data.at(bytes - i - 1) = static_cast(QIntC::to_uchar(val & 0xff)); val >>= 8; } std::cout << data; } -static int realmain(int argc, char* argv[]) +static int +realmain(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); QUtil::setLineBuf(stdout); char const* filename = 0; - if (argc > 2) - { + if (argc > 2) { usage(); - } - else if ((argc > 1) && (strcmp(argv[1], "--version") == 0)) - { - std::cout << whoami << " from qpdf version " - << QPDF::QPDFVersion() << std::endl; + } else if ((argc > 1) && (strcmp(argv[1], "--version") == 0)) { + std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() + << std::endl; return 0; - } - else if ((argc > 1) && (strcmp(argv[1], "--help") == 0)) - { + } else if ((argc > 1) && (strcmp(argv[1], "--help") == 0)) { usage(); - } - else if (argc == 2) - { + } else if (argc == 2) { filename = argv[1]; } std::list lines; - if (filename == 0) - { + if (filename == 0) { filename = "standard input"; QUtil::binary_stdin(); lines = QUtil::read_lines_from_file(stdin, true); - } - else - { + } else { lines = QUtil::read_lines_from_file(filename, true); } QUtil::binary_stdout(); @@ -497,15 +410,16 @@ static int realmain(int argc, char* argv[]) #ifdef WINDOWS_WMAIN -extern "C" -int wmain(int argc, wchar_t* argv[]) +extern "C" int +wmain(int argc, wchar_t* argv[]) { return QUtil::call_main_from_wmain(argc, argv, realmain); } #else -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { return realmain(argc, argv); } diff --git a/qpdf/pdf_from_scratch.cc b/qpdf/pdf_from_scratch.cc index 10f57c38..c401e9af 100644 --- a/qpdf/pdf_from_scratch.cc +++ b/qpdf/pdf_from_scratch.cc @@ -1,40 +1,43 @@ #include -#include -#include -#include #include #include +#include +#include +#include #include #include -#include #include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " n" << std::endl; exit(2); } -static QPDFObjectHandle createPageContents(QPDF& pdf, std::string const& text) +static QPDFObjectHandle +createPageContents(QPDF& pdf, std::string const& text) { std::string contents = "BT /F1 15 Tf 72 720 Td (" + text + ") Tj ET\n"; return QPDFObjectHandle::newStream(&pdf, contents); } -QPDFObjectHandle newName(std::string const& name) +QPDFObjectHandle +newName(std::string const& name) { return QPDFObjectHandle::newName(name); } -void runtest(int n) +void +runtest(int n) { QPDF pdf; pdf.emptyPDF(); - if (n == 0) - { + if (n == 0) { // Create a minimal PDF from scratch. QPDFObjectHandle font = pdf.makeIndirectObject( @@ -46,8 +49,8 @@ void runtest(int n) " /Encoding /WinAnsiEncoding" ">>")); - QPDFObjectHandle procset = pdf.makeIndirectObject( - QPDFObjectHandle::parse("[/PDF /Text]")); + QPDFObjectHandle procset = + pdf.makeIndirectObject(QPDFObjectHandle::parse("[/PDF /Text]")); QPDFObjectHandle contents = createPageContents(pdf, "First Page"); @@ -60,8 +63,8 @@ void runtest(int n) resources.replaceKey("/ProcSet", procset); resources.replaceKey("/Font", rfont); - QPDFObjectHandle page = pdf.makeIndirectObject( - QPDFObjectHandle::newDictionary()); + QPDFObjectHandle page = + pdf.makeIndirectObject(QPDFObjectHandle::newDictionary()); page.replaceKey("/Type", newName("/Page")); page.replaceKey("/MediaBox", mediabox); page.replaceKey("/Contents", contents); @@ -73,40 +76,32 @@ void runtest(int n) w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); - } - else - { - throw std::runtime_error(std::string("invalid test ") + - QUtil::int_to_string(n)); + } else { + throw std::runtime_error( + std::string("invalid test ") + QUtil::int_to_string(n)); } std::cout << "test " << n << " done" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { QUtil::setLineBuf(stdout); - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } - if (argc != 2) - { + if (argc != 2) { usage(); } - try - { + try { int n = QUtil::string_to_int(argv[1]); runtest(n); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/qpdf/qpdf-ctest.c b/qpdf/qpdf-ctest.c index 3a890a69..1f95b8de 100644 --- a/qpdf/qpdf-ctest.c +++ b/qpdf/qpdf-ctest.c @@ -1,8 +1,8 @@ #include +#include #include #include #include -#include #include // for LL_FMT -- special case in build @@ -15,33 +15,36 @@ static char* whoami = 0; static qpdf_data qpdf = 0; -static FILE* safe_fopen(char const* filename, char const* mode) +static FILE* +safe_fopen(char const* filename, char const* mode) { // This function is basically a "C" port of QUtil::safe_fopen. FILE* f = 0; #ifdef _MSC_VER errno_t err = fopen_s(&f, filename, mode); - if (err != 0) - { + if (err != 0) { char buf[94]; strerror_s(buf, sizeof(buf), errno); - fprintf(stderr, "%s: unable to open %s: %s\n", - whoami, filename, buf); + fprintf(stderr, "%s: unable to open %s: %s\n", whoami, filename, buf); exit(2); } #else f = fopen(filename, mode); - if (f == NULL) - { - fprintf(stderr, "%s: unable to open %s: %s\n", - whoami, filename, strerror(errno)); + if (f == NULL) { + fprintf( + stderr, + "%s: unable to open %s: %s\n", + whoami, + filename, + strerror(errno)); exit(2); } #endif return f; } -static void print_error(char const* label, qpdf_data q, qpdf_error e) +static void +print_error(char const* label, qpdf_data q, qpdf_error e) { #define POS_FMT " pos : " LL_FMT "\n" printf("%s: %s\n", label, qpdf_get_error_full_text(q, e)); @@ -51,22 +54,19 @@ static void print_error(char const* label, qpdf_data q, qpdf_error e) printf(" text: %s\n", qpdf_get_error_message_detail(q, e)); } -static void report_errors() +static void +report_errors() { qpdf_error e = 0; - while (qpdf_more_warnings(qpdf)) - { + while (qpdf_more_warnings(qpdf)) { e = qpdf_next_warning(qpdf); print_error("warning", qpdf, e); } - if (qpdf_has_error(qpdf)) - { + if (qpdf_has_error(qpdf)) { e = qpdf_get_error(qpdf); assert(qpdf_has_error(qpdf) == QPDF_FALSE); print_error("error", qpdf, e); - } - else - { + } else { e = qpdf_get_error(qpdf); assert(e == 0); assert(qpdf_get_error_code(qpdf, e) == qpdf_e_success); @@ -79,16 +79,16 @@ static void report_errors() } } -static void handle_oh_error(qpdf_data q, char const* label) +static void +handle_oh_error(qpdf_data q, char const* label) { - if (qpdf_has_error(q)) - { + if (qpdf_has_error(q)) { print_error(label, q, qpdf_get_error(q)); } } -static void read_file_into_memory(char const* filename, - char** buf, unsigned long* size) +static void +read_file_into_memory(char const* filename, char** buf, unsigned long* size) { char* buf_p = 0; FILE* f = NULL; @@ -97,103 +97,99 @@ static void read_file_into_memory(char const* filename, f = safe_fopen(filename, "rb"); fseek(f, 0, SEEK_END); - *size = (unsigned long) ftell(f); + *size = (unsigned long)ftell(f); fseek(f, 0, SEEK_SET); *buf = malloc(*size); - if (*buf == NULL) - { - fprintf(stderr, "%s: unable to allocate %lu bytes\n", - whoami, *size); + if (*buf == NULL) { + fprintf(stderr, "%s: unable to allocate %lu bytes\n", whoami, *size); exit(2); } buf_p = *buf; bytes_read = 0; len = 0; - while ((len = fread(buf_p + bytes_read, 1, *size - bytes_read, f)) > 0) - { + while ((len = fread(buf_p + bytes_read, 1, *size - bytes_read, f)) > 0) { bytes_read += len; } - if (bytes_read != *size) - { - if (ferror(f)) - { - fprintf(stderr, "%s: failure reading file %s into memory:", - whoami, filename); + if (bytes_read != *size) { + if (ferror(f)) { + fprintf( + stderr, + "%s: failure reading file %s into memory:", + whoami, + filename); + } else { + fprintf( + stderr, "%s: premature EOF reading file %s:", whoami, filename); } - else - { - fprintf(stderr, "%s: premature EOF reading file %s:", - whoami, filename); - } - fprintf(stderr, " read %lu, wanted %lu\n", - (unsigned long) bytes_read, (unsigned long) *size); + fprintf( + stderr, + " read %lu, wanted %lu\n", + (unsigned long)bytes_read, + (unsigned long)*size); exit(2); } fclose(f); } -static void count_progress(int percent, void* data) +static void +count_progress(int percent, void* data) { ++(*(int*)data); } -static void test01(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test01( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); printf("version: %s\n", qpdf_get_pdf_version(qpdf)); - if (qpdf_get_pdf_extension_level(qpdf) > 0) - { + if (qpdf_get_pdf_extension_level(qpdf) > 0) { printf("extension level: %d\n", qpdf_get_pdf_extension_level(qpdf)); } printf("linearized: %d\n", qpdf_is_linearized(qpdf)); printf("encrypted: %d\n", qpdf_is_encrypted(qpdf)); - if (qpdf_is_encrypted(qpdf)) - { + if (qpdf_is_encrypted(qpdf)) { printf("user password: %s\n", qpdf_get_user_password(qpdf)); - printf("extract for accessibility: %d\n", - qpdf_allow_accessibility(qpdf)); - printf("extract for any purpose: %d\n", - qpdf_allow_extract_all(qpdf)); - printf("print low resolution: %d\n", - qpdf_allow_print_low_res(qpdf)); - printf("print high resolution: %d\n", - qpdf_allow_print_high_res(qpdf)); - printf("modify document assembly: %d\n", - qpdf_allow_modify_assembly(qpdf)); - printf("modify forms: %d\n", - qpdf_allow_modify_form(qpdf)); - printf("modify annotations: %d\n", - qpdf_allow_modify_annotation(qpdf)); - printf("modify other: %d\n", - qpdf_allow_modify_other(qpdf)); - printf("modify anything: %d\n", - qpdf_allow_modify_all(qpdf)); + printf( + "extract for accessibility: %d\n", qpdf_allow_accessibility(qpdf)); + printf("extract for any purpose: %d\n", qpdf_allow_extract_all(qpdf)); + printf("print low resolution: %d\n", qpdf_allow_print_low_res(qpdf)); + printf("print high resolution: %d\n", qpdf_allow_print_high_res(qpdf)); + printf( + "modify document assembly: %d\n", qpdf_allow_modify_assembly(qpdf)); + printf("modify forms: %d\n", qpdf_allow_modify_form(qpdf)); + printf("modify annotations: %d\n", qpdf_allow_modify_annotation(qpdf)); + printf("modify other: %d\n", qpdf_allow_modify_other(qpdf)); + printf("modify anything: %d\n", qpdf_allow_modify_all(qpdf)); } report_errors(); } -static void test02(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test02( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_set_suppress_warnings(qpdf, QPDF_TRUE); if (((qpdf_read(qpdf, infile, password) & QPDF_ERRORS) == 0) && - ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) - { + ((qpdf_init_write(qpdf, outfile) & QPDF_ERRORS) == 0)) { qpdf_set_static_ID(qpdf, QPDF_TRUE); qpdf_write(qpdf); } report_errors(); } -static void test03(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test03( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -203,10 +199,12 @@ static void test03(char const* infile, report_errors(); } -static void test04(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test04( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_set_ignore_xref_streams(qpdf, QPDF_TRUE); qpdf_read(qpdf, infile, password); @@ -216,10 +214,12 @@ static void test04(char const* infile, report_errors(); } -static void test05(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test05( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { int count = 0; qpdf_read(qpdf, infile, password); @@ -233,10 +233,12 @@ static void test05(char const* infile, report_errors(); } -static void test06(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test06( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { char* buf = NULL; unsigned long size = 0; @@ -250,10 +252,12 @@ static void test06(char const* infile, free(buf); } -static void test07(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test07( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -263,10 +267,12 @@ static void test07(char const* infile, report_errors(); } -static void test08(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test08( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -277,10 +283,12 @@ static void test08(char const* infile, report_errors(); } -static void test09(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test09( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -290,20 +298,24 @@ static void test09(char const* infile, report_errors(); } -static void test10(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test10( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_set_attempt_recovery(qpdf, QPDF_FALSE); qpdf_read(qpdf, infile, password); report_errors(); } -static void test11(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test11( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -314,26 +326,37 @@ static void test11(char const* infile, report_errors(); } -static void test12(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test12( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); qpdf_set_static_ID(qpdf, QPDF_TRUE); qpdf_set_r3_encryption_parameters2( - qpdf, "user2", "owner2", QPDF_TRUE, QPDF_TRUE, - QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, + qpdf, + "user2", + "owner2", + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, qpdf_r3p_low); qpdf_write(qpdf); report_errors(); } -static void test13(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test13( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); printf("user password: %s\n", qpdf_get_user_password(qpdf)); @@ -344,10 +367,12 @@ static void test13(char const* infile, report_errors(); } -static void test14(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test14( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -361,34 +386,47 @@ static void test14(char const* infile, report_errors(); } -static void test15(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test15( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); qpdf_set_static_ID(qpdf, QPDF_TRUE); qpdf_set_static_aes_IV(qpdf, QPDF_TRUE); qpdf_set_r4_encryption_parameters2( - qpdf, "user2", "owner2", QPDF_TRUE, QPDF_TRUE, - QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, - qpdf_r3p_low, QPDF_TRUE, QPDF_TRUE); + qpdf, + "user2", + "owner2", + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + qpdf_r3p_low, + QPDF_TRUE, + QPDF_TRUE); qpdf_write(qpdf); report_errors(); } -static void print_info(char const* key) +static void +print_info(char const* key) { char const* value = qpdf_get_info_key(qpdf, key); - printf("Info key %s: %s\n", - key, (value ? value : "(null)")); + printf("Info key %s: %s\n", key, (value ? value : "(null)")); } -static void test16(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test16( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { unsigned long buflen = 0L; unsigned char const* buf = 0; @@ -417,44 +455,66 @@ static void test16(char const* infile, report_errors(); } -static void test17(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test17( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); qpdf_set_static_ID(qpdf, QPDF_TRUE); qpdf_set_static_aes_IV(qpdf, QPDF_TRUE); qpdf_set_r5_encryption_parameters2( - qpdf, "user3", "owner3", QPDF_TRUE, QPDF_TRUE, - QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, - qpdf_r3p_low, QPDF_TRUE); + qpdf, + "user3", + "owner3", + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + qpdf_r3p_low, + QPDF_TRUE); qpdf_write(qpdf); report_errors(); } -static void test18(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test18( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); qpdf_set_static_ID(qpdf, QPDF_TRUE); qpdf_set_static_aes_IV(qpdf, QPDF_TRUE); qpdf_set_r6_encryption_parameters2( - qpdf, "user4", "owner4", QPDF_TRUE, QPDF_TRUE, - QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, QPDF_TRUE, - qpdf_r3p_low, QPDF_TRUE); + qpdf, + "user4", + "owner4", + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + QPDF_TRUE, + qpdf_r3p_low, + QPDF_TRUE); qpdf_write(qpdf); report_errors(); } -static void test19(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test19( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -463,10 +523,12 @@ static void test19(char const* infile, report_errors(); } -static void test20(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test20( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -478,10 +540,12 @@ static void test20(char const* infile, report_errors(); } -static void test21(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test21( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -492,10 +556,12 @@ static void test21(char const* infile, report_errors(); } -static void test22(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test22( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { qpdf_read(qpdf, infile, password); qpdf_init_write(qpdf, outfile); @@ -507,10 +573,12 @@ static void test22(char const* infile, report_errors(); } -static void test23(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test23( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { QPDF_ERROR_CODE status = 0; qpdf_read(qpdf, infile, password); @@ -519,10 +587,12 @@ static void test23(char const* infile, report_errors(); } -static void test24(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test24( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test case is designed for minimal.pdf. Pull objects out of * minimal.pdf to make sure all our accessors work as expected. @@ -537,8 +607,9 @@ static void test24(char const* infile, qpdf_oh root = qpdf_get_root(qpdf); assert(qpdf_oh_get_generation(qpdf, root) == 0); qpdf_oh root_from_trailer = qpdf_oh_get_key(qpdf, trailer, "/Root"); - assert(qpdf_oh_get_object_id(qpdf, root) == - qpdf_oh_get_object_id(qpdf, root_from_trailer)); + assert( + qpdf_oh_get_object_id(qpdf, root) == + qpdf_oh_get_object_id(qpdf, root_from_trailer)); /* Go to the first page and look at all the keys */ qpdf_oh pages = qpdf_oh_get_key(qpdf, root, "/Pages"); @@ -553,8 +624,7 @@ static void test24(char const* infile, assert(qpdf_oh_get_array_n_items(qpdf, kids) == 1); qpdf_oh page1 = qpdf_oh_get_array_item(qpdf, kids, 0); qpdf_oh_begin_dict_key_iter(qpdf, page1); - while (qpdf_oh_dict_more_keys(qpdf)) - { + while (qpdf_oh_dict_more_keys(qpdf)) { printf("page dictionary key: %s\n", qpdf_oh_dict_next_key(qpdf)); } @@ -567,15 +637,16 @@ static void test24(char const* infile, qpdf_oh parent = qpdf_oh_get_key(qpdf, page1, "/Parent"); assert(qpdf_oh_is_indirect(qpdf, parent)); qpdf_oh mediabox = qpdf_oh_get_key(qpdf, page1, "/MediaBox"); - assert(! qpdf_oh_is_scalar(qpdf, mediabox)); + assert(!qpdf_oh_is_scalar(qpdf, mediabox)); assert(qpdf_oh_is_array(qpdf, mediabox)); assert(qpdf_oh_get_array_n_items(qpdf, mediabox) == 4); - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { qpdf_oh item = qpdf_oh_get_array_item(qpdf, mediabox, i); - printf("item %d: %d %.2f\n", - i, qpdf_oh_get_int_value_as_int(qpdf, item), - qpdf_oh_get_numeric_value(qpdf, item)); + printf( + "item %d: %d %.2f\n", + i, + qpdf_oh_get_int_value_as_int(qpdf, item), + qpdf_oh_get_numeric_value(qpdf, item)); } /* Exercise different ways of looking at integers */ @@ -585,15 +656,15 @@ static void test24(char const* infile, assert(qpdf_oh_get_uint_value_as_uint(qpdf, i2) == 612u); assert(qpdf_oh_get_uint_value(qpdf, i2) == 612ull); /* Exercise accessors of other object types */ - assert(! qpdf_oh_is_operator(qpdf, i2)); - assert(! qpdf_oh_is_inline_image(qpdf, i2)); + assert(!qpdf_oh_is_operator(qpdf, i2)); + assert(!qpdf_oh_is_inline_image(qpdf, i2)); /* Chain calls. */ qpdf_oh encoding = qpdf_oh_get_key( - qpdf, qpdf_oh_get_key( - qpdf, qpdf_oh_get_key( - qpdf, qpdf_oh_get_key( - qpdf, page1, "/Resources"), - "/Font"), + qpdf, + qpdf_oh_get_key( + qpdf, + qpdf_oh_get_key( + qpdf, qpdf_oh_get_key(qpdf, page1, "/Resources"), "/Font"), "/F1"), "/Encoding"); assert(strcmp(qpdf_oh_get_name(qpdf, encoding), "/WinAnsiEncoding") == 0); @@ -601,13 +672,12 @@ static void test24(char const* infile, qpdf_oh res = qpdf_oh_get_key_if_dict(qpdf, page1, "/Resources"); assert(qpdf_oh_has_key(qpdf, res, "/Font")); /* check no warning when called with null */ - while (qpdf_more_warnings(qpdf)) - { + while (qpdf_more_warnings(qpdf)) { qpdf_next_warning(qpdf); } res = qpdf_oh_get_key_if_dict( qpdf, qpdf_oh_get_key_if_dict(qpdf, page1, "/Missing"), "/Font"); - assert(! qpdf_more_warnings(qpdf)); + assert(!qpdf_more_warnings(qpdf)); /* Look at page contents to exercise stream functions */ qpdf_oh contents = qpdf_oh_get_key(qpdf, page1, "/Contents"); @@ -615,37 +685,38 @@ static void test24(char const* infile, assert(qpdf_oh_get_type_code(qpdf, contents) == ot_stream); assert(strcmp(qpdf_oh_get_type_name(qpdf, contents), "stream") == 0); qpdf_oh contents_dict = qpdf_oh_get_dict(qpdf, contents); - assert(! qpdf_oh_is_scalar(qpdf, contents)); - assert(! qpdf_oh_is_scalar(qpdf, contents_dict)); + assert(!qpdf_oh_is_scalar(qpdf, contents)); + assert(!qpdf_oh_is_scalar(qpdf, contents_dict)); qpdf_oh contents_length = qpdf_oh_get_key(qpdf, contents_dict, "/Length"); assert(qpdf_oh_is_integer(qpdf, contents_length)); assert(qpdf_oh_get_type_code(qpdf, contents_length) == ot_integer); - assert(strcmp(qpdf_oh_get_type_name(qpdf, contents_length), "integer") == 0); + assert( + strcmp(qpdf_oh_get_type_name(qpdf, contents_length), "integer") == 0); assert(qpdf_oh_is_scalar(qpdf, contents_length)); assert(qpdf_oh_is_number(qpdf, contents_length)); qpdf_oh contents_array = qpdf_oh_wrap_in_array(qpdf, contents); assert(qpdf_oh_get_array_n_items(qpdf, contents_array) == 1); - assert(qpdf_oh_get_object_id( - qpdf, qpdf_oh_get_array_item(qpdf, contents_array, 0)) == - qpdf_oh_get_object_id(qpdf, contents)); + assert( + qpdf_oh_get_object_id( + qpdf, qpdf_oh_get_array_item(qpdf, contents_array, 0)) == + qpdf_oh_get_object_id(qpdf, contents)); /* Wrap in array for a non-trivial case */ qpdf_oh wrapped_contents_array = qpdf_oh_wrap_in_array(qpdf, contents_array); assert(qpdf_oh_get_array_n_items(qpdf, wrapped_contents_array) == 1); - assert(qpdf_oh_get_object_id( - qpdf, qpdf_oh_get_array_item(qpdf, wrapped_contents_array, 0)) == - qpdf_oh_get_object_id(qpdf, contents)); + assert( + qpdf_oh_get_object_id( + qpdf, qpdf_oh_get_array_item(qpdf, wrapped_contents_array, 0)) == + qpdf_oh_get_object_id(qpdf, contents)); /* Exercise functions that work with indirect objects */ qpdf_oh resources = qpdf_oh_get_key(qpdf, page1, "/Resources"); qpdf_oh procset = qpdf_oh_get_key(qpdf, resources, "/ProcSet"); - assert(strcmp(qpdf_oh_unparse(qpdf, procset), - "5 0 R") == 0); - assert(strcmp(qpdf_oh_unparse_resolved(qpdf, procset), - "[ /PDF /Text ]") == 0); + assert(strcmp(qpdf_oh_unparse(qpdf, procset), "5 0 R") == 0); + assert( + strcmp(qpdf_oh_unparse_resolved(qpdf, procset), "[ /PDF /Text ]") == 0); qpdf_oh_make_direct(qpdf, procset); - assert(strcmp(qpdf_oh_unparse(qpdf, procset), - "[ /PDF /Text ]") == 0); + assert(strcmp(qpdf_oh_unparse(qpdf, procset), "[ /PDF /Text ]") == 0); /* The replaced /ProcSet can be seen to be a direct object in the * expected output PDF. */ @@ -664,8 +735,8 @@ static void test24(char const* infile, assert(strcmp(qpdf_oh_get_type_name(qpdf, contents), "null") == 0); assert(qpdf_oh_is_array(qpdf, mediabox)); qpdf_oh_release_all(qpdf); - assert(! qpdf_oh_is_null(qpdf, mediabox)); - assert(! qpdf_oh_is_array(qpdf, mediabox)); + assert(!qpdf_oh_is_null(qpdf, mediabox)); + assert(!qpdf_oh_is_array(qpdf, mediabox)); /* Make sure something is assigned when we exit so we check that * it gets properly freed. */ @@ -679,10 +750,12 @@ static void test24(char const* infile, report_errors(); } -static void test25(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test25( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test case is designed for minimal.pdf. */ qpdf_read(qpdf, infile, password); @@ -699,107 +772,116 @@ static void test25(char const* infile, qpdf_oh p_bool = qpdf_oh_get_array_item(qpdf, parsed, 5); qpdf_oh p_bool_f = qpdf_oh_get_array_item(qpdf, parsed, 6); qpdf_oh p_name = qpdf_oh_get_array_item(qpdf, parsed, 7); - assert(qpdf_oh_is_integer(qpdf, p_int) && - qpdf_oh_get_int_value_as_int(qpdf, p_int) == 1); + assert( + qpdf_oh_is_integer(qpdf, p_int) && + qpdf_oh_get_int_value_as_int(qpdf, p_int) == 1); long long l = 0; assert(qpdf_oh_get_value_as_longlong(qpdf, p_bool, &l) == QPDF_FALSE); - assert((qpdf_oh_get_value_as_longlong(qpdf, p_int, &l) == QPDF_TRUE) && - (l == 1)); + assert( + (qpdf_oh_get_value_as_longlong(qpdf, p_int, &l) == QPDF_TRUE) && + (l == 1)); int i = 0; assert(qpdf_oh_get_value_as_int(qpdf, p_bool, &i) == QPDF_FALSE); - assert((qpdf_oh_get_value_as_int(qpdf, p_int, &i) == QPDF_TRUE) && - (i == 1)); + assert( + (qpdf_oh_get_value_as_int(qpdf, p_int, &i) == QPDF_TRUE) && (i == 1)); unsigned long long ul = 0u; assert(qpdf_oh_get_value_as_ulonglong(qpdf, p_bool, &ul) == QPDF_FALSE); - assert((qpdf_oh_get_value_as_ulonglong(qpdf, p_int, &ul) == QPDF_TRUE) && - (ul == 1u)); + assert( + (qpdf_oh_get_value_as_ulonglong(qpdf, p_int, &ul) == QPDF_TRUE) && + (ul == 1u)); unsigned int u = 0u; assert(qpdf_oh_get_value_as_uint(qpdf, p_bool, &u) == QPDF_FALSE); - assert((qpdf_oh_get_value_as_uint(qpdf, p_int, &u) == QPDF_TRUE) && - (u == 1u)); + assert( + (qpdf_oh_get_value_as_uint(qpdf, p_int, &u) == QPDF_TRUE) && (u == 1u)); double d = 0.0; assert(qpdf_oh_get_value_as_number(qpdf, p_bool, &d) == QPDF_FALSE); - assert((qpdf_oh_get_value_as_number(qpdf, p_int, &d) == QPDF_TRUE) && - ((d - 1.0) < 1e-6) && ((d - 1.0) > -1e-6)); + assert( + (qpdf_oh_get_value_as_number(qpdf, p_int, &d) == QPDF_TRUE) && + ((d - 1.0) < 1e-6) && ((d - 1.0) > -1e-6)); assert(qpdf_oh_get_type_code(qpdf, p_int) == ot_integer); assert(strcmp(qpdf_oh_get_type_name(qpdf, p_int), "integer") == 0); - assert(qpdf_oh_is_real(qpdf, p_real) && - (strcmp(qpdf_oh_get_real_value(qpdf, p_real), "2.0") == 0) && - qpdf_oh_get_numeric_value(qpdf, p_real) == 2.0); + assert( + qpdf_oh_is_real(qpdf, p_real) && + (strcmp(qpdf_oh_get_real_value(qpdf, p_real), "2.0") == 0) && + qpdf_oh_get_numeric_value(qpdf, p_real) == 2.0); const char* r = ""; size_t length = 0; - assert((qpdf_oh_get_value_as_real(qpdf, p_name, &r, &length) == - QPDF_FALSE) && - (strcmp(r, "") == 0) && - (length == 0)); - assert((qpdf_oh_get_value_as_real(qpdf, p_real, &r, &length) == - QPDF_TRUE) && - (strcmp(r, "2.0") == 0) && - (length == 3)); + assert( + (qpdf_oh_get_value_as_real(qpdf, p_name, &r, &length) == QPDF_FALSE) && + (strcmp(r, "") == 0) && (length == 0)); + assert( + (qpdf_oh_get_value_as_real(qpdf, p_real, &r, &length) == QPDF_TRUE) && + (strcmp(r, "2.0") == 0) && (length == 3)); assert(qpdf_oh_get_type_code(qpdf, p_real) == ot_real); assert(strcmp(qpdf_oh_get_type_name(qpdf, p_real), "real") == 0); - assert(qpdf_oh_is_string(qpdf, p_string) && - (strcmp(qpdf_oh_get_string_value(qpdf, p_string), "3\xf7") == 0) && - (strcmp(qpdf_oh_get_utf8_value(qpdf, p_string), "3\xc3\xb7") == 0) && - (strcmp(qpdf_oh_unparse_binary(qpdf, p_string), "<33f7>") == 0)); + assert( + qpdf_oh_is_string(qpdf, p_string) && + (strcmp(qpdf_oh_get_string_value(qpdf, p_string), "3\xf7") == 0) && + (strcmp(qpdf_oh_get_utf8_value(qpdf, p_string), "3\xc3\xb7") == 0) && + (strcmp(qpdf_oh_unparse_binary(qpdf, p_string), "<33f7>") == 0)); const char* str = ""; length = 0; - assert((qpdf_oh_get_value_as_string(qpdf, p_name, &str, &length) == - QPDF_FALSE) && - (strcmp(str, "") == 0) && - (length == 0)); - assert((qpdf_oh_get_value_as_string(qpdf, p_string, &str, &length) == - QPDF_TRUE) && - (strcmp(str, "3\xf7") == 0) && - (length == 2)); + assert( + (qpdf_oh_get_value_as_string(qpdf, p_name, &str, &length) == + QPDF_FALSE) && + (strcmp(str, "") == 0) && (length == 0)); + assert( + (qpdf_oh_get_value_as_string(qpdf, p_string, &str, &length) == + QPDF_TRUE) && + (strcmp(str, "3\xf7") == 0) && (length == 2)); const char* utf8 = ""; length = 0; - assert((qpdf_oh_get_value_as_utf8(qpdf, p_name, &utf8, &length) == - QPDF_FALSE) && - (strcmp(utf8, "") == 0) && - (length == 0)); - assert((qpdf_oh_get_value_as_utf8(qpdf, p_string, &utf8, &length) == - QPDF_TRUE) && - (strcmp(utf8, "3\xc3\xb7") == 0) && - (length == 3)); + assert( + (qpdf_oh_get_value_as_utf8(qpdf, p_name, &utf8, &length) == + QPDF_FALSE) && + (strcmp(utf8, "") == 0) && (length == 0)); + assert( + (qpdf_oh_get_value_as_utf8(qpdf, p_string, &utf8, &length) == + QPDF_TRUE) && + (strcmp(utf8, "3\xc3\xb7") == 0) && (length == 3)); assert(qpdf_oh_get_type_code(qpdf, p_string) == ot_string); - assert(! qpdf_oh_is_name_and_equals(qpdf, p_string, "3\xf7")); + assert(!qpdf_oh_is_name_and_equals(qpdf, p_string, "3\xf7")); assert(strcmp(qpdf_oh_get_type_name(qpdf, p_string), "string") == 0); assert(qpdf_oh_is_dictionary(qpdf, p_dict)); qpdf_oh p_five = qpdf_oh_get_key(qpdf, p_dict, "/Four"); assert(qpdf_oh_is_or_has_name(qpdf, p_five, "/Five")); - assert(! qpdf_oh_is_name_and_equals(qpdf, p_five, "/Five")); + assert(!qpdf_oh_is_name_and_equals(qpdf, p_five, "/Five")); assert(qpdf_oh_is_or_has_name( - qpdf, qpdf_oh_get_array_item(qpdf, p_five, 0), "/Five")); + qpdf, qpdf_oh_get_array_item(qpdf, p_five, 0), "/Five")); assert(qpdf_oh_is_name_and_equals( - qpdf, qpdf_oh_get_array_item(qpdf, p_five, 0), "/Five")); + qpdf, qpdf_oh_get_array_item(qpdf, p_five, 0), "/Five")); assert(qpdf_oh_is_null(qpdf, p_null)); assert(qpdf_oh_get_type_code(qpdf, p_null) == ot_null); assert(strcmp(qpdf_oh_get_type_name(qpdf, p_null), "null") == 0); - assert(qpdf_oh_is_bool(qpdf, p_bool) && - (qpdf_oh_get_bool_value(qpdf, p_bool) == QPDF_TRUE)); + assert( + qpdf_oh_is_bool(qpdf, p_bool) && + (qpdf_oh_get_bool_value(qpdf, p_bool) == QPDF_TRUE)); QPDF_BOOL b = QPDF_FALSE; - assert((qpdf_oh_get_value_as_bool(qpdf, p_int, &b) == QPDF_FALSE) && - b == QPDF_FALSE); - assert((qpdf_oh_get_value_as_bool(qpdf, p_bool, &b) == QPDF_TRUE) && - b == QPDF_TRUE); - assert((qpdf_oh_get_value_as_bool(qpdf, p_bool_f, &b) == QPDF_TRUE) && - b == QPDF_FALSE); + assert( + (qpdf_oh_get_value_as_bool(qpdf, p_int, &b) == QPDF_FALSE) && + b == QPDF_FALSE); + assert( + (qpdf_oh_get_value_as_bool(qpdf, p_bool, &b) == QPDF_TRUE) && + b == QPDF_TRUE); + assert( + (qpdf_oh_get_value_as_bool(qpdf, p_bool_f, &b) == QPDF_TRUE) && + b == QPDF_FALSE); assert(qpdf_oh_get_type_code(qpdf, p_bool) == ot_boolean); assert(strcmp(qpdf_oh_get_type_name(qpdf, p_bool), "boolean") == 0); const char* n = ""; length = 0; - assert((qpdf_oh_get_value_as_name(qpdf, p_string, &n, &length) == - QPDF_FALSE) && - (strcmp(n, "") == 0) && - (length == 0)); - assert((qpdf_oh_get_value_as_name(qpdf, p_name, &n, &length) == - QPDF_TRUE) && - (strcmp(n, "/Six") == 0) && - (length == 4)); + assert( + (qpdf_oh_get_value_as_name(qpdf, p_string, &n, &length) == + QPDF_FALSE) && + (strcmp(n, "") == 0) && (length == 0)); + assert( + (qpdf_oh_get_value_as_name(qpdf, p_name, &n, &length) == QPDF_TRUE) && + (strcmp(n, "/Six") == 0) && (length == 4)); qpdf_oh_erase_item(qpdf, parsed, 4); qpdf_oh_insert_item( - qpdf, parsed, 2, + qpdf, + parsed, + 2, qpdf_oh_parse( qpdf, "<>")); qpdf_oh new_dict = qpdf_oh_get_array_item(qpdf, parsed, 2); @@ -808,43 +890,35 @@ static void test25(char const* infile, assert(qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test", "")); assert(qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test", 0)); assert(qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test", "/Marvin")); - assert(! qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test2", "")); - assert(! qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test", "/M")); + assert(!qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test2", "")); + assert(!qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "/Test", "/M")); assert(qpdf_oh_is_dictionary_of_type(qpdf, new_dict, "", "")); qpdf_oh new_array = qpdf_oh_new_array(qpdf); - qpdf_oh_replace_or_remove_key( - qpdf, new_dict, "/A", qpdf_oh_new_null(qpdf)); - qpdf_oh_replace_or_remove_key( - qpdf, new_dict, "/B", new_array); - qpdf_oh_replace_key( - qpdf, new_dict, "/C", qpdf_oh_new_dictionary(qpdf)); + qpdf_oh_replace_or_remove_key(qpdf, new_dict, "/A", qpdf_oh_new_null(qpdf)); + qpdf_oh_replace_or_remove_key(qpdf, new_dict, "/B", new_array); + qpdf_oh_replace_key(qpdf, new_dict, "/C", qpdf_oh_new_dictionary(qpdf)); qpdf_oh_remove_key(qpdf, new_dict, "/D"); - assert(! qpdf_oh_has_key(qpdf, new_dict, "/A")); - assert(! qpdf_oh_has_key(qpdf, new_dict, "/D")); + assert(!qpdf_oh_has_key(qpdf, new_dict, "/A")); + assert(!qpdf_oh_has_key(qpdf, new_dict, "/D")); + qpdf_oh_append_item(qpdf, new_array, qpdf_oh_new_string(qpdf, "potato")); qpdf_oh_append_item( - qpdf, new_array, qpdf_oh_new_string(qpdf, "potato")); - qpdf_oh_append_item( - qpdf, new_array, + qpdf, + new_array, qpdf_oh_new_unicode_string(qpdf, "qww\xc3\xb7\xcf\x80")); qpdf_oh_append_item( - qpdf, new_array, + qpdf, + new_array, qpdf_oh_new_binary_unicode_string(qpdf, "qw\x00w\xc3\xb7\xcf\x80", 8)); qpdf_oh_append_item(qpdf, new_array, qpdf_oh_new_null(qpdf)); /* 2 */ qpdf_oh_append_item(qpdf, new_array, qpdf_oh_new_null(qpdf)); /* 3 */ qpdf_oh_set_array_item( - qpdf, new_array, 3, - qpdf_oh_new_name(qpdf, "/Quack")); + qpdf, new_array, 3, qpdf_oh_new_name(qpdf, "/Quack")); qpdf_oh_append_item( - qpdf, new_array, - qpdf_oh_new_real_from_double(qpdf, 4.123, 2)); + qpdf, new_array, qpdf_oh_new_real_from_double(qpdf, 4.123, 2)); qpdf_oh_append_item( - qpdf, new_array, - qpdf_oh_new_real_from_string(qpdf, "5.0")); - qpdf_oh_append_item( - qpdf, new_array, - qpdf_oh_new_integer(qpdf, 6)); - qpdf_oh_append_item( - qpdf, new_array, qpdf_oh_new_bool(qpdf, QPDF_TRUE)); + qpdf, new_array, qpdf_oh_new_real_from_string(qpdf, "5.0")); + qpdf_oh_append_item(qpdf, new_array, qpdf_oh_new_integer(qpdf, 6)); + qpdf_oh_append_item(qpdf, new_array, qpdf_oh_new_bool(qpdf, QPDF_TRUE)); qpdf_oh_replace_key(qpdf, root, "/QTest", new_dict); qpdf_init_write(qpdf, outfile); @@ -854,23 +928,27 @@ static void test25(char const* infile, qpdf_write(qpdf); report_errors(); } -static void test26(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test26( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* Make sure we detect uninitialized objects */ qpdf_data qpdf2 = qpdf_init(); qpdf_oh trailer = qpdf_get_trailer(qpdf2); - assert(! qpdf_oh_is_initialized(qpdf2, trailer)); + assert(!qpdf_oh_is_initialized(qpdf2, trailer)); assert(qpdf_oh_get_type_code(qpdf, trailer) == ot_uninitialized); qpdf_cleanup(&qpdf2); } -static void test27(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test27( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* Exercise a string with a null. Since the regular methods return * char*, we can't see past the null character without looking @@ -878,44 +956,59 @@ static void test27(char const* infile, */ qpdf_oh p_string_with_null = qpdf_oh_parse(qpdf, "<6f6e650074776f>"); assert(qpdf_oh_is_string(qpdf, p_string_with_null)); - assert(strcmp(qpdf_oh_get_string_value(qpdf, p_string_with_null), - "one") == 0); + assert( + strcmp(qpdf_oh_get_string_value(qpdf, p_string_with_null), "one") == 0); assert(qpdf_get_last_string_length(qpdf) == 7); /* memcmp adds a character to verify the trailing null */ - assert(memcmp(qpdf_oh_get_string_value(qpdf, p_string_with_null), - "one\000two", 8) == 0); + assert( + memcmp( + qpdf_oh_get_string_value(qpdf, p_string_with_null), + "one\000two", + 8) == 0); size_t length = 0; p_string_with_null = qpdf_oh_new_binary_string(qpdf, "potato\000salad", 12); /* memcmp adds a character to verify the trailing null */ - assert(memcmp(qpdf_oh_get_binary_string_value( - qpdf, p_string_with_null, &length), - "potato\000salad", 13) == 0); + assert( + memcmp( + qpdf_oh_get_binary_string_value(qpdf, p_string_with_null, &length), + "potato\000salad", + 13) == 0); assert(qpdf_get_last_string_length(qpdf) == 12); assert(length == 12); /* repeat for UTF8 string */ - qpdf_oh p_utf8_string_with_null = qpdf_oh_parse(qpdf, - ""); + qpdf_oh p_utf8_string_with_null = + qpdf_oh_parse(qpdf, ""); assert(qpdf_oh_is_string(qpdf, p_utf8_string_with_null)); - assert(strcmp(qpdf_oh_get_utf8_value(qpdf, p_utf8_string_with_null), - "qw\x00w\xc3\xb7\xcf\x80") == 0); + assert( + strcmp( + qpdf_oh_get_utf8_value(qpdf, p_utf8_string_with_null), + "qw\x00w\xc3\xb7\xcf\x80") == 0); assert(qpdf_get_last_string_length(qpdf) == 8); /* memcmp adds a character to verify the trailing null */ - assert(memcmp(qpdf_oh_get_utf8_value(qpdf, p_utf8_string_with_null), - "qw\x00w\xc3\xb7\xcf\x80", 8) == 0); - p_utf8_string_with_null = qpdf_oh_new_binary_unicode_string( - qpdf, "qw\x00w\xc3\xb7\xcf\x80", 8); + assert( + memcmp( + qpdf_oh_get_utf8_value(qpdf, p_utf8_string_with_null), + "qw\x00w\xc3\xb7\xcf\x80", + 8) == 0); + p_utf8_string_with_null = + qpdf_oh_new_binary_unicode_string(qpdf, "qw\x00w\xc3\xb7\xcf\x80", 8); /* memcmp adds a character to verify the trailing null */ - assert(memcmp(qpdf_oh_get_binary_utf8_value( - qpdf, p_utf8_string_with_null, &length), - "qw\x00w\xc3\xb7\xcf\x80", 9) == 0); + assert( + memcmp( + qpdf_oh_get_binary_utf8_value( + qpdf, p_utf8_string_with_null, &length), + "qw\x00w\xc3\xb7\xcf\x80", + 9) == 0); assert(qpdf_get_last_string_length(qpdf) == 8); assert(length == 8); } -static void test28(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test28( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test case is designed for minimal.pdf. */ @@ -934,29 +1027,33 @@ static void test28(char const* infile, assert(wrapped_mediabox != mediabox); assert(cloned_mediabox != mediabox); assert(qpdf_oh_get_array_n_items(qpdf, wrapped_mediabox) == 4); - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { qpdf_oh item = qpdf_oh_get_array_item(qpdf, mediabox, i); qpdf_oh item2 = qpdf_oh_get_array_item(qpdf, wrapped_mediabox, i); qpdf_oh item3 = qpdf_oh_get_array_item(qpdf, cloned_mediabox, i); - assert(qpdf_oh_get_int_value_as_int(qpdf, item) == - (i == 0 ? 0 : - i == 1 ? 0 : - i == 2 ? 612 : - i == 3 ? 792 : - -1)); - assert(qpdf_oh_get_int_value_as_int(qpdf, item) == - qpdf_oh_get_int_value_as_int(qpdf, item2)); - assert(qpdf_oh_get_int_value_as_int(qpdf, item) == - qpdf_oh_get_int_value_as_int(qpdf, item3)); + assert( + qpdf_oh_get_int_value_as_int(qpdf, item) == + (i == 0 ? 0 + : i == 1 ? 0 + : i == 2 ? 612 + : i == 3 ? 792 + : -1)); + assert( + qpdf_oh_get_int_value_as_int(qpdf, item) == + qpdf_oh_get_int_value_as_int(qpdf, item2)); + assert( + qpdf_oh_get_int_value_as_int(qpdf, item) == + qpdf_oh_get_int_value_as_int(qpdf, item3)); qpdf_oh_release(qpdf, item); } } -static void test29(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test29( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* Trap exceptions thrown by object accessors. Type mismatches are * errors rather than warnings when they don't have an owning QPDF @@ -968,14 +1065,14 @@ static void test29(char const* infile, qpdf_oh root = qpdf_get_root(qpdf); handle_oh_error(qpdf, "get root"); assert(root != 0); - assert(! qpdf_oh_is_initialized(qpdf, root)); + assert(!qpdf_oh_is_initialized(qpdf, root)); - assert(! qpdf_oh_is_initialized(qpdf, qpdf_oh_parse(qpdf, "[oops"))); + assert(!qpdf_oh_is_initialized(qpdf, qpdf_oh_parse(qpdf, "[oops"))); handle_oh_error(qpdf, "bad parse"); report_errors(); - assert(qpdf_oh_get_int_value_as_int( - qpdf, qpdf_oh_new_string(qpdf, "x")) == 0); + assert( + qpdf_oh_get_int_value_as_int(qpdf, qpdf_oh_new_string(qpdf, "x")) == 0); handle_oh_error(qpdf, "type mismatch (int operation on string)"); qpdf_oh int_oh = qpdf_oh_new_integer(qpdf, 12); assert(strlen(qpdf_oh_get_string_value(qpdf, int_oh)) == 0); @@ -1004,19 +1101,23 @@ static void test29(char const* infile, report_errors(); } -static void test30(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test30( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { assert(qpdf_read(qpdf, infile, password) & QPDF_ERRORS); /* Fail to handle error */ } -static void test31(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test31( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* Make sure type warnings have a specific error code. This test * case is designed for minimal.pdf. @@ -1024,17 +1125,19 @@ static void test31(char const* infile, qpdf_read(qpdf, infile, password); qpdf_oh trailer = qpdf_get_trailer(qpdf); assert(qpdf_oh_get_int_value(qpdf, trailer) == 0LL); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_more_warnings(qpdf)); qpdf_error e = qpdf_next_warning(qpdf); assert(qpdf_get_error_code(qpdf, e) == qpdf_e_object); report_errors(); } -static void test32(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test32( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test case is designed for minimal.pdf. */ assert(qpdf_read(qpdf, infile, password) == 0); @@ -1044,10 +1147,12 @@ static void test32(char const* infile, report_errors(); } -static void test33(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test33( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test case is designed for minimal.pdf. */ @@ -1058,7 +1163,7 @@ static void test33(char const* infile, qpdf_oh kids = qpdf_oh_get_key(qpdf, pages, "/Kids"); qpdf_oh page1 = qpdf_oh_get_array_item(qpdf, kids, 0); qpdf_oh mediabox = qpdf_oh_get_key(qpdf, page1, "/MediaBox"); - assert(! qpdf_oh_is_indirect(qpdf, mediabox)); + assert(!qpdf_oh_is_indirect(qpdf, mediabox)); qpdf_oh i_mediabox = qpdf_make_indirect_object(qpdf, mediabox); assert(qpdf_oh_is_indirect(qpdf, i_mediabox)); qpdf_oh_replace_key(qpdf, page1, "/MediaBox", i_mediabox); @@ -1081,10 +1186,12 @@ static void test33(char const* infile, report_errors(); } -static void test34(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test34( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test expects 11-pages.pdf as file1 and minimal.pdf as xarg. */ @@ -1103,8 +1210,8 @@ static void test34(char const* infile, assert(qpdf_oh_get_object_id(qpdf, qpdf_get_page_n(qpdf, 10)) == 14); qpdf_oh page3 = qpdf_get_page_n(qpdf, 3); assert(qpdf_find_page_by_oh(qpdf, page3) == 3); - assert(qpdf_find_page_by_id( - qpdf, qpdf_oh_get_object_id(qpdf, page3), 0) == 3); + assert( + qpdf_find_page_by_id(qpdf, qpdf_oh_get_object_id(qpdf, page3), 0) == 3); /* Add other page to the end */ qpdf_oh opage0 = qpdf_get_page_n(qpdf2, 0); @@ -1125,10 +1232,12 @@ static void test34(char const* infile, qpdf_cleanup(&qpdf2); } -static void test35(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test35( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test uses 11-pages.pdf */ @@ -1136,22 +1245,22 @@ static void test35(char const* infile, assert(qpdf_has_error(qpdf)); qpdf_error e = qpdf_get_error(qpdf); assert(qpdf_get_error_code(qpdf, e) != QPDF_SUCCESS); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_read(qpdf, infile, password) == 0); qpdf_oh range = qpdf_get_page_n(qpdf, 11); - assert(! qpdf_oh_is_initialized(qpdf, range)); + assert(!qpdf_oh_is_initialized(qpdf, range)); assert(qpdf_has_error(qpdf)); e = qpdf_get_error(qpdf); assert(qpdf_get_error_code(qpdf, e) != QPDF_SUCCESS); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_find_page_by_id(qpdf, 100, 0) == -1); assert(qpdf_has_error(qpdf)); e = qpdf_get_error(qpdf); assert(qpdf_get_error_code(qpdf, e) != QPDF_SUCCESS); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_find_page_by_oh(qpdf, qpdf_get_root(qpdf)) == -1); assert(qpdf_more_warnings(qpdf)); @@ -1160,23 +1269,25 @@ static void test35(char const* infile, assert(qpdf_has_error(qpdf)); e = qpdf_get_error(qpdf); assert(qpdf_get_error_code(qpdf, e) != QPDF_SUCCESS); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_find_page_by_id(qpdf, 100, 0) == -1); assert(qpdf_has_error(qpdf)); e = qpdf_get_error(qpdf); assert(qpdf_get_error_code(qpdf, e) != QPDF_SUCCESS); - assert(! qpdf_has_error(qpdf)); + assert(!qpdf_has_error(qpdf)); assert(qpdf_add_page(qpdf, qpdf, 1000, QPDF_FALSE) != 0); report_errors(); } -static void test36(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test36( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test uses inherited-rotate.pdf */ @@ -1188,7 +1299,7 @@ static void test36(char const* infile, qpdf_oh r = qpdf_oh_get_key(qpdf, page0, "/Rotate"); assert(qpdf_oh_get_int_value(qpdf, r) == 90); qpdf_oh_remove_key(qpdf, page0, "/Rotate"); - assert(! qpdf_oh_has_key(qpdf, page0, "/Rotate")); + assert(!qpdf_oh_has_key(qpdf, page0, "/Rotate")); assert(qpdf_push_inherited_attributes_to_page(qpdf) == 0); r = qpdf_oh_get_key(qpdf, page0, "/Rotate"); @@ -1197,10 +1308,12 @@ static void test36(char const* infile, assert(qpdf_add_page(qpdf, qpdf, page0, QPDF_TRUE) == 0); } -static void test37(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test37( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test uses 11-pages.pdf */ @@ -1216,10 +1329,12 @@ static void test37(char const* infile, assert(qpdf_get_num_pages(qpdf) == 10); } -static void test38(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test38( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test expects 11-pages.pdf. */ @@ -1228,30 +1343,35 @@ static void test38(char const* infile, assert(qpdf_read(qpdf, infile, password) == 0); qpdf_oh stream = qpdf_get_object_by_id(qpdf, 17, 0); qpdf_oh dict = qpdf_oh_get_dict(qpdf, stream); - assert(qpdf_oh_get_int_value_as_int( - qpdf, qpdf_oh_get_key(qpdf, dict, "/Length")) == 53); + assert( + qpdf_oh_get_int_value_as_int( + qpdf, qpdf_oh_get_key(qpdf, dict, "/Length")) == 53); /* Get raw data */ - unsigned char *buf = 0; + unsigned char* buf = 0; size_t len = 0; - assert(qpdf_oh_get_stream_data( - qpdf, stream, qpdf_dl_none, 0, &buf, &len) == 0); + assert( + qpdf_oh_get_stream_data(qpdf, stream, qpdf_dl_none, 0, &buf, &len) == + 0); assert(len == 53); assert(((int)buf[0] == 'x') && ((int)buf[1] == 0234)); free(buf); /* Test whether filterable */ QPDF_BOOL filtered = QPDF_FALSE; - assert(qpdf_oh_get_stream_data( - qpdf, stream, qpdf_dl_all, &filtered, 0, 0) == 0); + assert( + qpdf_oh_get_stream_data(qpdf, stream, qpdf_dl_all, &filtered, 0, 0) == + 0); assert(filtered == QPDF_TRUE); /* Get filtered data */ - assert(qpdf_oh_get_stream_data( - qpdf, stream, qpdf_dl_all, 0, &buf, &len) == 0); + assert( + qpdf_oh_get_stream_data(qpdf, stream, qpdf_dl_all, 0, &buf, &len) == 0); assert(len == 47); - assert(memcmp((char const*)buf, - "BT /F1 15 Tf 72 720 Td (Original page 2) Tj ET\n", - len) == 0); + assert( + memcmp( + (char const*)buf, + "BT /F1 15 Tf 72 720 Td (Original page 2) Tj ET\n", + len) == 0); /* Get page data */ qpdf_oh page2 = qpdf_get_page_n(qpdf, 1); /* 0-based index */ @@ -1275,10 +1395,12 @@ static void test38(char const* infile, report_errors(); } -static void test39(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test39( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test expects 11-pages.pdf as file1 and minimal.pdf as xarg. */ @@ -1302,10 +1424,12 @@ static void test39(char const* infile, qpdf_cleanup(&qpdf2); } -static void test40(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test40( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* This test expects minimal.pdf. */ @@ -1314,9 +1438,12 @@ static void test40(char const* infile, assert(qpdf_read(qpdf, infile, password) == 0); qpdf_oh stream = qpdf_oh_new_stream(qpdf); qpdf_oh_replace_stream_data( - qpdf, stream, - (unsigned char*)"12345\000abcde", 11, /* embedded null */ - qpdf_oh_new_null(qpdf), qpdf_oh_new_null(qpdf)); + qpdf, + stream, + (unsigned char*)"12345\000abcde", + 11, /* embedded null */ + qpdf_oh_new_null(qpdf), + qpdf_oh_new_null(qpdf)); qpdf_oh root = qpdf_get_root(qpdf); qpdf_oh_replace_key(qpdf, root, "/Potato", stream); @@ -1328,10 +1455,12 @@ static void test40(char const* infile, report_errors(); } -static void test41(char const* infile, - char const* password, - char const* outfile, - char const* xarg) +static void +test41( + char const* infile, + char const* password, + char const* outfile, + char const* xarg) { /* Empty PDF -- infile is ignored*/ assert(qpdf_empty_pdf(qpdf) == 0); @@ -1341,7 +1470,8 @@ static void test41(char const* infile, report_errors(); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { char* p = 0; int n = 0; @@ -1351,26 +1481,19 @@ int main(int argc, char* argv[]) char const* xarg = 0; void (*fn)(char const*, char const*, char const*, char const*) = 0; - if ((p = strrchr(argv[0], '/')) != NULL) - { + if ((p = strrchr(argv[0], '/')) != NULL) { whoami = p + 1; - } - else if ((p = strrchr(argv[0], '\\')) != NULL) - { + } else if ((p = strrchr(argv[0], '\\')) != NULL) { whoami = p + 1; - } - else - { + } else { whoami = argv[0]; } - if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { printf("qpdf-ctest version %s\n", qpdf_get_qpdf_version()); return 0; } - if (argc < 5) - { + if (argc < 5) { fprintf(stderr, "usage: %s n infile password outfile\n", whoami); exit(2); } @@ -1381,51 +1504,51 @@ int main(int argc, char* argv[]) outfile = argv[4]; xarg = (argc > 5 ? argv[5] : 0); - fn = ((n == 1) ? test01 : - (n == 2) ? test02 : - (n == 3) ? test03 : - (n == 4) ? test04 : - (n == 5) ? test05 : - (n == 6) ? test06 : - (n == 7) ? test07 : - (n == 8) ? test08 : - (n == 9) ? test09 : - (n == 10) ? test10 : - (n == 11) ? test11 : - (n == 12) ? test12 : - (n == 13) ? test13 : - (n == 14) ? test14 : - (n == 15) ? test15 : - (n == 16) ? test16 : - (n == 17) ? test17 : - (n == 18) ? test18 : - (n == 19) ? test19 : - (n == 20) ? test20 : - (n == 21) ? test21 : - (n == 22) ? test22 : - (n == 23) ? test23 : - (n == 24) ? test24 : - (n == 25) ? test25 : - (n == 26) ? test26 : - (n == 27) ? test27 : - (n == 28) ? test28 : - (n == 29) ? test29 : - (n == 30) ? test30 : - (n == 31) ? test31 : - (n == 32) ? test32 : - (n == 33) ? test33 : - (n == 34) ? test34 : - (n == 35) ? test35 : - (n == 36) ? test36 : - (n == 37) ? test37 : - (n == 38) ? test38 : - (n == 39) ? test39 : - (n == 40) ? test40 : - (n == 41) ? test41 : - 0); + fn = + ((n == 1) ? test01 + : (n == 2) ? test02 + : (n == 3) ? test03 + : (n == 4) ? test04 + : (n == 5) ? test05 + : (n == 6) ? test06 + : (n == 7) ? test07 + : (n == 8) ? test08 + : (n == 9) ? test09 + : (n == 10) ? test10 + : (n == 11) ? test11 + : (n == 12) ? test12 + : (n == 13) ? test13 + : (n == 14) ? test14 + : (n == 15) ? test15 + : (n == 16) ? test16 + : (n == 17) ? test17 + : (n == 18) ? test18 + : (n == 19) ? test19 + : (n == 20) ? test20 + : (n == 21) ? test21 + : (n == 22) ? test22 + : (n == 23) ? test23 + : (n == 24) ? test24 + : (n == 25) ? test25 + : (n == 26) ? test26 + : (n == 27) ? test27 + : (n == 28) ? test28 + : (n == 29) ? test29 + : (n == 30) ? test30 + : (n == 31) ? test31 + : (n == 32) ? test32 + : (n == 33) ? test33 + : (n == 34) ? test34 + : (n == 35) ? test35 + : (n == 36) ? test36 + : (n == 37) ? test37 + : (n == 38) ? test38 + : (n == 39) ? test39 + : (n == 40) ? test40 + : (n == 41) ? test41 + : 0); - if (fn == 0) - { + if (fn == 0) { fprintf(stderr, "%s: invalid test number %d\n", whoami, n); exit(2); } diff --git a/qpdf/qpdf.cc b/qpdf/qpdf.cc index 5e47327b..ea7f338a 100644 --- a/qpdf/qpdf.cc +++ b/qpdf/qpdf.cc @@ -1,6 +1,6 @@ #include -#include #include +#include #include #include @@ -9,43 +9,40 @@ static char const* whoami = 0; -static void usageExit(std::string const& msg) +static void +usageExit(std::string const& msg) { - std::cerr - << std::endl - << whoami << ": " << msg << std::endl - << std::endl - << "For help:" << std::endl - << " " << whoami << " --help=usage usage information" - << std::endl - << " " << whoami << " --help=topic help on a topic" - << std::endl - << " " << whoami << " --help=--option help on an option" - << std::endl - << " " << whoami << " --help general help and a topic list" - << std::endl - << std::endl; + std::cerr << std::endl + << whoami << ": " << msg << std::endl + << std::endl + << "For help:" << std::endl + << " " << whoami << " --help=usage usage information" + << std::endl + << " " << whoami << " --help=topic help on a topic" + << std::endl + << " " << whoami << " --help=--option help on an option" + << std::endl + << " " << whoami + << " --help general help and a topic list" + << std::endl + << std::endl; exit(QPDFJob::EXIT_ERROR); } -int realmain(int argc, char* argv[]) +int +realmain(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); QUtil::setLineBuf(stdout); QPDFJob j; - try - { + try { // See "HOW TO ADD A COMMAND-LINE ARGUMENT" in README-maintainer. j.initializeFromArgv(argv); j.run(); - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { usageExit(e.what()); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; return QPDFJob::EXIT_ERROR; } @@ -54,15 +51,16 @@ int realmain(int argc, char* argv[]) #ifdef WINDOWS_WMAIN -extern "C" -int wmain(int argc, wchar_t* argv[]) +extern "C" int +wmain(int argc, wchar_t* argv[]) { return QUtil::call_main_from_wmain(argc, argv, realmain); } #else -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { return realmain(argc, argv); } diff --git a/qpdf/qpdfjob-ctest.c b/qpdf/qpdfjob-ctest.c index 5ee21f31..e67890e8 100644 --- a/qpdf/qpdfjob-ctest.c +++ b/qpdf/qpdfjob-ctest.c @@ -10,7 +10,8 @@ #include #ifndef QPDF_NO_WCHAR_T -static void wide_test() +static void +wide_test() { wchar_t const* argv[5]; argv[0] = L"qpdfjob"; @@ -23,7 +24,8 @@ static void wide_test() } #endif // QPDF_NO_WCHAR_T -static void run_tests() +static void +run_tests() { /* Be sure to use a different output file for each test. */ @@ -61,10 +63,10 @@ static void run_tests() printf("json error test passed\n"); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if ((argc == 2) && (strcmp(argv[1], "wide") == 0)) - { + if ((argc == 2) && (strcmp(argv[1], "wide") == 0)) { #ifndef QPDF_NO_WCHAR_T wide_test(); #else diff --git a/qpdf/sizes.cc b/qpdf/sizes.cc index bf7f5e9c..691f879c 100644 --- a/qpdf/sizes.cc +++ b/qpdf/sizes.cc @@ -48,8 +48,7 @@ #include #define ignore_class(cls) -#define print_size(cls) \ - std::cout << #cls << " " << sizeof(cls) << std::endl +#define print_size(cls) std::cout << #cls << " " << sizeof(cls) << std::endl // These classes are not really public. // ------ @@ -82,7 +81,8 @@ ignore_class(InputSource::Members); ignore_class(QUtil); ignore_class(QTC); -int main() +int +main() { // Print the size of every class in the public API. This file is // read by the check_abi script at the top of the repository as diff --git a/qpdf/test_driver.cc b/qpdf/test_driver.cc index 46916e15..c697bdc9 100644 --- a/qpdf/test_driver.cc +++ b/qpdf/test_driver.cc @@ -3,33 +3,33 @@ #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include #include -#include -#include +#include +#include #include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include #include -#include -#include +#include +#include +#include #include -#include -#include -#include +#include #include #include +#include +#include +#include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -39,10 +39,10 @@ static char const* whoami = 0; -void usage() +void +usage() { - std::cerr << "Usage: " << whoami << " n filename1 [arg2]" - << std::endl; + std::cerr << "Usage: " << whoami << " n filename1 [arg2]" << std::endl; exit(2); } @@ -57,18 +57,18 @@ class Provider: public QPDFObjectHandle::StreamDataProvider virtual ~Provider() { } - virtual void provideStreamData(int objid, int generation, - Pipeline* p) + virtual void + provideStreamData(int objid, int generation, Pipeline* p) { p->write(b->getBuffer(), b->getSize()); - if (this->bad_length) - { + if (this->bad_length) { unsigned char ch = ' '; p->write(&ch, 1); } p->finish(); } - void badLength(bool v) + void + badLength(bool v) { this->bad_length = v; } @@ -97,24 +97,20 @@ ParserCallbacks::contentSize(size_t size) } void -ParserCallbacks::handleObject(QPDFObjectHandle obj, - size_t offset, size_t length) +ParserCallbacks::handleObject( + QPDFObjectHandle obj, size_t offset, size_t length) { - if (obj.isName() && (obj.getName() == "/Abort")) - { + if (obj.isName() && (obj.getName() == "/Abort")) { std::cout << "test suite: terminating parsing" << std::endl; terminateParsing(); } std::cout << obj.getTypeName() << ", offset=" << offset << ", length=" << length << ": "; - if (obj.isInlineImage()) - { + if (obj.isInlineImage()) { // Exercise getTypeCode assert(obj.getTypeCode() == QPDFObject::ot_inlineimage); std::cout << QUtil::hex_encode(obj.getInlineImageValue()) << std::endl; - } - else - { + } else { std::cout << obj.unparse() << std::endl; } } @@ -134,79 +130,77 @@ class TokenFilter: public QPDFObjectHandle::TokenFilter virtual ~TokenFilter() { } - virtual void handleToken(QPDFTokenizer::Token const& t) + virtual void + handleToken(QPDFTokenizer::Token const& t) { - if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Potato")) - { + if (t == QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Potato")) { // Exercise unparsing of strings by token constructor - writeToken( - QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Salad")); - } - else - { + writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_string, "Salad")); + } else { writeToken(t); } } - virtual void handleEOF() + virtual void + handleEOF() { writeToken(QPDFTokenizer::Token(QPDFTokenizer::tt_name, "/bye")); write("\n"); } }; -static std::string getPageContents(QPDFObjectHandle page) +static std::string +getPageContents(QPDFObjectHandle page) { - PointerHolder b1 = - page.getKey("/Contents").getStreamData(); + PointerHolder b1 = page.getKey("/Contents").getStreamData(); return std::string( - reinterpret_cast(b1->getBuffer()), b1->getSize()) + "\0"; + reinterpret_cast(b1->getBuffer()), b1->getSize()) + + "\0"; } -static void checkPageContents(QPDFObjectHandle page, - std::string const& wanted_string) +static void +checkPageContents(QPDFObjectHandle page, std::string const& wanted_string) { std::string contents = getPageContents(page); - if (contents.find(wanted_string) == std::string::npos) - { - std::cout << "didn't find " << wanted_string << " in " - << contents << std::endl; + if (contents.find(wanted_string) == std::string::npos) { + std::cout << "didn't find " << wanted_string << " in " << contents + << std::endl; } } -static QPDFObjectHandle createPageContents(QPDF& pdf, std::string const& text) +static QPDFObjectHandle +createPageContents(QPDF& pdf, std::string const& text) { std::string contents = "BT /F1 15 Tf 72 720 Td (" + text + ") Tj ET\n"; return QPDFObjectHandle::newStream(&pdf, contents); } -static void print_rect(std::ostream& out, - QPDFObjectHandle::Rectangle const& r) +static void +print_rect(std::ostream& out, QPDFObjectHandle::Rectangle const& r) { - out << "[" << r.llx << ", " << r.lly << ", " - << r.urx << ", " << r.ury << "]"; + out << "[" << r.llx << ", " << r.lly << ", " << r.urx << ", " << r.ury + << "]"; } #define assert_compare_numbers(expected, expr) \ - compare_numbers(#expr, expected, expr) + compare_numbers(#expr, expected, expr) template -static void compare_numbers( - char const* description, T1 const& expected, T2 const& actual) +static void +compare_numbers(char const* description, T1 const& expected, T2 const& actual) { - if (expected != actual) - { + if (expected != actual) { std::cerr << description << ": expected = " << expected << "; actual = " << actual << std::endl; } } -static void test_0_1(QPDF& pdf, char const* arg2) +static void +test_0_1(QPDF& pdf, char const* arg2) { QPDFObjectHandle trailer = pdf.getTrailer(); QPDFObjectHandle qtest = trailer.getKey("/QTest"); - if (! trailer.hasKey("/QTest")) - { + if (!trailer.hasKey("/QTest")) { // This will always happen when /QTest is null because // hasKey returns false for null keys regardless of // whether the key exists or not. That way there's never @@ -216,82 +210,60 @@ static void test_0_1(QPDF& pdf, char const* arg2) std::cout << "/QTest is implicit" << std::endl; } - QTC::TC("qpdf", "main QTest indirect", - qtest.isIndirect() ? 1 : 0); - std::cout << "/QTest is " - << (qtest.isIndirect() ? "in" : "") - << "direct and has type " - << qtest.getTypeName() - << " (" << qtest.getTypeCode() << ")" << std::endl; + QTC::TC("qpdf", "main QTest indirect", qtest.isIndirect() ? 1 : 0); + std::cout << "/QTest is " << (qtest.isIndirect() ? "in" : "") + << "direct and has type " << qtest.getTypeName() << " (" + << qtest.getTypeCode() << ")" << std::endl; - if (qtest.isNull()) - { + if (qtest.isNull()) { QTC::TC("qpdf", "main QTest null"); std::cout << "/QTest is null" << std::endl; - } - else if (qtest.isBool()) - { - QTC::TC("qpdf", "main QTest bool", - qtest.getBoolValue() ? 1 : 0); + } else if (qtest.isBool()) { + QTC::TC("qpdf", "main QTest bool", qtest.getBoolValue() ? 1 : 0); std::cout << "/QTest is Boolean with value " - << (qtest.getBoolValue() ? "true" : "false") - << std::endl; - } - else if (qtest.isInteger()) - { + << (qtest.getBoolValue() ? "true" : "false") << std::endl; + } else if (qtest.isInteger()) { QTC::TC("qpdf", "main QTest int"); - std::cout << "/QTest is an integer with value " - << qtest.getIntValue() << std::endl; - } - else if (qtest.isReal()) - { + std::cout << "/QTest is an integer with value " << qtest.getIntValue() + << std::endl; + } else if (qtest.isReal()) { QTC::TC("qpdf", "main QTest real"); std::cout << "/QTest is a real number with value " << qtest.getRealValue() << std::endl; - } - else if (qtest.isName()) - { + } else if (qtest.isName()) { QTC::TC("qpdf", "main QTest name"); - std::cout << "/QTest is a name with value " - << qtest.getName() << std::endl; - } - else if (qtest.isString()) - { + std::cout << "/QTest is a name with value " << qtest.getName() + << std::endl; + } else if (qtest.isString()) { QTC::TC("qpdf", "main QTest string"); - std::cout << "/QTest is a string with value " - << qtest.getStringValue() << std::endl; - } - else if (qtest.isArray()) - { + std::cout << "/QTest is a string with value " << qtest.getStringValue() + << std::endl; + } else if (qtest.isArray()) { QTC::TC("qpdf", "main QTest array"); - std::cout << "/QTest is an array with " - << qtest.getArrayNItems() << " items" << std::endl; + std::cout << "/QTest is an array with " << qtest.getArrayNItems() + << " items" << std::endl; int i = 0; - for (auto& iter: qtest.aitems()) - { - QTC::TC("qpdf", "main QTest array indirect", - iter.isIndirect() ? 1 : 0); + for (auto& iter : qtest.aitems()) { + QTC::TC( + "qpdf", "main QTest array indirect", iter.isIndirect() ? 1 : 0); std::cout << " item " << i << " is " - << (iter.isIndirect() ? "in" : "") - << "direct" << std::endl; + << (iter.isIndirect() ? "in" : "") << "direct" + << std::endl; ++i; } - } - else if (qtest.isDictionary()) - { + } else if (qtest.isDictionary()) { QTC::TC("qpdf", "main QTest dictionary"); std::cout << "/QTest is a dictionary" << std::endl; - for (auto& iter: qtest.ditems()) - { - QTC::TC("qpdf", "main QTest dictionary indirect", - iter.second.isIndirect() ? 1 : 0); + for (auto& iter : qtest.ditems()) { + QTC::TC( + "qpdf", + "main QTest dictionary indirect", + iter.second.isIndirect() ? 1 : 0); std::cout << " " << iter.first << " is " - << (iter.second.isIndirect() ? "in" : "") - << "direct" << std::endl; + << (iter.second.isIndirect() ? "in" : "") << "direct" + << std::endl; } - } - else if (qtest.isStream()) - { + } else if (qtest.isStream()) { QTC::TC("qpdf", "main QTest stream"); std::cout << "/QTest is a stream. Dictionary: " << qtest.getDict().unparse() << std::endl; @@ -303,40 +275,36 @@ static void test_0_1(QPDF& pdf, char const* arg2) qtest.pipeStreamData(out.get(), 0, qpdf_dl_none); std::cout << std::endl << "Uncompressed stream data:" << std::endl; - if (qtest.pipeStreamData(0, 0, qpdf_dl_all)) - { + if (qtest.pipeStreamData(0, 0, qpdf_dl_all)) { std::cout.flush(); QUtil::binary_stdout(); out = make_pointer_holder("filtered", stdout); qtest.pipeStreamData(out.get(), 0, qpdf_dl_all); std::cout << std::endl << "End of stream data" << std::endl; - } - else - { + } else { std::cout << "Stream data is not filterable." << std::endl; } - } - else - { + } else { // Should not happen! std::cout << "/QTest is an unknown object" << std::endl; } std::cout << "unparse: " << qtest.unparse() << std::endl - << "unparseResolved: " << qtest.unparseResolved() - << std::endl; + << "unparseResolved: " << qtest.unparseResolved() << std::endl; } -static void test_2(QPDF& pdf, char const* arg2) +static void +test_2(QPDF& pdf, char const* arg2) { // Encrypted file. This test case is designed for a specific // PDF file. QPDFObjectHandle trailer = pdf.getTrailer(); - std::cout << trailer.getKey("/Info"). - getKey("/CreationDate").getStringValue() << std::endl; - std::cout << trailer.getKey("/Info"). - getKey("/Producer").getStringValue() << std::endl; + std::cout + << trailer.getKey("/Info").getKey("/CreationDate").getStringValue() + << std::endl; + std::cout << trailer.getKey("/Info").getKey("/Producer").getStringValue() + << std::endl; QPDFObjectHandle encrypt = trailer.getKey("/Encrypt"); std::cout << encrypt.getKey("/O").unparse() << std::endl; @@ -352,23 +320,24 @@ static void test_2(QPDF& pdf, char const* arg2) contents.pipeStreamData(out.get(), 0, qpdf_dl_generalized); } -static void test_3(QPDF& pdf, char const* arg2) +static void +test_3(QPDF& pdf, char const* arg2) { QPDFObjectHandle streams = pdf.getTrailer().getKey("/QStreams"); - for (int i = 0; i < streams.getArrayNItems(); ++i) - { + for (int i = 0; i < streams.getArrayNItems(); ++i) { QPDFObjectHandle stream = streams.getArrayItem(i); std::cout << "-- stream " << i << " --" << std::endl; std::cout.flush(); QUtil::binary_stdout(); - auto out = make_pointer_holder( - "tokenized stream", stdout); - stream.pipeStreamData(out.get(), - qpdf_ef_normalize, qpdf_dl_generalized); + auto out = + make_pointer_holder("tokenized stream", stdout); + stream.pipeStreamData( + out.get(), qpdf_ef_normalize, qpdf_dl_generalized); } } -static void test_4(QPDF& pdf, char const* arg2) +static void +test_4(QPDF& pdf, char const* arg2) { // Mutability testing: Make /QTest direct recursively, then // copy to /Info. Also make some other mutations so we can @@ -378,25 +347,21 @@ static void test_4(QPDF& pdf, char const* arg2) QPDFObjectHandle qtest = trailer.getKey("/QTest"); qtest.makeDirect(); qtest.removeKey("/Subject"); - qtest.replaceKey("/Author", - QPDFObjectHandle::newString("Mr. Potato Head")); + qtest.replaceKey("/Author", QPDFObjectHandle::newString("Mr. Potato Head")); // qtest.A and qtest.B.A were originally the same object. // They no longer are after makeDirect(). Mutate one of them // and ensure the other is not changed. These test cases are // crafted around a specific set of input files. QPDFObjectHandle A = qtest.getKey("/A"); - if (A.getArrayItem(0).getIntValue() == 1) - { + if (A.getArrayItem(0).getIntValue() == 1) { // Test mutators A.setArrayItem(1, QPDFObjectHandle::newInteger(5)); // 1 5 3 - A.insertItem(2, QPDFObjectHandle::newInteger(10)); // 1 5 10 3 - A.appendItem(QPDFObjectHandle::newInteger(12)); // 1 5 10 3 12 - A.eraseItem(3); // 1 5 10 12 - A.insertItem(4, QPDFObjectHandle::newInteger(6)); // 1 5 10 12 6 - A.insertItem(0, QPDFObjectHandle::newInteger(9)); // 9 1 5 10 12 6 - } - else - { + A.insertItem(2, QPDFObjectHandle::newInteger(10)); // 1 5 10 3 + A.appendItem(QPDFObjectHandle::newInteger(12)); // 1 5 10 3 12 + A.eraseItem(3); // 1 5 10 12 + A.insertItem(4, QPDFObjectHandle::newInteger(6)); // 1 5 10 12 6 + A.insertItem(0, QPDFObjectHandle::newInteger(9)); // 9 1 5 10 12 6 + } else { std::vector items; items.push_back(QPDFObjectHandle::newInteger(14)); items.push_back(QPDFObjectHandle::newInteger(15)); @@ -405,8 +370,7 @@ static void test_4(QPDF& pdf, char const* arg2) } QPDFObjectHandle qtest2 = trailer.getKey("/QTest2"); - if (! qtest2.isNull()) - { + if (!qtest2.isNull()) { // Test allow_streams=true qtest2.makeDirect(true); trailer.replaceKey("/QTest2", qtest2); @@ -422,14 +386,15 @@ static void test_4(QPDF& pdf, char const* arg2) exit(0); } -static void test_5(QPDF& pdf, char const* arg2) +static void +test_5(QPDF& pdf, char const* arg2) { QPDFPageDocumentHelper dh(pdf); std::vector pages = dh.getAllPages(); int pageno = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); ++pageno; @@ -437,22 +402,19 @@ static void test_5(QPDF& pdf, char const* arg2) std::cout << " images:" << std::endl; std::map images = page.getImages(); - for (auto const& iter2: images) - { + for (auto const& iter2 : images) { std::string const& name = iter2.first; QPDFObjectHandle image = iter2.second; QPDFObjectHandle dict = image.getDict(); long long width = dict.getKey("/Width").getIntValue(); long long height = dict.getKey("/Height").getIntValue(); - std::cout << " " << name - << ": " << width << " x " << height + std::cout << " " << name << ": " << width << " x " << height << std::endl; } std::cout << " content:" << std::endl; std::vector content = page.getPageContents(); - for (auto& iter2: content) - { + for (auto& iter2 : content) { std::cout << " " << iter2.unparse() << std::endl; } @@ -461,37 +423,34 @@ static void test_5(QPDF& pdf, char const* arg2) QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstrings = root.getKey("/QStrings"); - if (qstrings.isArray()) - { + if (qstrings.isArray()) { std::cout << "QStrings:" << std::endl; int nitems = qstrings.getArrayNItems(); - for (int i = 0; i < nitems; ++i) - { - std::cout << qstrings.getArrayItem(i).getUTF8Value() - << std::endl; + for (int i = 0; i < nitems; ++i) { + std::cout << qstrings.getArrayItem(i).getUTF8Value() << std::endl; } } QPDFObjectHandle qnumbers = root.getKey("/QNumbers"); - if (qnumbers.isArray()) - { + if (qnumbers.isArray()) { std::cout << "QNumbers:" << std::endl; int nitems = qnumbers.getArrayNItems(); - for (int i = 0; i < nitems; ++i) - { + for (int i = 0; i < nitems; ++i) { std::cout << QUtil::double_to_string( - qnumbers.getArrayItem(i).getNumericValue(), 3, false) + qnumbers.getArrayItem(i).getNumericValue(), + 3, + false) << std::endl; } } } -static void test_6(QPDF& pdf, char const* arg2) +static void +test_6(QPDF& pdf, char const* arg2) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle metadata = root.getKey("/Metadata"); - if (! metadata.isStream()) - { + if (!metadata.isStream()) { throw std::logic_error("test 6 run on file with no metadata"); } Pl_Buffer bufpl("buffer"); @@ -500,48 +459,45 @@ static void test_6(QPDF& pdf, char const* arg2) unsigned char const* data = buf->getBuffer(); bool cleartext = false; if ((buf->getSize() > 9) && - (strncmp(reinterpret_cast(data), - "(data), "(provider); qstream.replaceStreamData( - p, QPDFObjectHandle::newName("/FlateDecode"), + p, + QPDFObjectHandle::newName("/FlateDecode"), QPDFObjectHandle::newNull()); provider->badLength(false); QPDFWriter w(pdf, "a.pdf"); @@ -562,39 +519,34 @@ static void test_8(QPDF& pdf, char const* arg2) // Every time a provider pipes stream data, it has to provide // the same amount of data. provider->badLength(true); - try - { + try { qstream.getStreamData(); std::cout << "oops -- getStreamData didn't throw" << std::endl; - } - catch (std::exception const& e) - { + } catch (std::exception const& e) { std::cout << "exception: " << e.what() << std::endl; } } -static void test_9(QPDF& pdf, char const* arg2) +static void +test_9(QPDF& pdf, char const* arg2) { QPDFObjectHandle root = pdf.getRoot(); // Explicitly exercise the Buffer version of newStream auto buf = make_pointer_holder(20U); unsigned char* bp = buf->getBuffer(); memcpy(bp, "data for new stream\n", 20); // no null! - QPDFObjectHandle qstream = QPDFObjectHandle::newStream( - &pdf, buf); + QPDFObjectHandle qstream = QPDFObjectHandle::newStream(&pdf, buf); QPDFObjectHandle rstream = QPDFObjectHandle::newStream(&pdf); - try - { + try { rstream.getStreamData(); std::cout << "oops -- getStreamData didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "exception: " << e.what() << std::endl; } rstream.replaceStreamData( "data for other stream\n", - QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); + QPDFObjectHandle::newNull(), + QPDFObjectHandle::newNull()); root.replaceKey("/QStream", qstream); root.replaceKey("/RStream", rstream); QPDFWriter w(pdf, "a.pdf"); @@ -603,17 +555,20 @@ static void test_9(QPDF& pdf, char const* arg2) w.write(); } -static void test_10(QPDF& pdf, char const* arg2) +static void +test_10(QPDF& pdf, char const* arg2) { std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); QPDFPageObjectHelper& ph(pages.at(0)); ph.addPageContents( QPDFObjectHandle::newStream( - &pdf, "BT /F1 12 Tf 72 620 Td (Baked) Tj ET\n"), true); + &pdf, "BT /F1 12 Tf 72 620 Td (Baked) Tj ET\n"), + true); ph.addPageContents( QPDFObjectHandle::newStream( - &pdf, "BT /F1 18 Tf 72 520 Td (Mashed) Tj ET\n"), false); + &pdf, "BT /F1 18 Tf 72 520 Td (Mashed) Tj ET\n"), + false); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); @@ -621,49 +576,48 @@ static void test_10(QPDF& pdf, char const* arg2) w.write(); } -static void test_11(QPDF& pdf, char const* arg2) +static void +test_11(QPDF& pdf, char const* arg2) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstream = root.getKey("/QStream"); PointerHolder b1 = qstream.getStreamData(); PointerHolder b2 = qstream.getRawStreamData(); - if ((b1->getSize() == 7) && - (memcmp(b1->getBuffer(), "potato\n", 7) == 0)) - { + if ((b1->getSize() == 7) && (memcmp(b1->getBuffer(), "potato\n", 7) == 0)) { std::cout << "filtered stream data okay" << std::endl; } if ((b2->getSize() == 15) && - (memcmp(b2->getBuffer(), "706F7461746F0A\n", 15) == 0)) - { + (memcmp(b2->getBuffer(), "706F7461746F0A\n", 15) == 0)) { std::cout << "raw stream data okay" << std::endl; } } -static void test_12(QPDF& pdf, char const* arg2) +static void +test_12(QPDF& pdf, char const* arg2) { pdf.setOutputStreams(0, 0); pdf.showLinearizationData(); } -static void test_13(QPDF& pdf, char const* arg2) +static void +test_13(QPDF& pdf, char const* arg2) { std::ostringstream out; std::ostringstream err; pdf.setOutputStreams(&out, &err); pdf.showLinearizationData(); std::cout << "---output---" << std::endl - << out.str() - << "---error---" << std::endl + << out.str() << "---error---" << std::endl << err.str(); } -static void test_14(QPDF& pdf, char const* arg2) +static void +test_14(QPDF& pdf, char const* arg2) { // Exercise swap and replace. This test case is designed for // a specific file. std::vector pages = pdf.getAllPages(); - if (pages.size() != 4) - { + if (pages.size() != 4) { throw std::logic_error("test 14 not called 4-page file"); } // Swap pages 2 and 3 @@ -682,13 +636,10 @@ static void test_14(QPDF& pdf, char const* arg2) qdict.isDictionary(); QPDFObjectHandle new_dict = QPDFObjectHandle::newDictionary(); new_dict.replaceKey("/NewDict", QPDFObjectHandle::newInteger(2)); - try - { + try { // Do it wrong first... pdf.replaceObject(qdict.getObjGen(), qdict); - } - catch (std::logic_error const&) - { + } catch (std::logic_error const&) { std::cout << "caught logic error as expected" << std::endl; } pdf.replaceObject(qdict.getObjGen(), new_dict); @@ -709,22 +660,17 @@ static void test_14(QPDF& pdf, char const* arg2) << std::endl; // Exercise getAsMap and getAsArray - std::vector array_elements = - qdict.getArrayAsVector(); - std::map dict_items = - qarray.getDictAsMap(); + std::vector array_elements = qdict.getArrayAsVector(); + std::map dict_items = qarray.getDictAsMap(); if ((array_elements.size() == 1) && (array_elements.at(0).getName() == "/Array") && (dict_items.size() == 1) && - (dict_items["/NewDict"].getIntValue() == 2)) - { - std::cout << "array and dictionary contents are correct" - << std::endl; + (dict_items["/NewDict"].getIntValue() == 2)) { + std::cout << "array and dictionary contents are correct" << std::endl; } // Exercise writing to memory buffer - for (int i = 0; i < 2; ++i) - { + for (int i = 0; i < 2; ++i) { QPDFWriter w(pdf); w.setOutputMemory(); // Exercise setOutputMemory with and without static ID @@ -740,7 +686,8 @@ static void test_14(QPDF& pdf, char const* arg2) } } -static void test_15(QPDF& pdf, char const* arg2) +static void +test_15(QPDF& pdf, char const* arg2) { std::vector const& pages = pdf.getAllPages(); // Reference to original page numbers for this test case are @@ -778,19 +725,16 @@ static void test_15(QPDF& pdf, char const* arg2) QPDFObjectHandle page_template = pages.at(0); std::vector new_pages; for (std::vector::iterator iter = contents.begin(); - iter != contents.end(); ++iter) - { + iter != contents.end(); + ++iter) { // We will retain indirect object references to other // indirect objects other than page content. QPDFObjectHandle page = page_template.shallowCopy(); page.replaceKey("/Contents", *iter); - if (iter == contents.begin()) - { + if (iter == contents.begin()) { // leave direct new_pages.push_back(page); - } - else - { + } else { new_pages.push_back(pdf.makeIndirectObject(page)); } } @@ -817,22 +761,22 @@ static void test_15(QPDF& pdf, char const* arg2) checkPageContents(pages.at(12), "New page 12"); // Exercise writing to FILE* - FILE* out = QUtil::safe_fopen("a.pdf", "wb"); + FILE* out = QUtil::safe_fopen("a.pdf", "wb"); QPDFWriter w(pdf, "FILE* a.pdf", out, true); w.setStaticID(true); w.setStreamDataMode(qpdf_s_preserve); w.write(); } -static void test_16(QPDF& pdf, char const* arg2) +static void +test_16(QPDF& pdf, char const* arg2) { // Insert a page manually and then update the cache. std::vector const& all_pages = pdf.getAllPages(); QPDFObjectHandle contents = createPageContents(pdf, "New page 10"); QPDFObjectHandle page = - pdf.makeIndirectObject( - QPDFObjectHandle(all_pages.at(0)).shallowCopy()); + pdf.makeIndirectObject(QPDFObjectHandle(all_pages.at(0)).shallowCopy()); page.replaceKey("/Contents", contents); // Insert the page manually. @@ -842,8 +786,7 @@ static void test_16(QPDF& pdf, char const* arg2) page.replaceKey("/Parent", pages); pages.replaceKey( "/Count", - QPDFObjectHandle::newInteger( - 1 + QIntC::to_longlong(all_pages.size()))); + QPDFObjectHandle::newInteger(1 + QIntC::to_longlong(all_pages.size()))); kids.appendItem(page); assert(all_pages.size() == 10); pdf.updateAllPagesCache(); @@ -856,29 +799,31 @@ static void test_16(QPDF& pdf, char const* arg2) w.write(); } -static void test_17(QPDF& pdf, char const* arg2) +static void +test_17(QPDF& pdf, char const* arg2) { // The input file to this test case has a duplicated page. - QPDFObjectHandle page_kids = - pdf.getRoot().getKey("/Pages").getKey("/Kids"); - assert(page_kids.getArrayItem(0).getObjGen() == - page_kids.getArrayItem(1).getObjGen()); + QPDFObjectHandle page_kids = pdf.getRoot().getKey("/Pages").getKey("/Kids"); + assert( + page_kids.getArrayItem(0).getObjGen() == + page_kids.getArrayItem(1).getObjGen()); std::vector const& pages = pdf.getAllPages(); assert(pages.size() == 3); - assert(! (pages.at(0).getObjGen() == pages.at(1).getObjGen())); - assert(QPDFObjectHandle(pages.at(0)).getKey("/Contents").getObjGen() == - QPDFObjectHandle(pages.at(1)).getKey("/Contents").getObjGen()); + assert(!(pages.at(0).getObjGen() == pages.at(1).getObjGen())); + assert( + QPDFObjectHandle(pages.at(0)).getKey("/Contents").getObjGen() == + QPDFObjectHandle(pages.at(1)).getKey("/Contents").getObjGen()); pdf.removePage(pages.at(0)); assert(pages.size() == 2); - PointerHolder b = QPDFObjectHandle(pages.at(0)). - getKey("/Contents").getStreamData(); + PointerHolder b = + QPDFObjectHandle(pages.at(0)).getKey("/Contents").getStreamData(); std::string contents = std::string( - reinterpret_cast(b->getBuffer()), - b->getSize()); + reinterpret_cast(b->getBuffer()), b->getSize()); assert(contents.find("page 0") != std::string::npos); } -static void test_18(QPDF& pdf, char const* arg2) +static void +test_18(QPDF& pdf, char const* arg2) { // Remove a page and re-insert it in the same file. std::vector const& pages = pdf.getAllPages(); @@ -899,7 +844,8 @@ static void test_18(QPDF& pdf, char const* arg2) w.write(); } -static void test_19(QPDF& pdf, char const* arg2) +static void +test_19(QPDF& pdf, char const* arg2) { // Remove a page and re-insert it in the same file. std::vector const& pages = pdf.getAllPages(); @@ -911,12 +857,14 @@ static void test_19(QPDF& pdf, char const* arg2) pdf.addPage(newpage, false); auto last = pages.back(); assert(pages.size() == count + 1); - assert(! (last.getObjGen() == newpage.getObjGen())); - assert(last.getKey("/Contents").getObjGen() == - newpage.getKey("/Contents").getObjGen()); + assert(!(last.getObjGen() == newpage.getObjGen())); + assert( + last.getKey("/Contents").getObjGen() == + newpage.getKey("/Contents").getObjGen()); } -static void test_20(QPDF& pdf, char const* arg2) +static void +test_20(QPDF& pdf, char const* arg2) { // Shallow copy an array QPDFObjectHandle trailer = pdf.getTrailer(); @@ -932,7 +880,8 @@ static void test_20(QPDF& pdf, char const* arg2) w.write(); } -static void test_21(QPDF& pdf, char const* arg2) +static void +test_21(QPDF& pdf, char const* arg2) { // Try to shallow copy a stream std::vector const& pages = pdf.getAllPages(); @@ -942,7 +891,8 @@ static void test_21(QPDF& pdf, char const* arg2) std::cout << "you can't see this" << std::endl; } -static void test_22(QPDF& pdf, char const* arg2) +static void +test_22(QPDF& pdf, char const* arg2) { // Try to remove a page we don't have QPDFPageDocumentHelper dh(pdf); @@ -953,14 +903,16 @@ static void test_22(QPDF& pdf, char const* arg2) std::cout << "you can't see this" << std::endl; } -static void test_23(QPDF& pdf, char const* arg2) +static void +test_23(QPDF& pdf, char const* arg2) { QPDFPageDocumentHelper dh(pdf); std::vector pages = dh.getAllPages(); dh.removePage(pages.back()); } -static void test_24(QPDF& pdf, char const* arg2) +static void +test_24(QPDF& pdf, char const* arg2) { // Test behavior of reserved objects QPDFObjectHandle res1 = QPDFObjectHandle::newReserved(&pdf); @@ -977,43 +929,32 @@ static void test_24(QPDF& pdf, char const* arg2) array2.appendItem(QPDFObjectHandle::newInteger(2)); // Make sure trying to ask questions about a reserved object // doesn't break it. - if (res1.isArray()) - { + if (res1.isArray()) { std::cout << "oops -- res1 is an array" << std::endl; } - if (res1.isReserved()) - { + if (res1.isReserved()) { std::cout << "res1 is still reserved after checking if array" << std::endl; } pdf.replaceReserved(res1, array1); - if (res1.isReserved()) - { + if (res1.isReserved()) { std::cout << "oops -- res1 is still reserved" << std::endl; - } - else - { + } else { std::cout << "res1 is no longer reserved" << std::endl; } res1.assertArray(); std::cout << "res1 is an array" << std::endl; - try - { + try { res2.unparseResolved(); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } - try - { + try { res2.makeDirect(); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } @@ -1026,8 +967,7 @@ static void test_24(QPDF& pdf, char const* arg2) // dereferenced properly now int i1 = res1.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); int i2 = res2.getArrayItem(0).getArrayItem(1).getIntValueAsInt(); - if ((i1 == 2) && (i2 == 1)) - { + if ((i1 == 2) && (i2 == 1)) { std::cout << "circular access and lazy resolution worked" << std::endl; } @@ -1037,7 +977,8 @@ static void test_24(QPDF& pdf, char const* arg2) w.write(); } -static void test_25(QPDF& pdf, char const* arg2) +static void +test_25(QPDF& pdf, char const* arg2) { // The copy object tests are designed to work with a specific // file. Look at the test suite for the file, and look at the @@ -1052,8 +993,7 @@ static void test_25(QPDF& pdf, char const* arg2) QPDF oldpdf; oldpdf.processFile(arg2); QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest"); - pdf.getTrailer().replaceKey( - "/QTest", pdf.copyForeignObject(qtest)); + pdf.getTrailer().replaceKey("/QTest", pdf.copyForeignObject(qtest)); } QPDFWriter w(pdf, "a.pdf"); @@ -1062,7 +1002,8 @@ static void test_25(QPDF& pdf, char const* arg2) w.write(); } -static void test_26(QPDF& pdf, char const* arg2) +static void +test_26(QPDF& pdf, char const* arg2) { // Copy the O3 page using addPage. Copy qtest without // crossing page boundaries. In addition to previous results, @@ -1078,8 +1019,7 @@ static void test_26(QPDF& pdf, char const* arg2) QPDFObjectHandle qtest = oldpdf.getTrailer().getKey("/QTest"); QPDFObjectHandle O3 = qtest.getKey("/O3"); QPDFPageDocumentHelper(pdf).addPage(O3, false); - pdf.getTrailer().replaceKey( - "/QTest", pdf.copyForeignObject(qtest)); + pdf.getTrailer().replaceKey("/QTest", pdf.copyForeignObject(qtest)); } QPDFWriter w(pdf, "a.pdf"); @@ -1088,7 +1028,8 @@ static void test_26(QPDF& pdf, char const* arg2) w.write(); } -static void test_27(QPDF& pdf, char const* arg2) +static void +test_27(QPDF& pdf, char const* arg2) { // Copy O3 and the page O3 refers to before copying qtest. // Should get qtest plus only the O3 page and the page that O3 @@ -1102,8 +1043,9 @@ static void test_27(QPDF& pdf, char const* arg2) { // Local scope Pl_Buffer pl("buffer"); - pl.write(QUtil::unsigned_char_pointer("new data for stream\n"), - 20); // no null! + pl.write( + QUtil::unsigned_char_pointer("new data for stream\n"), + 20); // no null! pl.finish(); auto b = pl.getBufferSharedPointer(); Provider* provider = new Provider(b); @@ -1130,9 +1072,9 @@ static void test_27(QPDF& pdf, char const* arg2) { // Local scope Pl_Buffer pl("buffer"); - pl.write(QUtil::unsigned_char_pointer( - "more data for stream\n"), - 21); // no null! + pl.write( + QUtil::unsigned_char_pointer("more data for stream\n"), + 21); // no null! pl.finish(); auto b = pl.getBufferSharedPointer(); Provider* provider = new Provider(b); @@ -1152,12 +1094,9 @@ static void test_27(QPDF& pdf, char const* arg2) QPDFPageDocumentHelper dh(pdf); dh.addPage(O3.getKey("/OtherPage"), false); dh.addPage(O3, false); - QPDFObjectHandle s2 = QPDFObjectHandle::newStream( - &oldpdf, "potato\n"); - pdf.getTrailer().replaceKey( - "/QTest", pdf.copyForeignObject(qtest)); - pdf.getTrailer().replaceKey( - "/QTest2", QPDFObjectHandle::newArray()); + QPDFObjectHandle s2 = QPDFObjectHandle::newStream(&oldpdf, "potato\n"); + pdf.getTrailer().replaceKey("/QTest", pdf.copyForeignObject(qtest)); + pdf.getTrailer().replaceKey("/QTest2", QPDFObjectHandle::newArray()); pdf.getTrailer().getKey("/QTest2").appendItem( pdf.copyForeignObject(s1)); pdf.getTrailer().getKey("/QTest2").appendItem( @@ -1173,64 +1112,54 @@ static void test_27(QPDF& pdf, char const* arg2) w.write(); } -static void test_28(QPDF& pdf, char const* arg2) +static void +test_28(QPDF& pdf, char const* arg2) { // Copy foreign object errors - try - { + try { pdf.copyForeignObject(pdf.getTrailer().getKey("/QTest")); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } - try - { + try { pdf.copyForeignObject(QPDFObjectHandle::newInteger(1)); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } } -static void test_29(QPDF& pdf, char const* arg2) +static void +test_29(QPDF& pdf, char const* arg2) { // Detect mixed objects in QPDFWriter assert(arg2 != 0); QPDF other; other.processFile(arg2); // Should use copyForeignObject instead - other.getTrailer().replaceKey( - "/QTest", pdf.getTrailer().getKey("/QTest")); + other.getTrailer().replaceKey("/QTest", pdf.getTrailer().getKey("/QTest")); - try - { + try { QPDFWriter w(other, "a.pdf"); w.write(); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } // Detect adding a foreign object auto root1 = pdf.getRoot(); auto root2 = other.getRoot(); - try - { + try { root1.replaceKey("/Oops", root2); - } - catch (std::logic_error const& e) - { + } catch (std::logic_error const& e) { std::cout << "logic error: " << e.what() << std::endl; } } -static void test_30(QPDF& pdf, char const* arg2) +static void +test_30(QPDF& pdf, char const* arg2) { assert(arg2 != 0); QPDF encrypted; @@ -1247,72 +1176,63 @@ static void test_30(QPDF& pdf, char const* arg2) std::string orig_contents = getPageContents(pages.at(0)); pages = final.getAllPages(); std::string new_contents = getPageContents(pages.at(0)); - if (orig_contents != new_contents) - { + if (orig_contents != new_contents) { std::cout << "oops -- page contents don't match" << std::endl - << "original:\n" << orig_contents - << "new:\n" << new_contents - << std::endl; + << "original:\n" + << orig_contents << "new:\n" + << new_contents << std::endl; } } -static void test_31(QPDF& pdf, char const* arg2) +static void +test_31(QPDF& pdf, char const* arg2) { // Test object parsing from a string. The input file is not used. auto o1 = "[/name 16059 3.14159 false\n" - " << /key true /other [ (string1) (string2) ] >> null]"_qpdf; + " << /key true /other [ (string1) (string2) ] >> null]"_qpdf; std::cout << o1.unparse() << std::endl; QPDFObjectHandle o2 = QPDFObjectHandle::parse(" 12345 \f "); assert(o2.isInteger() && (o2.getIntValue() == 12345)); - try - { + try { QPDFObjectHandle::parse("[1 0 R]", "indirect test"); std::cout << "oops -- didn't throw" << std::endl; + } catch (std::logic_error const& e) { + std::cout << "logic error parsing indirect: " << e.what() << std::endl; } - catch (std::logic_error const& e) - { - std::cout << "logic error parsing indirect: " << e.what() - << std::endl; - } - try - { + try { QPDFObjectHandle::parse("0 trailing", "trailing test"); std::cout << "oops -- didn't throw" << std::endl; + } catch (std::runtime_error const& e) { + std::cout << "trailing data: " << e.what() << std::endl; } - catch (std::runtime_error const& e) - { - std::cout << "trailing data: " << e.what() - << std::endl; - } - assert(QPDFObjectHandle::parse( - &pdf, "[1 0 R]", "indirect test").unparse() == - "[ 1 0 R ]"); + assert( + QPDFObjectHandle::parse(&pdf, "[1 0 R]", "indirect test").unparse() == + "[ 1 0 R ]"); } -static void test_32(QPDF& pdf, char const* arg2) +static void +test_32(QPDF& pdf, char const* arg2) { // Extra header text char const* filenames[] = {"a.pdf", "b.pdf", "c.pdf", "d.pdf"}; - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { bool linearized = ((i & 1) != 0); bool newline = ((i & 2) != 0); QPDFWriter w(pdf, filenames[i]); w.setStaticID(true); - std::cout - << "file: " << filenames[i] << std::endl - << "linearized: " << (linearized ? "yes" : "no") << std::endl - << "newline: " << (newline ? "yes" : "no") << std::endl; + std::cout << "file: " << filenames[i] << std::endl + << "linearized: " << (linearized ? "yes" : "no") << std::endl + << "newline: " << (newline ? "yes" : "no") << std::endl; w.setLinearization(linearized); - w.setExtraHeaderText(newline - ? "%% Comment with newline\n" - : "%% Comment\n% No newline"); + w.setExtraHeaderText( + newline ? "%% Comment with newline\n" : "%% Comment\n% No newline"); w.write(); } } -static void test_33(QPDF& pdf, char const* arg2) +static void +test_33(QPDF& pdf, char const* arg2) { // Test writing to a custom pipeline Pl_Buffer p("buffer"); @@ -1326,7 +1246,8 @@ static void test_33(QPDF& pdf, char const* arg2) fclose(f); } -static void test_34(QPDF& pdf, char const* arg2) +static void +test_34(QPDF& pdf, char const* arg2) { // Look at Extensions dictionary std::cout << "version: " << pdf.getPDFVersion() << std::endl @@ -1340,58 +1261,49 @@ static void test_34(QPDF& pdf, char const* arg2) << std::endl; } -static void test_35(QPDF& pdf, char const* arg2) +static void +test_35(QPDF& pdf, char const* arg2) { // Extract attachments - std::map > attachments; + std::map> attachments; QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle names = root.getKey("/Names"); QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles"); names = embeddedFiles.getKey("/Names"); - for (int i = 0; i < names.getArrayNItems(); ++i) - { + for (int i = 0; i < names.getArrayNItems(); ++i) { QPDFObjectHandle item = names.getArrayItem(i); - if (item.isDictionary() && - item.getKey("/Type").isName() && + if (item.isDictionary() && item.getKey("/Type").isName() && (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() && - item.getKey("/EF").getKey("/F").isStream()) - { + item.getKey("/EF").getKey("/F").isStream()) { std::string filename = item.getKey("/F").getStringValue(); QPDFObjectHandle stream = item.getKey("/EF").getKey("/F"); attachments[filename] = stream.getStreamData(); } } - for (std::map >::iterator iter = - attachments.begin(); iter != attachments.end(); ++iter) - { + for (std::map>::iterator iter = + attachments.begin(); + iter != attachments.end(); + ++iter) { std::string const& filename = (*iter).first; std::string data = std::string( reinterpret_cast((*iter).second->getBuffer()), (*iter).second->getSize()); bool is_binary = false; - for (size_t i = 0; i < data.size(); ++i) - { - if ((data.at(i) < 0) || (data.at(i) > 126)) - { + for (size_t i = 0; i < data.size(); ++i) { + if ((data.at(i) < 0) || (data.at(i) > 126)) { is_binary = true; break; } } - if (is_binary) - { + if (is_binary) { std::string t; - for (size_t i = 0; - i < std::min(data.size(), QIntC::to_size(20)); - ++i) - { - if ((data.at(i) >= 32) && (data.at(i) <= 126)) - { + for (size_t i = 0; i < std::min(data.size(), QIntC::to_size(20)); + ++i) { + if ((data.at(i) >= 32) && (data.at(i) <= 126)) { t += data.at(i); - } - else - { + } else { t += "."; } } @@ -1402,7 +1314,8 @@ static void test_35(QPDF& pdf, char const* arg2) } } -static void test_36(QPDF& pdf, char const* arg2) +static void +test_36(QPDF& pdf, char const* arg2) { // Extract raw unfilterable attachment @@ -1410,16 +1323,13 @@ static void test_36(QPDF& pdf, char const* arg2) QPDFObjectHandle names = root.getKey("/Names"); QPDFObjectHandle embeddedFiles = names.getKey("/EmbeddedFiles"); names = embeddedFiles.getKey("/Names"); - for (int i = 0; i < names.getArrayNItems(); ++i) - { + for (int i = 0; i < names.getArrayNItems(); ++i) { QPDFObjectHandle item = names.getArrayItem(i); - if (item.isDictionary() && - item.getKey("/Type").isName() && + if (item.isDictionary() && item.getKey("/Type").isName() && (item.getKey("/Type").getName() == "/Filespec") && item.getKey("/EF").isDictionary() && item.getKey("/EF").getKey("/F").isStream() && - (item.getKey("/F").getStringValue() == "attachment1.txt")) - { + (item.getKey("/F").getStringValue() == "attachment1.txt")) { std::string filename = item.getKey("/F").getStringValue(); QPDFObjectHandle stream = item.getKey("/EF").getKey("/F"); Pl_Buffer p1("buffer"); @@ -1429,52 +1339,53 @@ static void test_36(QPDF& pdf, char const* arg2) std::string data = std::string( reinterpret_cast(buf->getBuffer()), buf->getSize()); - std::cout << stream.getDict().unparse() - << filename << ":\n" << data << "--END--\n"; + std::cout << stream.getDict().unparse() << filename << ":\n" + << data << "--END--\n"; } } } -static void test_37(QPDF& pdf, char const* arg2) +static void +test_37(QPDF& pdf, char const* arg2) { // Parse content streams of all pages std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& page(*iter); ParserCallbacks cb; page.parseContents(&cb); } } -static void test_38(QPDF& pdf, char const* arg2) +static void +test_38(QPDF& pdf, char const* arg2) { // Designed for override-compressed-object.pdf QPDFObjectHandle qtest = pdf.getRoot().getKey("/QTest"); - for (int i = 0; i < qtest.getArrayNItems(); ++i) - { + for (int i = 0; i < qtest.getArrayNItems(); ++i) { std::cout << qtest.getArrayItem(i).unparseResolved() << std::endl; } } -static void test_39(QPDF& pdf, char const* arg2) +static void +test_39(QPDF& pdf, char const* arg2) { // Display image filter and color set for each image on each page std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); int pageno = 0; - for (std::vector::iterator p_iter = - pages.begin(); - p_iter != pages.end(); ++p_iter) - { + for (std::vector::iterator p_iter = pages.begin(); + p_iter != pages.end(); + ++p_iter) { std::cout << "page " << ++pageno << std::endl; - std::map images = - (*p_iter).getImages(); + std::map images = (*p_iter).getImages(); for (std::map::iterator i_iter = - images.begin(); i_iter != images.end(); ++i_iter) - { + images.begin(); + i_iter != images.end(); + ++i_iter) { QPDFObjectHandle image_dict = (*i_iter).second.getDict(); std::cout << "filter: " << image_dict.getKey("/Filter").unparseResolved() @@ -1485,7 +1396,8 @@ static void test_39(QPDF& pdf, char const* arg2) } } -static void test_40(QPDF& pdf, char const* arg2) +static void +test_40(QPDF& pdf, char const* arg2) { // Write PCLm. This requires specially crafted PDF files. This // feature was implemented by Sahil Arora @@ -1498,16 +1410,16 @@ static void test_40(QPDF& pdf, char const* arg2) w.write(); } -static void test_41(QPDF& pdf, char const* arg2) +static void +test_41(QPDF& pdf, char const* arg2) { // Apply a token filter. This test case is crafted to work // with coalesce.pdf. std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); - for (std::vector::iterator iter = - pages.begin(); - iter != pages.end(); ++iter) - { + for (std::vector::iterator iter = pages.begin(); + iter != pages.end(); + ++iter) { (*iter).addContentTokenFilter( PointerHolder(new TokenFilter())); } @@ -1517,7 +1429,8 @@ static void test_41(QPDF& pdf, char const* arg2) w.write(); } -static void test_42(QPDF& pdf, char const* arg2) +static void +test_42(QPDF& pdf, char const* arg2) { // Access objects as wrong type. This test case is crafted to // work with object-types.pdf. @@ -1541,7 +1454,7 @@ static void test_42(QPDF& pdf, char const* arg2) assert(i == ai.end()); ++i; assert(i == ai.end()); - assert(! i_value.isInitialized()); + assert(!i_value.isInitialized()); --i; assert(i_value.getName() == "/Item2"); assert(i->getName() == "/Item2"); @@ -1557,7 +1470,7 @@ static void test_42(QPDF& pdf, char const* arg2) ++i; ++i; assert(i == di.end()); - assert(! i_value.second.isInitialized()); + assert(!i_value.second.isInitialized()); } assert("" == qtest.getStringValue()); array.getArrayItem(-1).assertNull(); @@ -1600,129 +1513,117 @@ static void test_42(QPDF& pdf, char const* arg2) assert(array.getArrayItem(1).isDictionary()); assert(array.getArrayItem(1).getKey("/K").isArray()); assert(array.getArrayItem(1).getKey("/K").getArrayItem(0).isName()); - assert("/V" == - array.getArrayItem(1).getKey("/K").getArrayItem(0).getName()); + assert( + "/V" == array.getArrayItem(1).getKey("/K").getArrayItem(0).getName()); std::cerr << "Two errors\n"; assert(array.getArrayItem(16059).getStringValue().empty()); std::cerr << "One error\n"; array.getArrayItem(1).getKey("/K").getArrayItem(0).getStringValue(); // Stream dictionary QPDFObjectHandle page = pdf.getAllPages().at(0); - assert("/QPDFFakeName" == - page.getKey("/Contents").getDict().getKey("/Potato").getName()); + assert( + "/QPDFFakeName" == + page.getKey("/Contents").getDict().getKey("/Potato").getName()); // Rectangles QPDFObjectHandle::Rectangle r0 = integer.getArrayAsRectangle(); - assert((r0.llx == 0) && (r0.lly == 0) && - (r0.urx == 0) && (r0.ury == 0)); + assert((r0.llx == 0) && (r0.lly == 0) && (r0.urx == 0) && (r0.ury == 0)); QPDFObjectHandle rect = QPDFObjectHandle::newFromRectangle( QPDFObjectHandle::Rectangle(1.2, 3.4, 5.6, 7.8)); QPDFObjectHandle::Rectangle r1 = rect.getArrayAsRectangle(); - assert((r1.llx > 1.19) && (r1.llx < 1.21) && - (r1.lly > 3.39) && (r1.lly < 3.41) && - (r1.urx > 5.59) && (r1.urx < 5.61) && - (r1.ury > 7.79) && (r1.ury < 7.81)); + assert( + (r1.llx > 1.19) && (r1.llx < 1.21) && (r1.lly > 3.39) && + (r1.lly < 3.41) && (r1.urx > 5.59) && (r1.urx < 5.61) && + (r1.ury > 7.79) && (r1.ury < 7.81)); QPDFObjectHandle uninitialized; - assert(! uninitialized.isInitialized()); - assert(! uninitialized.isInteger()); - assert(! uninitialized.isDictionary()); + assert(!uninitialized.isInitialized()); + assert(!uninitialized.isInteger()); + assert(!uninitialized.isDictionary()); } -static void test_43(QPDF& pdf, char const* arg2) +static void +test_43(QPDF& pdf, char const* arg2) { // Forms QPDFAcroFormDocumentHelper afdh(pdf); - if (! afdh.hasAcroForm()) - { + if (!afdh.hasAcroForm()) { std::cout << "no forms\n"; return; } std::cout << "iterating over form fields\n"; - std::vector form_fields = - afdh.getFormFields(); + std::vector form_fields = afdh.getFormFields(); for (std::vector::iterator iter = form_fields.begin(); - iter != form_fields.end(); ++iter) - { + iter != form_fields.end(); + ++iter) { QPDFFormFieldObjectHelper ffh(*iter); - std::cout << "Field: " << ffh.getObjectHandle().unparse() - << std::endl; + std::cout << "Field: " << ffh.getObjectHandle().unparse() << std::endl; QPDFFormFieldObjectHelper node = ffh; - while (! node.isNull()) - { + while (!node.isNull()) { QPDFFormFieldObjectHelper parent(node.getParent()); std::cout << " Parent: " - << (parent.isNull() - ? std::string("none") - : parent.getObjectHandle().unparse()) + << (parent.isNull() ? std::string("none") + : parent.getObjectHandle().unparse()) << std::endl; node = parent; } - std::cout << " Fully qualified name: " - << ffh.getFullyQualifiedName() << std::endl; - std::cout << " Partial name: " - << ffh.getPartialName() << std::endl; - std::cout << " Alternative name: " - << ffh.getAlternativeName() << std::endl; - std::cout << " Mapping name: " - << ffh.getMappingName() << std::endl; - std::cout << " Field type: " - << ffh.getFieldType() << std::endl; - std::cout << " Value: " - << ffh.getValue().unparse() << std::endl; - std::cout << " Value as string: " - << ffh.getValueAsString() << std::endl; - std::cout << " Default value: " - << ffh.getDefaultValue().unparse() << std::endl; + std::cout << " Fully qualified name: " << ffh.getFullyQualifiedName() + << std::endl; + std::cout << " Partial name: " << ffh.getPartialName() << std::endl; + std::cout << " Alternative name: " << ffh.getAlternativeName() + << std::endl; + std::cout << " Mapping name: " << ffh.getMappingName() << std::endl; + std::cout << " Field type: " << ffh.getFieldType() << std::endl; + std::cout << " Value: " << ffh.getValue().unparse() << std::endl; + std::cout << " Value as string: " << ffh.getValueAsString() + << std::endl; + std::cout << " Default value: " << ffh.getDefaultValue().unparse() + << std::endl; std::cout << " Default value as string: " << ffh.getDefaultValueAsString() << std::endl; - std::cout << " Default appearance: " - << ffh.getDefaultAppearance() << std::endl; - std::cout << " Quadding: " - << ffh.getQuadding() << std::endl; + std::cout << " Default appearance: " << ffh.getDefaultAppearance() + << std::endl; + std::cout << " Quadding: " << ffh.getQuadding() << std::endl; std::vector annotations = afdh.getAnnotationsForField(ffh); for (std::vector::iterator i2 = annotations.begin(); - i2 != annotations.end(); ++i2) - { - std::cout << " Annotation: " - << (*i2).getObjectHandle().unparse() << std::endl; + i2 != annotations.end(); + ++i2) { + std::cout << " Annotation: " << (*i2).getObjectHandle().unparse() + << std::endl; } } std::cout << "iterating over annotations per page\n"; std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { std::cout << "Page: " << (*iter).getObjectHandle().unparse() << std::endl; std::vector annotations = afdh.getWidgetAnnotationsForPage(*iter); for (std::vector::iterator i2 = annotations.begin(); - i2 != annotations.end(); ++i2) - { + i2 != annotations.end(); + ++i2) { QPDFAnnotationObjectHelper ah(*i2); std::cout << " Annotation: " << ah.getObjectHandle().unparse() << std::endl; - std::cout << " Field: " - << (afdh.getFieldForAnnotation(ah). - getObjectHandle().unparse()) - << std::endl; + std::cout + << " Field: " + << (afdh.getFieldForAnnotation(ah).getObjectHandle().unparse()) + << std::endl; std::cout << " Subtype: " << ah.getSubtype() << std::endl; std::cout << " Rect: "; print_rect(std::cout, ah.getRect()); std::cout << std::endl; std::string state = ah.getAppearanceState(); - if (! state.empty()) - { - std::cout << " Appearance state: " << state - << std::endl; + if (!state.empty()) { + std::cout << " Appearance state: " << state << std::endl; } std::cout << " Appearance stream (/N): " - << ah.getAppearanceStream("/N").unparse() - << std::endl; + << ah.getAppearanceStream("/N").unparse() << std::endl; std::cout << " Appearance stream (/N, /3): " << ah.getAppearanceStream("/N", "/3").unparse() << std::endl; @@ -1730,26 +1631,22 @@ static void test_43(QPDF& pdf, char const* arg2) } } -static void test_44(QPDF& pdf, char const* arg2) +static void +test_44(QPDF& pdf, char const* arg2) { // Set form fields. QPDFAcroFormDocumentHelper afdh(pdf); std::vector fields = afdh.getFormFields(); - for (std::vector::iterator iter = - fields.begin(); - iter != fields.end(); ++iter) - { + for (std::vector::iterator iter = fields.begin(); + iter != fields.end(); + ++iter) { QPDFFormFieldObjectHelper& field(*iter); QPDFObjectHandle ft = field.getInheritableFieldValue("/FT"); - if (ft.isName() && (ft.getName() == "/Tx")) - { + if (ft.isName() && (ft.getName() == "/Tx")) { // \xc3\xb7 is utf-8 for U+00F7 (divided by) field.setV("3.14 \xc3\xb7 0"); - std::cout << "Set field value: " - << field.getFullyQualifiedName() - << " -> " - << field.getValueAsString() - << std::endl; + std::cout << "Set field value: " << field.getFullyQualifiedName() + << " -> " << field.getValueAsString() << std::endl; } } QPDFWriter w(pdf, "a.pdf"); @@ -1759,7 +1656,8 @@ static void test_44(QPDF& pdf, char const* arg2) w.write(); } -static void test_45(QPDF& pdf, char const* arg2) +static void +test_45(QPDF& pdf, char const* arg2) { // Decode obfuscated files. This is here to help test with // files that trigger anti-virus warnings. See comments in @@ -1767,41 +1665,37 @@ static void test_45(QPDF& pdf, char const* arg2) QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); w.write(); - if (! pdf.getWarnings().empty()) - { + if (!pdf.getWarnings().empty()) { exit(3); } } -static void test_46(QPDF& pdf, char const* arg2) +static void +test_46(QPDF& pdf, char const* arg2) { // Test number tree. This test is crafted to work with // number-tree.pdf QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNumberTreeObjectHelper ntoh(qtest, pdf); - for (auto& iter: ntoh) - { - std::cout << iter.first << " " - << iter.second.getStringValue() + for (auto& iter : ntoh) { + std::cout << iter.first << " " << iter.second.getStringValue() << std::endl; } QPDFNumberTreeObjectHelper::idx_map ntoh_map = ntoh.getAsMap(); - for (auto& iter: ntoh_map) - { - std::cout << iter.first << " " - << iter.second.getStringValue() + for (auto& iter : ntoh_map) { + std::cout << iter.first << " " << iter.second.getStringValue() << std::endl; } assert(1 == ntoh.getMin()); assert(29 == ntoh.getMax()); assert(ntoh.hasIndex(6)); - assert(! ntoh.hasIndex(500)); + assert(!ntoh.hasIndex(500)); QPDFObjectHandle oh; - assert(! ntoh.findObject(4, oh)); + assert(!ntoh.findObject(4, oh)); assert(ntoh.findObject(3, oh)); assert("three" == oh.getStringValue()); QPDFNumberTreeObjectHelper::numtree_number offset = 0; - assert(! ntoh.findObjectAtOrBelow(0, oh, offset)); + assert(!ntoh.findObjectAtOrBelow(0, oh, offset)); assert(ntoh.findObjectAtOrBelow(8, oh, offset)); assert("six" == oh.getStringValue()); assert(2 == offset); @@ -1828,7 +1722,7 @@ static void test_46(QPDF& pdf, char const* arg2) assert(iter1_val.first == 2); ++iter1; assert(iter1 == new1.end()); - assert(! iter1_val.second.isInitialized()); + assert(!iter1_val.second.isInitialized()); ++iter1; assert(iter1->first == 1); --iter1; @@ -1844,47 +1738,42 @@ static void test_46(QPDF& pdf, char const* arg2) assert(iter2->first == 3); iter2.insertAfter(4, QPDFObjectHandle::newString("4!")); assert(iter2->first == 4); - for (auto& i: new2) - { + for (auto& i : new2) { std::cout << i.first << " " << i.second.unparse() << std::endl; } // Exercise deprecated API until qpdf 11 std::cout << "/Bad1: deprecated API" << std::endl; #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif - auto bad1 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Bad1")); + auto bad1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad1")); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif assert(bad1.begin() == bad1.end()); std::cout << "/Bad1" << std::endl; - bad1 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Bad1"), pdf); + bad1 = QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf); assert(bad1.begin() == bad1.end()); assert(bad1.last() == bad1.end()); std::cout << "/Bad2" << std::endl; - auto bad2 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Bad2"), pdf); - for (auto& i: bad2) - { + auto bad2 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf); + for (auto& i : bad2) { std::cout << i.first << " " << i.second.unparse() << std::endl; } std::vector empties = {"/Empty1", "/Empty2"}; - for (auto const& k: empties) - { + for (auto const& k : empties) { std::cout << k << std::endl; - auto empty = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey(k), pdf); + auto empty = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey(k), pdf); assert(empty.begin() == empty.end()); assert(empty.last() == empty.end()); auto i = empty.insert(5, QPDFObjectHandle::newString("5")); @@ -1905,89 +1794,80 @@ static void test_46(QPDF& pdf, char const* arg2) assert(empty.last()->second.getStringValue() == "6"); } std::cout << "Insert into invalid" << std::endl; - auto invalid1 = QPDFNumberTreeObjectHelper( - QPDFObjectHandle::newDictionary(), pdf); - try - { + auto invalid1 = + QPDFNumberTreeObjectHelper(QPDFObjectHandle::newDictionary(), pdf); + try { invalid1.insert(1, QPDFObjectHandle::newNull()); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { std::cout << e.what() << std::endl; } std::cout << "/Bad3, no repair" << std::endl; auto bad3_oh = pdf.getTrailer().getKey("/Bad3"); auto bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, false); - for (auto& i: bad3) - { + for (auto& i : bad3) { std::cout << i.first << " " << i.second.unparse() << std::endl; } - assert(! bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect()); + assert(!bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect()); std::cout << "/Bad3, repair" << std::endl; bad3 = QPDFNumberTreeObjectHelper(bad3_oh, pdf, true); - for (auto& i: bad3) - { + for (auto& i : bad3) { std::cout << i.first << " " << i.second.unparse() << std::endl; } assert(bad3_oh.getKey("/Kids").getArrayItem(0).isIndirect()); std::cout << "/Bad4 -- missing limits" << std::endl; - auto bad4 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Bad4"), pdf); + auto bad4 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf); bad4.insert(5, QPDFObjectHandle::newString("5")); - for (auto& i: bad4) - { + for (auto& i : bad4) { std::cout << i.first << " " << i.second.unparse() << std::endl; } std::cout << "/Bad5 -- limit errors" << std::endl; - auto bad5 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Bad5"), pdf); + auto bad5 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf); assert(bad5.find(10) == bad5.end()); } -static void test_47(QPDF& pdf, char const* arg2) +static void +test_47(QPDF& pdf, char const* arg2) { // Test page labels. QPDFPageLabelDocumentHelper pldh(pdf); - long long npages = pdf.getRoot().getKey("/Pages"). - getKey("/Count").getIntValue(); + long long npages = + pdf.getRoot().getKey("/Pages").getKey("/Count").getIntValue(); std::vector labels; pldh.getLabelsForPageRange(0, npages - 1, 1, labels); assert(labels.size() % 2 == 0); - for (size_t i = 0; i < labels.size(); i+= 2) - { + for (size_t i = 0; i < labels.size(); i += 2) { std::cout << labels.at(i).getIntValue() << " " - << labels.at(i+1).unparse() << std::endl; + << labels.at(i + 1).unparse() << std::endl; } } -static void test_48(QPDF& pdf, char const* arg2) +static void +test_48(QPDF& pdf, char const* arg2) { // Test name tree. This test is crafted to work with // name-tree.pdf QPDFObjectHandle qtest = pdf.getTrailer().getKey("/QTest"); QPDFNameTreeObjectHelper ntoh(qtest, pdf); - for (auto& iter: ntoh) - { - std::cout << iter.first << " -> " - << iter.second.getStringValue() + for (auto& iter : ntoh) { + std::cout << iter.first << " -> " << iter.second.getStringValue() << std::endl; } std::map ntoh_map = ntoh.getAsMap(); - for (auto& iter: ntoh_map) - { - std::cout << iter.first << " -> " - << iter.second.getStringValue() + for (auto& iter : ntoh_map) { + std::cout << iter.first << " -> " << iter.second.getStringValue() << std::endl; } assert(ntoh.hasName("11 elephant")); assert(ntoh.hasName("07 sev\xe2\x80\xa2n")); - assert(! ntoh.hasName("potato")); + assert(!ntoh.hasName("potato")); QPDFObjectHandle oh; - assert(! ntoh.findObject("potato", oh)); + assert(!ntoh.findObject("potato", oh)); assert(ntoh.findObject("07 sev\xe2\x80\xa2n", oh)); assert("seven!" == oh.getStringValue()); auto last = ntoh.last(); @@ -2016,7 +1896,7 @@ static void test_48(QPDF& pdf, char const* arg2) assert(iter1_val.first == "2"); ++iter1; assert(iter1 == new1.end()); - assert(! iter1_val.second.isInitialized()); + assert(!iter1_val.second.isInitialized()); ++iter1; assert(iter1->first == "1"); --iter1; @@ -2032,17 +1912,14 @@ static void test_48(QPDF& pdf, char const* arg2) assert(iter2->first == "3"); iter2.insertAfter("4", QPDFObjectHandle::newString("4!")); assert(iter2->first == "4"); - for (auto& i: new2) - { + for (auto& i : new2) { std::cout << i.first << " " << i.second.unparse() << std::endl; } std::vector empties = {"/Empty1", "/Empty2"}; - for (auto const& k: empties) - { + for (auto const& k : empties) { std::cout << k << std::endl; - auto empty = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey(k), pdf); + auto empty = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey(k), pdf); assert(empty.begin() == empty.end()); assert(empty.last() == empty.end()); auto i = empty.insert("five", QPDFObjectHandle::newString("5")); @@ -2066,71 +1943,59 @@ static void test_48(QPDF& pdf, char const* arg2) // Exercise deprecated API until qpdf 11 std::cout << "/Bad1: deprecated API" << std::endl; #ifdef _MSC_VER -# pragma warning (disable: 4996) +# pragma warning(disable : 4996) #endif #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif - auto bad1 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad1")); + auto bad1 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad1")); #if (defined(__GNUC__) || defined(__clang__)) # pragma GCC diagnostic pop #endif - try - { + try { bad1.find("G", true); assert(false); - } - catch (std::runtime_error& e) - { + } catch (std::runtime_error& e) { std::cout << e.what() << std::endl; } std::cout << "/Bad1 -- wrong key type" << std::endl; - bad1 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad1"), pdf); + bad1 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad1"), pdf); assert(bad1.find("G", true)->first == "A"); - for (auto const& i: bad1) - { + for (auto const& i : bad1) { std::cout << i.first << std::endl; } std::cout << "/Bad2 -- invalid kid" << std::endl; - auto bad2 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad2"), pdf); + auto bad2 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad2"), pdf); assert(bad2.find("G", true)->first == "B"); - for (auto const& i: bad2) - { + for (auto const& i : bad2) { std::cout << i.first << std::endl; } std::cout << "/Bad3 -- invalid kid" << std::endl; - auto bad3 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad3"), pdf); + auto bad3 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad3"), pdf); assert(bad3.find("G", true) == bad3.end()); std::cout << "/Bad4 -- invalid kid" << std::endl; - auto bad4 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad4"), pdf); + auto bad4 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad4"), pdf); assert(bad4.find("F", true)->first == "C"); - for (auto const& i: bad4) - { + for (auto const& i : bad4) { std::cout << i.first << std::endl; } std::cout << "/Bad5 -- loop in find" << std::endl; - auto bad5 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad5"), pdf); + auto bad5 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad5"), pdf); assert(bad5.find("F", true)->first == "D"); std::cout << "/Bad6 -- bad limits" << std::endl; - auto bad6 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Bad6"), pdf); + auto bad6 = QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Bad6"), pdf); assert(bad6.insert("H", QPDFObjectHandle::newNull())->first == "H"); } -static void test_49(QPDF& pdf, char const* arg2) +static void +test_49(QPDF& pdf, char const* arg2) { // Outlines std::vector pages = @@ -2138,23 +2003,23 @@ static void test_49(QPDF& pdf, char const* arg2) QPDFOutlineDocumentHelper odh(pdf); int pageno = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter, ++pageno) - { + iter != pages.end(); + ++iter, ++pageno) { std::vector outlines = odh.getOutlinesForPage((*iter).getObjectHandle().getObjGen()); for (std::vector::iterator oiter = outlines.begin(); - oiter != outlines.end(); ++oiter) - { - std::cout - << "page " << pageno << ": " - << (*oiter).getTitle() << " -> " - << (*oiter).getDest().unparseResolved() << std::endl; + oiter != outlines.end(); + ++oiter) { + std::cout << "page " << pageno << ": " << (*oiter).getTitle() + << " -> " << (*oiter).getDest().unparseResolved() + << std::endl; } } } -static void test_50(QPDF& pdf, char const* arg2) +static void +test_50(QPDF& pdf, char const* arg2) { // Test dictionary merge. This test is crafted to work with // merge-dict.pdf @@ -2166,13 +2031,14 @@ static void test_50(QPDF& pdf, char const* arg2) d1.mergeResources(d2.getKey("/k1")); std::set names = d1.getResourceNames(); for (std::set::iterator iter = names.begin(); - iter != names.end(); ++iter) - { + iter != names.end(); + ++iter) { std::cout << *iter << std::endl; } } -static void test_51(QPDF& pdf, char const* arg2) +static void +test_51(QPDF& pdf, char const* arg2) { // Test radio button and checkbox field setting. The input // files must have radios button called r1 and r2 and @@ -2181,36 +2047,27 @@ static void test_51(QPDF& pdf, char const* arg2) QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm"); QPDFObjectHandle fields = acroform.getKey("/Fields"); int nitems = fields.getArrayNItems(); - for (int i = 0; i < nitems; ++i) - { + for (int i = 0; i < nitems; ++i) { QPDFObjectHandle field = fields.getArrayItem(i); QPDFObjectHandle T = field.getKey("/T"); - if (! T.isString()) - { + if (!T.isString()) { continue; } std::string Tval = T.getUTF8Value(); - if (Tval == "r1") - { + if (Tval == "r1") { std::cout << "setting r1 via parent\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/2")); - } - else if (Tval == "r2") - { + } else if (Tval == "r2") { std::cout << "setting r2 via child\n"; field = field.getKey("/Kids").getArrayItem(1); QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/3")); - } - else if (Tval == "checkbox1") - { + } else if (Tval == "checkbox1") { std::cout << "turning checkbox1 on\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/Yes")); - } - else if (Tval == "checkbox2") - { + } else if (Tval == "checkbox2") { std::cout << "turning checkbox2 off\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newName("/Off")); @@ -2222,24 +2079,22 @@ static void test_51(QPDF& pdf, char const* arg2) w.write(); } -static void test_52(QPDF& pdf, char const* arg2) +static void +test_52(QPDF& pdf, char const* arg2) { // This test just sets a field value for appearance stream // generating testing. QPDFObjectHandle acroform = pdf.getRoot().getKey("/AcroForm"); QPDFObjectHandle fields = acroform.getKey("/Fields"); int nitems = fields.getArrayNItems(); - for (int i = 0; i < nitems; ++i) - { + for (int i = 0; i < nitems; ++i) { QPDFObjectHandle field = fields.getArrayItem(i); QPDFObjectHandle T = field.getKey("/T"); - if (! T.isString()) - { + if (!T.isString()) { continue; } std::string Tval = T.getUTF8Value(); - if (Tval == "list1") - { + if (Tval == "list1") { std::cout << "setting list1 value\n"; QPDFFormFieldObjectHelper foh(field); foh.setV(QPDFObjectHandle::newString(arg2)); @@ -2249,18 +2104,18 @@ static void test_52(QPDF& pdf, char const* arg2) w.write(); } -static void test_53(QPDF& pdf, char const* arg2) +static void +test_53(QPDF& pdf, char const* arg2) { // Test get all objects and dangling ref handling QPDFObjectHandle root = pdf.getRoot(); root.replaceKey( - "/Q1", - pdf.makeIndirectObject(QPDFObjectHandle::newString("potato"))); + "/Q1", pdf.makeIndirectObject(QPDFObjectHandle::newString("potato"))); std::cout << "all objects" << std::endl; std::vector all = pdf.getAllObjects(); for (std::vector::iterator iter = all.begin(); - iter != all.end(); ++iter) - { + iter != all.end(); + ++iter) { std::cout << (*iter).unparse() << std::endl; } @@ -2269,28 +2124,29 @@ static void test_53(QPDF& pdf, char const* arg2) w.write(); } -static void test_54(QPDF& pdf, char const* arg2) +static void +test_54(QPDF& pdf, char const* arg2) { // Test getFinalVersion. This must be invoked with a file // whose final version is not 1.5. QPDFWriter w(pdf, "a.pdf"); assert(pdf.getPDFVersion() != "1.5"); w.setObjectStreamMode(qpdf_o_generate); - if (w.getFinalVersion() != "1.5") - { + if (w.getFinalVersion() != "1.5") { std::cout << "oops: " << w.getFinalVersion() << std::endl; } } -static void test_55(QPDF& pdf, char const* arg2) +static void +test_55(QPDF& pdf, char const* arg2) { // Form XObjects std::vector pages = QPDFPageDocumentHelper(pdf).getAllPages(); QPDFObjectHandle qtest = QPDFObjectHandle::newArray(); for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { QPDFPageObjectHelper& ph(*iter); qtest.appendItem(ph.getFormXObjectForPage()); qtest.appendItem(ph.getFormXObjectForPage(false)); @@ -2302,9 +2158,12 @@ static void test_55(QPDF& pdf, char const* arg2) w.write(); } -static void test_56_59(QPDF& pdf, char const* arg2, - bool handle_from_transformation, - bool invert_to_transformation) +static void +test_56_59( + QPDF& pdf, + char const* arg2, + bool handle_from_transformation, + bool invert_to_transformation) { // red pages are from pdf, blue pages are from pdf2 // red pages always have stated rotation absolutely @@ -2322,32 +2181,28 @@ static void test_56_59(QPDF& pdf, char const* arg2, QPDFPageDocumentHelper(pdf).getAllPages(); std::vector pages2 = QPDFPageDocumentHelper(pdf2).getAllPages(); - size_t npages = (pages1.size() < pages2.size() - ? pages1.size() : pages2.size()); - for (size_t i = 0; i < npages; ++i) - { + size_t npages = + (pages1.size() < pages2.size() ? pages1.size() : pages2.size()); + for (size_t i = 0; i < npages; ++i) { QPDFPageObjectHelper& ph1 = pages1.at(i); QPDFPageObjectHelper& ph2 = pages2.at(i); QPDFObjectHandle fo = pdf.copyForeignObject( ph2.getFormXObjectForPage(handle_from_transformation)); int min_suffix = 1; QPDFObjectHandle resources = ph1.getAttribute("/Resources", true); - std::string name = resources.getUniqueResourceName( - "/Fx", min_suffix); - std::string content = - ph1.placeFormXObject( - fo, name, ph1.getTrimBox().getArrayAsRectangle(), - invert_to_transformation); - if (! content.empty()) - { + std::string name = resources.getUniqueResourceName("/Fx", min_suffix); + std::string content = ph1.placeFormXObject( + fo, + name, + ph1.getTrimBox().getArrayAsRectangle(), + invert_to_transformation); + if (!content.empty()) { resources.mergeResources( QPDFObjectHandle::parse("<< /XObject << >> >>")); resources.getKey("/XObject").replaceKey(name, fo); + ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "q\n"), true); ph1.addPageContents( - QPDFObjectHandle::newStream(&pdf, "q\n"), true); - ph1.addPageContents( - QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), - false); + QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false); } } QPDFWriter w(pdf, "a.pdf"); @@ -2356,39 +2211,42 @@ static void test_56_59(QPDF& pdf, char const* arg2, w.write(); } -static void test_56(QPDF& pdf, char const* arg2) +static void +test_56(QPDF& pdf, char const* arg2) { test_56_59(pdf, arg2, false, false); } -static void test_57(QPDF& pdf, char const* arg2) +static void +test_57(QPDF& pdf, char const* arg2) { test_56_59(pdf, arg2, true, false); } -static void test_58(QPDF& pdf, char const* arg2) +static void +test_58(QPDF& pdf, char const* arg2) { test_56_59(pdf, arg2, false, true); } -static void test_59(QPDF& pdf, char const* arg2) +static void +test_59(QPDF& pdf, char const* arg2) { test_56_59(pdf, arg2, true, true); } -static void test_60(QPDF& pdf, char const* arg2) +static void +test_60(QPDF& pdf, char const* arg2) { // Boundary condition testing for getUniqueResourceName; // additional testing of mergeResources with conflict // detection QPDFObjectHandle r1 = QPDFObjectHandle::newDictionary(); int min_suffix = 1; - for (int i = 1; i < 3; ++i) - { + for (int i = 1; i < 3; ++i) { std::string name = r1.getUniqueResourceName("/Quack", min_suffix); r1.mergeResources(QPDFObjectHandle::parse("<< /Z << >> >>")); - r1.getKey("/Z").replaceKey( - name, QPDFObjectHandle::newString("moo")); + r1.getKey("/Z").replaceKey(name, QPDFObjectHandle::newString("moo")); } auto make_resource = [&](QPDFObjectHandle& dict, std::string const& key, @@ -2405,8 +2263,7 @@ static void test_60(QPDF& pdf, char const* arg2) make_resource(z, "/F2", "r1.Z.F2"); make_resource(y, "/F2", "r1.Y.F2"); make_resource(y, "/F3", "r1.Y.F3"); - QPDFObjectHandle r2 = - QPDFObjectHandle::parse("<< /Z << >> /Y << >> >>"); + QPDFObjectHandle r2 = QPDFObjectHandle::parse("<< /Z << >> /Y << >> >>"); z = r2.getKey("/Z"); y = r2.getKey("/Y"); make_resource(z, "/F2", "r2.Z.F2"); @@ -2418,11 +2275,9 @@ static void test_60(QPDF& pdf, char const* arg2) std::map> conflicts; auto show_conflicts = [&](std::string const& msg) { std::cout << msg << std::endl; - for (auto const& i1: conflicts) - { + for (auto const& i1 : conflicts) { std::cout << i1.first << ":" << std::endl; - for (auto const& i2: i1.second) - { + for (auto const& i2 : i1.second) { std::cout << " " << i2.first << " -> " << i2.second << std::endl; } @@ -2457,47 +2312,37 @@ static void test_60(QPDF& pdf, char const* arg2) w.write(); } -static void test_61(QPDF& pdf, char const* arg2) +static void +test_61(QPDF& pdf, char const* arg2) { // Test to make sure exceptions can be caught properly across // shared library boundaries. pdf.setAttemptRecovery(false); pdf.setSuppressWarnings(true); - try - { + try { pdf.processMemoryFile("empty", "", 0); - } - catch (QPDFExc const&) - { + } catch (QPDFExc const&) { std::cout << "Caught QPDFExc as expected" << std::endl; } - try - { + try { QUtil::safe_fopen("/does/not/exist", "r"); - } - catch (QPDFSystemError const&) - { + } catch (QPDFSystemError const&) { std::cout << "Caught QPDFSystemError as expected" << std::endl; } - try - { + try { QUtil::int_to_string_base(0, 12); - } - catch (std::logic_error const&) - { + } catch (std::logic_error const&) { std::cout << "Caught logic_error as expected" << std::endl; } - try - { + try { QUtil::toUTF8(0xffffffff); - } - catch (std::runtime_error const&) - { + } catch (std::runtime_error const&) { std::cout << "Caught runtime_error as expected" << std::endl; } } -static void test_62(QPDF& pdf, char const* arg2) +static void +test_62(QPDF& pdf, char const* arg2) { // Test int size checks. This test will fail if int and long // long are the same size. @@ -2523,7 +2368,8 @@ static void test_62(QPDF& pdf, char const* arg2) assert_compare_numbers(UINT_MAX, t.getKey("/Q3").getUIntValueAsUInt()); } -static void test_63(QPDF& pdf, char const* arg2) +static void +test_63(QPDF& pdf, char const* arg2) { QPDFWriter w(pdf); // Exercise setting encryption parameters before setting the @@ -2537,8 +2383,8 @@ static void test_63(QPDF& pdf, char const* arg2) w.write(); } -static void test_64_67(QPDF& pdf, char const* arg2, - bool allow_shrink, bool allow_expand) +static void +test_64_67(QPDF& pdf, char const* arg2, bool allow_shrink, bool allow_expand) { // Overlay file2 on file1. // 64: allow neither shrink nor shrink @@ -2555,32 +2401,30 @@ static void test_64_67(QPDF& pdf, char const* arg2, QPDFPageDocumentHelper(pdf).getAllPages(); std::vector pages2 = QPDFPageDocumentHelper(pdf2).getAllPages(); - size_t npages = (pages1.size() < pages2.size() - ? pages1.size() : pages2.size()); - for (size_t i = 0; i < npages; ++i) - { + size_t npages = + (pages1.size() < pages2.size() ? pages1.size() : pages2.size()); + for (size_t i = 0; i < npages; ++i) { QPDFPageObjectHelper& ph1 = pages1.at(i); QPDFPageObjectHelper& ph2 = pages2.at(i); - QPDFObjectHandle fo = pdf.copyForeignObject( - ph2.getFormXObjectForPage()); + QPDFObjectHandle fo = + pdf.copyForeignObject(ph2.getFormXObjectForPage()); int min_suffix = 1; QPDFObjectHandle resources = ph1.getAttribute("/Resources", true); - std::string name = resources.getUniqueResourceName( - "/Fx", min_suffix); - std::string content = - ph1.placeFormXObject( - fo, name, ph1.getTrimBox().getArrayAsRectangle(), - false, allow_shrink, allow_expand); - if (! content.empty()) - { + std::string name = resources.getUniqueResourceName("/Fx", min_suffix); + std::string content = ph1.placeFormXObject( + fo, + name, + ph1.getTrimBox().getArrayAsRectangle(), + false, + allow_shrink, + allow_expand); + if (!content.empty()) { resources.mergeResources( QPDFObjectHandle::parse("<< /XObject << >> >>")); resources.getKey("/XObject").replaceKey(name, fo); + ph1.addPageContents(QPDFObjectHandle::newStream(&pdf, "q\n"), true); ph1.addPageContents( - QPDFObjectHandle::newStream(&pdf, "q\n"), true); - ph1.addPageContents( - QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), - false); + QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false); } } QPDFWriter w(pdf, "a.pdf"); @@ -2589,74 +2433,74 @@ static void test_64_67(QPDF& pdf, char const* arg2, w.write(); } -static void test_64(QPDF& pdf, char const* arg2) +static void +test_64(QPDF& pdf, char const* arg2) { test_64_67(pdf, arg2, false, false); } -static void test_65(QPDF& pdf, char const* arg2) +static void +test_65(QPDF& pdf, char const* arg2) { test_64_67(pdf, arg2, true, false); } -static void test_66(QPDF& pdf, char const* arg2) +static void +test_66(QPDF& pdf, char const* arg2) { test_64_67(pdf, arg2, false, true); } -static void test_67(QPDF& pdf, char const* arg2) +static void +test_67(QPDF& pdf, char const* arg2) { test_64_67(pdf, arg2, true, true); } -static void test_68(QPDF& pdf, char const* arg2) +static void +test_68(QPDF& pdf, char const* arg2) { QPDFObjectHandle root = pdf.getRoot(); QPDFObjectHandle qstream = root.getKey("/QStream"); - try - { + try { qstream.getStreamData(); std::cout << "oops -- didn't throw" << std::endl; - } - catch (std::exception& e) - { - std::cout << "get unfilterable stream: " << e.what() - << std::endl; + } catch (std::exception& e) { + std::cout << "get unfilterable stream: " << e.what() << std::endl; } PointerHolder b1 = qstream.getStreamData(qpdf_dl_all); if ((b1->getSize() > 10) && - (memcmp(b1->getBuffer(), - "wwwwwwwww", 9) == 0)) - { + (memcmp(b1->getBuffer(), "wwwwwwwww", 9) == 0)) { std::cout << "filtered stream data okay" << std::endl; } PointerHolder b2 = qstream.getRawStreamData(); if ((b2->getSize() > 10) && - (memcmp(b2->getBuffer(), - "\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46", 10) == 0)) - { + (memcmp( + b2->getBuffer(), "\xff\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46", 10) == + 0)) { std::cout << "raw stream data okay" << std::endl; } } -static void test_69(QPDF& pdf, char const* arg2) +static void +test_69(QPDF& pdf, char const* arg2) { pdf.setImmediateCopyFrom(true); auto pages = pdf.getAllPages(); - for (size_t i = 0; i < pages.size(); ++i) - { + for (size_t i = 0; i < pages.size(); ++i) { QPDF out; out.emptyPDF(); out.addPage(pages.at(i), false); - std::string outname = std::string("auto-") + - QUtil::uint_to_string(i) + ".pdf"; + std::string outname = + std::string("auto-") + QUtil::uint_to_string(i) + ".pdf"; QPDFWriter w(out, outname.c_str()); w.setStaticID(true); w.write(); } } -static void test_70(QPDF& pdf, char const* arg2) +static void +test_70(QPDF& pdf, char const* arg2) { auto trailer = pdf.getTrailer(); trailer.getKey("/S1").setFilterOnWrite(false); @@ -2667,13 +2511,14 @@ static void test_70(QPDF& pdf, char const* arg2) w.write(); } -static void test_71(QPDF& pdf, char const* arg2) +static void +test_71(QPDF& pdf, char const* arg2) { auto show = [](QPDFObjectHandle& obj, QPDFObjectHandle& xobj_dict, std::string const& key) { - std::cout << xobj_dict.unparse() << " -> " - << key << " -> " << obj.unparse() << std::endl; + std::cout << xobj_dict.unparse() << " -> " << key << " -> " + << obj.unparse() << std::endl; }; auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0); std::cout << "--- recursive, all ---" << std::endl; @@ -2688,63 +2533,54 @@ static void test_71(QPDF& pdf, char const* arg2) page.forEachFormXObject(true, show); std::cout << "--- non-recursive, form XObjects ---" << std::endl; page.forEachFormXObject(false, show); - auto fx1 = QPDFPageObjectHelper( - page.getObjectHandle() - .getKey("/Resources") - .getKey("/XObject") - .getKey("/Fx1")); + auto fx1 = QPDFPageObjectHelper(page.getObjectHandle() + .getKey("/Resources") + .getKey("/XObject") + .getKey("/Fx1")); std::cout << "--- recursive, all, from fx1 ---" << std::endl; fx1.forEachXObject(true, show); std::cout << "--- non-recursive, all, from fx1 ---" << std::endl; fx1.forEachXObject(false, show); std::cout << "--- get images, page ---" << std::endl; - for (auto& i: page.getImages()) - { + for (auto& i : page.getImages()) { std::cout << i.first << " -> " << i.second.unparse() << std::endl; } std::cout << "--- get images, fx ---" << std::endl; - for (auto& i: fx1.getImages()) - { + for (auto& i : fx1.getImages()) { std::cout << i.first << " -> " << i.second.unparse() << std::endl; } std::cout << "--- get form XObjects, page ---" << std::endl; - for (auto& i: page.getFormXObjects()) - { + for (auto& i : page.getFormXObjects()) { std::cout << i.first << " -> " << i.second.unparse() << std::endl; } std::cout << "--- get form XObjects, fx ---" << std::endl; - for (auto& i: fx1.getFormXObjects()) - { + for (auto& i : fx1.getFormXObjects()) { std::cout << i.first << " -> " << i.second.unparse() << std::endl; } } -static void test_72(QPDF& pdf, char const* arg2) +static void +test_72(QPDF& pdf, char const* arg2) { // Call some QPDFPageObjectHelper methods on form XObjects. auto page = QPDFPageDocumentHelper(pdf).getAllPages().at(0); - auto fx1 = QPDFPageObjectHelper( - page.getObjectHandle() - .getKey("/Resources") - .getKey("/XObject") - .getKey("/Fx1")); + auto fx1 = QPDFPageObjectHelper(page.getObjectHandle() + .getKey("/Resources") + .getKey("/XObject") + .getKey("/Fx1")); std::cout << "--- parseContents ---" << std::endl; ParserCallbacks cb; fx1.parseContents(&cb); // Do this once with addContentTokenFilter and once with // addTokenFilter to show that they are the same and to ensure // that addTokenFilter is directly exercised in testing. - for (int i = 0; i < 2; i++) - { + for (int i = 0; i < 2; i++) { Pl_Buffer b("buffer"); - if (i == 0) - { + if (i == 0) { fx1.addContentTokenFilter( PointerHolder( new TokenFilter())); - } - else - { + } else { fx1.getObjectHandle().addTokenFilter( PointerHolder( new TokenFilter())); @@ -2752,21 +2588,18 @@ static void test_72(QPDF& pdf, char const* arg2) fx1.pipeContents(&b); std::unique_ptr buf(b.getBuffer()); std::string s( - reinterpret_cast(buf->getBuffer()), - buf->getSize()); + reinterpret_cast(buf->getBuffer()), buf->getSize()); assert(s.find("/bye") != std::string::npos); } } -static void test_73(QPDF& pdf, char const* arg2) +static void +test_73(QPDF& pdf, char const* arg2) { - try - { + try { QPDF pdf2; pdf2.getRoot(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "getRoot: " << e.what() << std::endl; } @@ -2774,29 +2607,29 @@ static void test_73(QPDF& pdf, char const* arg2) pdf.getRoot().getKey("/Pages").unparseResolved(); } -static void test_74(QPDF& pdf, char const* arg2) +static void +test_74(QPDF& pdf, char const* arg2) { // This test is crafted to work with split-nntree.pdf std::cout << "/Split1" << std::endl; - auto split1 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Split1"), pdf); + auto split1 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Split1"), pdf); split1.setSplitThreshold(4); auto check_split1 = [&split1](int k) { - auto i = split1.insert(k, QPDFObjectHandle::newString( - QUtil::int_to_string(k))); + auto i = split1.insert( + k, QPDFObjectHandle::newString(QUtil::int_to_string(k))); assert(i->first == k); }; check_split1(15); check_split1(35); check_split1(125); - for (auto const& i: split1) - { + for (auto const& i : split1) { std::cout << i.first << std::endl; } std::cout << "/Split2" << std::endl; - auto split2 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Split2"), pdf); + auto split2 = + QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split2"), pdf); split2.setSplitThreshold(4); auto check_split2 = [](QPDFNameTreeObjectHelper& noh, std::string const& k) { @@ -2804,19 +2637,17 @@ static void test_74(QPDF& pdf, char const* arg2) assert(i->first == k); }; check_split2(split2, "C"); - for (auto const& i: split2) - { + for (auto const& i : split2) { std::cout << i.first << std::endl; } std::cout << "/Split3" << std::endl; - auto split3 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Split3"), pdf); + auto split3 = + QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Split3"), pdf); split3.setSplitThreshold(4); check_split2(split3, "P"); check_split2(split3, "\xcf\x80"); - for (auto& i: split3) - { + for (auto& i : split3) { std::cout << i.first << " " << i.second.unparse() << std::endl; } @@ -2826,13 +2657,14 @@ static void test_74(QPDF& pdf, char const* arg2) w.write(); } -static void test_75(QPDF& pdf, char const* arg2) +static void +test_75(QPDF& pdf, char const* arg2) { // This test is crafted to work with erase-nntree.pdf - auto erase1 = QPDFNameTreeObjectHelper( - pdf.getTrailer().getKey("/Erase1"), pdf); + auto erase1 = + QPDFNameTreeObjectHelper(pdf.getTrailer().getKey("/Erase1"), pdf); QPDFObjectHandle value; - assert(! erase1.remove("1X")); + assert(!erase1.remove("1X")); assert(erase1.remove("1C", &value)); assert(value.getUTF8Value() == "c"); auto iter1 = erase1.find("1B"); @@ -2866,16 +2698,16 @@ static void test_75(QPDF& pdf, char const* arg2) k1 = k1.getKey("/Kids"); assert(k1.getArrayNItems() == 1); - auto erase3 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Erase3"), pdf); + auto erase3 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Erase3"), pdf); iter2 = erase3.find(320); iter2.remove(); assert(iter2 == erase3.end()); erase3.remove(310); assert(erase3.begin() == erase3.end()); - auto erase4 = QPDFNumberTreeObjectHelper( - pdf.getTrailer().getKey("/Erase4"), pdf); + auto erase4 = + QPDFNumberTreeObjectHelper(pdf.getTrailer().getKey("/Erase4"), pdf); iter2 = erase4.find(420); iter2.remove(); assert(iter2->first == 430); @@ -2886,21 +2718,20 @@ static void test_75(QPDF& pdf, char const* arg2) w.write(); } -static void test_76(QPDF& pdf, char const* arg2) +static void +test_76(QPDF& pdf, char const* arg2) { // Embedded files. arg2 is a file to attach. Hard-code the // mime type and file name for test purposes. QPDFEmbeddedFileDocumentHelper efdh(pdf); - auto fs1 = QPDFFileSpecObjectHelper::createFileSpec( - pdf, "att1.txt", arg2); + auto fs1 = QPDFFileSpecObjectHelper::createFileSpec(pdf, "att1.txt", arg2); fs1.setDescription("some text"); auto efs1 = QPDFEFStreamObjectHelper(fs1.getEmbeddedFileStream()); efs1.setSubtype("text/plain") .setCreationDate("D:20210207191121-05'00'") .setModDate("D:20210208001122Z"); efdh.replaceEmbeddedFile("att1", fs1); - auto efs2 = QPDFEFStreamObjectHelper::createEFStream( - pdf, "from string"); + auto efs2 = QPDFEFStreamObjectHelper::createEFStream(pdf, "from string"); efs2.setSubtype("text/plain"); Pl_Buffer p("buffer"); p.write(QUtil::unsigned_char_pointer("from buffer"), 11); @@ -2909,10 +2740,9 @@ static void test_76(QPDF& pdf, char const* arg2) pdf, p.getBufferSharedPointer()); efs3.setSubtype("text/plain"); efdh.replaceEmbeddedFile( - "att2", QPDFFileSpecObjectHelper::createFileSpec( - pdf, "att2.txt", efs2)); - auto fs3 = QPDFFileSpecObjectHelper::createFileSpec( - pdf, "att3.txt", efs3); + "att2", + QPDFFileSpecObjectHelper::createFileSpec(pdf, "att2.txt", efs2)); + auto fs3 = QPDFFileSpecObjectHelper::createFileSpec(pdf, "att3.txt", efs3); efdh.replaceEmbeddedFile("att3", fs3); fs3.setFilename("\xcf\x80.txt", "att3.txt"); @@ -2920,16 +2750,16 @@ static void test_76(QPDF& pdf, char const* arg2) assert(efs1.getModDate() == "D:20210208001122Z"); assert(efs2.getSize() == 11); assert(efs2.getSubtype() == "text/plain"); - assert(QUtil::hex_encode(efs2.getChecksum()) == - "2fce9c8228e360ba9b04a1bd1bf63d6b"); + assert( + QUtil::hex_encode(efs2.getChecksum()) == + "2fce9c8228e360ba9b04a1bd1bf63d6b"); - for (auto iter: efdh.getEmbeddedFiles()) - { + for (auto iter : efdh.getEmbeddedFiles()) { std::cout << iter.first << " -> " << iter.second->getFilename() << std::endl; } assert(efdh.getEmbeddedFile("att1")->getFilename() == "att1.txt"); - assert(! efdh.getEmbeddedFile("potato")); + assert(!efdh.getEmbeddedFile("potato")); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); @@ -2937,11 +2767,12 @@ static void test_76(QPDF& pdf, char const* arg2) w.write(); } -static void test_77(QPDF& pdf, char const* arg2) +static void +test_77(QPDF& pdf, char const* arg2) { QPDFEmbeddedFileDocumentHelper efdh(pdf); assert(efdh.removeEmbeddedFile("att2")); - assert(! efdh.removeEmbeddedFile("att2")); + assert(!efdh.removeEmbeddedFile("att2")); QPDFWriter w(pdf, "a.pdf"); w.setStaticID(true); @@ -2949,7 +2780,8 @@ static void test_77(QPDF& pdf, char const* arg2) w.write(); } -static void test_78(QPDF& pdf, char const* arg2) +static void +test_78(QPDF& pdf, char const* arg2) { // Test functional versions of replaceStreamData() @@ -2959,13 +2791,11 @@ static void test_78(QPDF& pdf, char const* arg2) }; auto f2 = [](Pipeline* p, bool suppress_warnings, bool will_retry) { std::cerr << "f2" << std::endl; - if (will_retry) - { + if (will_retry) { std::cerr << "failing" << std::endl; return false; } - if (! suppress_warnings) - { + if (!suppress_warnings) { std::cerr << "warning" << std::endl; } p->write(QUtil::unsigned_char_pointer("salad"), 5); @@ -2992,7 +2822,8 @@ static void test_78(QPDF& pdf, char const* arg2) w.write(); } -static void test_79(QPDF& pdf, char const* arg2) +static void +test_79(QPDF& pdf, char const* arg2) { // Exercise stream copier @@ -3014,8 +2845,9 @@ static void test_79(QPDF& pdf, char const* arg2) QPDFObjectHandle::parse( &pdf, "<< /Direct 3 /Indirect " + - pdf.makeIndirectObject( - QPDFObjectHandle::newInteger(16059)).unparse() + ">>")); + pdf.makeIndirectObject(QPDFObjectHandle::newInteger(16059)) + .unparse() + + ">>")); s2.getDict().replaceKey( "/Other", QPDFObjectHandle::newString("other stuff")); @@ -3031,8 +2863,7 @@ static void test_79(QPDF& pdf, char const* arg2) "/Originals", QPDFObjectHandle::newArray(streams)); int i = 0; - for (auto orig: streams) - { + for (auto orig : streams) { ++i; auto istr = QUtil::int_to_string(i); auto orig_data = orig.getStreamData(); @@ -3042,9 +2873,11 @@ static void test_79(QPDF& pdf, char const* arg2) orig.replaceStreamData("something new " + istr, null, null); auto copy_data = copy.getStreamData(); assert(orig_data->getSize() == copy_data->getSize()); - assert(memcmp(orig_data->getBuffer(), - copy_data->getBuffer(), - orig_data->getSize()) == 0); + assert( + memcmp( + orig_data->getBuffer(), + copy_data->getBuffer(), + orig_data->getSize()) == 0); copies.appendItem(copy); } @@ -3054,7 +2887,8 @@ static void test_79(QPDF& pdf, char const* arg2) w.write(); } -static void test_80(QPDF& pdf, char const* arg2) +static void +test_80(QPDF& pdf, char const* arg2) { // Exercise transform/copy annotations without passing in // QPDFAcroFormDocumentHelper pointers. The case of passing @@ -3077,8 +2911,7 @@ static void test_80(QPDF& pdf, char const* arg2) // Use defaults for from_qpdf and from_afdh. afdh.transformAnnotations( old_annots, new_annots, new_fields, old_fields, m); - for (auto const& annot: new_annots) - { + for (auto const& annot : new_annots) { old_annots.appendItem(annot); } afdh.addAndRenameFormFields(new_fields); @@ -3102,64 +2935,65 @@ static void test_80(QPDF& pdf, char const* arg2) w2.write(); } -static void test_81(QPDF& pdf, char const* arg2) +static void +test_81(QPDF& pdf, char const* arg2) { // Exercise that type errors get their own special type - try - { + try { QPDFObjectHandle::newNull().getIntValue(); assert(false); - } - catch (QPDFExc& e) - { + } catch (QPDFExc& e) { assert(e.getErrorCode() == qpdf_e_object); } } -static void test_82(QPDF& pdf, char const* arg2) +static void +test_82(QPDF& pdf, char const* arg2) { // Exercise compound test methods QPDFObjectHandle::isNameAndEquals, // isDictionaryOfType and isStreamOfType auto name = QPDFObjectHandle::newName("/Marvin"); auto str = QPDFObjectHandle::newString("/Marvin"); assert(name.isNameAndEquals("/Marvin")); - assert(! name.isNameAndEquals("Marvin")); - assert(! str.isNameAndEquals("/Marvin")); - auto dict = QPDFObjectHandle::parse("<>"); - assert(dict.isDictionaryOfType( "/Test", "")); + assert(!name.isNameAndEquals("Marvin")); + assert(!str.isNameAndEquals("/Marvin")); + auto dict = + QPDFObjectHandle::parse("<>"); + assert(dict.isDictionaryOfType("/Test", "")); assert(dict.isDictionaryOfType("/Test")); assert(dict.isDictionaryOfType("/Test", "/Marvin")); assert(dict.isDictionaryOfType("", "/Marvin")); assert(dict.isDictionaryOfType("", "")); - assert(! dict.isDictionaryOfType("/Test2", "")); - assert(! dict.isDictionaryOfType("/Test2", "/Marvin")); - assert(! dict.isDictionaryOfType("/Test", "/M")); - assert(! name.isDictionaryOfType("", "")); + assert(!dict.isDictionaryOfType("/Test2", "")); + assert(!dict.isDictionaryOfType("/Test2", "/Marvin")); + assert(!dict.isDictionaryOfType("/Test", "/M")); + assert(!name.isDictionaryOfType("", "")); dict = QPDFObjectHandle::parse("<>"); - assert(! dict.isDictionaryOfType("/Test")); + assert(!dict.isDictionaryOfType("/Test")); dict = QPDFObjectHandle::parse("<>"); - assert(! dict.isDictionaryOfType("Test")); + assert(!dict.isDictionaryOfType("Test")); dict = QPDFObjectHandle::parse("<>"); - assert(! dict.isDictionaryOfType("Test")); + assert(!dict.isDictionaryOfType("Test")); dict = QPDFObjectHandle::parse("<>"); - assert(! dict.isDictionaryOfType("/Test", "Marvin")); - auto stream = pdf.getObjectByID(1,0); + assert(!dict.isDictionaryOfType("/Test", "Marvin")); + auto stream = pdf.getObjectByID(1, 0); assert(stream.isStreamOfType("/ObjStm")); - assert(! stream.isStreamOfType("/Test")); - assert(! pdf.getObjectByID(2,0).isStreamOfType("/Pages")); + assert(!stream.isStreamOfType("/Test")); + assert(!pdf.getObjectByID(2, 0).isStreamOfType("/Pages")); /* cSpell: ignore Blaah Blaaah Blaaaah */ auto array = QPDFObjectHandle::parse("[/Blah /Blaah /Blaaah]"); assert(array.isOrHasName("/Blah")); assert(array.isOrHasName("/Blaaah")); - assert(! array.isOrHasName("/Blaaaah")); + assert(!array.isOrHasName("/Blaaaah")); assert(array.getArrayItem(0).isOrHasName("/Blah")); - assert(! array.getArrayItem(1).isOrHasName("/Blah")); + assert(!array.getArrayItem(1).isOrHasName("/Blah")); array = QPDFObjectHandle::parse("[]"); - assert(! array.isOrHasName("/Blah")); - assert(! str.isOrHasName("/Marvin")); + assert(!array.isOrHasName("/Blah")); + assert(!str.isOrHasName("/Marvin")); } -static void test_83(QPDF& pdf, char const* arg2) +static void +test_83(QPDF& pdf, char const* arg2) { // Test QPDFJob json with partial = false. For testing with // partial = true, we just use qpdf --job-json-file. @@ -3168,23 +3002,19 @@ static void test_83(QPDF& pdf, char const* arg2) PointerHolder file_buf; size_t size; QUtil::read_file_into_memory(arg2, file_buf, size); - try - { + try { std::cout << "calling initializeFromJson" << std::endl; j.initializeFromJson(std::string(file_buf.get(), size)); std::cout << "called initializeFromJson" << std::endl; - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { std::cerr << "usage: " << e.what() << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; } } -static void test_84(QPDF& pdf, char const* arg2) +static void +test_84(QPDF& pdf, char const* arg2) { // Test QPDFJob API @@ -3200,44 +3030,35 @@ static void test_84(QPDF& pdf, char const* arg2) ->checkConfiguration(); j.run(); assert(j.getExitCode() == 0); - assert(! j.hasWarnings()); + assert(!j.hasWarnings()); assert(j.getEncryptionStatus() == 0); } std::cout << "error caught by check" << std::endl; - try - { + try { QPDFJob j; - j.config() - ->outputFile("a.pdf") - ->qdf(); + j.config()->outputFile("a.pdf")->qdf(); std::cout << "finished config" << std::endl; j.checkConfiguration(); assert(false); - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { std::cout << "usage: " << e.what() << std::endl; } std::cout << "error caught by run" << std::endl; - try - { + try { QPDFJob j; - j.config() - ->outputFile("a.pdf") - ->qdf(); + j.config()->outputFile("a.pdf")->qdf(); std::cout << "finished config" << std::endl; j.run(); assert(false); - } - catch (QPDFUsage& e) - { + } catch (QPDFUsage& e) { std::cout << "usage: " << e.what() << std::endl; } } -static void test_85(QPDF& pdf, char const* arg2) +static void +test_85(QPDF& pdf, char const* arg2) { // Test QPDFObjectHandle::getValueAs... accessors @@ -3258,18 +3079,18 @@ static void test_85(QPDF& pdf, char const* arg2) bool b = true; assert(oh_b.getValueAsBool(b)); - assert(! b); - assert(! oh_i.getValueAsBool(b)); - assert(! b); + assert(!b); + assert(!oh_i.getValueAsBool(b)); + assert(!b); long long li = 0LL; assert(oh_i.getValueAsInt(li)); assert(li == 1LL); - assert(! oh_b.getValueAsInt(li)); + assert(!oh_b.getValueAsInt(li)); assert(li == 1LL); int i = 0; assert(oh_i.getValueAsInt(i)); assert(i == 1); - assert(! oh_b.getValueAsInt(i)); + assert(!oh_b.getValueAsInt(i)); assert(i == 1); assert(oh_i_maxplus.getValueAsInt(i)); assert(i == INT_MAX); @@ -3278,14 +3099,14 @@ static void test_85(QPDF& pdf, char const* arg2) unsigned long long uli = 0U; assert(oh_i.getValueAsUInt(uli)); assert(uli == 1u); - assert(! oh_b.getValueAsUInt(uli)); + assert(!oh_b.getValueAsUInt(uli)); assert(uli == 1u); assert(oh_i_neg.getValueAsUInt(uli)); assert(uli == 0u); unsigned int ui = 0U; assert(oh_i.getValueAsUInt(ui)); assert(ui == 1u); - assert(! oh_b.getValueAsUInt(ui)); + assert(!oh_b.getValueAsUInt(ui)); assert(ui == 1u); assert(oh_i_neg.getValueAsUInt(ui)); assert(ui == 0u); @@ -3294,43 +3115,44 @@ static void test_85(QPDF& pdf, char const* arg2) std::string s = "0"; assert(oh_r.getValueAsReal(s)); assert(s == "42.0"); - assert(! oh_i.getValueAsReal(s)); + assert(!oh_i.getValueAsReal(s)); assert(s == "42.0"); double num = 0.0; assert(oh_i.getValueAsNumber(num)); assert(((num - 1.0) < 1e-6) && (num - 1.0 > -1e-6)); assert(oh_r.getValueAsNumber(num)); assert(((num - 42.0) < 1e-6) && (num - 42.0 > -1e-6)); - assert(! oh_b.getValueAsNumber(num)); + assert(!oh_b.getValueAsNumber(num)); assert(((num - 42.0) < 1e-6) && (num - 42.0 > -1e-6)); s = ""; assert(oh_n.getValueAsName(s)); - assert(s == "/Test") ; - assert(! oh_r.getValueAsName(s)); + assert(s == "/Test"); + assert(!oh_r.getValueAsName(s)); assert(s == "/Test"); s = ""; assert(oh_s.getValueAsUTF8(s)); assert(s == "/Test"); - assert(! oh_r.getValueAsUTF8(s)); + assert(!oh_r.getValueAsUTF8(s)); assert(s == "/Test"); s = ""; assert(oh_s.getValueAsUTF8(s)); assert(s == "/Test"); - assert(! oh_r.getValueAsUTF8(s)); + assert(!oh_r.getValueAsUTF8(s)); assert(s == "/Test"); s = ""; assert(oh_o.getValueAsOperator(s)); assert(s == "/Test"); - assert(! oh_r.getValueAsOperator(s)); + assert(!oh_r.getValueAsOperator(s)); assert(s == "/Test"); s = ""; assert(oh_ii.getValueAsInlineImage(s)); assert(s == "/Test"); - assert(! oh_r.getValueAsInlineImage(s)); + assert(!oh_r.getValueAsInlineImage(s)); assert(s == "/Test"); } -static void test_86(QPDF& pdf, char const* arg2) +static void +test_86(QPDF& pdf, char const* arg2) { // Test symmetry between newUnicodeString and getUTF8Value for // strings that can't be encoded as PDFDoc but don't contain any @@ -3341,7 +3163,7 @@ static void test_86(QPDF& pdf, char const* arg2) std::string result; assert(QUtil::utf8_to_ascii(utf8_val, result, '?')); assert(result == utf8_val); - assert(! QUtil::utf8_to_pdf_doc(utf8_val, result, '?')); + assert(!QUtil::utf8_to_pdf_doc(utf8_val, result, '?')); assert(result == "?"); assert(QUtil::utf8_to_utf16(utf8_val) == utf16_val); assert(QUtil::utf16_to_utf8(utf16_val) == utf8_val); @@ -3350,7 +3172,8 @@ static void test_86(QPDF& pdf, char const* arg2) assert(h.getUTF8Value() == utf8_val); } -void runtest(int n, char const* filename1, char const* arg2) +void +runtest(int n, char const* filename1, char const* arg2) { // Most tests here are crafted to work on specific files. Look at // the test suite to see how the test is invoked to find the file @@ -3358,8 +3181,7 @@ void runtest(int n, char const* filename1, char const* arg2) std::set ignore_filename = {61, 81, 83, 84, 85, 86}; - if (n == 0) - { + if (n == 0) { // Throw in some random test cases that don't fit anywhere // else. This is in addition to whatever else is going on in // test 0. @@ -3368,8 +3190,7 @@ void runtest(int n, char const* filename1, char const* arg2) // "(") since it marks the beginning of the padding. Exercise // the code to make sure it skips over 0x28 characters that // aren't part of padding. - std::string password( - "1234567890123456789012(45678\x28\xbf\x4e\x5e"); + std::string password("1234567890123456789012(45678\x28\xbf\x4e\x5e"); assert(password.length() == 32); QPDF::trim_user_password(password); assert(password == "1234567890123456789012(45678"); @@ -3382,17 +3203,13 @@ void runtest(int n, char const* filename1, char const* arg2) QPDF pdf; PointerHolder file_buf; FILE* filep = 0; - if (n == 0) - { + if (n == 0) { pdf.setAttemptRecovery(false); } - if (((n == 35) || (n == 36)) && (arg2 != 0)) - { + if (((n == 35) || (n == 36)) && (arg2 != 0)) { // arg2 is password pdf.processFile(filename1, arg2); - } - else if (n == 45) - { + } else if (n == 45) { // Decode obfuscated files. To obfuscated, run the input file // through this perl script, and save the result to // filename.obfuscated. This pretends that the input was @@ -3411,33 +3228,23 @@ void runtest(int n, char const* filename1, char const* arg2) size_t size = 0; QUtil::read_file_into_memory(filename.c_str(), file_buf, size); char* p = file_buf.get(); - for (size_t i = 0; i < size; ++i) - { + for (size_t i = 0; i < size; ++i) { p[i] = static_cast(p[i] ^ 0xcc); } - pdf.processMemoryFile((std::string(filename1) + ".pdf").c_str(), - p, size); - } - else if (ignore_filename.count(n)) - { + pdf.processMemoryFile( + (std::string(filename1) + ".pdf").c_str(), p, size); + } else if (ignore_filename.count(n)) { // Ignore filename argument entirely - } - else if (n % 2 == 0) - { - if (n % 4 == 0) - { + } else if (n % 2 == 0) { + if (n % 4 == 0) { QTC::TC("qpdf", "exercise processFile(name)"); pdf.processFile(filename1); - } - else - { + } else { QTC::TC("qpdf", "exercise processFile(FILE*)"); filep = QUtil::safe_fopen(filename1, "rb"); pdf.processFile(filename1, filep, false); } - } - else - { + } else { QTC::TC("qpdf", "exercise processMemoryFile"); size_t size = 0; QUtil::read_file_into_memory(filename1, file_buf, size); @@ -3445,9 +3252,9 @@ void runtest(int n, char const* filename1, char const* arg2) } std::map test_functions = { - {0, test_0_1}, {1, test_0_1}, {2, test_2}, {3, test_3}, - {4, test_4}, {5, test_5}, {6, test_6}, {7, test_7}, - {8, test_8}, {9, test_9}, {10, test_10}, {11, test_11}, + {0, test_0_1}, {1, test_0_1}, {2, test_2}, {3, test_3}, + {4, test_4}, {5, test_5}, {6, test_6}, {7, test_7}, + {8, test_8}, {9, test_9}, {10, test_10}, {11, test_11}, {12, test_12}, {13, test_13}, {14, test_14}, {15, test_15}, {16, test_16}, {17, test_17}, {18, test_18}, {19, test_19}, {20, test_20}, {21, test_21}, {22, test_22}, {23, test_23}, @@ -3470,46 +3277,38 @@ void runtest(int n, char const* filename1, char const* arg2) }; auto fn = test_functions.find(n); - if (fn == test_functions.end()) - { - throw std::runtime_error(std::string("invalid test ") + - QUtil::int_to_string(n)); + if (fn == test_functions.end()) { + throw std::runtime_error( + std::string("invalid test ") + QUtil::int_to_string(n)); } (fn->second)(pdf, arg2); - if (filep) - { + if (filep) { fclose(filep); } std::cout << "test " << n << " done" << std::endl; } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { QUtil::setLineBuf(stdout); - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } - if ((argc < 3) || (argc > 4)) - { + if ((argc < 3) || (argc > 4)) { usage(); } - try - { + try { int n = QUtil::string_to_int(argv[1]); char const* filename1 = argv[2]; char const* arg2 = argv[3]; runtest(n, filename1, arg2); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } diff --git a/qpdf/test_large_file.cc b/qpdf/test_large_file.cc index 8f7f8755..0a81dcc7 100644 --- a/qpdf/test_large_file.cc +++ b/qpdf/test_large_file.cc @@ -4,15 +4,15 @@ // internally by the library as long as they don't do their own file // I/O. +#include #include +#include #include #include -#include #include -#include #include -#include #include +#include #ifdef NDEBUG // We need assert even in a release build for test code. @@ -53,9 +53,11 @@ size_t width = 0; size_t height = 0; static unsigned char* buf = 0; -static inline unsigned char get_pixel_color(size_t n, size_t row) +static inline unsigned char +get_pixel_color(size_t n, size_t row) { - return ((n & (1LLU << (nstripes - 1LLU - row))) + return ( + (n & (1LLU << (nstripes - 1LLU - row))) ? static_cast('\xc0') : static_cast('\x40')); } @@ -89,12 +91,10 @@ ImageChecker::~ImageChecker() void ImageChecker::write(unsigned char* data, size_t len) { - for (size_t i = 0; i < len; ++i) - { + for (size_t i = 0; i < len; ++i) { size_t y = (this->offset + i) / width / stripesize; unsigned char color = get_pixel_color(n, y); - if (data[i] != color) - { + if (data[i] != color) { okay = false; } } @@ -104,8 +104,7 @@ ImageChecker::write(unsigned char* data, size_t len) void ImageChecker::finish() { - if (! okay) - { + if (!okay) { std::cout << "errors found checking image data for page " << n << std::endl; } @@ -116,8 +115,8 @@ class ImageProvider: public QPDFObjectHandle::StreamDataProvider public: ImageProvider(size_t n); virtual ~ImageProvider(); - virtual void provideStreamData(int objid, int generation, - Pipeline* pipeline); + virtual void + provideStreamData(int objid, int generation, Pipeline* pipeline); private: size_t n; @@ -133,16 +132,13 @@ ImageProvider::~ImageProvider() } void -ImageProvider::provideStreamData(int objid, int generation, - Pipeline* pipeline) +ImageProvider::provideStreamData(int objid, int generation, Pipeline* pipeline) { - if (buf == 0) - { + if (buf == 0) { buf = new unsigned char[width * stripesize]; } std::cout << "page " << n << " of " << npages << std::endl; - for (size_t y = 0; y < nstripes; ++y) - { + for (size_t y = 0; y < nstripes; ++y) { unsigned char color = get_pixel_color(n, y); memset(buf, color, width * stripesize); pipeline->write(buf, width * stripesize); @@ -150,52 +146,59 @@ ImageProvider::provideStreamData(int objid, int generation, pipeline->finish(); } -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " {read|write} {large|small} outfile" << std::endl; exit(2); } -static void set_parameters(bool large) +static void +set_parameters(bool large) { stripesize = large ? stripesize_large : stripesize_small; height = nstripes * stripesize; width = height; } -std::string generate_page_contents(size_t pageno) +std::string +generate_page_contents(size_t pageno) { - std::string contents = - "BT /F1 24 Tf 72 720 Td (page " + QUtil::uint_to_string(pageno) + + std::string contents = "BT /F1 24 Tf 72 720 Td (page " + + QUtil::uint_to_string(pageno) + ") Tj ET\n" "q 468 0 0 468 72 72 cm /Im1 Do Q\n"; return contents; } -static QPDFObjectHandle create_page_contents(QPDF& pdf, size_t pageno) +static QPDFObjectHandle +create_page_contents(QPDF& pdf, size_t pageno) { return QPDFObjectHandle::newStream(&pdf, generate_page_contents(pageno)); } -QPDFObjectHandle newName(std::string const& name) +QPDFObjectHandle +newName(std::string const& name) { return QPDFObjectHandle::newName(name); } -QPDFObjectHandle newInteger(size_t val) +QPDFObjectHandle +newInteger(size_t val) { return QPDFObjectHandle::newInteger(QIntC::to_longlong(val)); } -static void create_pdf(char const* filename) +static void +create_pdf(char const* filename) { QPDF pdf; pdf.emptyPDF(); - QPDFObjectHandle font = pdf.makeIndirectObject( - QPDFObjectHandle::newDictionary()); + QPDFObjectHandle font = + pdf.makeIndirectObject(QPDFObjectHandle::newDictionary()); font.replaceKey("/Type", newName("/Font")); font.replaceKey("/Subtype", newName("/Type1")); font.replaceKey("/Name", newName("/F1")); @@ -218,8 +221,7 @@ static void create_pdf(char const* filename) mediabox.appendItem(newInteger(792)); QPDFPageDocumentHelper dh(pdf); - for (size_t pageno = 1; pageno <= npages; ++pageno) - { + for (size_t pageno = 1; pageno <= npages; ++pageno) { QPDFObjectHandle image = QPDFObjectHandle::newStream(&pdf); QPDFObjectHandle image_dict = image.getDict(); image_dict.replaceKey("/Type", newName("/XObject")); @@ -230,9 +232,8 @@ static void create_pdf(char const* filename) image_dict.replaceKey("/Height", newInteger(height)); ImageProvider* p = new ImageProvider(pageno); PointerHolder provider(p); - image.replaceStreamData(provider, - QPDFObjectHandle::newNull(), - QPDFObjectHandle::newNull()); + image.replaceStreamData( + provider, QPDFObjectHandle::newNull(), QPDFObjectHandle::newNull()); QPDFObjectHandle xobject = QPDFObjectHandle::newDictionary(); xobject.replaceKey("/Im1", image); @@ -244,8 +245,8 @@ static void create_pdf(char const* filename) QPDFObjectHandle contents = create_page_contents(pdf, pageno); - QPDFObjectHandle page = pdf.makeIndirectObject( - QPDFObjectHandle::newDictionary()); + QPDFObjectHandle page = + pdf.makeIndirectObject(QPDFObjectHandle::newDictionary()); page.replaceKey("/Type", newName("/Page")); page.replaceKey("/MediaBox", mediabox); page.replaceKey("/Contents", contents); @@ -255,30 +256,28 @@ static void create_pdf(char const* filename) } QPDFWriter w(pdf, filename); - w.setStaticID(true); // for testing only + w.setStaticID(true); // for testing only w.setStreamDataMode(qpdf_s_preserve); w.setObjectStreamMode(qpdf_o_disable); w.write(); } -static void check_page_contents(size_t pageno, QPDFObjectHandle page) +static void +check_page_contents(size_t pageno, QPDFObjectHandle page) { - PointerHolder buf = - page.getKey("/Contents").getStreamData(); + PointerHolder buf = page.getKey("/Contents").getStreamData(); std::string actual_contents = - std::string(reinterpret_cast(buf->getBuffer()), - buf->getSize()); + std::string(reinterpret_cast(buf->getBuffer()), buf->getSize()); std::string expected_contents = generate_page_contents(pageno); - if (expected_contents != actual_contents) - { + if (expected_contents != actual_contents) { std::cout << "page contents wrong for page " << pageno << std::endl << "ACTUAL: " << actual_contents - << "EXPECTED: " << expected_contents - << "----\n"; + << "EXPECTED: " << expected_contents << "----\n"; } } -static void check_image(size_t pageno, QPDFObjectHandle page) +static void +check_image(size_t pageno, QPDFObjectHandle page) { QPDFObjectHandle image = page.getKey("/Resources").getKey("/XObject").getKey("/Im1"); @@ -286,14 +285,14 @@ static void check_image(size_t pageno, QPDFObjectHandle page) image.pipeStreamData(&ic, 0, qpdf_dl_specialized); } -static void check_pdf(char const* filename) +static void +check_pdf(char const* filename) { QPDF pdf; pdf.processFile(filename); std::vector const& pages = pdf.getAllPages(); assert(pages.size() == QIntC::to_size(npages)); - for (size_t i = 0; i < npages; ++i) - { + for (size_t i = 0; i < npages; ++i) { size_t pageno = i + 1; std::cout << "page " << pageno << " of " << npages << std::endl; check_page_contents(pageno, pages.at(i)); @@ -301,13 +300,13 @@ static void check_pdf(char const* filename) } } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { whoami = QUtil::getWhoami(argv[0]); QUtil::setLineBuf(stdout); - if (argc != 4) - { + if (argc != 4) { usage(); } char const* operation = argv[1]; @@ -317,52 +316,36 @@ int main(int argc, char* argv[]) bool op_write = false; bool size_large = false; - if (strcmp(operation, "write") == 0) - { + if (strcmp(operation, "write") == 0) { op_write = true; - } - else if (strcmp(operation, "read") == 0) - { + } else if (strcmp(operation, "read") == 0) { op_write = false; - } - else - { + } else { usage(); } - if (strcmp(size, "large") == 0) - { + if (strcmp(size, "large") == 0) { size_large = true; - } - else if (strcmp(size, "small") == 0) - { + } else if (strcmp(size, "small") == 0) { size_large = false; - } - else - { + } else { usage(); } set_parameters(size_large); - try - { - if (op_write) - { + try { + if (op_write) { create_pdf(filename); - } - else - { + } else { check_pdf(filename); } - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit(2); } - delete [] buf; + delete[] buf; return 0; } diff --git a/qpdf/test_parsedoffset.cc b/qpdf/test_parsedoffset.cc index 2fea9cdb..aecaf404 100644 --- a/qpdf/test_parsedoffset.cc +++ b/qpdf/test_parsedoffset.cc @@ -2,40 +2,31 @@ #include #include +#include #include #include #include #include #include #include -#include -void usage() +void +usage() { - std::cerr - << "Usage: test_parsedoffset INPUT.pdf" - << std::endl; + std::cerr << "Usage: test_parsedoffset INPUT.pdf" << std::endl; } -std::string make_objdesc(qpdf_offset_t offset, QPDFObjectHandle obj) +std::string +make_objdesc(qpdf_offset_t offset, QPDFObjectHandle obj) { std::stringstream ss; - ss << "offset = " - << offset - << " (0x" - << std::hex << offset << std::dec + ss << "offset = " << offset << " (0x" << std::hex << offset << std::dec << "), "; - if (obj.isIndirect()) - { - ss << "indirect " - << obj.getObjectID() - << "/" - << obj.getGeneration() + if (obj.isIndirect()) { + ss << "indirect " << obj.getObjectID() << "/" << obj.getGeneration() << ", "; - } - else - { + } else { ss << "direct, "; } @@ -44,65 +35,53 @@ std::string make_objdesc(qpdf_offset_t offset, QPDFObjectHandle obj) return ss.str(); } -void walk(size_t stream_number, QPDFObjectHandle obj, - std::vector< - std::vector< - std::pair - > - > - &result) +void +walk( + size_t stream_number, + QPDFObjectHandle obj, + std::vector>>& result) { qpdf_offset_t offset = obj.getParsedOffset(); std::pair p = std::make_pair(offset, make_objdesc(offset, obj)); - if (result.size() < stream_number + 1) - { + if (result.size() < stream_number + 1) { result.resize(stream_number + 1); } result[stream_number].push_back(p); - if (obj.isArray()) - { + if (obj.isArray()) { std::vector array = obj.getArrayAsVector(); - for(std::vector::iterator iter = array.begin(); - iter != array.end(); ++iter) - { - if (!iter->isIndirect()) - { + for (std::vector::iterator iter = array.begin(); + iter != array.end(); + ++iter) { + if (!iter->isIndirect()) { // QPDF::GetAllObjects() enumerates all indirect objects. // So only the direct objects are recursed here. walk(stream_number, *iter, result); } } - } - else if(obj.isDictionary()) - { + } else if (obj.isDictionary()) { std::set keys = obj.getKeys(); - for(std::set::iterator iter = keys.begin(); - iter != keys.end(); ++iter) - { + for (std::set::iterator iter = keys.begin(); + iter != keys.end(); + ++iter) { QPDFObjectHandle item = obj.getKey(*iter); - if (!item.isIndirect()) - { + if (!item.isIndirect()) { // QPDF::GetAllObjects() enumerates all indirect objects. // So only the direct objects are recursed here. walk(stream_number, item, result); } } - } - else if(obj.isStream()) - { + } else if (obj.isStream()) { walk(stream_number, obj.getDict(), result); } } -void process(std::string fn, - std::vector< - std::vector< - std::pair - > - > &result) +void +process( + std::string fn, + std::vector>>& result) { QPDF qpdf; qpdf.processFile(fn.c_str()); @@ -110,39 +89,29 @@ void process(std::string fn, std::map xrefs = qpdf.getXRefTable(); for (std::vector::iterator iter = objs.begin(); - iter != objs.end(); ++iter) - { - if (xrefs.count(iter->getObjGen()) == 0) - { - std::cerr - << iter->getObjectID() - << "/" - << iter->getGeneration() - << " is not found in xref table" - << std::endl; + iter != objs.end(); + ++iter) { + if (xrefs.count(iter->getObjGen()) == 0) { + std::cerr << iter->getObjectID() << "/" << iter->getGeneration() + << " is not found in xref table" << std::endl; std::exit(2); } QPDFXRefEntry xref = xrefs[iter->getObjGen()]; size_t stream_number; - switch (xref.getType()) - { - case 0: - std::cerr - << iter->getObjectID() - << "/" - << iter->getGeneration() - << " xref entry is free" - << std::endl; + switch (xref.getType()) { + case 0: + std::cerr << iter->getObjectID() << "/" << iter->getGeneration() + << " xref entry is free" << std::endl; std::exit(2); - case 1: + case 1: stream_number = 0; break; - case 2: + case 2: stream_number = static_cast(xref.getObjStreamNumber()); break; - default: + default: std::cerr << "unknown xref entry type" << std::endl; std::exit(2); } @@ -151,58 +120,42 @@ void process(std::string fn, } } -int main(int argc, char *argv[]) +int +main(int argc, char* argv[]) { - if (argc != 2) - { + if (argc != 2) { usage(); std::exit(2); } - try - { - std::vector< - std::vector< - std::pair - > - > table; + try { + std::vector>> table; process(argv[1], table); - for (size_t i = 0; i < table.size(); ++i) - { - if (table[i].size() == 0) - { + for (size_t i = 0; i < table.size(); ++i) { + if (table[i].size() == 0) { continue; } std::sort(table[i].begin(), table[i].end()); - if (i == 0) - { + if (i == 0) { std::cout << "--- objects not in streams ---" << std::endl; - } - else - { - std::cout - << "--- objects in stream " << i << " ---" << std::endl; + } else { + std::cout << "--- objects in stream " << i << " ---" + << std::endl; } - for (std::vector< - std::pair - >::iterator + for (std::vector>::iterator iter = table[i].begin(); - iter != table[i].end(); ++iter) - { - std::cout - << iter->second - << std::endl; + iter != table[i].end(); + ++iter) { + std::cout << iter->second << std::endl; } } std::cout << "succeeded" << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::exit(2); } diff --git a/qpdf/test_pdf_doc_encoding.cc b/qpdf/test_pdf_doc_encoding.cc index c29b2d94..3dafceac 100644 --- a/qpdf/test_pdf_doc_encoding.cc +++ b/qpdf/test_pdf_doc_encoding.cc @@ -1,38 +1,35 @@ -#include #include +#include #include #include #include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } - if (argc != 2) - { + if (argc != 2) { usage(); } char const* infilename = argv[1]; - std::list lines = - QUtil::read_lines_from_file(infilename); + std::list lines = QUtil::read_lines_from_file(infilename); for (std::list::iterator iter = lines.begin(); - iter != lines.end(); ++iter) - { + iter != lines.end(); + ++iter) { QPDFObjectHandle str = QPDFObjectHandle::newString(*iter); std::cout << str.getUTF8Value() << std::endl; } diff --git a/qpdf/test_pdf_unicode.cc b/qpdf/test_pdf_unicode.cc index 8964e8a5..ead143b3 100644 --- a/qpdf/test_pdf_unicode.cc +++ b/qpdf/test_pdf_unicode.cc @@ -1,41 +1,38 @@ -#include #include +#include #include #include #include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " infile" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } - if (argc != 2) - { + if (argc != 2) { usage(); } char const* infilename = argv[1]; - std::list lines = - QUtil::read_lines_from_file(infilename); + std::list lines = QUtil::read_lines_from_file(infilename); for (std::list::iterator iter = lines.begin(); - iter != lines.end(); ++iter) - { + iter != lines.end(); + ++iter) { QPDFObjectHandle str = QPDFObjectHandle::newUnicodeString(*iter); - std::cout << str.getUTF8Value() << " // " - << str.unparseBinary() << std::endl; + std::cout << str.getUTF8Value() << " // " << str.unparseBinary() + << std::endl; } return 0; } diff --git a/qpdf/test_renumber.cc b/qpdf/test_renumber.cc index 68acf60c..9892340a 100644 --- a/qpdf/test_renumber.cc +++ b/qpdf/test_renumber.cc @@ -1,157 +1,119 @@ #include #include #include +#include #include #include -#include #include #include #include +#include #include #include #include #include -#include -void usage() +void +usage() { - std::cerr - << "Usage: test_renumber [OPTION] INPUT.pdf" - << std::endl - << "Option:" - << std::endl - << " --object-streams=preserve|disable|generate" - << std::endl - << " --linearize" - << std::endl - << " --preserve-unreferenced" - << std::endl; + std::cerr << "Usage: test_renumber [OPTION] INPUT.pdf" << std::endl + << "Option:" << std::endl + << " --object-streams=preserve|disable|generate" << std::endl + << " --linearize" << std::endl + << " --preserve-unreferenced" << std::endl; } -bool compare(QPDFObjectHandle a, QPDFObjectHandle b) +bool +compare(QPDFObjectHandle a, QPDFObjectHandle b) { static std::set visited; - if (a.isIndirect()) - { - if (visited.count(a.getObjGen())) - { + if (a.isIndirect()) { + if (visited.count(a.getObjGen())) { return true; } visited.insert(a.getObjGen()); } - if (a.getTypeCode() != b.getTypeCode()) - { - std::cerr - << "different type code" - << std::endl; + if (a.getTypeCode() != b.getTypeCode()) { + std::cerr << "different type code" << std::endl; return false; } - switch (a.getTypeCode()) - { - case QPDFObject::ot_boolean: - if (a.getBoolValue() != b.getBoolValue()) - { - std::cerr - << "different boolean" - << std::endl; + switch (a.getTypeCode()) { + case QPDFObject::ot_boolean: + if (a.getBoolValue() != b.getBoolValue()) { + std::cerr << "different boolean" << std::endl; return false; } break; - case QPDFObject::ot_integer: - if (a.getIntValue() != b.getIntValue()) - { - std::cerr - << "different integer" - << std::endl; + case QPDFObject::ot_integer: + if (a.getIntValue() != b.getIntValue()) { + std::cerr << "different integer" << std::endl; return false; } break; - case QPDFObject::ot_real: - if (a.getRealValue() != b.getRealValue()) - { - std::cerr - << "different real" - << std::endl; + case QPDFObject::ot_real: + if (a.getRealValue() != b.getRealValue()) { + std::cerr << "different real" << std::endl; return false; } break; - case QPDFObject::ot_string: - if (a.getStringValue() != b.getStringValue()) - { - std::cerr - << "different string" - << std::endl; + case QPDFObject::ot_string: + if (a.getStringValue() != b.getStringValue()) { + std::cerr << "different string" << std::endl; return false; } break; - case QPDFObject::ot_name: - if (a.getName() != b.getName()) - { - std::cerr - << "different name" - << std::endl; + case QPDFObject::ot_name: + if (a.getName() != b.getName()) { + std::cerr << "different name" << std::endl; return false; } break; - case QPDFObject::ot_array: + case QPDFObject::ot_array: { std::vector objs_a = a.getArrayAsVector(); std::vector objs_b = b.getArrayAsVector(); size_t items = objs_a.size(); - if (items != objs_b.size()) - { - std::cerr - << "different array size" - << std::endl; + if (items != objs_b.size()) { + std::cerr << "different array size" << std::endl; return false; } - for (size_t i = 0; i < items; ++i) - { - if (!compare(objs_a[i], objs_b[i])) - { - std::cerr - << "different array item" - << std::endl; + for (size_t i = 0; i < items; ++i) { + if (!compare(objs_a[i], objs_b[i])) { + std::cerr << "different array item" << std::endl; return false; } } } break; - case QPDFObject::ot_dictionary: + case QPDFObject::ot_dictionary: { std::set keys_a = a.getKeys(); std::set keys_b = b.getKeys(); - if (keys_a != keys_b) - { - std::cerr - << "different dictionary keys" - << std::endl; + if (keys_a != keys_b) { + std::cerr << "different dictionary keys" << std::endl; return false; } - for(std::set::iterator iter = keys_a.begin(); - iter != keys_a.end(); ++iter) - { - if (!compare(a.getKey(*iter), b.getKey(*iter))) - { - std::cerr - << "different dictionary item" - << std::endl; + for (std::set::iterator iter = keys_a.begin(); + iter != keys_a.end(); + ++iter) { + if (!compare(a.getKey(*iter), b.getKey(*iter))) { + std::cerr << "different dictionary item" << std::endl; return false; } } } break; - case QPDFObject::ot_null: + case QPDFObject::ot_null: break; - case QPDFObject::ot_stream: + case QPDFObject::ot_stream: std::cout << "stream objects are not compared" << std::endl; break; - default: + default: std::cerr << "unknown object type" << std::endl; std::exit(2); } @@ -159,70 +121,52 @@ bool compare(QPDFObjectHandle a, QPDFObjectHandle b) return true; } -bool compare_xref_table(std::map a, - std::map b) +bool +compare_xref_table( + std::map a, + std::map b) { - if (a.size() != b.size()) - { - std::cerr - << "different size" - << std::endl; + if (a.size() != b.size()) { + std::cerr << "different size" << std::endl; return false; } for (std::map::iterator iter = a.begin(); - iter != a.end(); ++iter) - { - std::cout - << "xref entry for " - << iter->first.getObj() << "/" << iter->first.getGen() - << std::endl; + iter != a.end(); + ++iter) { + std::cout << "xref entry for " << iter->first.getObj() << "/" + << iter->first.getGen() << std::endl; - if (b.count(iter->first) == 0) - { - std::cerr - << "not found" - << std::endl; + if (b.count(iter->first) == 0) { + std::cerr << "not found" << std::endl; return false; } QPDFXRefEntry xref_a = iter->second; QPDFXRefEntry xref_b = b[iter->first]; - if (xref_a.getType() != xref_b.getType()) - { - std::cerr - << "different xref entry type" - << std::endl; + if (xref_a.getType() != xref_b.getType()) { + std::cerr << "different xref entry type" << std::endl; return false; } - switch (xref_a.getType()) - { - case 0: + switch (xref_a.getType()) { + case 0: break; - case 1: - if (xref_a.getOffset() != xref_a.getOffset()) - { - std::cerr - << "different offset" - << std::endl; + case 1: + if (xref_a.getOffset() != xref_a.getOffset()) { + std::cerr << "different offset" << std::endl; return false; } break; - case 2: + case 2: if (xref_a.getObjStreamNumber() != xref_a.getObjStreamNumber() || - xref_a.getObjStreamIndex() != xref_a.getObjStreamIndex()) - { - std::cerr - << "different stream number or index" - << std::endl; + xref_a.getObjStreamIndex() != xref_a.getObjStreamIndex()) { + std::cerr << "different stream number or index" << std::endl; return false; } break; - default: - std::cerr - << "unknown xref entry type" - << std::endl; + default: + std::cerr << "unknown xref entry type" << std::endl; std::exit(2); } } @@ -230,10 +174,10 @@ bool compare_xref_table(std::map a, return true; } -int main(int argc, char *argv[]) +int +main(int argc, char* argv[]) { - if (argc < 2) - { + if (argc < 2) { usage(); std::exit(2); } @@ -242,53 +186,35 @@ int main(int argc, char *argv[]) bool blinearize = false; bool bpreserve_unreferenced = false; std::string filename_input; - for (int i = 1; i < argc; ++i) - { - if (argv[i][0] == '-') - { + for (int i = 1; i < argc; ++i) { + if (argv[i][0] == '-') { std::string opt = argv[i]; - if (opt == "--object-streams=preserve") - { + if (opt == "--object-streams=preserve") { mode = qpdf_o_preserve; - } - else if (opt == "--object-streams=disable") - { + } else if (opt == "--object-streams=disable") { mode = qpdf_o_disable; - } - else if (opt == "--object-streams=generate") - { + } else if (opt == "--object-streams=generate") { mode = qpdf_o_generate; - } - else if (opt == "--linearize") - { + } else if (opt == "--linearize") { blinearize = true; - } - else if (opt == "--preserve-unreferenced") - { + } else if (opt == "--preserve-unreferenced") { bpreserve_unreferenced = true; - } - else - { + } else { usage(); std::exit(2); } - } - else if (argc == i + 1) - { + } else if (argc == i + 1) { filename_input = argv[i]; break; - } - else - { + } else { usage(); std::exit(2); } } - try - { + try { QPDF qpdf_in; - qpdf_in.processFile(filename_input.c_str ()); + qpdf_in.processFile(filename_input.c_str()); std::vector objs_in = qpdf_in.getAllObjects(); QPDFWriter w(qpdf_in); @@ -298,65 +224,50 @@ int main(int argc, char *argv[]) w.setPreserveUnreferencedObjects(bpreserve_unreferenced); w.write(); - std::map xrefs_w - = w.getWrittenXRefTable(); + std::map xrefs_w = w.getWrittenXRefTable(); auto buf = w.getBufferSharedPointer(); QPDF qpdf_ren; - qpdf_ren.processMemoryFile("renumbered", - reinterpret_cast(buf->getBuffer()), - buf->getSize()); - std::map xrefs_ren - = qpdf_ren.getXRefTable(); + qpdf_ren.processMemoryFile( + "renumbered", + reinterpret_cast(buf->getBuffer()), + buf->getSize()); + std::map xrefs_ren = qpdf_ren.getXRefTable(); - std::cout - << "--- compare between input and renumbered objects ---" - << std::endl; + std::cout << "--- compare between input and renumbered objects ---" + << std::endl; for (std::vector::iterator iter = objs_in.begin(); - iter != objs_in.end(); ++iter) - { + iter != objs_in.end(); + ++iter) { QPDFObjGen og_in = iter->getObjGen(); QPDFObjGen og_ren = w.getRenumberedObjGen(og_in); - std::cout - << "input " - << og_in.getObj() << "/" << og_in.getGen() - << " -> renumbered " - << og_ren.getObj() << "/" << og_ren.getGen() - << std::endl; + std::cout << "input " << og_in.getObj() << "/" << og_in.getGen() + << " -> renumbered " << og_ren.getObj() << "/" + << og_ren.getGen() << std::endl; - if (og_ren.getObj() == 0) - { + if (og_ren.getObj() == 0) { std::cout << "deleted" << std::endl; continue; } - if (!compare(*iter, qpdf_ren.getObjectByObjGen(og_ren))) - { - std::cerr - << "different" - << std::endl; + if (!compare(*iter, qpdf_ren.getObjectByObjGen(og_ren))) { + std::cerr << "different" << std::endl; std::exit(2); } } std::cout << "complete" << std::endl; - std::cout - << "--- compare between written and reloaded xref tables ---" - << std::endl; - if (!compare_xref_table(xrefs_w, xrefs_ren)) - { - std::cerr - << "different" - << std::endl; + std::cout << "--- compare between written and reloaded xref tables ---" + << std::endl; + if (!compare_xref_table(xrefs_w, xrefs_ren)) { + std::cerr << "different" << std::endl; std::exit(2); } std::cout << "complete" << std::endl; std::cout << "succeeded" << std::endl; - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::exit(2); } diff --git a/qpdf/test_shell_glob.cc b/qpdf/test_shell_glob.cc index 34582197..c2cfb422 100644 --- a/qpdf/test_shell_glob.cc +++ b/qpdf/test_shell_glob.cc @@ -1,8 +1,9 @@ -#include -#include #include +#include +#include -int realmain(int argc, char* argv[]) +int +realmain(int argc, char* argv[]) { // In Windows, shell globbing is handled by the runtime, so // passing '*' as argument results in wildcard expansion. In @@ -17,46 +18,40 @@ int realmain(int argc, char* argv[]) // msvc and seeing that the test fails under that condition. bool found_star = false; - for (int i = 1; i < argc; ++i) - { - if (strchr(argv[i], '*') != nullptr) - { + for (int i = 1; i < argc; ++i) { + if (strchr(argv[i], '*') != nullptr) { found_star = true; break; } } #ifdef _WIN32 - bool passed = ((! found_star) && (argc > 2)); + bool passed = ((!found_star) && (argc > 2)); #else bool passed = (found_star && (argc == 2)); #endif - if (passed) - { + if (passed) { std::cout << "PASSED" << std::endl; - } - else - { + } else { std::cout << "FAILED" << std::endl; - for (int i = 1; i < argc; ++i) - { + for (int i = 1; i < argc; ++i) { std::cout << argv[i] << std::endl; } } return 0; } - #ifdef WINDOWS_WMAIN -extern "C" -int wmain(int argc, wchar_t* argv[]) +extern "C" int +wmain(int argc, wchar_t* argv[]) { return QUtil::call_main_from_wmain(argc, argv, realmain); } #else -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { return realmain(argc, argv); } diff --git a/qpdf/test_tokenizer.cc b/qpdf/test_tokenizer.cc index b7eae323..c609d848 100644 --- a/qpdf/test_tokenizer.cc +++ b/qpdf/test_tokenizer.cc @@ -1,24 +1,24 @@ -#include -#include -#include -#include -#include #include -#include +#include #include #include -#include -#include -#include +#include +#include +#include +#include +#include #include +#include +#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami - << " [-maxlen len | -no-ignorable] filename" - << std::endl; + << " [-maxlen len | -no-ignorable] filename" << std::endl; exit(2); } @@ -51,47 +51,47 @@ Finder::check() return result; } -static char const* tokenTypeName(QPDFTokenizer::token_type_e ttype) +static char const* +tokenTypeName(QPDFTokenizer::token_type_e ttype) { // Do this is a case statement instead of a lookup so the compiler // will warn if we miss any. - switch (ttype) - { - case QPDFTokenizer::tt_bad: + switch (ttype) { + case QPDFTokenizer::tt_bad: return "bad"; - case QPDFTokenizer::tt_array_close: + case QPDFTokenizer::tt_array_close: return "array_close"; - case QPDFTokenizer::tt_array_open: + case QPDFTokenizer::tt_array_open: return "array_open"; - case QPDFTokenizer::tt_brace_close: + case QPDFTokenizer::tt_brace_close: return "brace_close"; - case QPDFTokenizer::tt_brace_open: + case QPDFTokenizer::tt_brace_open: return "brace_open"; - case QPDFTokenizer::tt_dict_close: + case QPDFTokenizer::tt_dict_close: return "dict_close"; - case QPDFTokenizer::tt_dict_open: + case QPDFTokenizer::tt_dict_open: return "dict_open"; - case QPDFTokenizer::tt_integer: + case QPDFTokenizer::tt_integer: return "integer"; - case QPDFTokenizer::tt_name: + case QPDFTokenizer::tt_name: return "name"; - case QPDFTokenizer::tt_real: + case QPDFTokenizer::tt_real: return "real"; - case QPDFTokenizer::tt_string: + case QPDFTokenizer::tt_string: return "string"; - case QPDFTokenizer::tt_null: + case QPDFTokenizer::tt_null: return "null"; - case QPDFTokenizer::tt_bool: + case QPDFTokenizer::tt_bool: return "bool"; - case QPDFTokenizer::tt_word: + case QPDFTokenizer::tt_word: return "word"; - case QPDFTokenizer::tt_eof: + case QPDFTokenizer::tt_eof: return "eof"; - case QPDFTokenizer::tt_space: + case QPDFTokenizer::tt_space: return "space"; - case QPDFTokenizer::tt_comment: + case QPDFTokenizer::tt_comment: return "comment"; - case QPDFTokenizer::tt_inline_image: + case QPDFTokenizer::tt_inline_image: return "inline-image"; } return 0; @@ -102,56 +102,56 @@ sanitize(std::string const& value) { std::string result; for (std::string::const_iterator iter = value.begin(); iter != value.end(); - ++iter) - { - if ((*iter >= 32) && (*iter <= 126)) - { + ++iter) { + if ((*iter >= 32) && (*iter <= 126)) { result.append(1, *iter); - } - else - { - result += "\\x" + QUtil::int_to_string_base( - static_cast(*iter), 16, 2); + } else { + result += "\\x" + + QUtil::int_to_string_base( + static_cast(*iter), 16, 2); } } return result; } static void -try_skipping(QPDFTokenizer& tokenizer, PointerHolder is, - size_t max_len, char const* what, Finder& f) +try_skipping( + QPDFTokenizer& tokenizer, + PointerHolder is, + size_t max_len, + char const* what, + Finder& f) { std::cout << "skipping to " << what << std::endl; qpdf_offset_t offset = is->tell(); - if (! is->findFirst(what, offset, 0, f)) - { + if (!is->findFirst(what, offset, 0, f)) { std::cout << what << " not found" << std::endl; is->seek(offset, SEEK_SET); } } static void -dump_tokens(PointerHolder is, std::string const& label, - size_t max_len, bool include_ignorable, - bool skip_streams, bool skip_inline_images) +dump_tokens( + PointerHolder is, + std::string const& label, + size_t max_len, + bool include_ignorable, + bool skip_streams, + bool skip_inline_images) { Finder f1(is, "endstream"); std::cout << "--- BEGIN " << label << " ---" << std::endl; bool done = false; QPDFTokenizer tokenizer; tokenizer.allowEOF(); - if (include_ignorable) - { + if (include_ignorable) { tokenizer.includeIgnorable(); } qpdf_offset_t inline_image_offset = 0; - while (! done) - { - QPDFTokenizer::Token token = - tokenizer.readToken(is, "test", true, - inline_image_offset ? 0 : max_len); - if (inline_image_offset && (token.getType() == QPDFTokenizer::tt_bad)) - { + while (!done) { + QPDFTokenizer::Token token = tokenizer.readToken( + is, "test", true, inline_image_offset ? 0 : max_len); + if (inline_image_offset && (token.getType() == QPDFTokenizer::tt_bad)) { std::cout << "EI not found; resuming normal scanning" << std::endl; is->seek(inline_image_offset, SEEK_SET); inline_image_offset = 0; @@ -160,45 +160,36 @@ dump_tokens(PointerHolder is, std::string const& label, inline_image_offset = 0; qpdf_offset_t offset = is->getLastOffset(); - std::cout << offset << ": " - << tokenTypeName(token.getType()); - if (token.getType() != QPDFTokenizer::tt_eof) - { - std::cout << ": " - << sanitize(token.getValue()); - if (token.getValue() != token.getRawValue()) - { + std::cout << offset << ": " << tokenTypeName(token.getType()); + if (token.getType() != QPDFTokenizer::tt_eof) { + std::cout << ": " << sanitize(token.getValue()); + if (token.getValue() != token.getRawValue()) { std::cout << " (raw: " << sanitize(token.getRawValue()) << ")"; } } - if (! token.getErrorMessage().empty()) - { + if (!token.getErrorMessage().empty()) { std::cout << " (" << token.getErrorMessage() << ")"; } std::cout << std::endl; if (skip_streams && - (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream"))) - { + (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "stream"))) { try_skipping(tokenizer, is, max_len, "endstream", f1); - } - else if (skip_inline_images && - (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "ID"))) - { + } else if ( + skip_inline_images && + (token == QPDFTokenizer::Token(QPDFTokenizer::tt_word, "ID"))) { char ch; is->read(&ch, 1); tokenizer.expectInlineImage(is); inline_image_offset = is->tell(); - } - else if (token.getType() == QPDFTokenizer::tt_eof) - { + } else if (token.getType() == QPDFTokenizer::tt_eof) { done = true; } } std::cout << "--- END " << label << " ---" << std::endl; } -static void process(char const* filename, bool include_ignorable, - size_t max_len) +static void +process(char const* filename, bool include_ignorable, size_t max_len) { PointerHolder is; @@ -215,96 +206,85 @@ static void process(char const* filename, bool include_ignorable, QPDFPageDocumentHelper(qpdf).getAllPages(); int pageno = 0; for (std::vector::iterator iter = pages.begin(); - iter != pages.end(); ++iter) - { + iter != pages.end(); + ++iter) { ++pageno; Pl_Buffer plb("buffer"); (*iter).pipeContents(&plb); auto content_data = plb.getBufferSharedPointer(); - BufferInputSource* bis = new BufferInputSource( - "content data", content_data.get()); + BufferInputSource* bis = + new BufferInputSource("content data", content_data.get()); is = PointerHolder(bis); - dump_tokens(is, "PAGE " + QUtil::int_to_string(pageno), - max_len, include_ignorable, false, true); + dump_tokens( + is, + "PAGE " + QUtil::int_to_string(pageno), + max_len, + include_ignorable, + false, + true); } // Tokenize object streams std::vector all = qpdf.getAllObjects(); for (std::vector::iterator iter = all.begin(); - iter != all.end(); ++iter) - { - if ((*iter).isStream() && - (*iter).getDict().getKey("/Type").isName() && - (*iter).getDict().getKey("/Type").getName() == "/ObjStm") - { + iter != all.end(); + ++iter) { + if ((*iter).isStream() && (*iter).getDict().getKey("/Type").isName() && + (*iter).getDict().getKey("/Type").getName() == "/ObjStm") { PointerHolder b = (*iter).getStreamData(qpdf_dl_specialized); - BufferInputSource* bis = new BufferInputSource( - "object stream data", b.get()); + BufferInputSource* bis = + new BufferInputSource("object stream data", b.get()); is = PointerHolder(bis); - dump_tokens(is, "OBJECT STREAM " + - QUtil::int_to_string((*iter).getObjectID()), - max_len, include_ignorable, false, false); + dump_tokens( + is, + "OBJECT STREAM " + QUtil::int_to_string((*iter).getObjectID()), + max_len, + include_ignorable, + false, + false); } } } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { QUtil::setLineBuf(stdout); - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } char const* filename = 0; size_t max_len = 0; bool include_ignorable = true; - for (int i = 1; i < argc; ++i) - { - if (argv[i][0] == '-') - { - if (strcmp(argv[i], "-maxlen") == 0) - { - if (++i >= argc) - { + for (int i = 1; i < argc; ++i) { + if (argv[i][0] == '-') { + if (strcmp(argv[i], "-maxlen") == 0) { + if (++i >= argc) { usage(); } max_len = QUtil::string_to_uint(argv[i]); - } - else if (strcmp(argv[i], "-no-ignorable") == 0) - { + } else if (strcmp(argv[i], "-no-ignorable") == 0) { include_ignorable = false; - } - else - { + } else { usage(); } - } - else if (filename) - { + } else if (filename) { usage(); - } - else - { + } else { filename = argv[i]; } } - if (filename == 0) - { + if (filename == 0) { usage(); } - try - { + try { process(filename, include_ignorable, max_len); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": exception: " << e.what(); exit(2); } diff --git a/qpdf/test_unicode_filenames.cc b/qpdf/test_unicode_filenames.cc index 3ef71be5..3d9e8038 100644 --- a/qpdf/test_unicode_filenames.cc +++ b/qpdf/test_unicode_filenames.cc @@ -1,29 +1,27 @@ #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN -# include # include # include +# include #endif #include -#include #include +#include -static void do_copy(FILE* in, FILE* out) +static void +do_copy(FILE* in, FILE* out) { - if ((in == 0) || (out == 0)) - { + if ((in == 0) || (out == 0)) { std::cerr << "errors opening files" << std::endl; exit(2); } char buf[10240]; size_t len = 0; - while ((len = fread(buf, 1, sizeof(buf), in)) > 0) - { + while ((len = fread(buf, 1, sizeof(buf), in)) > 0) { fwrite(buf, 1, len, out); } - if (len != 0) - { + if (len != 0) { std::cerr << "errors reading or writing" << std::endl; exit(2); } @@ -33,22 +31,23 @@ static void do_copy(FILE* in, FILE* out) #ifdef WINDOWS_WMAIN -void copy(wchar_t const* outname) +void +copy(wchar_t const* outname) { -#ifdef _MSC_VER +# ifdef _MSC_VER FILE* in = 0; _wfopen_s(&in, L"minimal.pdf", L"rb"); FILE* out = 0; _wfopen_s(&out, outname, L"wb"); -#else +# else FILE* in = _wfopen(L"minimal.pdf", L"rb"); FILE* out = _wfopen(outname, L"wb"); -#endif +# endif do_copy(in, out); } -extern "C" -int wmain(int argc, wchar_t* argv[]) +extern "C" int +wmain(int argc, wchar_t* argv[]) { // Unicode wchar_t const* f1 = L"auto-\xfc.pdf"; @@ -61,14 +60,16 @@ int wmain(int argc, wchar_t* argv[]) #else -void copy(char const* outname) +void +copy(char const* outname) { FILE* in = fopen("minimal.pdf", "rb"); FILE* out = fopen(outname, "wb"); do_copy(in, out); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { // Explicit UTF-8 encoding char const* f1 = "auto-\xc3\xbc.pdf"; diff --git a/qpdf/test_xref.cc b/qpdf/test_xref.cc index 9e04f3f7..238ef2a0 100644 --- a/qpdf/test_xref.cc +++ b/qpdf/test_xref.cc @@ -2,67 +2,52 @@ #include #include +#include #include #include #include -#include -int main(int argc, char *argv[]) +int +main(int argc, char* argv[]) { - if (argc != 2) - { + if (argc != 2) { std::cerr << "usage: test_xref INPUT.pdf" << std::endl; std::exit(2); } - try - { + try { QPDF qpdf; qpdf.processFile(argv[1]); - std::map xref - = qpdf.getXRefTable(); + std::map xref = qpdf.getXRefTable(); for (std::map::iterator iter = xref.begin(); - iter != xref.end(); ++iter) - { - std::cout - << iter->first.getObj() << "/" << iter->first.getGen() - << ", "; - switch (iter->second.getType()) - { - case 0: - std::cout - << "free entry" - << std::endl; + iter != xref.end(); + ++iter) { + std::cout << iter->first.getObj() << "/" << iter->first.getGen() + << ", "; + switch (iter->second.getType()) { + case 0: + std::cout << "free entry" << std::endl; break; - case 1: - std::cout - << "uncompressed, offset = " - << iter->second.getOffset() - << " (0x" - << std::hex << iter->second.getOffset() << std::dec - << ")" - << std::endl; + case 1: + std::cout << "uncompressed, offset = " + << iter->second.getOffset() << " (0x" << std::hex + << iter->second.getOffset() << std::dec << ")" + << std::endl; break; - case 2: - std::cout - << "compressed, stream number = " - << iter->second.getObjStreamNumber() - << ", stream index = " - << iter->second.getObjStreamIndex() - << std::endl; + case 2: + std::cout << "compressed, stream number = " + << iter->second.getObjStreamNumber() + << ", stream index = " + << iter->second.getObjStreamIndex() << std::endl; break; - default: - std::cerr - << "unknown" - << std::endl; + default: + std::cerr << "unknown" << std::endl; std::exit(2); } } - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::exit(2); } diff --git a/zlib-flate/zlib-flate.cc b/zlib-flate/zlib-flate.cc index 57bec46a..671227b1 100644 --- a/zlib-flate/zlib-flate.cc +++ b/zlib-flate/zlib-flate.cc @@ -1,17 +1,18 @@ #include #include -#include #include +#include -#include -#include -#include -#include #include +#include +#include +#include +#include static char const* whoami = 0; -void usage() +void +usage() { std::cerr << "Usage: " << whoami << " { -uncompress | -compress[=n] }" << std::endl @@ -19,52 +20,40 @@ void usage() << " zlib compression level from" << std::endl << "1 to 9 where lower numbers are faster and" << " less compressed and higher" << std::endl - << "numbers are slower and more compressed" - << std::endl; + << "numbers are slower and more compressed" << std::endl; exit(2); } -int main(int argc, char* argv[]) +int +main(int argc, char* argv[]) { - if ((whoami = strrchr(argv[0], '/')) == NULL) - { + if ((whoami = strrchr(argv[0], '/')) == NULL) { whoami = argv[0]; - } - else - { + } else { ++whoami; } - if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) - { - std::cout << whoami << " from qpdf version " - << QPDF::QPDFVersion() << std::endl; + if ((argc == 2) && (strcmp(argv[1], "--version") == 0)) { + std::cout << whoami << " from qpdf version " << QPDF::QPDFVersion() + << std::endl; exit(0); } - if (argc != 2) - { + if (argc != 2) { usage(); } Pl_Flate::action_e action = Pl_Flate::a_inflate; - if ((strcmp(argv[1], "-uncompress") == 0)) - { + if ((strcmp(argv[1], "-uncompress") == 0)) { // okay - } - else if ((strcmp(argv[1], "-compress") == 0)) - { + } else if ((strcmp(argv[1], "-compress") == 0)) { action = Pl_Flate::a_deflate; - } - else if ((strncmp(argv[1], "-compress=", 10) == 0)) - { + } else if ((strncmp(argv[1], "-compress=", 10) == 0)) { action = Pl_Flate::a_deflate; int level = QUtil::string_to_int(argv[1] + 10); Pl_Flate::setCompressionLevel(level); - } - else - { + } else { usage(); } @@ -79,32 +68,24 @@ int main(int argc, char* argv[]) << ", msg = " << msg << std::endl; }); - try - { + try { unsigned char buf[10000]; bool done = false; - while (! done) - { + while (!done) { size_t len = fread(buf, 1, sizeof(buf), stdin); - if (len <= 0) - { + if (len <= 0) { done = true; - } - else - { + } else { flate->write(buf, len); } } flate->finish(); - } - catch (std::exception& e) - { + } catch (std::exception& e) { std::cerr << whoami << ": " << e.what() << std::endl; exit(2); } - if (warn) - { + if (warn) { exit(3); } return 0;