diff --git a/AUTHORS b/AUTHORS index a7bfeb888c..6f9cf07d75 100644 --- a/AUTHORS +++ b/AUTHORS @@ -20,6 +20,7 @@ Bill Denney Chenguang Shao Chery Cherian Claudio DeSouza +Cristiano Fraga G. Nunes Dan Ilan Deepak Mohan Dmitrii Chunikhin diff --git a/DEPS b/DEPS index e51f3204e9..bc799f7de5 100644 --- a/DEPS +++ b/DEPS @@ -126,7 +126,7 @@ vars = { # Three lines of non-changing comments so that # the commit queue can handle CLs rolling depot_tools # and whatever else without interference from each other. - 'depot_tools_revision': 'a03dfbf7f2d1cefa2795d81d59ca4f16c8616a8f', + 'depot_tools_revision': '96a7c1418eedaa6bea333a8941e8a0078681b4d0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling dragonbox # and whatever else without interference from each other. @@ -256,7 +256,7 @@ vars = { # Three lines of non-changing comments so that # the commit queue can handle CLs rolling tools_memory # and whatever else without interference from each other. - 'tools_memory_revision': '3d4610fc0dd49053c0395bc2825dfc6ac72ab64e', + 'tools_memory_revision': 'db1b13009b4ae8a321f7055bcce8e7267ef74729', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling tools_rust # and whatever else without interference from each other. diff --git a/core/fpdfapi/font/cpdf_cmapparser.cpp b/core/fpdfapi/font/cpdf_cmapparser.cpp index 3597bc36a8..4ea5c74a1e 100644 --- a/core/fpdfapi/font/cpdf_cmapparser.cpp +++ b/core/fpdfapi/font/cpdf_cmapparser.cpp @@ -14,6 +14,7 @@ #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_simple_parser.h" #include "core/fxcrt/check.h" +#include "core/fxcrt/containers/extend.h" #include "core/fxcrt/fx_extension.h" #include "core/fxcrt/fx_safe_types.h" #include "core/fxcrt/to_underlying.h" @@ -134,10 +135,7 @@ void CPDF_CMapParser::HandleCodeSpaceRange(ByteStringView word) { : CPDF_CMap::OneByte); } else if (nSegs > 1) { cmap_->SetCodingScheme(CPDF_CMap::MixedFourBytes); - ranges_.reserve(nSegs); - std::move(pending_ranges_.begin(), pending_ranges_.end(), - std::back_inserter(ranges_)); - pending_ranges_.clear(); + pdfium::Extend(ranges_, std::move(pending_ranges_)); } status_ = kStart; } diff --git a/core/fpdfapi/page/cpdf_image.cpp b/core/fpdfapi/page/cpdf_image.cpp index 74bbc1320c..2352202e18 100644 --- a/core/fpdfapi/page/cpdf_image.cpp +++ b/core/fpdfapi/page/cpdf_image.cpp @@ -27,11 +27,11 @@ #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "core/fxcodec/flate/flatemodule.h" +#include "core/fxcodec/fx_codec.h" #include "core/fxcodec/jpeg/jpegmodule.h" #include "core/fxcodec/png/pngmodule.h" #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" -#include "core/fxcrt/compiler_specific.h" #include "core/fxcrt/data_vector.h" #include "core/fxcrt/fx_2d_size.h" #include "core/fxcrt/fx_ceil_div.h" @@ -42,6 +42,12 @@ #include "core/fxge/dib/cfx_dibitmap.h" #include "core/fxge/dib/fx_dib.h" +#if defined(PDF_USE_LIBYUV) +#include "core/fxge/fx_libyuv_wrappers.h" +#else +#include "core/fxcrt/zip.h" +#endif + // EmbedPDF(redaction): rewriting an image's stream in place, for // OverwriteStreamInPlace(). namespace { @@ -434,23 +440,33 @@ void CPDF_Image::SetImage(const RetainPtr& pBitmap) { dest_span = fxcrt::spancpy(dest_span, src_span.first(dest_pitch)); src_span = src_span.subspan(static_cast(src_pitch)); } + } else if (bpp == 24) { + for (int32_t row = 0; row < BitmapHeight; row++) { + fxcodec::ReverseRGB(dest_span, src_span, BitmapWidth); + dest_span = dest_span.subspan(dest_pitch); + src_span = src_span.subspan(static_cast(src_pitch)); + } } else { - const size_t src_step = bpp == 24 ? 3 : 4; +#if defined(PDF_USE_LIBYUV) + pdfium::ARGBToRAW(src_span, src_pitch, dest_span, + pdfium::checked_cast(dest_pitch), BitmapWidth, + BitmapHeight); +#else for (int32_t row = 0; row < BitmapHeight; row++) { - uint8_t* dest_ptr = dest_span.data(); - const uint8_t* src_ptr = src_span.data(); - for (int32_t column = 0; column < BitmapWidth; column++) { - UNSAFE_TODO({ - dest_ptr[0] = src_ptr[2]; - dest_ptr[1] = src_ptr[1]; - dest_ptr[2] = src_ptr[0]; - dest_ptr += 3; - src_ptr += src_step; - }); + auto src_row = + fxcrt::reinterpret_span>(src_span) + .first(static_cast(BitmapWidth)); + auto dest_row = + fxcrt::reinterpret_span>(dest_span); + for (auto [input, output] : fxcrt::Zip(src_row, dest_row)) { + output.red = input.red; + output.green = input.green; + output.blue = input.blue; } dest_span = dest_span.subspan(dest_pitch); src_span = src_span.subspan(static_cast(src_pitch)); } +#endif } stream_ = diff --git a/core/fpdfapi/parser/BUILD.gn b/core/fpdfapi/parser/BUILD.gn index 1dc29d54a3..69f6ec612a 100644 --- a/core/fpdfapi/parser/BUILD.gn +++ b/core/fpdfapi/parser/BUILD.gn @@ -99,6 +99,8 @@ source_set("parser") { "fpdf_parser_utility.h", "object_tree_traversal_util.cpp", "object_tree_traversal_util.h", + "tree_traversal_util.cpp", + "tree_traversal_util.h", ] configs += [ "../../../:pdfium_strict_config" ] public_deps = [ @@ -173,6 +175,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_syntax_parser_unittest.cpp", "fpdf_parser_decode_unittest.cpp", "fpdf_parser_utility_unittest.cpp", + "tree_traversal_util_unittest.cpp", ] deps = [ ":parser", diff --git a/core/fpdfapi/parser/cpdf_crypto_handler.cpp b/core/fpdfapi/parser/cpdf_crypto_handler.cpp index a584d3c5ca..ff2e473916 100644 --- a/core/fpdfapi/parser/cpdf_crypto_handler.cpp +++ b/core/fpdfapi/parser/cpdf_crypto_handler.cpp @@ -28,6 +28,8 @@ #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" #include "core/fxcrt/epdf_secure_random.h" +#include "core/fxcrt/notreached.h" +#include "core/fxcrt/span_util.h" #include "core/fxcrt/stl_util.h" namespace { @@ -44,6 +46,36 @@ struct AESCryptContext { } // namespace +// static +bool CPDF_CryptoHandler::IsValidKeyLength(Cipher cipher, size_t key_len) { + switch (cipher) { + case Cipher::kAES: + return key_len == 16 || key_len == 32; + case Cipher::kAES2: + return key_len == 32; + case Cipher::kRC4: + return key_len >= 5 && key_len <= 16; + case Cipher::kNone: + return true; + } + NOTREACHED(); +} + +// static +bool CPDF_CryptoHandler::RequiresPerObjectKeyDerivation(Cipher cipher, + size_t key_len) { + switch (cipher) { + case Cipher::kNone: + case Cipher::kAES2: + return false; + case Cipher::kRC4: + return true; + case Cipher::kAES: + return key_len == 16; + } + NOTREACHED(); +} + // static bool CPDF_CryptoHandler::IsSignatureDictionary( const CPDF_Dictionary* dictionary) { @@ -74,7 +106,9 @@ std::optional> CPDF_CryptoHandler::EncryptContent( } std::array realkey; size_t realkeylen = realkey.size(); - if (cipher_ != Cipher::kAES || key_len_ != 32) { + const bool requires_derivation = + RequiresPerObjectKeyDerivation(cipher_, key_len_); + if (requires_derivation) { std::array key1; PopulateKey(objnum, gennum, key1); if (cipher_ == Cipher::kAES) { @@ -86,11 +120,11 @@ std::optional> CPDF_CryptoHandler::EncryptContent( realkeylen = std::min(key_len_ + 5, realkeylen); } if (cipher_ == Cipher::kAES) { - if (key_len_ == 32) { - CRYPT_AESSetKey(aes_context_.get(), encrypt_key_); - } else { + if (requires_derivation) { CRYPT_AESSetKey(aes_context_.get(), pdfium::span(realkey).first(key_len_)); + } else { + CRYPT_AESSetKey(aes_context_.get(), encrypt_key_); } static constexpr size_t kIVSize = 16; @@ -134,7 +168,7 @@ void* CPDF_CryptoHandler::DecryptStart(uint32_t objnum, uint32_t gennum) { AESCryptContext* context = FX_Alloc(AESCryptContext, 1); context->iv_ = true; context->block_offset_ = 0; - if (key_len_ == 32) { + if (!RequiresPerObjectKeyDerivation(cipher_, key_len_)) { CRYPT_AESSetKey(&context->context_, encrypt_key_); return context; } @@ -340,10 +374,7 @@ bool CPDF_CryptoHandler::DecryptObjectTree(RetainPtr object) { CPDF_CryptoHandler::CPDF_CryptoHandler(Cipher cipher, pdfium::span key) : key_len_(std::min(key.size(), 32)), cipher_(cipher) { - DCHECK(cipher != Cipher::kAES || key.size() == 16 || key.size() == 24 || - key.size() == 32); - DCHECK(cipher != Cipher::kAES2 || key.size() == 32); - DCHECK(cipher != Cipher::kRC4 || (key.size() >= 5 && key.size() <= 16)); + DCHECK(IsValidKeyLength(cipher, key.size())); if (cipher_ != Cipher::kNone) { fxcrt::Copy(key.first(key_len_), encrypt_key_); diff --git a/core/fpdfapi/parser/cpdf_crypto_handler.h b/core/fpdfapi/parser/cpdf_crypto_handler.h index 15a9ce8435..86513324a7 100644 --- a/core/fpdfapi/parser/cpdf_crypto_handler.h +++ b/core/fpdfapi/parser/cpdf_crypto_handler.h @@ -34,6 +34,8 @@ class CPDF_CryptoHandler { kAES2 = 3, }; + static bool IsValidKeyLength(Cipher cipher, size_t key_len); + static bool RequiresPerObjectKeyDerivation(Cipher cipher, size_t key_len); static bool IsSignatureDictionary(const CPDF_Dictionary* dictionary); CPDF_CryptoHandler(Cipher cipher, pdfium::span key); diff --git a/core/fpdfapi/parser/cpdf_security_handler.cpp b/core/fpdfapi/parser/cpdf_security_handler.cpp index c7e939a1a6..d8f79a397b 100644 --- a/core/fpdfapi/parser/cpdf_security_handler.cpp +++ b/core/fpdfapi/parser/cpdf_security_handler.cpp @@ -87,20 +87,6 @@ void CalcEncryptKey(const CPDF_Dictionary* pEncrypt, fxcrt::Copy(digest_span, key); } -bool IsValidKeyLengthForCipher(CPDF_CryptoHandler::Cipher cipher, - size_t keylen) { - switch (cipher) { - case CPDF_CryptoHandler::Cipher::kAES: - return keylen == 16 || keylen == 24 || keylen == 32; - case CPDF_CryptoHandler::Cipher::kAES2: - return keylen == 32; - case CPDF_CryptoHandler::Cipher::kRC4: - return keylen >= 5 && keylen <= 16; - case CPDF_CryptoHandler::Cipher::kNone: - return true; - } -} - int BigOrder64BitsMod3(pdfium::span data) { uint64_t ret = 0; for (int i = 0; i < 4; ++i) { @@ -326,7 +312,7 @@ static bool LoadCryptInfo(const CPDF_Dictionary* pEncryptDict, if (keylen < 0 || keylen > 32) { return false; } - if (!IsValidKeyLengthForCipher(*cipher, keylen)) { + if (!CPDF_CryptoHandler::IsValidKeyLength(*cipher, keylen)) { return false; } diff --git a/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp b/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp index 7bb1191871..77bff48987 100644 --- a/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp +++ b/core/fpdfapi/parser/cpdf_security_handler_embeddertest.cpp @@ -730,3 +730,7 @@ TEST_F(CPDFSecurityHandlerEmbedderTest, Bug424613308) { // Test passes if CHECK() does not fail. ASSERT_FALSE(OpenDocument("bug_424613308.pdf")); } + +TEST_F(CPDFSecurityHandlerEmbedderTest, Bug585348292) { + EXPECT_FALSE(OpenDocument("bug_585348292.pdf")); +} diff --git a/core/fpdfapi/parser/object_tree_traversal_util.cpp b/core/fpdfapi/parser/object_tree_traversal_util.cpp index cce3fa3906..b0e5cc0f81 100644 --- a/core/fpdfapi/parser/object_tree_traversal_util.cpp +++ b/core/fpdfapi/parser/object_tree_traversal_util.cpp @@ -17,17 +17,21 @@ #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" +#include "core/fpdfapi/parser/tree_traversal_util.h" #include "core/fxcrt/check.h" #include "core/fxcrt/containers/contains.h" #include "core/fxcrt/unowned_ptr.h" namespace { -class ObjectTreeTraverser { +// Traverses the PDF object hierarchy in a document to extract an `AdjacencyMap` +// and root node IDs. +class PdfReferenceGraphBuilder { public: // EmbedPDF(layer-save): collect objects through a layer's view. - ObjectTreeTraverser(const CPDF_Document* document, - ObjectTreeReferenceResolveMode resolve_mode) + PdfReferenceGraphBuilder(const CPDF_Document* document, + ObjectTreeReferenceResolveMode resolve_mode = + ObjectTreeReferenceResolveMode::kReferenceHolder) : document_(document), resolve_mode_(resolve_mode) { const CPDF_Parser* parser = document_->GetParser(); const CPDF_Dictionary* trailer = parser ? parser->GetTrailer() : nullptr; @@ -36,33 +40,35 @@ class ObjectTreeTraverser { parser->GetTrailerObjectNumber()); } } - ~ObjectTreeTraverser() = default; - void Traverse() { CalculateReferenceCounts(GetReferenceEntries()); } + PdfReferenceGraph Build() { + DrainObjectQueue(); - const std::map& referenced_objects() { - return referenced_objects_; + // Also traverse the catalog if it was not reached from the trailer + // (e.g. if the trailer's `/Root` was missing, null, or diverged). + const CPDF_Dictionary* catalog = document_->GetRoot(); + if (catalog && !pdfium::Contains(seen_objects_, catalog)) { + EnqueueRoot(pdfium::WrapRetain(catalog), catalog->GetObjNum()); + DrainObjectQueue(); + } + + return {std::move(roots_), std::move(adj_)}; } private: - struct ReferenceEntry { - uint32_t ref_object_number; - uint32_t referenced_object_number; - }; - void EnqueueRoot(RetainPtr root, uint32_t root_object_number) { if (!root || !seen_objects_.insert(root.Get()).second) { return; } if (root_object_number) { - referenced_objects_[root_object_number] = 1; + roots_.push_back(root_object_number); object_number_map_[root.Get()] = root_object_number; } object_queue_.push(std::move(root)); } - void DrainObjectQueue(std::vector* reference_entries) { + void DrainObjectQueue() { while (!object_queue_.empty()) { RetainPtr current_object = object_queue_.front(); object_queue_.pop(); @@ -107,8 +113,13 @@ class ObjectTreeTraverser { // Unlike the other object types, CPDF_Reference can point at nullptr. if (referenced_object) { CHECK(referenced_object_number); - reference_entries->push_back( - {ref_object_number, referenced_object_number}); + if (ref_object_number) { + if (referenced_object_number != ref_object_number) { + adj_[ref_object_number].push_back(referenced_object_number); + } + } else { + roots_.push_back(referenced_object_number); + } PushNewObject(ref_object, referenced_object); } break; @@ -130,45 +141,6 @@ class ObjectTreeTraverser { } } - std::vector GetReferenceEntries() { - std::vector reference_entries; - DrainObjectQueue(&reference_entries); - - // Also traverse the catalog if it was not reached from the trailer - // (e.g. if the trailer's `/Root` was missing, null, or diverged). - const CPDF_Dictionary* catalog = document_->GetRoot(); - if (catalog && !pdfium::Contains(seen_objects_, catalog)) { - EnqueueRoot(pdfium::WrapRetain(catalog), catalog->GetObjNum()); - DrainObjectQueue(&reference_entries); - } - return reference_entries; - } - - void CalculateReferenceCounts( - const std::vector& reference_entries) { - // Tracks PDF objects that referenced other PDF objects, identified by their - // object numbers. Never 0. - std::set seen_ref_objects; - - for (const ReferenceEntry& entry : reference_entries) { - // Make sure this is not a self-reference. - if (entry.referenced_object_number == entry.ref_object_number) { - continue; - } - - // Make sure this is not a circular reference. - if (pdfium::Contains(seen_ref_objects, entry.ref_object_number) && - pdfium::Contains(seen_ref_objects, entry.referenced_object_number)) { - continue; - } - - ++referenced_objects_[entry.referenced_object_number]; - if (entry.ref_object_number) { - seen_ref_objects.insert(entry.ref_object_number); - } - } - } - void PushNewObject(const CPDF_Object* parent_object, RetainPtr child_object) { CHECK(parent_object); @@ -199,6 +171,8 @@ class ObjectTreeTraverser { UnownedPtr const document_; // EmbedPDF(layer-save): collect objects through a layer's view. const ObjectTreeReferenceResolveMode resolve_mode_; + std::vector roots_; + pdfium::AdjacencyMap adj_; // Queue of objects to traverse. // - Pointers in the queue are non-null. @@ -215,24 +189,26 @@ class ObjectTreeTraverser { // Tracks traversed objects to prevent duplicates from getting into // `object_queue_` and `object_number_map_`. std::set seen_objects_; - - // Tracks which PDF objects are referenced. - // Key: object number - // Value: number of times referenced - std::map referenced_objects_; }; } // namespace +PdfReferenceGraph BuildPdfReferenceGraphForTesting( + const CPDF_Document* document) { + return PdfReferenceGraphBuilder(document).Build(); +} + // EmbedPDF(layer-save): collect objects through a layer's view. std::set GetObjectsWithReferences( const CPDF_Document* document, ObjectTreeReferenceResolveMode resolve_mode) { - ObjectTreeTraverser traverser(document, resolve_mode); - traverser.Traverse(); + PdfReferenceGraph graph = + PdfReferenceGraphBuilder(document, resolve_mode).Build(); + std::map counts = + pdfium::CalculateReferenceCounts(graph.roots, graph.adj); std::set results; - for (const auto& it : traverser.referenced_objects()) { + for (const auto& it : counts) { results.insert(it.first); } return results; @@ -242,11 +218,13 @@ std::set GetObjectsWithReferences( std::set GetObjectsWithMultipleReferences( const CPDF_Document* document, ObjectTreeReferenceResolveMode resolve_mode) { - ObjectTreeTraverser traverser(document, resolve_mode); - traverser.Traverse(); + PdfReferenceGraph graph = + PdfReferenceGraphBuilder(document, resolve_mode).Build(); + std::map counts = + pdfium::CalculateReferenceCounts(graph.roots, graph.adj); std::set results; - for (const auto& it : traverser.referenced_objects()) { + for (const auto& it : counts) { if (it.second > 1) { results.insert(it.first); } diff --git a/core/fpdfapi/parser/object_tree_traversal_util.h b/core/fpdfapi/parser/object_tree_traversal_util.h index 7983d308de..1ea6f07319 100644 --- a/core/fpdfapi/parser/object_tree_traversal_util.h +++ b/core/fpdfapi/parser/object_tree_traversal_util.h @@ -8,6 +8,9 @@ #include #include +#include + +#include "core/fpdfapi/parser/tree_traversal_util.h" class CPDF_Document; @@ -23,12 +26,23 @@ enum class ObjectTreeReferenceResolveMode { kEffectiveDocument, }; +struct PdfReferenceGraph { + std::vector roots; + pdfium::AdjacencyMap adj; +}; + +// Traverses the PDF object hierarchy in `document` and returns the extracted +// reference graph without reference count analysis or cycle pruning. +PdfReferenceGraph BuildPdfReferenceGraphForTesting( + const CPDF_Document* document); + // Traverses `document` starting with its trailer, if it has one, and also from // the catalog if not reached from the trailer. The traversal avoids cycles. // -// In `kReferenceHolder` mode, references are followed through their -// CPDF_IndirectObjectHolder. In `kEffectiveDocument` mode, references are -// resolved through `document` so any overlay it provides is honored. +// EmbedPDF(layer-save): in `kReferenceHolder` mode, references are followed +// through their CPDF_IndirectObjectHolder. In `kEffectiveDocument` mode, +// references are resolved through `document` so any overlay it provides is +// honored. // // Returns all the PDF objects (not CPDF_Objects) the traversal reached as a set // of object numbers. diff --git a/core/fpdfapi/parser/object_tree_traversal_util_embeddertest.cpp b/core/fpdfapi/parser/object_tree_traversal_util_embeddertest.cpp index a129c4f06e..6cbc345675 100644 --- a/core/fpdfapi/parser/object_tree_traversal_util_embeddertest.cpp +++ b/core/fpdfapi/parser/object_tree_traversal_util_embeddertest.cpp @@ -8,14 +8,18 @@ #include +#include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_null.h" #include "core/fpdfapi/parser/cpdf_parser.h" +#include "core/fpdfapi/parser/cpdf_reference.h" #include "testing/embedder_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using testing::UnorderedElementsAreArray; +using testing::ElementsAre; +using testing::UnorderedElementsAre; + using ObjectTreeTraversalUtilEmbedderTest = EmbedderTest; namespace { @@ -33,8 +37,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, GetObjectsWithReferencesBasic) { ASSERT_TRUE(OpenDocument("hello_world.pdf")); CPDF_Document* doc = GetCPDFDocument(document()); std::set referenced_objects = GetObjectsWithReferences(doc); - EXPECT_THAT(referenced_objects, - UnorderedElementsAreArray({1, 2, 3, 4, 5, 6})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(1, 2, 3, 4, 5, 6)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, GetObjectsWithReferencesNewDoc) { @@ -42,7 +45,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, GetObjectsWithReferencesNewDoc) { CPDF_Document* doc = GetCPDFDocument(new_doc.get()); std::set referenced_objects = GetObjectsWithReferences(doc); // Empty documents have a catalog and an empty pages object. - EXPECT_THAT(referenced_objects, UnorderedElementsAreArray({1, 2})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(1, 2)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -51,7 +54,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, CPDF_Document* doc = GetCPDFDocument(document()); std::set referenced_objects = GetObjectsWithReferences(doc); // The trailer points at a catalog, and the catalog only references itself. - EXPECT_THAT(referenced_objects, UnorderedElementsAreArray({1})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(1)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -62,7 +65,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, // The trailer is the dictionary inside /XRef object 16 0. Note that it // references object 3 0, but the rest of the document does not. EXPECT_THAT(referenced_objects, - UnorderedElementsAreArray({1, 2, 3, 4, 5, 12, 13, 14, 16})); + UnorderedElementsAre(1, 2, 3, 4, 5, 12, 13, 14, 16)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -70,7 +73,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, ASSERT_TRUE(OpenDocument("rectangles_object_zero.pdf")); CPDF_Document* doc = GetCPDFDocument(document()); std::set referenced_objects = GetObjectsWithReferences(doc); - EXPECT_THAT(referenced_objects, UnorderedElementsAreArray({1, 2, 3, 4})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(1, 2, 3, 4)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -102,7 +105,7 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, ASSERT_TRUE(OpenDocument("hello_world_2_pages.pdf")); CPDF_Document* doc = GetCPDFDocument(document()); std::set referenced_objects = GetObjectsWithMultipleReferences(doc); - EXPECT_THAT(referenced_objects, UnorderedElementsAreArray({5, 6, 7})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(5, 6, 7)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -113,14 +116,56 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, EXPECT_TRUE(referenced_objects.empty()); } +TEST_F(ObjectTreeTraversalUtilEmbedderTest, + GetObjectsWithMultipleReferencesDAGCrossEdge) { + ScopedFPDFDocument new_doc(FPDF_CreateNewDocument()); + CPDF_Document* doc = GetCPDFDocument(new_doc.get()); + + RetainPtr root = doc->GetMutableRoot(); + ASSERT_TRUE(root); + RetainPtr pages = root->GetMutableDictFor("Pages"); + ASSERT_TRUE(pages); + + auto obj4 = doc->NewIndirect(); + auto obj5 = doc->NewIndirect(); + auto obj6 = doc->NewIndirect(); + auto obj7 = doc->NewIndirect(); + + const uint32_t obj4_num = obj4->GetObjNum(); + const uint32_t obj5_num = obj5->GetObjNum(); + const uint32_t obj6_num = obj6->GetObjNum(); + const uint32_t obj7_num = obj7->GetObjNum(); + + ASSERT_EQ(4u, obj4_num); + ASSERT_EQ(5u, obj5_num); + ASSERT_EQ(6u, obj6_num); + ASSERT_EQ(7u, obj7_num); + + pages->SetNewFor("A", doc, obj4_num); + pages->SetNewFor("B", doc, obj5_num); + obj4->SetNewFor("A", doc, obj6_num); + obj5->SetNewFor("A", doc, obj7_num); + obj5->SetNewFor("B", doc, obj4_num); + + // Verify the extracted reference graph before pruning. + PdfReferenceGraph graph = BuildPdfReferenceGraphForTesting(doc); + EXPECT_THAT(graph.roots, ElementsAre(1u)); + EXPECT_THAT(graph.adj[2], ElementsAre(obj4_num, obj5_num)); + EXPECT_THAT(graph.adj[obj4_num], ElementsAre(obj6_num)); + EXPECT_THAT(graph.adj[obj5_num], ElementsAre(obj7_num, obj4_num)); + + // Verify the subsequent cycle pruning and multi-reference calculation. + std::set referenced_objects = GetObjectsWithMultipleReferences(doc); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(obj4_num)); +} + TEST_F(ObjectTreeTraversalUtilEmbedderTest, GetObjectsWithReferencesTrailerWithoutRoot) { ASSERT_TRUE(OpenDocument("hello_world.pdf")); CPDF_Document* doc = GetCPDFDocument(document()); doc->GetParser()->GetMutableTrailerForTesting()->SetNewFor("Root"); std::set referenced_objects = GetObjectsWithReferences(doc); - EXPECT_THAT(referenced_objects, - UnorderedElementsAreArray({1, 2, 3, 4, 5, 6})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(1, 2, 3, 4, 5, 6)); } TEST_F(ObjectTreeTraversalUtilEmbedderTest, @@ -129,5 +174,5 @@ TEST_F(ObjectTreeTraversalUtilEmbedderTest, CPDF_Document* doc = GetCPDFDocument(document()); doc->GetParser()->GetMutableTrailerForTesting()->SetNewFor("Root"); std::set referenced_objects = GetObjectsWithMultipleReferences(doc); - EXPECT_THAT(referenced_objects, UnorderedElementsAreArray({5, 6, 7})); + EXPECT_THAT(referenced_objects, UnorderedElementsAre(5, 6, 7)); } diff --git a/core/fpdfapi/parser/tree_traversal_util.cpp b/core/fpdfapi/parser/tree_traversal_util.cpp new file mode 100644 index 0000000000..4ee6fdcbcd --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util.cpp @@ -0,0 +1,123 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfapi/parser/tree_traversal_util.h" + +#include +#include + +#include +#include +#include +#include + +#include "core/fxcrt/check.h" +#include "core/fxcrt/check_op.h" +#include "core/fxcrt/containers/contains.h" +#include "core/fxcrt/raw_span.h" +#include "core/fxcrt/span.h" +#include "core/fxcrt/unowned_ptr.h" + +namespace pdfium { + +namespace { + +// Traverses an `AdjacencyMap` using iterative DFS, ignoring self-references and +// ancestor back-edges (cycles). +class DfsTraverser { + public: + DfsTraverser(pdfium::span roots, + const AdjacencyMap* adjacency_map) + : roots_(roots), adjacency_map_(adjacency_map) {} + + RefcountMap Calculate() { + for (NodeId root : roots_) { + ++ref_counts_[root]; + } + for (NodeId root : roots_) { + Traverse(root); + } + for (const auto& it : *adjacency_map_) { + Traverse(it.first); + } + return std::move(ref_counts_); + } + + private: + struct Frame { + NodeId node; + size_t child_index = 0; + }; + + bool IsOnStack(NodeId node) const { + return Contains(fast_lookup_for_stack_, node); + } + bool IsFullyVisited(NodeId node) const { + return Contains(fully_visited_, node); + } + + void Push(NodeId node) { + CHECK(!IsFullyVisited(node)); + CHECK(fast_lookup_for_stack_.insert(node).second); + stack_.push_back({node, 0}); + } + + void Pop() { + CHECK(!stack_.empty()); + const NodeId node = stack_.back().node; + stack_.pop_back(); + CHECK_EQ(fast_lookup_for_stack_.erase(node), 1u); + fully_visited_.insert(node); + } + + void Traverse(NodeId root) { + if (IsFullyVisited(root)) { + return; + } + Push(root); + + while (!stack_.empty()) { + const NodeId current_node = stack_.back().node; + const size_t current_child_index = stack_.back().child_index; + auto it = adjacency_map_->find(current_node); + if (it == adjacency_map_->end() || + current_child_index >= it->second.size()) { + Pop(); + continue; + } + + const NodeId child = it->second[current_child_index]; + stack_.back().child_index++; + if (child == current_node || IsOnStack(child)) { + // Self-reference or back-edge (cycle). + continue; + } + + ++ref_counts_[child]; + if (IsFullyVisited(child)) { + // Cross-edge or forward-edge in DAG: already explored. + continue; + } + + // Tree-edge: advance into unvisited node. + Push(child); + } + } + + pdfium::raw_span const roots_; + UnownedPtr const adjacency_map_; + std::vector stack_; + std::set fast_lookup_for_stack_; + std::set fully_visited_; + RefcountMap ref_counts_; +}; + +} // namespace + +RefcountMap CalculateReferenceCounts(pdfium::span roots, + const AdjacencyMap& adjacency_map) { + return DfsTraverser(roots, &adjacency_map).Calculate(); +} + +} // namespace pdfium diff --git a/core/fpdfapi/parser/tree_traversal_util.h b/core/fpdfapi/parser/tree_traversal_util.h new file mode 100644 index 0000000000..394a3c8e95 --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util.h @@ -0,0 +1,30 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ +#define CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ + +#include + +#include + +#include "core/fxcrt/data_vector.h" +#include "core/fxcrt/span.h" + +namespace pdfium { + +using NodeId = uint32_t; +using AdjacencyMap = std::map>; +using RefcountMap = std::map; + +// Given roots and an adjacency map of a directed graph, calculates reference +// counts for all reachable nodes while ignoring self-references and back-edges +// (cycles). Also traverses any remaining disconnected components in +// `adjacency_map`. +RefcountMap CalculateReferenceCounts(pdfium::span roots, + const AdjacencyMap& adjacency_map); + +} // namespace pdfium + +#endif // CORE_FPDFAPI_PARSER_TREE_TRAVERSAL_UTIL_H_ diff --git a/core/fpdfapi/parser/tree_traversal_util_unittest.cpp b/core/fpdfapi/parser/tree_traversal_util_unittest.cpp new file mode 100644 index 0000000000..bcf0b22e79 --- /dev/null +++ b/core/fpdfapi/parser/tree_traversal_util_unittest.cpp @@ -0,0 +1,99 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfapi/parser/tree_traversal_util.h" + +#include + +#include +#include + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using testing::ElementsAre; +using testing::Pair; + +namespace pdfium { + +TEST(TreeTraversalUtilTest, EmptyGraph) { + AdjacencyMap adj; + std::map counts = CalculateReferenceCounts({}, adj); + EXPECT_TRUE(counts.empty()); +} + +TEST(TreeTraversalUtilTest, SingleNodeRoot) { + AdjacencyMap adj; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1))); +} + +TEST(TreeTraversalUtilTest, DuplicateRoots) { + AdjacencyMap adj = {{1, {2}}}; + std::map counts = CalculateReferenceCounts({1, 1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 2), Pair(2, 1))); +} + +TEST(TreeTraversalUtilTest, SimpleTree) { + // 1 -> 2 + // 1 -> 3 + AdjacencyMap adj = {{1, {2, 3}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 1))); +} + +TEST(TreeTraversalUtilTest, DiamondDAGCrossEdge) { + // 1 -> 2, 3 + // 2 -> 4 + // 3 -> 4 + AdjacencyMap adj = {{1, {2, 3}}, {2, {4}}, {3, {4}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, + ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 1), Pair(4, 2))); +} + +TEST(TreeTraversalUtilTest, CycleIgnored) { + // 1 -> 2 -> 3 -> 2 + AdjacencyMap adj = {{1, {2}}, {2, {3}}, {3, {2}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 1))); +} + +TEST(TreeTraversalUtilTest, SelfLoopIgnored) { + // 1 -> 2 -> 2 + AdjacencyMap adj = {{1, {2}}, {2, {2}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1))); +} + +TEST(TreeTraversalUtilTest, ForwardEdge) { + // 1 -> 2 -> 3 + // 1 -> 3 + AdjacencyMap adj = {{1, {2, 3}}, {2, {3}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(3, 2))); +} + +TEST(TreeTraversalUtilTest, DeepLinearChainNoStackOverflow) { + // 1 -> 2 -> 3 -> ... -> 10000 + AdjacencyMap adj; + for (uint32_t i = 1; i < 10000; ++i) { + adj[i].push_back(i + 1); + } + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_EQ(10000u, counts.size()); + EXPECT_EQ(1, counts.at(1)); + EXPECT_EQ(1, counts.at(5000)); + EXPECT_EQ(1, counts.at(10000)); +} + +TEST(TreeTraversalUtilTest, DisconnectedComponent) { + // Root 1 -> 2 + // Disconnected 3 -> 4 + AdjacencyMap adj = {{1, {2}}, {3, {4}}}; + std::map counts = CalculateReferenceCounts({1}, adj); + EXPECT_THAT(counts, ElementsAre(Pair(1, 1), Pair(2, 1), Pair(4, 1))); +} + +} // namespace pdfium diff --git a/core/fpdfdoc/BUILD.gn b/core/fpdfdoc/BUILD.gn index 3d57cf9096..1d311120b0 100644 --- a/core/fpdfdoc/BUILD.gn +++ b/core/fpdfdoc/BUILD.gn @@ -165,6 +165,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_formfield_unittest.cpp", "cpdf_appearancegenerator_unittest.cpp", "cpdf_ink_curves_unittest.cpp", + "cpdf_iconfit_unittest.cpp", "cpdf_interactiveform_unittest.cpp", "cpdf_metadata_unittest.cpp", "cpdf_measure_unittest.cpp", @@ -172,6 +173,7 @@ pdfium_unittest_source_set("unittests") { "cpdf_richtextparser_unittest.cpp", "cpdf_nametree_unittest.cpp", "cpdf_pagelabel_unittest.cpp", + "cpvt_fontmap_unittest.cpp", "cpvt_section_unittest.cpp", "cpvt_stub_provider.cpp", "cpvt_stub_provider.h", diff --git a/core/fpdfdoc/cpdf_iconfit.cpp b/core/fpdfdoc/cpdf_iconfit.cpp index c09135d641..dfe87cf786 100644 --- a/core/fpdfdoc/cpdf_iconfit.cpp +++ b/core/fpdfdoc/cpdf_iconfit.cpp @@ -22,8 +22,6 @@ constexpr float kDefaultPosition = 0.5f; CPDF_IconFit::CPDF_IconFit(RetainPtr dict) : dict_(std::move(dict)) {} -CPDF_IconFit::CPDF_IconFit(const CPDF_IconFit& that) = default; - CPDF_IconFit::~CPDF_IconFit() = default; CPDF_IconFit::ScaleMethod CPDF_IconFit::GetScaleMethod() const { diff --git a/core/fpdfdoc/cpdf_iconfit.h b/core/fpdfdoc/cpdf_iconfit.h index 7aa20646b4..bc0bb49351 100644 --- a/core/fpdfdoc/cpdf_iconfit.h +++ b/core/fpdfdoc/cpdf_iconfit.h @@ -17,7 +17,8 @@ class CPDF_IconFit { enum class ScaleMethod { kAlways = 0, kBigger, kSmaller, kNever }; explicit CPDF_IconFit(RetainPtr dict); - CPDF_IconFit(const CPDF_IconFit& that); + CPDF_IconFit(const CPDF_IconFit&) = delete; + CPDF_IconFit& operator=(const CPDF_IconFit&) = delete; ~CPDF_IconFit(); ScaleMethod GetScaleMethod() const; diff --git a/core/fpdfdoc/cpdf_iconfit_unittest.cpp b/core/fpdfdoc/cpdf_iconfit_unittest.cpp new file mode 100644 index 0000000000..8917820682 --- /dev/null +++ b/core/fpdfdoc/cpdf_iconfit_unittest.cpp @@ -0,0 +1,188 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfdoc/cpdf_iconfit.h" + +#include "core/fpdfapi/parser/cpdf_array.h" +#include "core/fpdfapi/parser/cpdf_boolean.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_number.h" +#include "core/fpdfapi/parser/cpdf_string.h" +#include "core/fxcrt/fx_coordinates.h" +#include "testing/gtest/include/gtest/gtest.h" + +TEST(CPDFIconFitTest, NullDict) { + CPDF_IconFit icon_fit(nullptr); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + EXPECT_TRUE(icon_fit.IsProportionalScale()); + EXPECT_FALSE(icon_fit.GetFittingBounds()); + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 200.0f, 200.0f); + const CFX_VectorF scale = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(2.0f, scale.x); + EXPECT_FLOAT_EQ(2.0f, scale.y); + + const CFX_VectorF offset = icon_fit.GetImageOffset(image_size, scale, plate); + EXPECT_FLOAT_EQ(0.0f, offset.x); + EXPECT_FLOAT_EQ(0.0f, offset.y); +} + +TEST(CPDFIconFitTest, ScaleMethod) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "A"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "B"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kBigger, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "S"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kSmaller, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "N"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kNever, icon_fit.GetScaleMethod()); + + dict->SetNewFor("SW", "unknown"); + EXPECT_EQ(CPDF_IconFit::ScaleMethod::kAlways, icon_fit.GetScaleMethod()); +} + +TEST(CPDFIconFitTest, IsProportionalScale) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_TRUE(icon_fit.IsProportionalScale()); + + dict->SetNewFor("S", "P"); + EXPECT_TRUE(icon_fit.IsProportionalScale()); + + dict->SetNewFor("S", "A"); + EXPECT_FALSE(icon_fit.IsProportionalScale()); +} + +TEST(CPDFIconFitTest, GetFittingBounds) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_FALSE(icon_fit.GetFittingBounds()); + + dict->SetNewFor("FB", true); + EXPECT_TRUE(icon_fit.GetFittingBounds()); + + dict->SetNewFor("FB", false); + EXPECT_FALSE(icon_fit.GetFittingBounds()); +} + +TEST(CPDFIconFitTest, GetIconBottomLeftPosition) { + auto dict = pdfium::MakeRetain(); + CPDF_IconFit icon_fit(dict); + + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + auto arr = dict->SetNewFor("A"); + EXPECT_EQ(CFX_PointF(0.5f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + arr->AppendNew(0.25f); + EXPECT_EQ(CFX_PointF(0.25f, 0.5f), icon_fit.GetIconBottomLeftPosition()); + + arr->AppendNew(0.75f); + EXPECT_EQ(CFX_PointF(0.25f, 0.75f), icon_fit.GetIconBottomLeftPosition()); +} + +TEST(CPDFIconFitTest, GetScaleAlways) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "A"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 300.0f, 200.0f); + const CFX_VectorF scale_anamorphic = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(3.0f, scale_anamorphic.x); + EXPECT_FLOAT_EQ(4.0f, scale_anamorphic.y); + + dict->SetNewFor("S", "P"); // Proportional. + const CFX_VectorF scale_proportional = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(3.0f, scale_proportional.x); + EXPECT_FLOAT_EQ(3.0f, scale_proportional.y); + + // Clamping for zero/negative image dimension. + const CFX_VectorF scale_clamped = + icon_fit.GetScale(CFX_SizeF(0.0f, 0.0f), plate); + EXPECT_FLOAT_EQ(200.0f, scale_clamped.x); + EXPECT_FLOAT_EQ(200.0f, scale_clamped.y); +} + +TEST(CPDFIconFitTest, GetScaleBigger) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "B"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + // Plate smaller than image: scales down. + const CFX_SizeF large_image(400.0f, 200.0f); + const CFX_FloatRect small_plate(0.0f, 0.0f, 200.0f, 50.0f); + const CFX_VectorF scale_down = icon_fit.GetScale(large_image, small_plate); + EXPECT_FLOAT_EQ(0.5f, scale_down.x); + EXPECT_FLOAT_EQ(0.25f, scale_down.y); + + // Plate larger than image: remains 1.0f. + const CFX_FloatRect large_plate(0.0f, 0.0f, 800.0f, 400.0f); + const CFX_VectorF scale_none = icon_fit.GetScale(large_image, large_plate); + EXPECT_FLOAT_EQ(1.0f, scale_none.x); + EXPECT_FLOAT_EQ(1.0f, scale_none.y); +} + +TEST(CPDFIconFitTest, GetScaleSmaller) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "S"); + dict->SetNewFor("S", "A"); // Anamorphic. + CPDF_IconFit icon_fit(dict); + + // Plate larger than image: scales up. + const CFX_SizeF small_image(50.0f, 100.0f); + const CFX_FloatRect large_plate(0.0f, 0.0f, 200.0f, 300.0f); + const CFX_VectorF scale_up = icon_fit.GetScale(small_image, large_plate); + EXPECT_FLOAT_EQ(4.0f, scale_up.x); + EXPECT_FLOAT_EQ(3.0f, scale_up.y); + + // Plate smaller than image: remains 1.0f. + const CFX_FloatRect small_plate(0.0f, 0.0f, 25.0f, 50.0f); + const CFX_VectorF scale_none = icon_fit.GetScale(small_image, small_plate); + EXPECT_FLOAT_EQ(1.0f, scale_none.x); + EXPECT_FLOAT_EQ(1.0f, scale_none.y); +} + +TEST(CPDFIconFitTest, GetScaleNever) { + auto dict = pdfium::MakeRetain(); + dict->SetNewFor("SW", "N"); + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 500.0f, 500.0f); + const CFX_VectorF scale = icon_fit.GetScale(image_size, plate); + EXPECT_FLOAT_EQ(1.0f, scale.x); + EXPECT_FLOAT_EQ(1.0f, scale.y); +} + +TEST(CPDFIconFitTest, GetImageOffset) { + auto dict = pdfium::MakeRetain(); + auto arr = dict->SetNewFor("A"); + arr->AppendNew(0.5f); + arr->AppendNew(0.5f); + CPDF_IconFit icon_fit(dict); + + const CFX_SizeF image_size(100.0f, 50.0f); + const CFX_VectorF scale(1.0f, 1.0f); + const CFX_FloatRect plate(0.0f, 0.0f, 200.0f, 200.0f); + const CFX_VectorF offset = icon_fit.GetImageOffset(image_size, scale, plate); + // (200 - 100) * 0.5 = 50 + // (200 - 50) * 0.5 = 75 + EXPECT_FLOAT_EQ(50.0f, offset.x); + EXPECT_FLOAT_EQ(75.0f, offset.y); +} diff --git a/core/fpdfdoc/cpvt_fontmap_unittest.cpp b/core/fpdfdoc/cpvt_fontmap_unittest.cpp new file mode 100644 index 0000000000..cdadfdd70b --- /dev/null +++ b/core/fpdfdoc/cpvt_fontmap_unittest.cpp @@ -0,0 +1,86 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fpdfdoc/cpvt_fontmap.h" + +#include + +#include "core/fpdfapi/font/cpdf_font.h" +#include "core/fpdfapi/page/cpdf_pagemodule.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_test_document.h" +#include "core/fxcrt/retain_ptr.h" +#include "testing/gtest/include/gtest/gtest.h" + +class CPVT_FontMapTest : public testing::Test { + public: + void SetUp() override { + pdfium::InitializePageModule(); + test_doc_ = std::make_unique(); + test_doc_->SetRoot(pdfium::MakeRetain()); + def_font_ = CPDF_Font::GetStockFont(test_doc_.get(), "Helvetica"); + ASSERT_TRUE(def_font_); + } + + void TearDown() override { + def_font_.Reset(); + test_doc_.reset(); + pdfium::DestroyPageModule(); + } + + CPDF_TestDocument* doc() { return test_doc_.get(); } + RetainPtr def_font() { return def_font_; } + + private: + std::unique_ptr test_doc_; + RetainPtr def_font_; +}; + +TEST_F(CPVT_FontMapTest, DefaultFontAndBounds) { + CPVT_FontMap font_map(doc(), nullptr, def_font(), "Helvetica"); + + EXPECT_EQ(def_font(), font_map.GetPDFFont(0)); + EXPECT_EQ("Helvetica", font_map.GetPDFFontAlias(0)); + + EXPECT_FALSE(font_map.GetPDFFont(-1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(-1).IsEmpty()); + + EXPECT_FALSE(font_map.GetPDFFont(2)); + EXPECT_TRUE(font_map.GetPDFFontAlias(2).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, NullDocumentSysFont) { + auto res_dict = pdfium::MakeRetain(); + CPVT_FontMap font_map(nullptr, res_dict, def_font(), "Helvetica"); + + EXPECT_FALSE(font_map.GetPDFFont(1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(1).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, NullResDictSysFont) { + CPVT_FontMap font_map(doc(), nullptr, def_font(), "Helvetica"); + + EXPECT_FALSE(font_map.GetPDFFont(1)); + EXPECT_TRUE(font_map.GetPDFFontAlias(1).IsEmpty()); +} + +TEST_F(CPVT_FontMapTest, ValidResDictSysFont) { + auto res_dict = pdfium::MakeRetain(); + auto font_list = res_dict->SetNewFor("Font"); + CPVT_FontMap font_map(doc(), res_dict, def_font(), "Helvetica"); + + RetainPtr sys_font = font_map.GetPDFFont(1); + ByteString sys_alias = font_map.GetPDFFontAlias(1); + + if (sys_font) { + EXPECT_FALSE(sys_alias.IsEmpty()); + EXPECT_TRUE(font_list->KeyExist(sys_alias.AsStringView())); + + // Repeated calls return the cached system font and alias. + EXPECT_EQ(sys_font, font_map.GetPDFFont(1)); + EXPECT_EQ(sys_alias, font_map.GetPDFFontAlias(1)); + } else { + EXPECT_TRUE(sys_alias.IsEmpty()); + } +} diff --git a/core/fxcodec/BUILD.gn b/core/fxcodec/BUILD.gn index 022db12057..ab7cf9da67 100644 --- a/core/fxcodec/BUILD.gn +++ b/core/fxcodec/BUILD.gn @@ -256,10 +256,6 @@ source_set("fxcodec") { public_deps += [ "//third_party/libjpeg_turbo:libjpeg_headers" ] deps += [ "//third_party:jpeg" ] } - - if (pdf_use_libyuv) { - deps += [ "//third_party/libyuv" ] - } visibility = [ "../../*" ] } diff --git a/core/fxcodec/DEPS b/core/fxcodec/DEPS index 1e9528069f..0574db2f87 100644 --- a/core/fxcodec/DEPS +++ b/core/fxcodec/DEPS @@ -5,7 +5,4 @@ specific_include_rules = { "codec_memory_sk_stream_unittest\\.cpp": [ '+third_party/skia/include', ], - "fx_codec\\.cpp": [ - '+third_party/libyuv/include/libyuv/planar_functions.h', - ], } diff --git a/core/fxcodec/fax/faxmodule.cpp b/core/fxcodec/fax/faxmodule.cpp index 20418c37e1..a4c36c4e7b 100644 --- a/core/fxcodec/fax/faxmodule.cpp +++ b/core/fxcodec/fax/faxmodule.cpp @@ -596,7 +596,9 @@ class FaxDecoder final : public ScanlineDecoder { const int encoding_; uint32_t bitpos_ = 0; + // Set to `orig_encoded_byte_align_` in Rewind() before it gets read. bool byte_align_ = false; + const bool orig_encoded_byte_align_; const bool end_of_line_; const bool black_; const pdfium::raw_span src_span_; @@ -619,7 +621,7 @@ FaxDecoder::FaxDecoder(pdfium::span src_span, kFaxBpc, fxge::CalculatePitch32OrDie(kFaxBpc, width)), encoding_(K), - byte_align_(EncodedByteAlign), + orig_encoded_byte_align_(EncodedByteAlign), end_of_line_(EndOfLine), black_(BlackIs1), src_span_(src_span), @@ -634,6 +636,7 @@ FaxDecoder::~FaxDecoder() { bool FaxDecoder::Rewind() { std::ranges::fill(ref_buf_, 0xff); bitpos_ = 0; + byte_align_ = orig_encoded_byte_align_; return true; } diff --git a/core/fxcodec/fax/faxmodule_unittest.cpp b/core/fxcodec/fax/faxmodule_unittest.cpp index 673e14d755..61e7074dfc 100644 --- a/core/fxcodec/fax/faxmodule_unittest.cpp +++ b/core/fxcodec/fax/faxmodule_unittest.cpp @@ -12,12 +12,15 @@ #include "core/fxcodec/scanlinedecoder.h" #include "core/fxcrt/data_vector.h" #include "core/fxcrt/span.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace fxcodec { namespace { +using ::testing::ElementsAreArray; + // Real-world 44x46 1-D CCITT Group 3 encoded fax stream (containing 38 rows). constexpr uint8_t kFax1DData[] = { 0x26, 0xa0, 0x86, 0x80, 0xde, 0x08, 0x1e, 0x11, 0xe1, 0x87, 0x84, @@ -169,4 +172,28 @@ TEST(FaxModuleTest, Group4_FaxG4Decode) { EXPECT_LE(end_bitpos, sizeof(kFaxG4Data) * 8); } +TEST(FaxModuleTest, EncodedByteAlignRewind) { + // 4x2 1-D CCITT Group 3 stream with `EncodedByteAlign` enabled: + // - Byte 0 (0xb0 = 1011_0000): 4-bit white run of 4 (1011), padded with four + // zero bits to align to the next byte boundary. + // - Byte 1 (0x7f = 0111_11_11): 4-bit white run of 2 (0111) + 2-bit black run + // of 2 (11), followed by non-zero trailing bits (11) that clear + // `byte_align_`. + static constexpr uint8_t kInput[] = {0xb0, 0x7f}; + static constexpr uint8_t kExpectedRow0[] = {0xff, 0xff, 0xff, 0xff}; + static constexpr uint8_t kExpectedRow1[] = {0xcf, 0xff, 0xff, 0xff}; + + auto decoder = FaxModule::CreateDecoder( + kInput, /*width=*/4, /*height=*/2, /*K=*/0, /*EndOfLine=*/false, + /*EncodedByteAlign=*/true, /*BlackIs1=*/false, /*Columns=*/4, /*Rows=*/2); + ASSERT_TRUE(decoder); + + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow0)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow1)); + + // Reading scanline 0 again rewinds the decoder. + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow0)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow1)); +} + } // namespace fxcodec diff --git a/core/fxcodec/flate/flatemodule.cpp b/core/fxcodec/flate/flatemodule.cpp index 39f58a047a..a071d2f270 100644 --- a/core/fxcodec/flate/flatemodule.cpp +++ b/core/fxcodec/flate/flatemodule.cpp @@ -459,10 +459,6 @@ bool FlatePredictorScanlineDecoder::Rewind() { } left_over_ = 0; - // EmbedPDF(bug-fix): upstream kept the last decoded row across a rewind, so - // an image decoded again (drawn twice) came out corrupt. - // The first line predicts from zeros again, not from the last line decoded - // before the rewind. std::ranges::fill(last_line_.span(), 0); return true; } diff --git a/core/fxcodec/flate/flatemodule_unittest.cpp b/core/fxcodec/flate/flatemodule_unittest.cpp index 894eb09375..28157541c6 100644 --- a/core/fxcodec/flate/flatemodule_unittest.cpp +++ b/core/fxcodec/flate/flatemodule_unittest.cpp @@ -273,3 +273,25 @@ TEST(FlateModule, LZWDecode) { EXPECT_THAT(result.data, ElementsAreArray(kExpected)); EXPECT_EQ(5u, result.bytes_consumed); } + +TEST(FlateModule, CreateDecoderPngPredictorRewind) { + // 2x2 RGB image encoded with PNG Paeth filter (tag 4) on each row. + static constexpr uint8_t kRawInput[] = { + 4, 80, 140, 200, 0, 0, 0, // Row 0 + 4, 0, 0, 0, 0, 0, 0, // Row 1 + }; + static constexpr uint8_t kExpectedRow[] = {80, 140, 200, 80, 140, 200}; + + DataVector encoded = FlateModule::Encode(kRawInput); + std::unique_ptr decoder = FlateModule::CreateDecoder( + encoded, /*width=*/2, /*height=*/2, /*nComps=*/3, /*bpc=*/8, + /*predictor=*/15, /*Colors=*/3, /*BitsPerComponent=*/8, /*Columns=*/2); + ASSERT_TRUE(decoder); + + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow)); + + // Reading scanline 0 again rewinds the decoder. + EXPECT_THAT(decoder->GetScanline(0), ElementsAreArray(kExpectedRow)); + EXPECT_THAT(decoder->GetScanline(1), ElementsAreArray(kExpectedRow)); +} diff --git a/core/fxcodec/fx_codec.cpp b/core/fxcodec/fx_codec.cpp index ec182cc2f8..35537d5aa5 100644 --- a/core/fxcodec/fx_codec.cpp +++ b/core/fxcodec/fx_codec.cpp @@ -11,7 +11,7 @@ #include "core/fxge/dib/fx_dib.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "core/fxge/fx_libyuv_wrappers.h" #else #include @@ -51,14 +51,16 @@ void ReverseRGB(pdfium::span pDestBuf, auto dst_span = fxcrt::reinterpret_span>(pDestBuf).first(count); +#if defined(PDF_USE_LIBYUV) + const auto src_span = + fxcrt::reinterpret_span>(pSrcBuf).first( + count); + pdfium::RGB24ToRAWRow(src_span, dst_span); +#else const auto src_span = fxcrt::reinterpret_span>(pSrcBuf).first( count); -#if defined(PDF_USE_LIBYUV) - libyuv::RGB24ToRAW(pdfium::as_bytes(src_span).data(), 0, - pdfium::as_writable_bytes(dst_span).data(), 0, pixels, 1); -#else if (dst_span.data() == src_span.data()) { for (auto& pix : dst_span) { std::swap(pix.red, pix.blue); diff --git a/core/fxcrt/BUILD.gn b/core/fxcrt/BUILD.gn index 048b61b8dd..a302b79376 100644 --- a/core/fxcrt/BUILD.gn +++ b/core/fxcrt/BUILD.gn @@ -59,6 +59,7 @@ source_set("fxcrt") { "component_export.h", "containers/adapters.h", "containers/contains.h", + "containers/extend.h", "containers/to_vector.h", "containers/unique_ptr_adapters.h", "data_vector.h", @@ -263,6 +264,7 @@ pdfium_unittest_source_set("unittests") { "cfx_seekablestreamproxy_unittest.cpp", "cfx_timer_unittest.cpp", "code_point_view_unittest.cpp", + "containers/extend_unittest.cc", "containers/to_vector_unittest.cpp", "data_vector_unittest.cpp", "epdf_secure_random_unittest.cpp", diff --git a/core/fxcrt/containers/extend.h b/core/fxcrt/containers/extend.h new file mode 100644 index 0000000000..9617ecfe0e --- /dev/null +++ b/core/fxcrt/containers/extend.h @@ -0,0 +1,50 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FXCRT_CONTAINERS_EXTEND_H_ +#define CORE_FXCRT_CONTAINERS_EXTEND_H_ + +#include +#include +#include +#include +#include +#include + +// This is Chromium's base/containers/extend.h, adapted to work with PDFium's +// codebase with the following modifications: +// +// - Updated include guards. +// - Replaced namespace base with namespace pdfium. +// - Added template parameter `Alloc` to support `DataVector`. + +namespace pdfium { + +// Append to `dst` all elements of `src` by std::move-ing them out of `src`. +// After this operation, `src` will be empty. +template +void Extend(std::vector& dst, std::vector&& src) { + dst.insert(dst.end(), std::make_move_iterator(src.begin()), + std::make_move_iterator(src.end())); + src.clear(); +} + +// Appends `range` to `dst`, copying them out of `range`. +template + requires std::ranges::range && + std::indirectly_unary_invocable> +void Extend(std::vector& dst, Range&& range, Proj proj = {}) { + if constexpr (std::ranges::sized_range) { + dst.reserve(dst.size() + std::ranges::size(range)); + } + std::ranges::transform(std::forward(range), std::back_inserter(dst), + std::move(proj)); +} + +} // namespace pdfium + +#endif // CORE_FXCRT_CONTAINERS_EXTEND_H_ diff --git a/core/fxcrt/containers/extend_unittest.cc b/core/fxcrt/containers/extend_unittest.cc new file mode 100644 index 0000000000..1ae04c52bb --- /dev/null +++ b/core/fxcrt/containers/extend_unittest.cc @@ -0,0 +1,197 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxcrt/containers/extend.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "core/fxcrt/containers/adapters.h" +#include "core/fxcrt/data_vector.h" +#include "core/fxcrt/span.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace pdfium { + +namespace { + +using testing::ElementsAre; + +struct NonCopyable { + char c_; + explicit NonCopyable(char c) : c_(c) {} + NonCopyable(NonCopyable&&) = default; + NonCopyable& operator=(NonCopyable&& other) = default; + + NonCopyable(const NonCopyable&) = delete; + NonCopyable& operator=(const NonCopyable&) = delete; +}; + +bool operator==(const NonCopyable& a, const NonCopyable& b) { + return a.c_ == b.c_; +} + +static_assert(std::is_move_constructible_v, ""); +static_assert(!std::is_copy_constructible_v, ""); + +struct CopyableMovable { + bool copied_ = false; + char c_; + explicit CopyableMovable(char c) : c_(c) {} + CopyableMovable(const CopyableMovable& other) : copied_(true), c_(other.c_) {} + + CopyableMovable& operator=(const CopyableMovable&) = default; + CopyableMovable(CopyableMovable&&) = default; + CopyableMovable& operator=(CopyableMovable&& other) = default; +}; + +bool operator==(const CopyableMovable& a, const CopyableMovable& b) { + return a.c_ == b.c_; +} + +} // namespace + +TEST(ExtendTest, ExtendWithMove) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + Extend(dst, std::move(src)); + EXPECT_EQ(dst, expected); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) +} + +TEST(ExtendTest, ExtendCopyableWithMove) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + Extend(dst, std::move(src)); + EXPECT_EQ(dst, expected); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) +} + +TEST(ExtendTest, ExtendWithCopy) { + std::vector dst; + for (char c : {'a', 'b', 'c', 'd'}) { + dst.emplace_back(c); + } + std::vector src; + for (char c : {'e', 'f', 'g'}) { + src.emplace_back(c); + } + std::vector expected; + for (char c : {'a', 'b', 'c', 'd', 'e', 'f', 'g'}) { + expected.emplace_back(c); + } + + EXPECT_FALSE(dst[0].copied_); + Extend(dst, src); + EXPECT_EQ(dst, expected); + EXPECT_FALSE(dst[0].copied_); + EXPECT_TRUE(dst[dst.size() - 1].copied_); +} + +TEST(ExtendTest, ExtendWithSpan) { + static constexpr uint8_t kRawArray[] = {3, 4, 5}; + + static constexpr auto kVectorGenerator = []() -> std::vector { + return {9, 10, 11}; + }; + + const std::vector kConstVector = kVectorGenerator(); + std::vector kMutVector = kVectorGenerator(); + + std::vector dst; + + // Selects overload for span. + Extend(dst, span(kRawArray)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5)); + + // Selects overload for span. + static std::array kArray = {6, 7, 8}; + Extend(dst, span(kArray)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8)); + + // Selects overload for span. + Extend(dst, span(kConstVector)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11)); + + // Selects overload for span. + Extend(dst, span(kMutVector)); + EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11)); + + // Input is convertible to span. + Extend(dst, kRawArray); + EXPECT_THAT(dst, + ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11, 3, 4, 5)); +} + +TEST(ExtendTest, ExtendWithRanges) { + std::set set = {1, 2, 3}; + std::deque deque = {4, 5, 6}; + { + std::vector dst; + Extend(dst, Reversed(set)); + EXPECT_THAT(dst, ElementsAre(3, 2, 1)); + Extend(dst, Reversed(deque)); + EXPECT_THAT(dst, ElementsAre(3, 2, 1, 6, 5, 4)); + } + + { + std::vector dst; + Extend(dst, set, [](int val) { return -val; }); + EXPECT_THAT(dst, ElementsAre(-1, -2, -3)); + Extend(dst, deque, [](int val) { return val + 1; }); + EXPECT_THAT(dst, ElementsAre(-1, -2, -3, 5, 6, 7)); + } + + { + std::vector dst; + Extend(dst, Reversed(set), [](int val) { return val * val; }); + EXPECT_THAT(dst, ElementsAre(9, 4, 1)); + Extend(dst, Reversed(deque), [](int val) { return val - 1; }); + EXPECT_THAT(dst, ElementsAre(9, 4, 1, 5, 4, 3)); + } +} + +TEST(ExtendTest, ExtendDataVector) { + DataVector dst = {1, 2, 3}; + DataVector src = {4, 5}; + Extend(dst, std::move(src)); + EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); + EXPECT_TRUE(src.empty()); // NOLINT(bugprone-use-after-move) + + static constexpr int kArray[] = {6, 7}; + Extend(dst, kArray, [](int val) { return val * 10; }); + EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5, 60, 70)); +} + +} // namespace pdfium diff --git a/core/fxcrt/css/BUILD.gn b/core/fxcrt/css/BUILD.gn index c7939ce188..734b8436d2 100644 --- a/core/fxcrt/css/BUILD.gn +++ b/core/fxcrt/css/BUILD.gn @@ -66,6 +66,7 @@ pdfium_unittest_source_set("unittests") { sources = [ "cfx_cssdata_unittest.cpp", "cfx_cssdeclaration_unittest.cpp", + "cfx_cssstyleselector_unittest.cpp", "cfx_cssstylesheet_unittest.cpp", "cfx_csssyntaxparser_unittest.cpp", "cfx_cssvaluelistparser_unittest.cpp", diff --git a/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp b/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp index 31f2542455..c6b6cb4556 100644 --- a/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp +++ b/core/fxcrt/css/cfx_cssdeclaration_unittest.cpp @@ -61,6 +61,79 @@ TEST(CFXCSSDeclarationTest, RGBEncodingParsing) { EXPECT_EQ(0xFF80FF30u, maybe_color.value()); } +TEST(CFXCSSDeclarationTest, NamedColorParsing) { + std::optional maybe_color = + CFX_CSSDeclaration::ParseCSSColor(L"red"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFFFF0000u, maybe_color.value()); + + maybe_color = CFX_CSSDeclaration::ParseCSSColor(L"green"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFF008000u, maybe_color.value()); + + maybe_color = CFX_CSSDeclaration::ParseCSSColor(L"blue"); + ASSERT_TRUE(maybe_color.has_value()); + EXPECT_EQ(0xFF0000FFu, maybe_color.value()); + + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSColor(L"notacolor")); +} + +TEST(CFXCSSDeclarationTest, ParseCSSString) { + EXPECT_EQ(L"Double Quoted", + CFX_CSSDeclaration::ParseCSSString(L"\"Double Quoted\"")); + EXPECT_EQ(L"Single Quoted", + CFX_CSSDeclaration::ParseCSSString(L"'Single Quoted'")); + EXPECT_EQ(L"Unquoted", CFX_CSSDeclaration::ParseCSSString(L"Unquoted")); + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSString(L"\"\"").has_value()); + EXPECT_FALSE(CFX_CSSDeclaration::ParseCSSString(L"").has_value()); +} + +TEST(CFXCSSDeclarationTest, AddProperty) { + CFX_CSSDeclaration decl; + EXPECT_TRUE(decl.empty()); + + bool important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::Color), + L"red"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::Color, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontSize), + L"16pt !important"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontSize, &important)); + EXPECT_TRUE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontStyle), + L"italic"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontStyle, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::FontWeight), + L"bold"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::FontWeight, &important)); + EXPECT_FALSE(important); + + important = false; + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::TextAlign), + L"center"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::TextAlign, &important)); + EXPECT_FALSE(important); + + decl.AddProperty(CFX_CSSData::GetPropertyByEnum(CFX_CSSProperty::Border), + L"1px"); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderLeftWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderTopWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderRightWidth, &important)); + EXPECT_TRUE(decl.GetProperty(CFX_CSSProperty::BorderBottomWidth, &important)); + + decl.AddProperty(L"--custom", L"custom_value"); + EXPECT_FALSE(decl.empty()); + EXPECT_EQ(1, std::distance(decl.custom_begin(), decl.custom_end())); +} + TEST(CFXCSSDeclarationTest, CustomPropertiesInInlineStyle) { CFX_CSSStyleSelector selector; RetainPtr style = selector.CreateComputedStyle(nullptr); diff --git a/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp b/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp new file mode 100644 index 0000000000..9a3d168db8 --- /dev/null +++ b/core/fxcrt/css/cfx_cssstyleselector_unittest.cpp @@ -0,0 +1,87 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxcrt/css/cfx_cssstyleselector.h" + +#include +#include +#include + +#include "core/fxcrt/css/cfx_csscomputedstyle.h" +#include "core/fxcrt/css/cfx_cssdeclaration.h" +#include "core/fxcrt/css/cfx_cssstylerule.h" +#include "core/fxcrt/css/cfx_cssstylesheet.h" +#include "core/fxcrt/retain_ptr.h" +#include "core/fxcrt/widestring.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +TEST(CFXCSSStyleSelectorTest, DefaultFontSize) { + CFX_CSSStyleSelector selector; + selector.SetDefaultFontSize(18.0f); + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle({}, L"font-size: medium", L"", style.Get()); + EXPECT_FLOAT_EQ(18.0f, style->GetFontSize()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleInline) { + CFX_CSSStyleSelector selector; + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle( + {}, L"color: red; font-size: 20pt; text-align: right; font-style: italic", + L"", style.Get()); + + EXPECT_EQ(0xFFFF0000u, style->GetColor()); + EXPECT_EQ(CFX_CSSTextAlign::Right, style->GetTextAlign()); + EXPECT_EQ(CFX_CSSFontStyle::Italic, style->GetFontStyle()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleWithAlignString) { + CFX_CSSStyleSelector selector; + RetainPtr style = selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(style); + selector.ComputeStyle({}, L"", L"center", style.Get()); + EXPECT_EQ(CFX_CSSTextAlign::Center, style->GetTextAlign()); + + selector.ComputeStyle({}, L"", L"justify", style.Get()); + EXPECT_EQ(CFX_CSSTextAlign::Justify, style->GetTextAlign()); +} + +TEST(CFXCSSStyleSelectorTest, ComputeStyleInheritance) { + CFX_CSSStyleSelector selector; + RetainPtr parent_style = + selector.CreateComputedStyle(nullptr); + ASSERT_TRUE(parent_style); + selector.ComputeStyle({}, L"color: #0000ff; font-weight: bold", L"", + parent_style.Get()); + + RetainPtr child_style = + selector.CreateComputedStyle(parent_style.Get()); + ASSERT_TRUE(child_style); + selector.ComputeStyle({}, L"", L"", child_style.Get()); + + // Inherited properties should match parent. + EXPECT_EQ(0xFF0000FFu, child_style->GetColor()); + EXPECT_EQ(700, child_style->GetFontWeight()); +} + +TEST(CFXCSSStyleSelectorTest, MatchDeclarationsWithUAStyleSheet) { + CFX_CSSStyleSelector selector; + auto sheet = std::make_unique(); + EXPECT_TRUE(sheet->LoadBuffer(L"p { color: blue; } h1 { font-size: 24pt; }")); + ASSERT_EQ(2u, sheet->CountRules()); + ASSERT_TRUE(sheet->GetRule(0)); + ASSERT_TRUE(sheet->GetRule(1)); + const CFX_CSSDeclaration* p_decl = sheet->GetRule(0)->GetDeclaration(); + const CFX_CSSDeclaration* h1_decl = sheet->GetRule(1)->GetDeclaration(); + + selector.SetUAStyleSheet(std::move(sheet)); + selector.UpdateStyleIndex(); + + EXPECT_THAT(selector.MatchDeclarations(L"p"), testing::ElementsAre(p_decl)); + EXPECT_THAT(selector.MatchDeclarations(L"h1"), testing::ElementsAre(h1_decl)); + EXPECT_THAT(selector.MatchDeclarations(L"unknown_tag"), testing::IsEmpty()); +} diff --git a/core/fxcrt/fx_unicode.cpp b/core/fxcrt/fx_unicode.cpp index 180f46cf15..803951116c 100644 --- a/core/fxcrt/fx_unicode.cpp +++ b/core/fxcrt/fx_unicode.cpp @@ -8,16 +8,14 @@ #include -#include +#include #include -#include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" -#include "core/fxcrt/compiler_specific.h" namespace { -// Format of uint16_t values in kTextLayoutCodeProperties[]. +// Format of uint16_t values in `kTextLayoutCodeProperties`. constexpr uint16_t kBidiClassBitPos = 0; constexpr uint16_t kBidiClassBitCount = 5; constexpr uint16_t kBidiClassBitMask = @@ -31,20 +29,17 @@ constexpr uint16_t kMirrorMax = (1 << kMirrorBitCount) - 1; #define CHARPROP____(mirror, ct, bd, bt) \ ((mirror << kMirrorBitPos) | \ (static_cast(BidiClass::bd) << kBidiClassBitPos)), -constexpr uint16_t kTextLayoutCodeProperties[] = { +constexpr auto kTextLayoutCodeProperties = std::to_array({ #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) -}; +}); #undef CHARPROP____ -static_assert(std::size(kTextLayoutCodeProperties) == 65536, - "missing characters"); +static_assert(kTextLayoutCodeProperties.size() == 65536, "missing characters"); std::optional GetUnicodeProperties(wchar_t wch) { size_t idx = static_cast(wch); - if (idx < std::size(kTextLayoutCodeProperties)) { - // SAFETY: `std::size(kTextLayoutCodeProperties)` is the size of the table, - // so the condition above verifies `idx` is in range. - return UNSAFE_BUFFERS(kTextLayoutCodeProperties[idx]); + if (idx < kTextLayoutCodeProperties.size()) { + return kTextLayoutCodeProperties[idx]; } return std::nullopt; } @@ -52,7 +47,7 @@ std::optional GetUnicodeProperties(wchar_t wch) { // EmbedPDF(rich-text): the extended table is compiled unconditionally (rich // text line breaking in core/fpdfdoc reads the break property); it used to be // XFA-only. -// Format of uint16_t values in kExtendedTextLayoutCodeProperties[]. +// Format of uint16_t values in `kExtendedTextLayoutCodeProperties`. constexpr uint16_t kBreakTypeBitPos = 0; constexpr uint16_t kBreakTypeBitCount = 6; constexpr uint16_t kBreakTypeBitMask = @@ -67,26 +62,24 @@ constexpr uint16_t kCharTypeBitMask = #define CHARPROP____(mirror, ct, bd, bt) \ ((static_cast(CharType::ct) << kCharTypeBitPos) | \ (static_cast(BreakProperty::bt) << kBreakTypeBitPos)), -constexpr uint16_t kExtendedTextLayoutCodeProperties[] = { +constexpr auto kExtendedTextLayoutCodeProperties = std::to_array({ #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) -}; +}); #undef CHARPROP____ -static_assert(std::size(kExtendedTextLayoutCodeProperties) == 65536, +static_assert(kExtendedTextLayoutCodeProperties.size() == 65536, "missing characters"); uint16_t GetExtendedUnicodeProperties(wchar_t wch) { size_t idx = static_cast(wch); - if (idx < std::size(kExtendedTextLayoutCodeProperties)) { - // SAFETY: `std::size(kExtendedTextLayoutCodeProperties)` is the size of - // the table, so the condition above verifies `idx` is in range. - return UNSAFE_BUFFERS(kExtendedTextLayoutCodeProperties[idx]); + if (idx < kExtendedTextLayoutCodeProperties.size()) { + return kExtendedTextLayoutCodeProperties[idx]; } return 0; } // EmbedPDF(rich-text): the PDF_ENABLE_XFA guard ended here; see above. -constexpr uint16_t kFXTextLayoutBidiMirror[] = { +constexpr auto kFXTextLayoutBidiMirror = std::to_array({ 0x0029, 0x0028, 0x003E, 0x003C, 0x005D, 0x005B, 0x007D, 0x007B, 0x00BB, 0x00AB, 0x0F3B, 0x0F3A, 0x0F3D, 0x0F3C, 0x169C, 0x169B, 0x2019, 0x2018, 0x201D, 0x201C, 0x203A, 0x2039, 0x2046, 0x2045, 0x207E, 0x207D, 0x208E, @@ -128,13 +121,13 @@ constexpr uint16_t kFXTextLayoutBidiMirror[] = { 0x3019, 0x3018, 0x301B, 0x301A, 0xFE5A, 0xFE59, 0xFE5C, 0xFE5B, 0xFE5E, 0xFE5D, 0xFE65, 0xFE64, 0xFF09, 0xFF08, 0xFF1E, 0xFF1C, 0xFF3D, 0xFF3B, 0xFF5D, 0xFF5B, 0xFF60, 0xFF5F, 0xFF63, 0xFF62, -}; +}); // Check that the mirror indicies in the fx_ucddata.inc table are in bounds. #undef CHARPROP____ -#define CHARPROP____(mirror, ct, bd, bt) \ - static_assert( \ - mirror == kMirrorMax || mirror < std::size(kFXTextLayoutBidiMirror), \ +#define CHARPROP____(mirror, ct, bd, bt) \ + static_assert( \ + mirror == kMirrorMax || mirror < kFXTextLayoutBidiMirror.size(), \ "Bad mirror index"); #include "core/fxcrt/fx_ucddata.inc" // NOLINT(build/include) #undef CHARPROP____ @@ -152,10 +145,7 @@ wchar_t GetMirrorChar(wchar_t wch) { if (idx == kMirrorMax) { return wch; } - CHECK_LT(idx, std::size(kFXTextLayoutBidiMirror)); - // SAFETY: `std::size(kFXTextLayoutBidiMirror)` is the size of the table, so - // the CHECK() above verifies `idx` is in range. - return UNSAFE_BUFFERS(kFXTextLayoutBidiMirror[idx]); + return kFXTextLayoutBidiMirror[idx]; } BidiClass GetBidiClass(wchar_t wch) { diff --git a/core/fxcrt/xml/cfx_xmlparser_unittest.cpp b/core/fxcrt/xml/cfx_xmlparser_unittest.cpp index 98235cf4c5..173ec2ca12 100644 --- a/core/fxcrt/xml/cfx_xmlparser_unittest.cpp +++ b/core/fxcrt/xml/cfx_xmlparser_unittest.cpp @@ -355,3 +355,24 @@ TEST_F(CFXXMLParserTest, BadEntity) { ""; ASSERT_TRUE(Parse(input) == nullptr); } + +TEST_F(CFXXMLParserTest, EmptyInput) { + std::unique_ptr doc = Parse(""); + ASSERT_TRUE(doc); + EXPECT_FALSE(doc->GetRoot()->GetFirstChild()); +} + +TEST_F(CFXXMLParserTest, InvalidTagNames) { + EXPECT_FALSE(Parse("<1tag>")); + EXPECT_FALSE(Parse("")); + EXPECT_FALSE(Parse("")); +} + +TEST_F(CFXXMLParserTest, InstructionWithQuestionMarks) { + constexpr char kInput[] = ""; + std::unique_ptr doc = Parse(kInput); + ASSERT_TRUE(doc); + CFX_XMLNode* first = doc->GetRoot()->GetFirstChild(); + ASSERT_TRUE(first); + EXPECT_EQ(CFX_XMLNode::Type::kInstruction, first->GetType()); +} diff --git a/core/fxge/BUILD.gn b/core/fxge/BUILD.gn index c844592e3b..c452174e40 100644 --- a/core/fxge/BUILD.gn +++ b/core/fxge/BUILD.gn @@ -242,6 +242,10 @@ source_set("fxge") { } if (pdf_use_libyuv) { + sources += [ + "fx_libyuv_wrappers.cpp", + "fx_libyuv_wrappers.h", + ] deps += [ "//third_party/libyuv" ] } diff --git a/core/fxge/DEPS b/core/fxge/DEPS index a25eb15df4..2bc5955849 100644 --- a/core/fxge/DEPS +++ b/core/fxge/DEPS @@ -1,5 +1,10 @@ include_rules = [ - '+third_party/libyuv/include', '+third_party/rust', '+third_party/skia/include', ] + +specific_include_rules = { + "fx_libyuv_wrappers\\.cpp": [ + '+third_party/libyuv/include', + ], +} diff --git a/core/fxge/cfx_renderdevice.cpp b/core/fxge/cfx_renderdevice.cpp index 895f4eb83c..763c250def 100644 --- a/core/fxge/cfx_renderdevice.cpp +++ b/core/fxge/cfx_renderdevice.cpp @@ -342,8 +342,8 @@ bool CheckSimpleLinePath(pdfium::span points, point = matrix->Transform(point); } - point = CFX_PointF(static_cast(point.x) + 0.5f, - static_cast(point.y) + 0.5f); + point = CFX_PointF(pdfium::saturated_cast(point.x) + 0.5f, + pdfium::saturated_cast(point.y) + 0.5f); } new_path->AppendPoint(point, points[i].type_); } diff --git a/core/fxge/cfx_renderdevice_unittest.cpp b/core/fxge/cfx_renderdevice_unittest.cpp index c2fb7b2c99..472ef5cf6c 100644 --- a/core/fxge/cfx_renderdevice_unittest.cpp +++ b/core/fxge/cfx_renderdevice_unittest.cpp @@ -108,6 +108,23 @@ TEST(CFXRenderDeviceTest, GetClipBoxRect) { EXPECT_EQ(FX_RECT(2, 4, 14, 12), device->GetClipBox()); } +// Regression test for b/582306045: CheckSimpleLinePath should not trigger +// float-cast-overflow when path points have large coordinate values. +TEST(CFXRenderDeviceTest, DrawPathSimpleLineLargeCoordinates) { + std::unique_ptr device = CreateDeviceForBitmap(16, 16); + ASSERT_TRUE(device); + + CFX_Path path; + path.AppendPoint(CFX_PointF(1e12f, 1e12f), CFX_Path::Point::Type::kMove); + path.AppendPoint(CFX_PointF(1e12f, 1e12f + 10.0f), + CFX_Path::Point::Type::kLine); + + const CFX_FillRenderOptions fill_options( + CFX_FillRenderOptions::FillType::kWinding); + EXPECT_TRUE(device->DrawPath(path, nullptr, nullptr, 0xFF000000, 0, + fill_options)); +} + TEST(CFXRenderDeviceTest, GetClipBoxEmpty) { std::unique_ptr device = CreateDeviceForBitmap(16, 16); ASSERT_TRUE(device); diff --git a/core/fxge/dib/cfx_dibbase.cpp b/core/fxge/dib/cfx_dibbase.cpp index 39a5744de4..26a03a95cd 100644 --- a/core/fxge/dib/cfx_dibbase.cpp +++ b/core/fxge/dib/cfx_dibbase.cpp @@ -30,11 +30,7 @@ #include "core/fxge/dib/cfx_imagetransformer.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" -#include "third_party/libyuv/include/libyuv/convert_from_argb.h" -#include "third_party/libyuv/include/libyuv/planar_functions.h" -#include "third_party/libyuv/include/libyuv/rotate.h" -#include "third_party/libyuv/include/libyuv/rotate_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -49,21 +45,19 @@ void ConvertBuffer_RgbToArgbPremul( #if defined(PDF_USE_LIBYUV) pdfium::span src_buffer = src_bitmap->GetBuffer(); if (!src_buffer.empty()) { - libyuv::RGB24ToARGB(src_buffer.data(), src_bitmap->GetPitch(), - dest_buf.data(), dest_pitch, width, height); + pdfium::RGB24ToARGB(src_buffer, src_bitmap->GetPitch(), dest_buf, + dest_pitch, width, height); return; } +#endif - for (int row = 0; row < height; ++row) { - auto dest_span = dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch)); - auto src_span = src_bitmap->GetScanline(row); - libyuv::RGB24ToARGB(src_span.data(), 0, dest_span.data(), 0, width, 1); - } -#else for (int row = 0; row < height; ++row) { auto dest_span = fxcrt::reinterpret_span>( dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch))); auto src_span = src_bitmap->GetScanlineAs>(row); +#if defined(PDF_USE_LIBYUV) + pdfium::RGB24ToARGBRow(src_span, dest_span); +#else for (auto [input, output] : fxcrt::Zip(src_span, dest_span)) { // Avoid interleaved load/stores. const uint8_t blue = input.blue; @@ -74,8 +68,8 @@ void ConvertBuffer_RgbToArgbPremul( output.red = red; output.alpha = 255; } - } #endif + } } void ConvertBuffer_ArgbPremulToRgb( @@ -432,19 +426,23 @@ void ConvertBuffer_32bppRgbToRgb24( #if defined(PDF_USE_LIBYUV) pdfium::span src_buffer = pSrcBitmap->GetBuffer(); if (!src_buffer.empty()) { - libyuv::ARGBToRGB24(src_buffer.data(), pSrcBitmap->GetPitch(), - dest_buf.data(), dest_pitch, width, height); + pdfium::ARGBToRGB24(src_buffer, pSrcBitmap->GetPitch(), dest_buf, + dest_pitch, width, height); return; } #endif for (int row = 0; row < height; ++row) { - uint8_t* dest_scan = - dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch)).data(); - const uint8_t* src_scan = pSrcBitmap->GetScanline(row).data(); + auto dest_span = fxcrt::reinterpret_span>( + dest_buf.subspan(Fx2DSizeOrDie(row, dest_pitch))); + auto src_span = + pSrcBitmap->GetScanlineAs>(row).first( + static_cast(width)); #if defined(PDF_USE_LIBYUV) - libyuv::ARGBToRGB24(src_scan, 0, dest_scan, 0, width, 1); + pdfium::ARGBToRGB24Row(src_span, dest_span); #else + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); UNSAFE_TODO({ for (int col = 0; col < width; ++col) { FXSYS_memcpy(dest_scan, src_scan, 3); @@ -875,9 +873,9 @@ RetainPtr CFX_DIBBase::CloneAlphaMask() const { } #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::ARGBExtractAlpha(GetBuffer().data(), GetPitch(), - pMask->GetWritableBuffer().data(), + pdfium::span src_buffer = GetBuffer(); + if (!src_buffer.empty()) { + pdfium::ARGBExtractAlpha(src_buffer, GetPitch(), pMask->GetWritableBuffer(), pMask->GetPitch(), GetWidth(), GetHeight()); return pMask; } @@ -885,9 +883,8 @@ RetainPtr CFX_DIBBase::CloneAlphaMask() const { for (int row = 0; row < GetHeight(); ++row) { #if defined(PDF_USE_LIBYUV) - libyuv::ARGBExtractAlpha(GetScanline(row).data(), 0, - pMask->GetWritableScanline(row).data(), 0, - GetWidth(), 1); + pdfium::ARGBExtractAlphaRow(GetScanlineAs>(row), + pMask->GetWritableScanlineAs(row)); #else const uint8_t* src_scan = GetScanline(row).subspan<3u>().data(); uint8_t* dest_scan = pMask->GetWritableScanline(row).data(); @@ -943,11 +940,13 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { return pFlipped; } +#if defined(PDF_USE_LIBYUV) + pdfium::span src_buffer = GetBuffer(); +#endif if (bytes_per_pixel == 1) { #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::MirrorPlane(GetBuffer().data(), GetPitch(), - pFlipped->GetWritableBuffer().data(), + if (!src_buffer.empty()) { + pdfium::MirrorPlane(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); return pFlipped; @@ -955,14 +954,15 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs(row); + auto dest_span = pFlipped->GetWritableScanlineAs( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::MirrorPlane(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::MirrorPlaneRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = src_span.data(); + uint8_t* dest_scan = dest_span.data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { *dest_scan = *src_scan; @@ -977,9 +977,8 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { if (bytes_per_pixel == 3) { #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::RGB24Mirror(GetBuffer().data(), GetPitch(), - pFlipped->GetWritableBuffer().data(), + if (!src_buffer.empty()) { + pdfium::RGB24Mirror(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); return pFlipped; @@ -987,14 +986,15 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs>(row); + auto dest_span = pFlipped->GetWritableScanlineAs>( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::RGB24Mirror(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::RGB24MirrorRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { FXSYS_memcpy(dest_scan, src_scan, 3); @@ -1009,23 +1009,24 @@ RetainPtr CFX_DIBBase::FlipImage(bool bXFlip, bool bYFlip) const { CHECK_EQ(bytes_per_pixel, 4); #if defined(PDF_USE_LIBYUV) - if (!GetBuffer().empty()) { - libyuv::ARGBMirror( - GetBuffer().data(), GetPitch(), pFlipped->GetWritableBuffer().data(), - pFlipped->GetPitch(), GetWidth(), bYFlip ? -GetHeight() : GetHeight()); + if (!src_buffer.empty()) { + pdfium::ARGBMirror(src_buffer, GetPitch(), pFlipped->GetWritableBuffer(), + pFlipped->GetPitch(), GetWidth(), + bYFlip ? -GetHeight() : GetHeight()); return pFlipped; } #endif for (int row = 0; row < GetHeight(); ++row) { - const uint8_t* src_scan = GetScanline(row).data(); - uint8_t* dest_scan = - pFlipped->GetWritableScanline(bYFlip ? GetHeight() - row - 1 : row) - .data(); + auto src_span = GetScanlineAs>(row); + auto dest_span = pFlipped->GetWritableScanlineAs>( + bYFlip ? GetHeight() - row - 1 : row); #if defined(PDF_USE_LIBYUV) - libyuv::ARGBMirror(src_scan, 0, dest_scan, 0, GetWidth(), 1); + pdfium::ARGBMirrorRow(src_span, dest_span); #else UNSAFE_TODO({ + const uint8_t* src_scan = pdfium::as_bytes(src_span).data(); + uint8_t* dest_scan = pdfium::as_writable_bytes(dest_span).data(); dest_scan += (GetWidth() - 1) * bytes_per_pixel; for (int col = 0; col < GetWidth(); ++col) { const auto* src_scan32 = reinterpret_cast(src_scan); @@ -1114,19 +1115,16 @@ RetainPtr CFX_DIBBase::SwapXY(bool bXFlip, bool bYFlip) const { pdfium::span src_buffer = GetBuffer(); if (!src_buffer.empty()) { const int height = bXFlip == bYFlip ? -GetHeight() : GetHeight(); - const libyuv::RotationMode mode = - bYFlip ? libyuv::kRotate270 : libyuv::kRotate90; + const pdfium::RotationMode mode = + bYFlip ? pdfium::kRotate270 : pdfium::kRotate90; if (bytes_per_pixel == 1) { - if (libyuv::RotatePlane(src_buffer.data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), height, mode) == 0) { - return pTransBitmap; - } + pdfium::RotatePlane(src_buffer, GetPitch(), dest_span, dest_pitch, + GetWidth(), height, mode); } else { - if (libyuv::ARGBRotate(src_buffer.data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), height, mode) == 0) { - return pTransBitmap; - } + pdfium::ARGBRotate(src_buffer, GetPitch(), dest_span, dest_pitch, + GetWidth(), height, mode); } + return pTransBitmap; } } #endif diff --git a/core/fxge/dib/cfx_dibitmap.cpp b/core/fxge/dib/cfx_dibitmap.cpp index 6bc06c7e61..6d63bc7d6b 100644 --- a/core/fxge/dib/cfx_dibitmap.cpp +++ b/core/fxge/dib/cfx_dibitmap.cpp @@ -29,8 +29,7 @@ #include "core/fxge/dib/cfx_scanlinecompositor.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" -#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -352,8 +351,8 @@ bool CFX_DIBitmap::MultiplyAlphaMask(RetainPtr mask) { // `FXDIB_Format::kBgraPremul` #if defined(PDF_USE_LIBYUV) SetFormat(FXDIB_Format::kBgra); - libyuv::ARGBCopyYToAlpha(mask->GetBuffer().data(), mask->GetPitch(), - GetWritableBuffer().data(), GetPitch(), GetWidth(), + pdfium::ARGBCopyYToAlpha(mask->GetBuffer(), mask->GetPitch(), + GetWritableBuffer(), GetPitch(), GetWidth(), GetHeight()); #else if (!ConvertFormat(FXDIB_Format::kBgra)) { @@ -1011,8 +1010,8 @@ bool CFX_DIBitmap::ConvertFormat(FXDIB_Format dest_format) { const uint32_t dest_pitch = pitch_size.value().pitch; #if defined(PDF_USE_LIBYUV) if (dest_format == FXDIB_Format::kBgra && GetFormat() == FXDIB_Format::kBgr) { - libyuv::RGB24ToARGB(GetBuffer().data(), GetPitch(), dest_span.data(), - dest_pitch, GetWidth(), GetHeight()); + pdfium::RGB24ToARGB(GetBuffer(), GetPitch(), dest_span, dest_pitch, + GetWidth(), GetHeight()); palette_.clear(); } else { #endif diff --git a/core/fxge/dib/cfx_scanlinecompositor.cpp b/core/fxge/dib/cfx_scanlinecompositor.cpp index b3f255951c..6d888c1c6e 100644 --- a/core/fxge/dib/cfx_scanlinecompositor.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor.cpp @@ -23,7 +23,7 @@ #include "core/fxge/dib/fx_dib.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif #if defined(PDF_USE_SKIA) @@ -189,6 +189,11 @@ void CompositePixelBgra2Mask(const FX_BGRA_STRUCT& input, void CompositeRowBgra2Mask(pdfium::span> src_span, pdfium::span clip_span, pdfium::span dest_span) { + // Short rows do not consistently amortize SIMD dispatch and tail handling. + if (src_span.size() >= 128) { + CompositeRowBgra2MaskSimd(src_span, clip_span, dest_span); + return; + } if (clip_span.empty()) { for (auto [input, output] : fxcrt::Zip(src_span, dest_span)) { CompositePixelBgra2Mask(input, /*clip=*/255, output); @@ -449,14 +454,17 @@ void CompositeRow_Bgr2Bgra_NoBlend_NoClip( fxcrt::reinterpret_span>(src_span).first( width); #if defined(PDF_USE_LIBYUV) - const int pixel_count = pdfium::checked_cast(width); - const uint8_t* src_bytes = pdfium::as_bytes(bgr_span).data(); - uint8_t* dest_bytes = pdfium::as_writable_bytes(dest_span).data(); if constexpr (std::is_same_v>) { - libyuv::RGB24ToARGB(src_bytes, 0, dest_bytes, 0, pixel_count, 1); + pdfium::RGB24ToARGBRow(bgr_span, dest_span); } else { static_assert(std::is_same_v>); - libyuv::RAWToARGB(src_bytes, 0, dest_bytes, 0, pixel_count, 1); + // Treating BGR as RGB and RGBA as BGRA achieves the same channel swap. + auto rgb_src = + fxcrt::reinterpret_span>(src_span).first( + width); + auto bgra_dest = + fxcrt::reinterpret_span>(dest_span); + pdfium::RAWToARGBRow(rgb_src, bgra_dest); } #else CopyRowToOpaqueBgra(dest_span, bgr_span); @@ -835,6 +843,19 @@ void CompositeRow_Rgb2Rgb_NoBlend_NoClip(pdfium::span dest_span, int width, int dest_Bpp, int src_Bpp) { +#if defined(PDF_USE_LIBYUV) + if (src_Bpp == 3 && dest_Bpp == 4) { + // BGR24 -> BGRx expand; libyuv stamps 4th byte 0xFF vs scalar's + // untouched. kBgrx padding, non-displayed: no output impact. + auto bgr_src = + fxcrt::reinterpret_span>(src_span).first( + pdfium::checked_cast(width)); + auto bgra_dest = + fxcrt::reinterpret_span>(dest_span); + pdfium::RGB24ToARGBRow(bgr_src, bgra_dest); + return; + } +#endif uint8_t* dest_scan = dest_span.data(); const uint8_t* src_scan = src_span.data(); UNSAFE_TODO({ @@ -842,14 +863,6 @@ void CompositeRow_Rgb2Rgb_NoBlend_NoClip(pdfium::span dest_span, FXSYS_memcpy(dest_scan, src_scan, width * dest_Bpp); return; } -#if defined(PDF_USE_LIBYUV) - if (src_Bpp == 3 && dest_Bpp == 4) { - // BGR24 -> BGRx expand; libyuv stamps 4th byte 0xFF vs scalar's - // untouched. kBgrx padding, non-displayed: no output impact. - libyuv::RGB24ToARGB(src_scan, width * 3, dest_scan, width * 4, width, 1); - return; - } -#endif for (int col = 0; col < width; col++) { FXSYS_memcpy(dest_scan, src_scan, 3); dest_scan += dest_Bpp; diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp index d4f304f8a9..f8d8e493f0 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.cpp @@ -10,7 +10,7 @@ #include "core/fxcrt/check_op.h" #include "core/fxcrt/compiler_specific.h" #include "core/fxcrt/span.h" -#include "core/fxcrt/span_util.h" +#include "core/fxcrt/zip.h" #undef HWY_TARGET_INCLUDE #define HWY_TARGET_INCLUDE "core/fxge/dib/cfx_scanlinecompositor_hwy.cpp" @@ -40,33 +40,38 @@ HWY_INLINE V AlphaMergeLanes(V back, V src, V alpha, V v255) { hn::Add(hn::Mul(back, hn::Sub(v255, alpha)), hn::Mul(src, alpha))); } -// scalar tail; bit-exact with CompositeRowBgra2Bgra normal/no-clip -inline uint32_t CompositePixelBgra2Bgra(uint32_t src, uint32_t back) { - const uint32_t back_alpha = FXARGB_A(back); - if (back_alpha == 0) { - return src; +// scalar tail; bit-exact with CompositeRowBgra2Bgra() normal/no-clip +inline void CompositePixelBgra2Bgra(const FX_BGRA_STRUCT& src, + FX_BGRA_STRUCT& dest) { + if (dest.alpha == 0) { + dest = src; + return; } - const uint32_t src_alpha = FXARGB_A(src); - if (src_alpha == 0) { - return back; + if (src.alpha == 0) { + return; } - if (src_alpha == 255) { - return src; + if (src.alpha == 255) { + dest = src; + return; } const uint32_t dest_alpha = - back_alpha + src_alpha - (back_alpha * src_alpha / 255); - const uint32_t ratio = src_alpha * 255 / dest_alpha; - return ArgbEncode(dest_alpha, - AlphaMerge(FXARGB_R(back), FXARGB_R(src), ratio), - AlphaMerge(FXARGB_G(back), FXARGB_G(src), ratio), - AlphaMerge(FXARGB_B(back), FXARGB_B(src), ratio)); + dest.alpha + src.alpha - (dest.alpha * src.alpha / 255); + const uint32_t ratio = src.alpha * 255 / dest_alpha; + dest.blue = AlphaMerge(dest.blue, src.blue, ratio); + dest.green = AlphaMerge(dest.green, src.green, ratio); + dest.red = AlphaMerge(dest.red, src.red, ratio); + dest.alpha = dest_alpha; } // Porter-Duff over, packed BGRA, normal, no clip. Per pixel: // dest a == 0 -> copy src src a == 255 -> copy src // src a == 0 -> keep dest else AlphaMerge/AlphaUnion over -// Byte spans bitcast to u32 lanes -> no 4-byte scanline alignment needed. -void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { +// Byte loads bitcast to u32 lanes -> no 4-byte scanline alignment needed. +void RunBgra2Bgra(pdfium::span> src, + pdfium::span> dest) { + // Make sure the compiler can see equal span sizes after the dispatch. + dest = dest.first(src.size()); +#if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); // pixels/vector @@ -74,10 +79,11 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { const auto one = hn::Set(d, 1); const auto zero = hn::Zero(d); - size_t count = src.size() / 4; - while (count >= n) { - const auto s = hn::BitCast(d, hn::LoadU(d8, src.data())); - const auto back = hn::BitCast(d, hn::LoadU(d8, dest.data())); + while (src.size() >= n) { + const auto s = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(src.data()))); + const auto back = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(dest.data()))); const auto sa = hn::ShiftRight<24>(s); const auto da = hn::ShiftRight<24>(back); @@ -87,10 +93,10 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { // all copy/keep -> skip divide; copy_src ? src : dest if (hn::AllTrue(d, hn::Or(copy_src, keep_dest))) { const auto result = hn::IfThenElse(copy_src, s, back); - hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + hn::StoreU(hn::BitCast(d8, result), d8, + reinterpret_cast(dest.data())); + src = src.subspan(n); + dest = dest.subspan(n); continue; } @@ -113,48 +119,106 @@ void RunBgra2Bgra(pdfium::span src, pdfium::span dest) { auto result = hn::IfThenElse(keep_dest, back, gen); result = hn::IfThenElse(copy_src, s, result); - hn::StoreU(hn::BitCast(d8, result), d8, dest.data()); + hn::StoreU(hn::BitCast(d8, result), d8, + reinterpret_cast(dest.data())); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + src = src.subspan(n); + dest = dest.subspan(n); } - for (size_t i = 0; i < count; ++i) { - const uint32_t s = FXARGB_GetDIB(src.first<4u>()); - const uint32_t back = FXARGB_GetDIB(dest.first<4u>()); - FXARGB_SetDIB(dest.first<4u>(), CompositePixelBgra2Bgra(s, back)); - src = src.subspan(4u); - dest = dest.subspan(4u); +#endif // HWY_TARGET != HWY_SCALAR + for (auto [src_elem, dest_elem] : fxcrt::Zip(src, dest)) { + CompositePixelBgra2Bgra(src_elem, dest_elem); } } // Opaque BGRA(4) -> BGRA, alpha forced 0xFF (src alpha ignored). Same byte // order required: src and dest both packed BGRA. -void RunBgra2BgrxForceOpaque(pdfium::span src, - pdfium::span dest) { +void RunBgra2BgrxForceOpaque(pdfium::span> src, + pdfium::span> dest) { + // Make sure the compiler can see equal span sizes after the dispatch. + dest = dest.first(src.size()); +#if HWY_TARGET != HWY_SCALAR const hn::ScalableTag d; const hn::ScalableTag d8; const size_t n = hn::Lanes(d); const auto alpha_ff = hn::Set(d, 0xFF000000u); - size_t count = src.size() / 4; - while (count >= n) { - const auto v = hn::BitCast(d, hn::LoadU(d8, src.data())); - hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, dest.data()); - src = src.subspan(n * 4); - dest = dest.subspan(n * 4); - count -= n; + while (src.size() >= n) { + const auto v = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(src.data()))); + hn::StoreU(hn::BitCast(d8, hn::Or(v, alpha_ff)), d8, + reinterpret_cast(dest.data())); + src = src.subspan(n); + dest = dest.subspan(n); } - for (size_t i = 0; i < count; ++i) { - dest[0] = src[0]; - dest[1] = src[1]; - dest[2] = src[2]; - dest[3] = 0xFF; - src = src.subspan(4u); - dest = dest.subspan(4u); +#endif // HWY_TARGET != HWY_SCALAR + for (auto [src_elem, dest_elem] : fxcrt::Zip(src, dest)) { + dest_elem.blue = src_elem.blue; + dest_elem.green = src_elem.green; + dest_elem.red = src_elem.red; + dest_elem.alpha = 0xFF; } } +// Keep the clip decision outside the loop. Both products passed to Div255() +// are at most 255 * 255, so its exact, truncating division matches +// AlphaUnion(). +template +void Bgra2Mask(pdfium::span> src, + pdfium::span clip, + pdfium::span dest) { + // Make sure the compiler can see equal span sizes after the dispatch. + dest = dest.first(src.size()); + if constexpr (kHasClip) { + clip = clip.first(src.size()); + } +#if HWY_TARGET != HWY_SCALAR + const hn::ScalableTag d; + const hn::ScalableTag d8; + const hn::Rebind dn; + const size_t n = hn::Lanes(d); + while (src.size() >= n) { + // The BGRA load reads 4*n bytes; the narrow descriptor reads/writes n + // bytes for clip and dest. The span sizes bound every vector access. + const auto packed = hn::BitCast( + d, hn::LoadU(d8, reinterpret_cast(src.data()))); + auto alpha = hn::ShiftRight<24>(packed); + if constexpr (kHasClip) { + alpha = + Div255(hn::Mul(alpha, hn::PromoteTo(d, hn::LoadU(dn, clip.data())))); + clip = clip.subspan(n); + } + const auto back = hn::PromoteTo(d, hn::LoadU(dn, dest.data())); + const auto result = + hn::Sub(hn::Add(back, alpha), Div255(hn::Mul(back, alpha))); + // Alpha union is in [0, 255], satisfying U8FromU32()'s precondition. + hn::StoreU(hn::U8FromU32(result), dn, dest.data()); + src = src.subspan(n); + dest = dest.subspan(n); + } +#endif // HWY_TARGET != HWY_SCALAR + while (!src.empty()) { + uint32_t alpha = src[0].alpha; + if constexpr (kHasClip) { + alpha = alpha * clip[0] / 255; + clip = clip.subspan<1u>(); + } + dest[0] = static_cast(dest[0] + alpha - dest[0] * alpha / 255); + src = src.subspan<1u>(); + dest = dest.subspan<1u>(); + } +} + +void RunBgra2Mask(pdfium::span> src, + pdfium::span clip, + pdfium::span dest) { + if (clip.empty()) { + Bgra2Mask(src, clip, dest); + return; + } + Bgra2Mask(src, clip, dest); +} + } // namespace } // namespace HWY_NAMESPACE } // namespace fxge_composite_simd @@ -165,21 +229,30 @@ namespace fxge_composite_simd { HWY_EXPORT(RunBgra2Bgra); HWY_EXPORT(RunBgra2BgrxForceOpaque); +HWY_EXPORT(RunBgra2Mask); // Unqualified name, in-namespace: a qualified name breaks single-target // HWY_STATIC_DISPATCH. -void DispatchBgra2Bgra(pdfium::span src, - pdfium::span dest) { +void DispatchBgra2Bgra(pdfium::span> src, + pdfium::span> dest) { // SAFETY: dispatch indexes Highway's per-target table; no span macro form. UNSAFE_BUFFERS(HWY_DYNAMIC_DISPATCH(RunBgra2Bgra)(src, dest)); } -void DispatchBgra2BgrxForceOpaque(pdfium::span src, - pdfium::span dest) { +void DispatchBgra2BgrxForceOpaque( + pdfium::span> src, + pdfium::span> dest) { // SAFETY: see DispatchBgra2Bgra(). UNSAFE_BUFFERS(HWY_DYNAMIC_DISPATCH(RunBgra2BgrxForceOpaque)(src, dest)); } +void DispatchBgra2Mask(pdfium::span> src, + pdfium::span clip, + pdfium::span dest) { + // SAFETY: see DispatchBgra2Bgra(). + UNSAFE_BUFFERS(HWY_DYNAMIC_DISPATCH(RunBgra2Mask)(src, clip, dest)); +} + } // namespace fxge_composite_simd void CompositeRowBgra2BgraSimd( @@ -187,9 +260,7 @@ void CompositeRowBgra2BgraSimd( pdfium::span> dest_span) { // `src_span.size()` pixels, like `fxcrt::Zip(src_span, dest_span)`. CHECK_LE(src_span.size(), dest_span.size()); - fxge_composite_simd::DispatchBgra2Bgra( - fxcrt::reinterpret_span(src_span), - fxcrt::reinterpret_span(dest_span)); + fxge_composite_simd::DispatchBgra2Bgra(src_span, dest_span); } void CompositeRowBgra2BgrxForceOpaqueSimd( @@ -197,8 +268,15 @@ void CompositeRowBgra2BgrxForceOpaqueSimd( pdfium::span> dest_span) { // `src_span.size()` pixels, like `fxcrt::Zip(src_span, dest_span)`. CHECK_LE(src_span.size(), dest_span.size()); - fxge_composite_simd::DispatchBgra2BgrxForceOpaque( - fxcrt::reinterpret_span(src_span), - fxcrt::reinterpret_span(dest_span)); + fxge_composite_simd::DispatchBgra2BgrxForceOpaque(src_span, dest_span); +} + +void CompositeRowBgra2MaskSimd( + pdfium::span> src_span, + pdfium::span clip_span, + pdfium::span dest_span) { + CHECK_LE(src_span.size(), dest_span.size()); + CHECK(clip_span.empty() || src_span.size() <= clip_span.size()); + fxge_composite_simd::DispatchBgra2Mask(src_span, clip_span, dest_span); } #endif // HWY_ONCE diff --git a/core/fxge/dib/cfx_scanlinecompositor_hwy.h b/core/fxge/dib/cfx_scanlinecompositor_hwy.h index 909c0ed443..bc23e920b6 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_hwy.h +++ b/core/fxge/dib/cfx_scanlinecompositor_hwy.h @@ -23,4 +23,10 @@ void CompositeRowBgra2BgrxForceOpaqueSimd( pdfium::span> src_span, pdfium::span> dest_span); +// SIMD replacement for BGRA -> alpha-mask scanlines. +void CompositeRowBgra2MaskSimd( + pdfium::span> src_span, + pdfium::span clip_span, + pdfium::span dest_span); + #endif // CORE_FXGE_DIB_CFX_SCANLINECOMPOSITOR_HWY_H_ diff --git a/core/fxge/dib/cfx_scanlinecompositor_unittest.cpp b/core/fxge/dib/cfx_scanlinecompositor_unittest.cpp index b0622a7175..4631476276 100644 --- a/core/fxge/dib/cfx_scanlinecompositor_unittest.cpp +++ b/core/fxge/dib/cfx_scanlinecompositor_unittest.cpp @@ -11,6 +11,7 @@ #include "build/build_config.h" #include "core/fxcrt/span.h" +#include "core/fxcrt/span_util.h" #include "core/fxcrt/stl_util.h" #include "core/fxcrt/zip.h" #include "core/fxge/dib/cfx_scanlinecompositor_hwy.h" @@ -176,6 +177,47 @@ void CheckBgra2BgrxForceOpaque(size_t width) { } } +void CheckBgra2Mask(size_t width, bool with_clip, size_t offset) { + // Byte offsets exercise unaligned BGRA loads as well as narrow mask loads. + static_assert(alignof(FX_BGRA_STRUCT) == 1); + std::vector src_storage(width * 4 + offset + 1, 0xA5); + auto src = fxcrt::reinterpret_span>( + pdfium::span(src_storage).subspan(offset, width * 4)); + std::vector clip_storage(width + offset + 1, 0xA5); + auto clip = with_clip ? pdfium::span(clip_storage).subspan(offset, width) + : pdfium::span(); + std::vector dest_storage(width + offset + 1, 0xA5); + auto dest = pdfium::span(dest_storage).subspan(offset, width); + auto expected = dest_storage; + for (size_t i = 0; i < width; ++i) { + src[i] = {.blue = static_cast(i * 7), + .green = static_cast(i * 11), + .red = static_cast(i * 17), + .alpha = static_cast(i * 37 + 1)}; + if (with_clip) { + clip[i] = static_cast(i * 53 + 9); + } + dest[i] = static_cast(i * 19 + 2); + const uint32_t alpha = src[i].alpha * (with_clip ? clip[i] : 255) / 255; + expected[offset + i] = + static_cast(dest[i] + alpha - dest[i] * alpha / 255); + } + auto via_public = dest_storage; + const auto original_src = src_storage; + const auto original_clip = clip_storage; + CompositeRowBgra2MaskSimd(src, clip, dest); + EXPECT_EQ(dest_storage, expected); + CFX_ScanlineCompositor compositor; + ASSERT_TRUE(compositor.Init(FXDIB_Format::k8bppMask, FXDIB_Format::kBgra, {}, + 0, BlendMode::kNormal, false)); + compositor.CompositeRgbBitmapLine( + pdfium::span(via_public).subspan(offset, width), pdfium::as_bytes(src), + static_cast(width), clip); + EXPECT_EQ(via_public, expected); + EXPECT_EQ(src_storage, original_src); + EXPECT_EQ(clip_storage, original_clip); +} + } // namespace namespace fxge { @@ -1002,6 +1044,86 @@ TEST(ScanlineCompositorSimdTest, Bgra2BgrxForceOpaqueMatchesScalar) { } } +TEST(ScanlineCompositorSimdTest, Bgra2MaskMatchesScalar) { + for (size_t width : + {0u, 1u, 2u, 3u, 4u, 5u, 7u, 8u, 9u, 15u, 16u, 17u, + 31u, 32u, 33u, 63u, 64u, 65u, 100u, 127u, 128u, 129u, 257u, 65537u}) { + for (size_t offset : {0u, 1u, 2u, 3u}) { + SCOPED_TRACE(testing::Message() + << "width=" << width << " offset=" << offset); + CheckBgra2Mask(width, false, offset); + CheckBgra2Mask(width, true, offset); + } + } +} + +TEST(ScanlineCompositorSimdTest, Bgra2MaskAllSourceAndClipAlphaCombinations) { + // A zero destination exposes the clipped alpha, covering every input pair + // and the rounding boundaries of the first division by 255. + constexpr size_t kWidth = 256 * 256; + std::vector> src(kWidth); + std::vector clip(kWidth); + std::vector dest(kWidth); + std::vector expected(kWidth); + for (size_t i = 0; i < kWidth; ++i) { + const uint32_t alpha = static_cast(i / 256); + const uint32_t clip_alpha = static_cast(i % 256); + src[i] = { + .blue = 1, .green = 2, .red = 3, .alpha = static_cast(alpha)}; + clip[i] = static_cast(clip_alpha); + expected[i] = static_cast(alpha * clip_alpha / 255); + } + CompositeRowBgra2MaskSimd(src, clip, dest); + ASSERT_EQ(dest, expected); +} + +TEST(ScanlineCompositorSimdTest, Bgra2MaskAllSourceAndDestAlphaCombinations) { + // Without clipping, cover every source/destination alpha pair and the + // rounding boundaries of the alpha union's division by 255. + constexpr size_t kWidth = 256 * 256; + std::vector> src(kWidth); + std::vector dest(kWidth); + std::vector expected(kWidth); + for (size_t i = 0; i < kWidth; ++i) { + const uint32_t alpha = static_cast(i / 256); + const uint32_t back = static_cast(i % 256); + src[i] = { + .blue = 1, .green = 2, .red = 3, .alpha = static_cast(alpha)}; + dest[i] = static_cast(back); + expected[i] = static_cast(back + alpha - back * alpha / 255); + } + CompositeRowBgra2MaskSimd(src, {}, dest); + ASSERT_EQ(dest, expected); +} + +TEST(ScanlineCompositorSimdTest, Bgra2MaskConstantAlphaAndTails) { + // Exercise the same extreme inputs in full vectors and scalar tails. + static constexpr std::array kAlpha = {0, 1, 127, 128, 254, 255}; + for (size_t width : {1u, 3u, 7u, 17u, 33u, 65u}) { + std::vector> src(width); + std::vector clip(width); + std::vector dest(width); + for (uint8_t a : kAlpha) { + for (uint8_t c : kAlpha) { + for (uint8_t back : kAlpha) { + for (size_t i = 0; i < width; ++i) { + src[i].alpha = a; + clip[i] = c; + dest[i] = back; + } + const uint32_t alpha = a * c / 255; + const uint8_t expected = + static_cast(back + alpha - back * alpha / 255); + CompositeRowBgra2MaskSimd(src, clip, dest); + for (uint8_t value : dest) { + ASSERT_EQ(value, expected) << "width=" << width; + } + } + } + } + } +} + // BGR24 -> BGRx expand via public path. RGB copied verbatim; padding byte // 0xFF under libyuv, untouched by scalar (kBgrx padding, not displayed). TEST(ScanlineCompositorSimdTest, CompositeRgbBitmapLineBgr24ToBgrx) { diff --git a/core/fxge/fx_libyuv_wrappers.cpp b/core/fxge/fx_libyuv_wrappers.cpp new file mode 100644 index 0000000000..67625eaf55 --- /dev/null +++ b/core/fxge/fx_libyuv_wrappers.cpp @@ -0,0 +1,274 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "core/fxge/fx_libyuv_wrappers.h" + +#include +#include + +#include "core/fxcrt/check.h" +#include "core/fxcrt/check_op.h" +#include "core/fxcrt/fx_2d_size.h" +#include "core/fxcrt/fx_safe_types.h" +#include "core/fxcrt/notreached.h" +#include "core/fxcrt/numerics/safe_conversions.h" +#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "third_party/libyuv/include/libyuv/convert_from_argb.h" +#include "third_party/libyuv/include/libyuv/planar_functions.h" +#include "third_party/libyuv/include/libyuv/rotate.h" +#include "third_party/libyuv/include/libyuv/rotate_argb.h" + +namespace pdfium { + +namespace { + +int GetAbsHeight(int height) { + FX_SAFE_INT32 safe_height = height; + int abs_height = safe_height.Abs().ValueOrDie(); + CHECK_GT(abs_height, 0); + return abs_height; +} + +template +int ValidateRowWidthsAndGetSrcRowWidth(pdfium::span src_span, + pdfium::span dst_span) { + CHECK(!src_span.empty()); + CHECK_LE(src_span.size(), dst_span.size()); + return pdfium::checked_cast(src_span.size()); +} + +size_t GetPlaneBytes(int stride, int width, int rows, int bytes_per_pixel) { + CHECK_GT(width, 0); + CHECK_GT(rows, 0); + CHECK_GT(bytes_per_pixel, 0); + const size_t row_bytes = Fx2DSizeOrDie(width, bytes_per_pixel); + CHECK_GE(stride, 0); + CHECK_GE(static_cast(stride), row_bytes); + // A subspan starting at a non-zero column offset has `stride` bytes for each + // of the first `rows - 1` rows, and only `row_bytes` bytes on the final row. + FX_SAFE_SIZE_T plane_bytes = rows - 1; + plane_bytes *= stride; + plane_bytes += row_bytes; + return plane_bytes.ValueOrDie(); +} + +libyuv::RotationMode ToLibyuvRotationMode(RotationMode mode) { + switch (mode) { + case kRotate90: + return libyuv::kRotate90; + case kRotate270: + return libyuv::kRotate270; + } + NOTREACHED(); +} + +} // namespace + +void RGB24ToARGB(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 3)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 4)); + int ret = libyuv::RGB24ToARGB(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBToRGB24(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 3)); + int ret = libyuv::ARGBToRGB24(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBToRAW(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 3)); + int ret = libyuv::ARGBToRAW(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBExtractAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 1)); + int ret = libyuv::ARGBExtractAlpha( + src_span.data(), src_stride, dst_span.data(), dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBCopyYToAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, height, 4)); + int ret = libyuv::ARGBCopyYToAlpha( + src_span.data(), src_stride, dst_span.data(), dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void MirrorPlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 1)); + libyuv::MirrorPlane(src_span.data(), src_stride, dst_span.data(), dst_stride, + width, height); +} + +void RGB24Mirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 3)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 3)); + int ret = libyuv::RGB24Mirror(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void ARGBMirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, width, abs_height, 4)); + int ret = libyuv::ARGBMirror(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height); + CHECK_EQ(ret, 0); +} + +void RotatePlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 1)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, abs_height, width, 1)); + int ret = libyuv::RotatePlane(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height, + ToLibyuvRotationMode(mode)); + CHECK_EQ(ret, 0); +} + +void ARGBRotate(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode) { + const int abs_height = GetAbsHeight(height); + CHECK_GE(src_span.size(), GetPlaneBytes(src_stride, width, abs_height, 4)); + CHECK_GE(dst_span.size(), GetPlaneBytes(dst_stride, abs_height, width, 4)); + int ret = + libyuv::ARGBRotate(src_span.data(), src_stride, dst_span.data(), + dst_stride, width, height, ToLibyuvRotationMode(mode)); + CHECK_EQ(ret, 0); +} + +void RGB24ToRAWRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24ToRAW(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void RGB24ToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24ToARGB(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void RAWToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RAWToARGB(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBToRGB24Row(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBToRGB24(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBExtractAlphaRow(pdfium::span> src_span, + pdfium::span dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBExtractAlpha(pdfium::as_bytes(src_span).data(), 0, + dst_span.data(), 0, width, 1); + CHECK_EQ(ret, 0); +} + +void MirrorPlaneRow(pdfium::span src_span, + pdfium::span dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + libyuv::MirrorPlane(src_span.data(), 0, dst_span.data(), 0, width, 1); +} + +void RGB24MirrorRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::RGB24Mirror(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +void ARGBMirrorRow(pdfium::span> src_span, + pdfium::span> dst_span) { + const int width = ValidateRowWidthsAndGetSrcRowWidth(src_span, dst_span); + int ret = libyuv::ARGBMirror(pdfium::as_bytes(src_span).data(), 0, + pdfium::as_writable_bytes(dst_span).data(), 0, + width, 1); + CHECK_EQ(ret, 0); +} + +} // namespace pdfium diff --git a/core/fxge/fx_libyuv_wrappers.h b/core/fxge/fx_libyuv_wrappers.h new file mode 100644 index 0000000000..36c7375894 --- /dev/null +++ b/core/fxge/fx_libyuv_wrappers.h @@ -0,0 +1,132 @@ +// Copyright 2026 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ +#define CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ + +#if !defined(PDF_USE_LIBYUV) +#error "PDF_USE_LIBYUV must be defined." +#endif + +#include + +#include "core/fxcrt/span.h" +#include "core/fxge/dib/fx_dib.h" + +namespace pdfium { + +enum RotationMode { + kRotate90 = 90, + kRotate270 = 270, +}; + +// Span-based wrappers around functions in third_party/libyuv/include/libyuv/. +// See the corresponding libyuv headers for detailed documentation. + +// 2D plane operations. +void RGB24ToARGB(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBToRGB24(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBToRAW(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBExtractAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBCopyYToAlpha(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +// For mirror and rotate functions below, negative `height` inverts the image +// vertically. +void MirrorPlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void RGB24Mirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void ARGBMirror(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height); + +void RotatePlane(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode); + +void ARGBRotate(pdfium::span src_span, + int src_stride, + pdfium::span dst_span, + int dst_stride, + int width, + int height, + RotationMode mode); + +// Single-row operations. Each function processes `src_span.size()` pixels. +// `src_span` must not be empty, and `dst_span` must have at least +// `src_span.size()` elements (any extra elements in `dst_span` are left +// unmodified). +void RGB24ToRAWRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void RGB24ToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void RAWToARGBRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBToRGB24Row(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBExtractAlphaRow(pdfium::span> src_span, + pdfium::span dst_span); + +void MirrorPlaneRow(pdfium::span src_span, + pdfium::span dst_span); + +void RGB24MirrorRow(pdfium::span> src_span, + pdfium::span> dst_span); + +void ARGBMirrorRow(pdfium::span> src_span, + pdfium::span> dst_span); + +} // namespace pdfium + +#endif // CORE_FXGE_FX_LIBYUV_WRAPPERS_H_ diff --git a/core/fxge/skia/cfx_dibbase_skia.cpp b/core/fxge/skia/cfx_dibbase_skia.cpp index 71d06fd4e9..f11a1aed3f 100644 --- a/core/fxge/skia/cfx_dibbase_skia.cpp +++ b/core/fxge/skia/cfx_dibbase_skia.cpp @@ -19,6 +19,7 @@ #include "core/fxcrt/numerics/safe_conversions.h" #include "core/fxcrt/retain_ptr.h" #include "core/fxcrt/span.h" +#include "core/fxcrt/span_util.h" #include "core/fxge/calculate_pitch.h" #include "core/fxge/dib/cfx_dibitmap.h" #include "core/fxge/dib/fx_dib.h" @@ -31,7 +32,7 @@ #include "third_party/skia/include/core/SkRefCnt.h" #if defined(PDF_USE_LIBYUV) -#include "third_party/libyuv/include/libyuv/convert_argb.h" +#include "core/fxge/fx_libyuv_wrappers.h" #endif namespace { @@ -152,22 +153,18 @@ sk_sp CreateSkiaImageFrom24BppDib(const CFX_DIBBase& source) { return nullptr; } - const size_t min_row_bytes = - fxge::CalculatePitch8OrDie(source.GetBPP(), /*components=*/1, width); - DCHECK_LE(min_row_bytes, source.GetPitch()); - - if (!source.GetBuffer().empty()) { - libyuv::RGB24ToARGB( - source.GetBuffer().data(), source.GetPitch(), output.span().data(), - pdfium::checked_cast(dst_row_bytes), width, height); + pdfium::span src_buffer = source.GetBuffer(); + if (!src_buffer.empty()) { + pdfium::RGB24ToARGB(src_buffer, source.GetPitch(), output, + pdfium::checked_cast(dst_row_bytes), width, + height); } else { + auto dst_span = + fxcrt::reinterpret_span>(output.span()); for (int row = 0; row < height; ++row) { - pdfium::span scanline = source.GetScanline(row); - ValidateScanlineSize(scanline, min_row_bytes); - libyuv::RGB24ToARGB( - scanline.data(), 0, - output.subspan(Fx2DSizeOrDie(row, dst_row_bytes)).data(), 0, width, - 1); + pdfium::RGB24ToARGBRow(source.GetScanlineAs>(row), + dst_span); + dst_span = dst_span.subspan(static_cast(width)); } } diff --git a/core/fxge/skia/fx_skia_device.cpp b/core/fxge/skia/fx_skia_device.cpp index ebf768461a..774442ba54 100644 --- a/core/fxge/skia/fx_skia_device.cpp +++ b/core/fxge/skia/fx_skia_device.cpp @@ -29,6 +29,7 @@ #include "core/fxcrt/cfx_bitstream.h" #include "core/fxcrt/check.h" #include "core/fxcrt/check_op.h" +#include "core/fxcrt/containers/extend.h" #include "core/fxcrt/data_vector.h" #include "core/fxcrt/fx_2d_size.h" #include "core/fxcrt/fx_coordinates.h" @@ -541,14 +542,11 @@ void SetupStrokePaint(SkPaint* stroke_paint, bool is_even_sized = count % 2 == 0; DataVector intervals; intervals.reserve(is_even_sized ? count : count * 2); - for (float dash_len : dash_array) { - if (dash_len <= 0.000001f) { - dash_len = 0.1f; - } - intervals.push_back(dash_len); - } + pdfium::Extend(intervals, dash_array, [](float dash_len) { + return dash_len <= 0.000001f ? 0.1f : dash_len; + }); if (!is_even_sized) { - intervals.insert(intervals.end(), intervals.begin(), intervals.end()); + pdfium::Extend(intervals, intervals); } stroke_paint->setPathEffect( SkDashPathEffect::Make(intervals, stroke_options->dash_phase())); diff --git a/docs/embedpdf/syncs/2026-11-15-1f02bc7d90.md b/docs/embedpdf/syncs/2026-11-15-1f02bc7d90.md new file mode 100644 index 0000000000..c896acf7f2 --- /dev/null +++ b/docs/embedpdf/syncs/2026-11-15-1f02bc7d90.md @@ -0,0 +1,131 @@ +# Sync 2026-11-15: upstream 6688c576f..1f02bc7d9 (47 commits) + +## Summary + +Upstream from 2026-11-08 to 2026-11-13, merged into `cd9bc9600`. + +Upstream reworked the object-tree traversal (graph building split from counting, cycles found by +DFS, so shared objects are no longer missed), makes new annotations indirect, rejects 192-bit AES, +fixed our own `FlatePredictorScanlineDecoder::Rewind()` bug, and added tests. Eight conflicts; our +resolve mode moves into upstream's graph builder, and three tests follow fork behaviour. + +## Likely security fixes + +- `4e04b1315d` 2026-11-12 Fix float-cast-overflow in CheckSimpleLinePath +- `2686a8c36c` 2026-11-11 Revert "Support conservative stack scanning in standalone cppgc heap" +- `d340036bb3` 2026-11-10 Support conservative stack scanning in standalone cppgc heap + +Taken as upstream wrote them. `4e04b1315d` is in our builds; the cppgc pair (added, then reverted) +is XFA only. Also security-relevant, though not flagged: `982029caf3` (a `/Length 192` AES file +reached a CHECK) and `583f8062d0` (shared streams taken for unshared and edited in place), below. + +## Conflicts (8 files, 12 blocks) + +A block with an `EPDF_TLS` count is never resolved by taking upstream's side without putting `EPDF_TLS` back (rule thread-confined-globals). + +| File | Blocks | Rules in the blocks | EPDF_TLS | Upstream commits | Resolution | +| :-- | --: | :-- | --: | :-- | :-- | +| `core/fpdfapi/page/cpdf_image.cpp` | 2 | redaction | | `2697090b6b` Fix UNSAFE_TODO() in CPDF_Image::SetImage() | Both: our flate/png includes with upstream's `fx_codec.h`, then upstream's libyuv/zip includes before our in-place stream rewrite (redaction). | +| `core/fpdfapi/parser/cpdf_crypto_handler.cpp` | 1 | untagged | | `982029caf3` Reject unsupported 192-bit AES keys and clean up per-object derivation | Includes: ours (`epdf_secure_random.h`, save-security) with upstream's `notreached.h` and `span_util.h`; no `FX_Random` is left, so no `fx_random.h`. Upstream's `RequiresPerObjectKeyDerivation()` merged around our secure IV. | +| `core/fpdfapi/parser/object_tree_traversal_util.cpp` | 4 | layer-save | | `a724e52c52` Separate graph reference counting into tree_traversal_util | Upstream's `PdfReferenceGraphBuilder` takes our resolve mode (default `kReferenceHolder`); `GetObjectsWithReferences()` and `GetObjectsWithMultipleReferences()` pass it on and count with upstream's `CalculateReferenceCounts()`. | +| `core/fpdfapi/parser/object_tree_traversal_util.h` | 1 | layer-save | | `a724e52c52` Separate graph reference counting into tree_traversal_util | Both: our resolve-mode enum, then upstream's `PdfReferenceGraph`; our mode's comment carries its own tag now. | +| `core/fpdfdoc/BUILD.gn` | 1 | untagged | | `497e33afb2` Add unit tests for CPVT_FontMap; `0880b61b2c` Add unit tests for CPDF_IconFit | Both sides' unit test sources. | +| `core/fxcodec/flate/flatemodule.cpp` | 1 | bug-fix | | `0254d297c7` Properly reset state in FlatePredictorScanlineDecoder::Rewind() | Upstream's: it is our bug-fix (clear `last_line_` on rewind), so ours is dropped (rule bug-fix). | +| `core/fxcodec/flate/flatemodule_unittest.cpp` | 1 | untagged | | `0254d297c7` Properly reset state in FlatePredictorScanlineDecoder::Rewind(); `ebffd53669` Add unit test for a bug in FlatePredictorScanlineDecoder::Rewind() | Includes: ours, a superset. Upstream's rewind test joins ours (`PredictorDecoderRewindRepeatsLines`); both pass. | +| `core/fxcrt/fx_unicode.cpp` | 1 | rich-text | | `701bec96db` Switch C-arrays constants inside fx_unicode.cpp to std::array | Ours: no `PDF_ENABLE_XFA` guard (rich-text), with upstream's comment wording. | + +## Write audit (0 lines) + +None. + +## Upstream changes outside the conflicts + +- **Shared objects found again (`a724e52c52`, `99da130a26`, `583f8062d0`):** the reference graph is + built first, then counted, and cycles are found by depth-first search. The old check dropped + valid edges as cycles, so a stream used twice (page content and an image, say) could count as + unshared and be edited in place. Our page content generator uses these counts. +- **New annotations are indirect (`89660bafdb`):** `FPDFPage_CreateAnnot()` makes the new `/Annots` + entry an indirect object (ISO 32000-1 table 30). `ConvertToIndirectObjectAt()` keeps our write + guards; the engine creates annotations through our own functions. +- **192-bit AES rejected (`982029caf3`):** the standard has no AES-192; a file asking for it fails to + load instead of reaching a CHECK when encrypting. Nothing of ours offers it. +- **`FPDFPage_GenerateContent()` ends an in-flight progressive render (`a6d2653579`).** +- **Decoder rewinds reset their state:** fax (`867e322d39`) and flate predictor (`0254d297c7`, our + fix, see Conflicts). +- **Rendering:** `CheckSimpleLinePath()` float overflow (`4e04b1315d`), BGRA-to-mask compositing with + Highway (`a5834506d0`), span wrappers for libyuv (`e24d49c9fa`; not on wasm32). +- **New tests that meet fork behaviour,** see Tests: `IsSupportedSubtype` (`7efd3f31d5`) and + `ActualTextOnRtlGlyphsWithNumbersAndPunctuation` (`ddb2abb6fb`); `RtlMultiCharGlyph` (`40367e9219`) + passes as upstream wrote it. +- Not in our builds: XFA and FormCalc (`1f02bc7d90`, `916d6f589a`, `e1f3a77c52`, `9a0f5b3e54`, + `4a9b009526`, `ec80692828`, `fc08db6a73`, `e3fba831d9`, `d340036bb3` and its revert), V8 JavaScript + tests, Highway's riscv config. Many new unit tests, all passing. + +## Upstream appearance generator + +None. + +## Globals + +No new globals by the heuristic. `check-globals.py` on the darwin-arm64 release build: ok (263 shared +writable, 25 thread-local). + +## Build and patches + +- `DEPS` changed in 2 commits: depot_tools (`96b71fa413`) and memory tools (`8ebce9f265`); neither is + in our builds. Synced with `gclient sync --no-history --shallow`. +- All of `patches/embedpdf-runtime/` apply: every target's patches dry-run against clean sources, + and darwin-arm64 and wasm32 build. + +## API diff + +None. The darwin-arm64 exports match the public headers, as in S17. + +## Tests + +- [x] fork unit + embedder tests (darwin-arm64): 1402 unit tests pass, upstream's new ones + included. Embedder: 1819 tests, 9 skipped, 12 failing after the fixes below: exactly S17's list, + every one "Pixels do not match" against a Mac PNG golden. Linux runs in the PR's CI. + The 12, as the baseline for the next sync: + - `EPDFMeasureEmbedderTest.CaptionAppearanceGolden` + - `FPDFEditEmbedderTest.SetTextRenderMode` + - `FPDFProgressiveRenderEmbedderTest.RenderAnnotWithPause` + - `FPDFProgressiveRenderEmbedderTest.RenderFormsWithPause` + - `FPDFProgressiveRenderEmbedderTest.RenderHighlightWithColorScheme` + - `FPDFProgressiveRenderEmbedderTest.RenderHighlightWithColorSchemeAndConvertFillToStroke` + - `FPDFProgressiveRenderEmbedderTest.RenderStampWithColorScheme` + - `FPDFProgressiveRenderEmbedderTest.RenderTextWithColorScheme` + - `FPDFProgressiveRenderEmbedderTest.RenderWithPause` + - `FPDFProgressiveRenderEmbedderTest.RenderWithoutPause` + - `FPDFViewEmbedderTest.RenderBug664284WithNoNativeText` + - `FPDFViewEmbedderTest.RenderHelloWorldWithFlags` +- [x] layer mode: exit 0; 213 layer-only failures, all expected; 185 crashes as in S17; 519 + writers, four of them new (below). One warning: + `EPDFSlicedLoadEmbedderTest.SlicesKeepToTheirBudget` failed under load and passed alone, a timing + test, as before. (A Mac recording drops the Linux-only `TransFormWithClipAndSaveWithLocale`; its + line stays.) +- [x] tag check (`--base 1f02bc7d90`): 1012 blocks, 0 untagged. +- [x] C API check: ok, 599 functions in 24 headers. +- [x] globals check: ok. +- [x] wasm build: builds locally. +- [ ] ThreadSanitizer soak: in the PR's CI. +- [ ] engine tests and engine-conformance with the local runtime: not run for this sync. +- changed expectations, each with its reason: + - `EPDFFlattenEmbedderTest.FlattenDirectAnnotationByHandle`: built its direct annotation with + `FPDFPage_CreateAnnot()`, which makes indirect ones now (`89660bafdb`); it writes the dictionary + into `/Annots` itself, as `EPDFAnnotRawEmbedderTest` does. Passes plain and in layer mode. + - `FPDFAnnotEmbedderTest.IsSupportedSubtype` (new, `7efd3f31d5`): line, caret, widget and redact are + supported subtypes in the fork (annot-appearance, forms-model, redaction). + - `FPDFTextEmbedderTest.ActualTextOnRtlGlyphsWithNumbersAndPunctuation` (new, `ddb2abb6fb`): the + fork's extraction (bug-fix). Against the typed text, upstream gets 1 of 6 lines right, the fork + 3 (lines 1, 2, 5); on lines 3, 4 and 6 the fork keeps the letters in order but puts the digits + or punctuation on the wrong side (RTL plan, B5). Upstream's TODOs stay on those three. + - Layer-mode writers: added upstream's new `FPDFAnnotEmbedderTest.CreateAnnotSavesIndirectReference` + (3 objects) and `FPDFTransformEmbedderTest.SetArtBox`, `SetBleedBox`, `SetTrimBox` (1 each); the + release gate rejects writers it doesn't know. + - Layer-mode writer counts, informational: 144 tests, mostly one object more per annotation + they make with `FPDFPage_CreateAnnot()`, now an object of its own (`89660bafdb`). + +## Ledger changes proposed + +None. diff --git a/fpdfsdk/epdf_flatten_embeddertest.cpp b/fpdfsdk/epdf_flatten_embeddertest.cpp index 9584a30c58..a50fb3fc1b 100644 --- a/fpdfsdk/epdf_flatten_embeddertest.cpp +++ b/fpdfsdk/epdf_flatten_embeddertest.cpp @@ -364,8 +364,15 @@ TEST_F(EPDFFlattenEmbedderTest, FlattenDirectAnnotationByHandle) { ScopedFPDFPage other_page(FPDFPage_New(document.get(), 1, 100, 100)); ASSERT_TRUE(other_page); - ScopedFPDFAnnotation annotation( - FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_INK)); + // An annotation dictionary written directly in /Annots, not an object of + // its own, as some writers do (FPDFPage_CreateAnnot() makes its own). + CPDF_Document* pdf = CPDFDocumentFromFPDFDocument(document.get()); + RetainPtr direct = pdf->GetMutablePageDictionary(0) + ->SetNewFor("Annots") + ->AppendNew(); + direct->SetNewFor("Type", "Annot"); + direct->SetNewFor("Subtype", "Ink"); + ScopedFPDFAnnotation annotation(FPDFPage_GetAnnot(page.get(), 0)); ASSERT_TRUE(annotation); ASSERT_EQ(0u, EPDFAnnot_GetObjectNumber(annotation.get())); const FS_RECTF rectangle = {10.0f, 40.0f, 40.0f, 10.0f}; diff --git a/fpdfsdk/fpdf_annot.cpp b/fpdfsdk/fpdf_annot.cpp index 88b871f3ca..6da29b5ee5 100644 --- a/fpdfsdk/fpdf_annot.cpp +++ b/fpdfsdk/fpdf_annot.cpp @@ -448,6 +448,9 @@ FPDFPage_CreateAnnot(FPDF_PAGE page, FPDF_ANNOTATION_SUBTYPE subtype) { RetainPtr pAnnotList = pPage->GetOrCreateAnnotsArray(); pAnnotList->Append(dict); + // ISO 32000-1:2008 spec, table 30: /Annots entries are indirect references. + pAnnotList->ConvertToIndirectObjectAt(pAnnotList->size() - 1, + pPage->GetDocument()); // Caller takes ownership. return FPDFAnnotationFromCPDFAnnotContext(pNewAnnot.release()); diff --git a/fpdfsdk/fpdf_annot_embeddertest.cpp b/fpdfsdk/fpdf_annot_embeddertest.cpp index 2f99c0f44e..babd272360 100644 --- a/fpdfsdk/fpdf_annot_embeddertest.cpp +++ b/fpdfsdk/fpdf_annot_embeddertest.cpp @@ -15,6 +15,7 @@ #include "build/build_config.h" #include "constants/annotation_common.h" #include "core/fpdfapi/page/cpdf_annotcontext.h" +#include "core/fpdfapi/page/cpdf_page.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fxcrt/compiler_specific.h" @@ -112,10 +113,97 @@ void VerifyUriActionInLink(FPDF_DOCUMENT doc, EXPECT_EQ(expected_uri, buffer.data()); } +// ISO 32000-1:2008 spec, table 30. +// Each /Annots entry is an indirect reference. +void ExpectHighlightAnnotsAreReferences(FPDF_PAGE page) { + CPDF_Page* cpdf_page = CPDFPageFromFPDFPage(page); + ASSERT_TRUE(cpdf_page); + RetainPtr annots = cpdf_page->GetAnnotsArray(); + ASSERT_TRUE(annots); + ASSERT_EQ(2u, annots->size()); + for (size_t i = 0; i < annots->size(); ++i) { + RetainPtr entry = annots->GetObjectAt(i); + ASSERT_TRUE(entry); + EXPECT_TRUE(entry->IsReference()); + RetainPtr dict = annots->GetDictAt(i); + ASSERT_TRUE(dict); + EXPECT_EQ("Highlight", + dict->GetByteStringFor(pdfium::annotation::kSubtype)); + } +} + } // namespace class FPDFAnnotEmbedderTest : public EmbedderTest {}; +TEST_F(FPDFAnnotEmbedderTest, IsSupportedSubtype) { + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_UNKNOWN)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_TEXT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_LINK)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_FREETEXT)); + // EmbedPDF(annot-appearance): our appearance generator draws lines. + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_LINE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SQUARE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_CIRCLE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_HIGHLIGHT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_UNDERLINE)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SQUIGGLY)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_STRIKEOUT)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_STAMP)); + // EmbedPDF(annot-appearance): our appearance generator draws carets. + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_CARET)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_INK)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_POPUP)); + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_FILEATTACHMENT)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SOUND)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_MOVIE)); + // EmbedPDF(forms-model): widgets are born through the annotation API. + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_WIDGET)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_SCREEN)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_PRINTERMARK)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_TRAPNET)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_WATERMARK)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_THREED)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_RICHMEDIA)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_XFAWIDGET)); + // EmbedPDF(redaction): redact annotations can be created. + EXPECT_TRUE(FPDFAnnot_IsSupportedSubtype(FPDF_ANNOT_REDACT)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(-1)); + EXPECT_FALSE(FPDFAnnot_IsSupportedSubtype(999)); +} + +TEST_F(FPDFAnnotEmbedderTest, IsObjectSupportedSubtype) { + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_UNKNOWN)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_TEXT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_LINK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_FREETEXT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_LINE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SQUARE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_CIRCLE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_HIGHLIGHT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_UNDERLINE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SQUIGGLY)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_STRIKEOUT)); + EXPECT_TRUE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_STAMP)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_CARET)); + EXPECT_TRUE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_INK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_POPUP)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_FILEATTACHMENT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SOUND)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_MOVIE)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_WIDGET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_SCREEN)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_PRINTERMARK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_TRAPNET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_WATERMARK)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_THREED)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_RICHMEDIA)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_XFAWIDGET)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(FPDF_ANNOT_REDACT)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(-1)); + EXPECT_FALSE(FPDFAnnot_IsObjectSupportedSubtype(999)); +} + TEST_F(FPDFAnnotEmbedderTest, SetAP) { ScopedFPDFDocument doc(FPDF_CreateNewDocument()); ASSERT_TRUE(doc); @@ -820,6 +908,43 @@ TEST_F(FPDFAnnotEmbedderTest, AddAndSaveUnderlineAnnotation) { } } +TEST_F(FPDFAnnotEmbedderTest, CreateAnnotSavesIndirectReference) { + // ISO 32000-1:2008 spec, table 30. + // The /Annots to hold indirect references. A direct dictionary has + // no object number, so readers that only follow references skip the + // annotation. + ASSERT_TRUE(OpenDocument("annotation_highlight_long_content.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + EXPECT_EQ(1, FPDFPage_GetAnnotCount(page.get())); + + { + ScopedFPDFAnnotation annot( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_HIGHLIGHT)); + ASSERT_TRUE(annot); + const FS_RECTF kRect = {10.0f, 40.0f, 80.0f, 60.0f}; + EXPECT_TRUE(FPDFAnnot_SetRect(annot.get(), &kRect)); + } + EXPECT_EQ(2, FPDFPage_GetAnnotCount(page.get())); + ExpectHighlightAnnotsAreReferences(page.get()); + + ASSERT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + + { + ScopedSavedDoc saved_doc = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_doc); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + EXPECT_EQ(2, FPDFPage_GetAnnotCount(saved_page.get())); + ExpectHighlightAnnotsAreReferences(saved_page.get()); + for (int index = 0; index < 2; ++index) { + ScopedFPDFAnnotation annot(FPDFPage_GetAnnot(saved_page.get(), index)); + ASSERT_TRUE(annot); + EXPECT_EQ(FPDF_ANNOT_HIGHLIGHT, FPDFAnnot_GetSubtype(annot.get())); + } + } +} + TEST_F(FPDFAnnotEmbedderTest, GetAndSetQuadPoints) { // Open a file with four annotations and load its first page. ASSERT_TRUE(OpenDocument("annotation_highlight_square_with_ap.pdf")); diff --git a/fpdfsdk/fpdf_edit_embeddertest.cpp b/fpdfsdk/fpdf_edit_embeddertest.cpp index 22048cff59..985f78fe9b 100644 --- a/fpdfsdk/fpdf_edit_embeddertest.cpp +++ b/fpdfsdk/fpdf_edit_embeddertest.cpp @@ -39,6 +39,7 @@ #include "public/fpdf_annot.h" #include "public/fpdf_doc.h" #include "public/fpdf_edit.h" +#include "public/fpdf_transformpage.h" #include "public/fpdfview.h" #include "testing/embedder_test.h" #include "testing/embedder_test_constants.h" @@ -692,6 +693,36 @@ TEST_F(FPDFEditEmbedderTest, ClipPath) { EXPECT_EQ(35, y); EXPECT_EQ(FPDF_SEGMENT_LINETO, FPDFPathSegment_GetType(segment)); EXPECT_FALSE(FPDFPathSegment_GetClose(segment)); + + // Null object does not crash. + FPDFPageObj_TransformClipPath(nullptr, 2.0, 0.0, 0.0, 3.0, 100.0, 200.0); + + // Transform clip path: scale X by 2, scale Y by 3, translate (100, 200). + FPDFPageObj_TransformClipPath(triangle, 2.0, 0.0, 0.0, 3.0, 100.0, 200.0); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 0); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(120.0f, x); + EXPECT_FLOAT_EQ(245.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 1); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(180.0f, x); + EXPECT_FLOAT_EQ(245.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 2); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(180.0f, x); + EXPECT_FLOAT_EQ(305.0f, y); + + segment = FPDFClipPath_GetPathSegment(clip_path, 0, 3); + ASSERT_TRUE(segment); + EXPECT_TRUE(FPDFPathSegment_GetPoint(segment, &x, &y)); + EXPECT_FLOAT_EQ(120.0f, x); + EXPECT_FLOAT_EQ(305.0f, y); } TEST_F(FPDFEditEmbedderTest, Bug1399) { diff --git a/fpdfsdk/fpdf_editpage.cpp b/fpdfsdk/fpdf_editpage.cpp index bc4f281a97..d5b7ba6e2a 100644 --- a/fpdfsdk/fpdf_editpage.cpp +++ b/fpdfsdk/fpdf_editpage.cpp @@ -902,6 +902,9 @@ FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDFPage_GenerateContent(FPDF_PAGE page) { return false; } + // Invalidate any in-flight progressive render context on `pPage` since + // mutating page content invalidates the active render state. + pPage->ClearRenderContext(); CPDF_PageContentGenerator CG(pPage); CG.GenerateContent(); return true; diff --git a/fpdfsdk/fpdf_editpage_embeddertest.cpp b/fpdfsdk/fpdf_editpage_embeddertest.cpp index ca5908dd58..08969612b3 100644 --- a/fpdfsdk/fpdf_editpage_embeddertest.cpp +++ b/fpdfsdk/fpdf_editpage_embeddertest.cpp @@ -9,6 +9,7 @@ #include "core/fxcrt/fx_system.h" #include "core/fxge/cfx_renderdevice.h" +#include "public/fpdf_progressive.h" #include "testing/embedder_test.h" #include "testing/gmock/include/gmock/gmock.h" @@ -17,6 +18,18 @@ using ::testing::Eq; using ::testing::FloatEq; using ::testing::Gt; +namespace { + +struct FakePause : public IFSDK_PAUSE { + FakePause() { + version = 1; + user = nullptr; + NeedToPauseNow = [](IFSDK_PAUSE*) -> FPDF_BOOL { return true; }; + } +}; + +} // namespace + class FPDFEditPageEmbedderTest : public EmbedderTest {}; TEST_F(FPDFEditPageEmbedderTest, Rotation) { @@ -703,3 +716,22 @@ TEST_F(FPDFEditPageEmbedderTest, Bug378464305) { EXPECT_EQ(kObjectCountWithNewPath, FPDFPage_CountObjects(saved_page.get())); } } + +TEST_F(FPDFEditPageEmbedderTest, GenerateContentClearsRenderContext) { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + ScopedFPDFBitmap bitmap(FPDFBitmap_Create(200, 300, 0)); + ASSERT_TRUE(bitmap); + + FakePause pause; + int rv = FPDF_RenderPageBitmap_Start(bitmap.get(), page.get(), 0, 0, 200, 300, + 0, 0, &pause); + EXPECT_EQ(rv, FPDF_RENDER_TOBECONTINUED); + + EXPECT_TRUE(FPDFPage_GenerateContent(page.get())); + + int cont_rv = FPDF_RenderPage_Continue(page.get(), &pause); + EXPECT_EQ(cont_rv, FPDF_RENDER_FAILED); +} diff --git a/fpdfsdk/fpdf_text_embeddertest.cpp b/fpdfsdk/fpdf_text_embeddertest.cpp index 5164d4c90d..85769373fa 100644 --- a/fpdfsdk/fpdf_text_embeddertest.cpp +++ b/fpdfsdk/fpdf_text_embeddertest.cpp @@ -2547,6 +2547,8 @@ TEST_F(FPDFTextEmbedderTest, ActualTextRtl) { // Third line: 'M', 'i', 'r', 'r', 'o', 'r', 'e', 'd', ' ', // ם: + // TODO(crbug.com/525087036): Should be {0x05dd, '[', ')'}, since + // /ActualText should not be modified. 0x05dd, ']', '(', '\r', '\n', // Pure RTL case: // שלום (logical order): @@ -2600,6 +2602,46 @@ TEST_F(FPDFTextEmbedderTest, ActualTextRtl) { ElementsAreArray(kExpectedText)); } +// Like ActualTextRtl, but the /ActualText spans mark RTL glyphs instead of +// Latin ones, which takes different code paths in CPDF_TextPage, and the +// /ActualText also contains numbers and punctuation. +TEST_F(FPDFTextEmbedderTest, ActualTextOnRtlGlyphsWithNumbersAndPunctuation) { + ASSERT_TRUE(OpenDocument("actual_text_rtl_glyphs.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + ScopedFPDFTextPage text_page(FPDFText_LoadPage(page.get())); + ASSERT_TRUE(text_page); + + // EmbedPDF(bug-fix): what the fork extracts. Its /ActualText rules keep the + // letters of every line in typed order and get lines 2 and 5 right; the + // digits and punctuation of lines 3, 4 and 6 still land on the wrong side. + static constexpr auto kExpectedText = std::to_array( + {// בין (literal text): + 0x05d1, 0x05d9, 0x05df, '\r', '\n', + // בין + 0x05d1, 0x05d9, 0x05df, '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {0x05d1, '\'', 0x05d9, 0x05df, '.'}. + '.', 0x05d1, '\'', 0x05d9, 0x05df, '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {0x05d1, 0x05d9, 0x05df, '1', '2', '3'}. + '1', '2', '3', 0x05d1, 0x05d9, 0x05df, '\r', '\n', + // Hello world בין. + 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 0x05d1, + 0x05d9, 0x05df, '.', '\r', '\n', + // TODO(crbug.com/525087036): Should be + // {'1', '-', ' ', 0x05d1, 0x05d9, 0x05df}. + 0x05d1, 0x05d9, 0x05df, ' ', '1', '-', '\0'}); + static constexpr int kExpectedTextSize = std::size(kExpectedText); + + unsigned short buffer[128] = {}; + EXPECT_EQ(kExpectedTextSize, + FPDFText_GetText(text_page.get(), 0, std::size(buffer), buffer)); + EXPECT_THAT(pdfium::span(buffer).first(), + ElementsAreArray(kExpectedText)); +} + TEST_F(FPDFTextEmbedderTest, Arabic) { ASSERT_TRUE(OpenDocument("arabic.pdf")); ScopedPage page = LoadScopedPage(0); @@ -2659,3 +2701,28 @@ TEST_F(FPDFTextEmbedderTest, ArabicActualTextOrdering) { ElementsAreArray(expected_page)); } } + +TEST_F(FPDFTextEmbedderTest, RtlMultiCharGlyph) { + ASSERT_TRUE(OpenDocument("rtl_multi_char_glyph.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + ScopedFPDFTextPage text_page(FPDFText_LoadPage(page.get())); + ASSERT_TRUE(text_page); + + static constexpr auto kExpectedText = std::to_array( + {// TODO(crbug.com/575985355): Should be سلام کلاس لاله, with lam and + // alef in ToUnicode order. + 0x0633, 0x0627, 0x0644, 0x0645, ' ', 0x06a9, 0x0627, 0x0644, 0x0633, ' ', + 0x0627, 0x0644, 0x0644, 0x0647, '\r', '\n', + // سلام کلاس لاله (mirrored matrix): + 0x0633, 0x0644, 0x0627, 0x0645, ' ', 0x06a9, 0x0644, 0x0627, 0x0633, ' ', + 0x0644, 0x0627, 0x0644, 0x0647, '\0'}); + static constexpr int kExpectedTextSize = std::size(kExpectedText); + + unsigned short buffer[64] = {}; + EXPECT_EQ(kExpectedTextSize, + FPDFText_GetText(text_page.get(), 0, std::size(buffer), buffer)); + EXPECT_THAT(pdfium::span(buffer).first(), + ElementsAreArray(kExpectedText)); +} diff --git a/fpdfsdk/fpdf_transformpage_embeddertest.cpp b/fpdfsdk/fpdf_transformpage_embeddertest.cpp index 2be3ea0bf1..2d50aa46d0 100644 --- a/fpdfsdk/fpdf_transformpage_embeddertest.cpp +++ b/fpdfsdk/fpdf_transformpage_embeddertest.cpp @@ -331,6 +331,127 @@ TEST_F(FPDFTransformEmbedderTest, SetMediaBox) { } } +TEST_F(FPDFTransformEmbedderTest, SetBleedBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF bleedbox; + EXPECT_FALSE(FPDFPage_GetBleedBox(page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + + // Null page does not crash. + FPDFPage_SetBleedBox(nullptr, 15, 25, 120, 180); + + FPDFPage_SetBleedBox(page.get(), 15, 25, 120, 180); + EXPECT_TRUE(FPDFPage_GetBleedBox(page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + EXPECT_EQ(15, bleedbox.left); + EXPECT_EQ(25, bleedbox.bottom); + EXPECT_EQ(120, bleedbox.right); + EXPECT_EQ(180, bleedbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF bleedbox; + EXPECT_TRUE(FPDFPage_GetBleedBox(saved_page.get(), &bleedbox.left, + &bleedbox.bottom, &bleedbox.right, + &bleedbox.top)); + EXPECT_EQ(15, bleedbox.left); + EXPECT_EQ(25, bleedbox.bottom); + EXPECT_EQ(120, bleedbox.right); + EXPECT_EQ(180, bleedbox.top); + } +} + +TEST_F(FPDFTransformEmbedderTest, SetTrimBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF trimbox; + EXPECT_FALSE(FPDFPage_GetTrimBox(page.get(), &trimbox.left, &trimbox.bottom, + &trimbox.right, &trimbox.top)); + + // Null page does not crash. + FPDFPage_SetTrimBox(nullptr, 20, 30, 110, 170); + + FPDFPage_SetTrimBox(page.get(), 20, 30, 110, 170); + EXPECT_TRUE(FPDFPage_GetTrimBox(page.get(), &trimbox.left, &trimbox.bottom, + &trimbox.right, &trimbox.top)); + EXPECT_EQ(20, trimbox.left); + EXPECT_EQ(30, trimbox.bottom); + EXPECT_EQ(110, trimbox.right); + EXPECT_EQ(170, trimbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF trimbox; + EXPECT_TRUE(FPDFPage_GetTrimBox(saved_page.get(), &trimbox.left, + &trimbox.bottom, &trimbox.right, + &trimbox.top)); + EXPECT_EQ(20, trimbox.left); + EXPECT_EQ(30, trimbox.bottom); + EXPECT_EQ(110, trimbox.right); + EXPECT_EQ(170, trimbox.top); + } +} + +TEST_F(FPDFTransformEmbedderTest, SetArtBox) { + { + ASSERT_TRUE(OpenDocument("rectangles.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + + FS_RECTF artbox; + EXPECT_FALSE(FPDFPage_GetArtBox(page.get(), &artbox.left, &artbox.bottom, + &artbox.right, &artbox.top)); + + // Null page does not crash. + FPDFPage_SetArtBox(nullptr, 25, 35, 100, 160); + + FPDFPage_SetArtBox(page.get(), 25, 35, 100, 160); + EXPECT_TRUE(FPDFPage_GetArtBox(page.get(), &artbox.left, &artbox.bottom, + &artbox.right, &artbox.top)); + EXPECT_EQ(25, artbox.left); + EXPECT_EQ(35, artbox.bottom); + EXPECT_EQ(100, artbox.right); + EXPECT_EQ(160, artbox.top); + } + + { + EXPECT_TRUE(FPDF_SaveAsCopy(document(), this, 0)); + ScopedSavedDoc saved_document = OpenScopedSavedDocument(); + ASSERT_TRUE(saved_document); + ScopedSavedPage saved_page = LoadScopedSavedPage(0); + ASSERT_TRUE(saved_page); + + FS_RECTF artbox; + EXPECT_TRUE(FPDFPage_GetArtBox(saved_page.get(), &artbox.left, + &artbox.bottom, &artbox.right, &artbox.top)); + EXPECT_EQ(25, artbox.left); + EXPECT_EQ(35, artbox.bottom); + EXPECT_EQ(100, artbox.right); + EXPECT_EQ(160, artbox.top); + } +} + TEST_F(FPDFTransformEmbedderTest, ClipPath) { ASSERT_TRUE(OpenDocument("hello_world.pdf")); diff --git a/fxbarcode/cbc_onecode.cpp b/fxbarcode/cbc_onecode.cpp index f5e5ef0f62..b59a13c319 100644 --- a/fxbarcode/cbc_onecode.cpp +++ b/fxbarcode/cbc_onecode.cpp @@ -50,10 +50,6 @@ void CBC_OneCode::SetFontSize(float size) { GetOneDimWriter()->SetFontSize(size); } -void CBC_OneCode::SetFontStyle(int32_t style) { - GetOneDimWriter()->SetFontStyle(style); -} - void CBC_OneCode::SetFontColor(FX_ARGB color) { GetOneDimWriter()->SetFontColor(color); } diff --git a/fxbarcode/cbc_onecode.h b/fxbarcode/cbc_onecode.h index 1eb313ff5f..1ddc48f947 100644 --- a/fxbarcode/cbc_onecode.h +++ b/fxbarcode/cbc_onecode.h @@ -27,7 +27,6 @@ class CBC_OneCode : public CBC_CodeBase { void SetCalChecksum(bool calc); bool SetFont(CFX_Font* cFont); void SetFontSize(float size); - void SetFontStyle(int32_t style); void SetFontColor(FX_ARGB color); private: diff --git a/fxbarcode/cfx_barcode_unittest.cpp b/fxbarcode/cfx_barcode_unittest.cpp index 626ed13565..53ccec1780 100644 --- a/fxbarcode/cfx_barcode_unittest.cpp +++ b/fxbarcode/cfx_barcode_unittest.cpp @@ -251,3 +251,182 @@ TEST_F(BarcodeTest, QrCode) { #endif EXPECT_EQ(kExpectedChecksum, BitmapChecksum()); } + +TEST_F(BarcodeTest, GetType) { + Create(BC_TYPE::kCode39); + EXPECT_EQ(BC_TYPE::kCode39, barcode()->GetType()); + + Create(BC_TYPE::kCodabar); + EXPECT_EQ(BC_TYPE::kCodabar, barcode()->GetType()); + + Create(BC_TYPE::kCode128); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kCode128B); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kCode128C); + EXPECT_EQ(BC_TYPE::kCode128, barcode()->GetType()); + + Create(BC_TYPE::kEAN8); + EXPECT_EQ(BC_TYPE::kEAN8, barcode()->GetType()); + + Create(BC_TYPE::kUPCA); + EXPECT_EQ(BC_TYPE::kUPCA, barcode()->GetType()); + + Create(BC_TYPE::kEAN13); + EXPECT_EQ(BC_TYPE::kEAN13, barcode()->GetType()); + + Create(BC_TYPE::kQRCode); + EXPECT_EQ(BC_TYPE::kQRCode, barcode()->GetType()); + + Create(BC_TYPE::kPDF417); + EXPECT_EQ(BC_TYPE::kPDF417, barcode()->GetType()); + + Create(BC_TYPE::kDataMatrix); + EXPECT_EQ(BC_TYPE::kDataMatrix, barcode()->GetType()); +} + +TEST_F(BarcodeTest, SetStartEndChar) { + Create(BC_TYPE::kCodabar); + EXPECT_TRUE(barcode()->SetStartChar('A')); + EXPECT_TRUE(barcode()->SetStartChar('B')); + EXPECT_TRUE(barcode()->SetStartChar('C')); + EXPECT_TRUE(barcode()->SetStartChar('D')); + EXPECT_TRUE(barcode()->SetStartChar('E')); + EXPECT_TRUE(barcode()->SetStartChar('N')); + EXPECT_TRUE(barcode()->SetStartChar('T')); + EXPECT_TRUE(barcode()->SetStartChar('*')); + EXPECT_FALSE(barcode()->SetStartChar('X')); + EXPECT_FALSE(barcode()->SetStartChar('0')); + EXPECT_FALSE(barcode()->SetStartChar('\0')); + + EXPECT_TRUE(barcode()->SetEndChar('A')); + EXPECT_TRUE(barcode()->SetEndChar('B')); + EXPECT_TRUE(barcode()->SetEndChar('C')); + EXPECT_TRUE(barcode()->SetEndChar('D')); + EXPECT_TRUE(barcode()->SetEndChar('E')); + EXPECT_TRUE(barcode()->SetEndChar('N')); + EXPECT_TRUE(barcode()->SetEndChar('T')); + EXPECT_TRUE(barcode()->SetEndChar('*')); + EXPECT_FALSE(barcode()->SetEndChar('X')); + EXPECT_FALSE(barcode()->SetEndChar('0')); + EXPECT_FALSE(barcode()->SetEndChar('\0')); + + Create(BC_TYPE::kCode39); + EXPECT_FALSE(barcode()->SetStartChar('A')); + EXPECT_FALSE(barcode()->SetEndChar('A')); + + Create(BC_TYPE::kQRCode); + EXPECT_FALSE(barcode()->SetStartChar('A')); + EXPECT_FALSE(barcode()->SetEndChar('A')); +} + +TEST_F(BarcodeTest, OneDimVsTwoDimProperties) { + Create(BC_TYPE::kCode39); + EXPECT_TRUE(barcode()->SetPrintChecksum(true)); + EXPECT_TRUE(barcode()->SetDataLength(10)); + EXPECT_TRUE(barcode()->SetCalChecksum(true)); + EXPECT_TRUE(barcode()->SetFontSize(12.0f)); + EXPECT_TRUE(barcode()->SetFontColor(0xFF000000)); + EXPECT_TRUE(barcode()->SetWideNarrowRatio(2)); + EXPECT_TRUE(barcode()->SetWideNarrowRatio(3)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(1)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(4)); + + Create(BC_TYPE::kQRCode); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); + + Create(BC_TYPE::kPDF417); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); + + Create(BC_TYPE::kDataMatrix); + EXPECT_FALSE(barcode()->SetPrintChecksum(true)); + EXPECT_FALSE(barcode()->SetDataLength(10)); + EXPECT_FALSE(barcode()->SetCalChecksum(true)); + EXPECT_FALSE(barcode()->SetFontSize(12.0f)); + EXPECT_FALSE(barcode()->SetFontColor(0xFF000000)); + EXPECT_FALSE(barcode()->SetWideNarrowRatio(2)); +} + +TEST_F(BarcodeTest, ErrorCorrectionLevel) { + Create(BC_TYPE::kQRCode); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(1)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(2)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(3)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(-1)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(4)); + + Create(BC_TYPE::kPDF417); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(4)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(8)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(-1)); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(9)); + + Create(BC_TYPE::kDataMatrix); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(0)); + EXPECT_TRUE(barcode()->SetErrorCorrectionLevel(3)); + + Create(BC_TYPE::kCode39); + EXPECT_FALSE(barcode()->SetErrorCorrectionLevel(0)); +} + +TEST_F(BarcodeTest, ModuleDimensionsAndTextLocation) { + Create(BC_TYPE::kCode39); + EXPECT_TRUE(barcode()->SetModuleHeight(1)); + EXPECT_TRUE(barcode()->SetModuleHeight(5)); + EXPECT_TRUE(barcode()->SetModuleHeight(10)); + EXPECT_FALSE(barcode()->SetModuleHeight(0)); + EXPECT_FALSE(barcode()->SetModuleHeight(11)); + + EXPECT_TRUE(barcode()->SetModuleWidth(1)); + EXPECT_TRUE(barcode()->SetModuleWidth(5)); + EXPECT_TRUE(barcode()->SetModuleWidth(10)); + EXPECT_FALSE(barcode()->SetModuleWidth(0)); + EXPECT_FALSE(barcode()->SetModuleWidth(11)); + + barcode()->SetTextLocation(BC_TEXT_LOC::kNone); + barcode()->SetTextLocation(BC_TEXT_LOC::kAbove); + barcode()->SetTextLocation(BC_TEXT_LOC::kBelow); + barcode()->SetTextLocation(BC_TEXT_LOC::kAboveEmbed); + barcode()->SetTextLocation(BC_TEXT_LOC::kBelowEmbed); +} + +TEST_F(BarcodeTest, EanTruncation) { + Create(BC_TYPE::kEAN8); + EXPECT_TRUE(barcode()->Encode(L"1234567890")); + + Create(BC_TYPE::kEAN13); + EXPECT_TRUE(barcode()->Encode(L"1234567890123456")); + + Create(BC_TYPE::kUPCA); + EXPECT_TRUE(barcode()->Encode(L"1234567890123456")); +} + +TEST_F(BarcodeTest, Code128COddLengthPadded) { + Create(BC_TYPE::kCode128C); + EXPECT_TRUE(barcode()->Encode(L"123")); + RenderDevice(); +} + +TEST_F(BarcodeTest, ValidationFailures) { + Create(BC_TYPE::kCode128); + EXPECT_FALSE(barcode()->Encode(L"")); + EXPECT_FALSE(barcode()->Encode(L"\"")); + + Create(BC_TYPE::kDataMatrix); + WideString long_str(std::wstring(3117, L'1').c_str()); + EXPECT_FALSE(barcode()->Encode(long_str.AsStringView())); +} diff --git a/fxbarcode/oned/BC_OneDimWriter.cpp b/fxbarcode/oned/BC_OneDimWriter.cpp index 3b59b1114f..1f99886db5 100644 --- a/fxbarcode/oned/BC_OneDimWriter.cpp +++ b/fxbarcode/oned/BC_OneDimWriter.cpp @@ -77,10 +77,6 @@ void CBC_OneDimWriter::SetFontSize(float size) { font_size_ = size; } -void CBC_OneDimWriter::SetFontStyle(int32_t style) { - font_style_ = style; -} - void CBC_OneDimWriter::SetFontColor(FX_ARGB color) { font_color_ = color; } diff --git a/fxbarcode/oned/BC_OneDimWriter.h b/fxbarcode/oned/BC_OneDimWriter.h index 7228005e92..509af9fc65 100644 --- a/fxbarcode/oned/BC_OneDimWriter.h +++ b/fxbarcode/oned/BC_OneDimWriter.h @@ -45,7 +45,6 @@ class CBC_OneDimWriter : public CBC_Writer { void SetPrintChecksum(bool checksum); void SetCalcChecksum(bool state); void SetFontSize(float size); - void SetFontStyle(int32_t style); void SetFontColor(FX_ARGB color); virtual DataVector Encode(const ByteString& contents) = 0; @@ -84,7 +83,6 @@ class CBC_OneDimWriter : public CBC_Writer { UnownedPtr font_; float font_size_ = 10.0f; - int32_t font_style_ = 0; uint32_t font_color_ = 0xff000000; BC_TEXT_LOC loc_text_loc_ = BC_TEXT_LOC::kBelowEmbed; diff --git a/fxjs/fx_date_helpers_unittest.cpp b/fxjs/fx_date_helpers_unittest.cpp index 9a4efc4724..3b6aa94261 100644 --- a/fxjs/fx_date_helpers_unittest.cpp +++ b/fxjs/fx_date_helpers_unittest.cpp @@ -4,6 +4,8 @@ #include "fxjs/fx_date_helpers.h" +#include + #include "core/fxcrt/fake_time_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -185,6 +187,118 @@ TEST(FXDateHelperTest, GetDayOfWeekFromTime) { } } +TEST(FXDateHelperTest, GetHourFromTime) { + EXPECT_EQ(0, FX_GetHourFromTime(0)); + EXPECT_EQ(1, FX_GetHourFromTime(3'600'000)); + EXPECT_EQ(12, FX_GetHourFromTime(12 * 3'600'000)); + EXPECT_EQ(23, FX_GetHourFromTime(23 * 3'600'000)); + EXPECT_EQ(0, FX_GetHourFromTime(24 * 3'600'000)); + EXPECT_EQ(23, FX_GetHourFromTime(-1)); + EXPECT_EQ(23, FX_GetHourFromTime(-3'600'000)); + EXPECT_EQ(22, FX_GetHourFromTime(-3'600'001)); +} + +TEST(FXDateHelperTest, GetMinFromTime) { + EXPECT_EQ(0, FX_GetMinFromTime(0)); + EXPECT_EQ(1, FX_GetMinFromTime(60'000)); + EXPECT_EQ(30, FX_GetMinFromTime(30 * 60'000)); + EXPECT_EQ(59, FX_GetMinFromTime(59 * 60'000)); + EXPECT_EQ(0, FX_GetMinFromTime(60 * 60'000)); + EXPECT_EQ(59, FX_GetMinFromTime(-1)); + EXPECT_EQ(59, FX_GetMinFromTime(-60'000)); + EXPECT_EQ(58, FX_GetMinFromTime(-60'001)); +} + +TEST(FXDateHelperTest, GetSecFromTime) { + EXPECT_EQ(0, FX_GetSecFromTime(0)); + EXPECT_EQ(1, FX_GetSecFromTime(1'000)); + EXPECT_EQ(45, FX_GetSecFromTime(45 * 1'000)); + EXPECT_EQ(59, FX_GetSecFromTime(59 * 1'000)); + EXPECT_EQ(0, FX_GetSecFromTime(60 * 1'000)); + EXPECT_EQ(59, FX_GetSecFromTime(-1)); + EXPECT_EQ(59, FX_GetSecFromTime(-1'000)); + EXPECT_EQ(58, FX_GetSecFromTime(-1'001)); +} + +TEST(FXDateHelperTest, ValidationHelpers) { + EXPECT_FALSE(FX_IsValidMonth(0)); + EXPECT_TRUE(FX_IsValidMonth(1)); + EXPECT_TRUE(FX_IsValidMonth(12)); + EXPECT_FALSE(FX_IsValidMonth(13)); + EXPECT_FALSE(FX_IsValidMonth(-1)); + + EXPECT_FALSE(FX_IsValidDay(0)); + EXPECT_TRUE(FX_IsValidDay(1)); + EXPECT_TRUE(FX_IsValidDay(31)); + EXPECT_FALSE(FX_IsValidDay(32)); + EXPECT_FALSE(FX_IsValidDay(-1)); + + EXPECT_FALSE(FX_IsValid24Hour(-1)); + EXPECT_TRUE(FX_IsValid24Hour(0)); + EXPECT_TRUE(FX_IsValid24Hour(24)); + EXPECT_FALSE(FX_IsValid24Hour(25)); + + EXPECT_FALSE(FX_IsValidMinute(-1)); + EXPECT_TRUE(FX_IsValidMinute(0)); + EXPECT_TRUE(FX_IsValidMinute(60)); + EXPECT_FALSE(FX_IsValidMinute(61)); + + EXPECT_FALSE(FX_IsValidSecond(-1)); + EXPECT_TRUE(FX_IsValidSecond(0)); + EXPECT_TRUE(FX_IsValidSecond(60)); + EXPECT_FALSE(FX_IsValidSecond(61)); +} + +TEST(FXDateHelperTest, MakeDay) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeDay(1970, 0, 1)); + EXPECT_DOUBLE_EQ(1.0, FX_MakeDay(1970, 0, 2)); + EXPECT_DOUBLE_EQ(31.0, FX_MakeDay(1970, 1, 1)); + EXPECT_DOUBLE_EQ(2 * 365 + 31 + 28, FX_MakeDay(1972, 1, 29)); + EXPECT_DOUBLE_EQ(2 * 365 + 31 + 29, FX_MakeDay(1972, 2, 1)); + EXPECT_DOUBLE_EQ(365.0, FX_MakeDay(1970, 12, 1)); + EXPECT_DOUBLE_EQ(-31.0, FX_MakeDay(1970, -1, 1)); +} + +TEST(FXDateHelperTest, MakeTime) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeTime(0, 0, 0, 0)); + EXPECT_DOUBLE_EQ(3'723'004.0, FX_MakeTime(1, 2, 3, 4)); +} + +TEST(FXDateHelperTest, MakeDate) { + EXPECT_DOUBLE_EQ(0.0, FX_MakeDate(0, 0)); + EXPECT_DOUBLE_EQ(86'400'500.0, FX_MakeDate(1, 500)); + EXPECT_TRUE(isnan(FX_MakeDate(nan(""), 0))); + EXPECT_TRUE(isnan(FX_MakeDate(0, nan("")))); + EXPECT_TRUE(isnan(FX_MakeDate(INFINITY, 0))); + EXPECT_TRUE(isnan(FX_MakeDate(0, INFINITY))); +} + +TEST(FXDateHelperTest, ParseStringInteger) { + size_t skip = 0; + EXPECT_EQ(123, FX_ParseStringInteger(L"12345", 0, &skip, 3)); + EXPECT_EQ(3u, skip); + + skip = 0; + EXPECT_EQ(12, FX_ParseStringInteger(L"12345", 0, &skip, 2)); + EXPECT_EQ(2u, skip); + + skip = 0; + EXPECT_EQ(12, FX_ParseStringInteger(L"12abc", 0, &skip, 4)); + EXPECT_EQ(2u, skip); + + skip = 1; + EXPECT_EQ(0, FX_ParseStringInteger(L"abc", 0, &skip, 2)); + EXPECT_EQ(0u, skip); + + skip = 1; + EXPECT_EQ(0, FX_ParseStringInteger(L"123", 5, &skip, 2)); + EXPECT_EQ(0u, skip); + + skip = 0; + EXPECT_EQ(123456789, FX_ParseStringInteger(L"123456789abc", 0, &skip, 15)); + EXPECT_EQ(9u, skip); +} + using FXDateHelperFakeTimeTest = FakeTimeTest; TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatWithEmptyParams) { @@ -192,9 +306,13 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatWithEmptyParams) { EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"", L"", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"value", L"", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"", L"format", &result)); EXPECT_DOUBLE_EQ(1'587'654'321'000, result); @@ -205,29 +323,43 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForValidMonthDay) { EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"01/02/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"1/2/2000", L"m/d/yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"1-2-2000", L"m-d-yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2-1-2000", L"d-m-yyyy", &result)); EXPECT_DOUBLE_EQ(946'825'521'000, result); + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11/12/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11/12/2000", L"m/d/yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"11-12-2000", L"m-d-yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"12-11-2000", L"d-m-yyyy", &result)); EXPECT_DOUBLE_EQ(974'041'521'000, result); + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"02/29/2000", L"mm/dd/yyyy", &result)); EXPECT_DOUBLE_EQ(951'836'721'000, result); @@ -235,77 +367,314 @@ TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForValidMonthDay) { TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatFor12HourTime) { double result = 0.0; - const double kBaseDay = FX_MakeDay(2020, 3, 23); // 12:30:00 PM is 12:30. EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 pm", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 PM", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); // 12:30:00 AM is 00:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 am", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 AM", L"yyyy/mm/dd hh:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); // 1:30:00 PM is 13:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 pm", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(13, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'648'600'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 PM", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(13, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'648'600'000, result); // 1:30:00 AM is 01:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 am", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(1, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'605'400'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 AM", L"yyyy/mm/dd h:MM:ss tt", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(1, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'605'400'000, result); // Single 't' marker. // 12:30:00 P is 12:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 p", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 P", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(12, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'645'000'000, result); // 12:30:00 A is 00:30. + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 a", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); + + result = 0.0; EXPECT_EQ(ConversionStatus::kSuccess, FX_ParseDateUsingFormat(L"2020/04/23 12:30:00 A", L"yyyy/mm/dd hh:MM:ss t", &result)); - EXPECT_DOUBLE_EQ(FX_MakeDate(kBaseDay, FX_MakeTime(0, 30, 0, 0)), result); + EXPECT_DOUBLE_EQ(1'587'601'800'000, result); // Malformed AM/PM markers should return kBadFormat. + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 xm", L"yyyy/mm/dd h:MM:ss tt", &result)); + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 px", L"yyyy/mm/dd h:MM:ss tt", &result)); + result = 0.0; EXPECT_EQ(ConversionStatus::kBadFormat, FX_ParseDateUsingFormat(L"2020/04/23 1:30:00 x", L"yyyy/mm/dd h:MM:ss t", &result)); } + +TEST_F(FXDateHelperFakeTimeTest, GetDateTime) { + EXPECT_DOUBLE_EQ(1'587'654'321'000.0, FX_GetDateTime()); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForFullMonthNames) { + double result = 0.0; + static constexpr struct { + const wchar_t* input; + double expected; + } kTests[] = { + {L"January 15, 2020", 1'579'100'721'000}, + {L"February 15, 2020", 1'581'779'121'000}, + {L"March 15, 2020", 1'584'284'721'000}, + {L"April 15, 2020", 1'586'963'121'000}, + {L"May 15, 2020", 1'589'555'121'000}, + {L"June 15, 2020", 1'592'233'521'000}, + {L"July 15, 2020", 1'594'825'521'000}, + {L"August 15, 2020", 1'597'503'921'000}, + {L"September 15, 2020", 1'600'182'321'000}, + {L"October 15, 2020", 1'602'774'321'000}, + {L"November 15, 2020", 1'605'452'721'000}, + {L"December 15, 2020", 1'608'044'721'000}, + }; + + for (const auto& test : kTests) { + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(test.input, L"mmmm dd, yyyy", &result)) + << test.input; + EXPECT_DOUBLE_EQ(test.expected, result) << test.input; + } +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatForAbbreviatedMonthNames) { + double result = 0.0; + static constexpr struct { + const wchar_t* input; + double expected; + } kTests[] = { + {L"Jan 15, 2020", 1'579'100'721'000}, + {L"feb 15, 2020", 1'581'779'121'000}, + {L"MAR 15, 2020", 1'584'284'721'000}, + {L"Apr 15, 2020", 1'586'963'121'000}, + {L"May 15, 2020", 1'589'555'121'000}, + {L"Jun 15, 2020", 1'592'233'521'000}, + {L"Jul 15, 2020", 1'594'825'521'000}, + {L"Aug 15, 2020", 1'597'503'921'000}, + {L"Sep 15, 2020", 1'600'182'321'000}, + {L"Oct 15, 2020", 1'602'774'321'000}, + {L"Nov 15, 2020", 1'605'452'721'000}, + {L"Dec 15, 2020", 1'608'044'721'000}, + }; + + for (const auto& test : kTests) { + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(test.input, L"mmm dd, yyyy", &result)) + << test.input; + EXPECT_DOUBLE_EQ(test.expected, result) << test.input; + } +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatNumericMonthFallback) { + double result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"03 15, 2020", L"mmm dd, yyyy", &result)); + EXPECT_DOUBLE_EQ(1'584'284'721'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"07 15, 2020", L"mmmm dd, yyyy", &result)); + EXPECT_DOUBLE_EQ(1'594'825'521'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatTwoDigitYear) { + double result = 0.0; + // Year < 50 maps to 2000s. + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/20", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/49", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(2'502'803'121'000, result); + + // Year >= 50 maps to 1900s. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/50", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(-621'420'879'000, result); + + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"04/23/99", L"mm/dd/yy", &result)); + EXPECT_DOUBLE_EQ(924'879'921'000, result); + + // 1-digit year 'y' skips 1 character, retaining current year. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"x 04/23", L"y mm/dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatSeparatorsAndLiterals) { + double result = 0.0; + // Dots, colons, and 24-hour 'HH'. + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020.04.23 18:30:45", + L"yyyy.mm.dd HH:MM:ss", &result)); + EXPECT_DOUBLE_EQ(1'587'666'645'000, result); + + // Backslashes. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020\\04\\23", L"yyyy\\mm\\dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len == 3 with non-m/y format character skips 3 characters. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"abc/04/23/2020", L"ddd/mm/dd/yyyy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len == 4 with non-m/y format character skips 4 characters. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"abcd/04/23/2020", L"dddd/mm/dd/yyyy", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // token_len > 4 matching literal characters. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"ddddd/04/23/2020", L"ddddd/mm/dd/yyyy", + &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // Separators are interchangeable: '-' in value matches '/' in format. + result = 0.0; + EXPECT_EQ(ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020-04-23", L"yyyy/mm/dd", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); + + // Trailing format characters when value ends are ignored. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kSuccess, + FX_ParseDateUsingFormat(L"2020/04/23", L"yyyy/mm/dd Extra", &result)); + EXPECT_DOUBLE_EQ(1'587'654'321'000, result); +} + +TEST_F(FXDateHelperFakeTimeTest, ParseDateUsingFormatErrors) { + double result = 0.0; + // Literal mismatch. + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"2020/04/23 X 12:00:00", + L"yyyy/mm/dd T HH:MM:ss", &result)); + + // token_len > 4 literal mismatch. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"12345/04/23/2020", L"ddddd/mm/dd/yyyy", + &result)); + + // 'yyy' token in format does not advance value_idx, triggering bad format. + result = 0.0; + EXPECT_EQ( + ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"abc 04/23/2020", L"yyy mm/dd/yyyy", &result)); + + // Long non-month word exceeding kLongestFullMonthLength. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadFormat, + FX_ParseDateUsingFormat(L"Superlonginvalidmonth 15, 2020", + L"mmmm dd, yyyy", &result)); + + // Invalid date components (kBadDate): + // Month out of range (13). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/13/15", L"yyyy/mm/dd", &result)); + + // Month 0. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/00/15", L"yyyy/mm/dd", &result)); + + // Day out of range (32). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/32", L"yyyy/mm/dd", &result)); + + // Day 0. + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/00", L"yyyy/mm/dd", &result)); + + // Hour out of range (25). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 25:00:00", + L"yyyy/mm/dd HH:MM:ss", &result)); + + // Minute out of range (61). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 12:61:00", + L"yyyy/mm/dd HH:MM:ss", &result)); + + // Second out of range (61). + result = 0.0; + EXPECT_EQ(ConversionStatus::kBadDate, + FX_ParseDateUsingFormat(L"2020/04/23 12:00:61", + L"yyyy/mm/dd HH:MM:ss", &result)); +} diff --git a/fxjs/xfa/cfxjse_context.cpp b/fxjs/xfa/cfxjse_context.cpp index bdb512ffa2..6132fe0c0e 100644 --- a/fxjs/xfa/cfxjse_context.cpp +++ b/fxjs/xfa/cfxjse_context.cpp @@ -22,6 +22,7 @@ #include "v8/include/v8-function.h" #include "v8/include/v8-message.h" #include "v8/include/v8-script.h" +#include "v8/include/v8-template.h" #include "xfa/fxfa/parser/cxfa_thisproxy.h" namespace { @@ -121,6 +122,17 @@ v8::Local CreateReturnValue(v8::Isolate* pIsolate, } // namespace +v8::Local FXJSE_CreateBoundObject( + v8::Isolate* isolate, + CFXJSE_HostObject* new_binding, + v8::Local function_template) { + v8::Local object = function_template->InstanceTemplate() + ->NewInstance(isolate->GetCurrentContext()) + .ToLocalChecked(); + FXJSE_UpdateObjectBinding(object, new_binding); + return object; +} + void FXJSE_UpdateObjectBinding(v8::Local hObject, CFXJSE_HostObject* pNewBinding) { DCHECK(!hObject.IsEmpty()); diff --git a/fxjs/xfa/cfxjse_context.h b/fxjs/xfa/cfxjse_context.h index fb736624b0..e0fc3a14b0 100644 --- a/fxjs/xfa/cfxjse_context.h +++ b/fxjs/xfa/cfxjse_context.h @@ -65,6 +65,11 @@ class CFXJSE_Context { cppgc::Persistent this_proxy_; }; +v8::Local FXJSE_CreateBoundObject( + v8::Isolate* isolate, + CFXJSE_HostObject* new_binding, + v8::Local function_template); + void FXJSE_UpdateObjectBinding(v8::Local hObject, CFXJSE_HostObject* pNewBinding); diff --git a/fxjs/xfa/cfxjse_engine.cpp b/fxjs/xfa/cfxjse_engine.cpp index 15f4bc94b9..24d79b6e04 100644 --- a/fxjs/xfa/cfxjse_engine.cpp +++ b/fxjs/xfa/cfxjse_engine.cpp @@ -151,6 +151,8 @@ CFXJSE_Engine::CFXJSE_Engine(CXFA_Document* document, v8::Isolate* isolate) &kGlobalClassDescriptor, document->GetRoot()->JSObject(), nullptr)), + up_object_array_(cppgc::MakeGarbageCollected>( + document->GetHeap()->GetAllocationHandle())), node_helper_(std::make_unique()), resolve_processor_( std::make_unique(this, node_helper_.get())) { @@ -615,11 +617,12 @@ CXFA_Script::Type CFXJSE_Engine::GetType() { } void CFXJSE_Engine::AddObjectToUpArray(CXFA_Node* pNode) { - up_object_array_.push_back(pNode); + up_object_array_->storage.push_back(pNode); } CXFA_Node* CFXJSE_Engine::LastObjectFromUpArray() { - return !up_object_array_.empty() ? up_object_array_.back() : nullptr; + return !up_object_array_->storage.empty() ? up_object_array_->storage.back() + : nullptr; } CFXJSE_Context* CFXJSE_Engine::CreateVariablesContext(CXFA_Script* pScriptNode, @@ -771,10 +774,10 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, !!(dwStyles & Mask{XFA_ResolveFlag::kParent, XFA_ResolveFlag::kSiblings}); if (script_type_ != CXFA_Script::Type::Formcalc || bParentOrSiblings) { - up_object_array_.clear(); + up_object_array_->storage.clear(); } if (refObject && refObject->IsNode() && bParentOrSiblings) { - up_object_array_.push_back(refObject->AsNode()); + up_object_array_->storage.push_back(refObject->AsNode()); } ResolveResult result; @@ -790,12 +793,18 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, int32_t nStart = 0; int32_t nLevel = 0; - std::vector> findObjects; - findObjects.emplace_back(refObject ? refObject : document_->GetRoot()); + cppgc::Persistent> find_objects = + cppgc::MakeGarbageCollected>( + document_->GetHeap()->GetAllocationHandle()); + find_objects->storage.emplace_back(refObject ? refObject + : document_->GetRoot()); + cppgc::Persistent> ret_objects = + cppgc::MakeGarbageCollected>( + document_->GetHeap()->GetAllocationHandle()); int32_t nNodes = 0; CFXJSE_ScopeUtil_IsolateHandleContext scope(GetJseContext()); while (true) { - nNodes = fxcrt::CollectionSize(findObjects); + nNodes = fxcrt::CollectionSize(find_objects->storage); int32_t i = 0; rndFind.styles_ = dwStyles; resolve_processor_->SetCurStart(nStart); @@ -805,21 +814,22 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, CXFA_Node* pDataNode = nullptr; nStart = node_helper_->cur_all_start_; if (nStart != -1) { - pDataNode = document_->GetNotBindNode(findObjects); + pDataNode = document_->GetNotBindNode(find_objects->storage); if (pDataNode) { - findObjects.clear(); - findObjects.emplace_back(pDataNode); + find_objects->storage.clear(); + find_objects->storage.emplace_back(pDataNode); break; } } else { - pDataNode = findObjects.front()->AsNode(); - findObjects.clear(); - findObjects.emplace_back(pDataNode); + pDataNode = find_objects->storage.front()->AsNode(); + find_objects->storage.clear(); + find_objects->storage.emplace_back(pDataNode); break; } dwStyles |= XFA_ResolveFlag::kBind; - findObjects.clear(); - findObjects.emplace_back(node_helper_->all_start_parent_.Get()); + find_objects->storage.clear(); + find_objects->storage.emplace_back( + node_helper_->all_start_parent_.Get()); continue; } break; @@ -833,7 +843,10 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, } break; } - std::vector> retObjects; + // Could make a new `ret_objects` every time through here, execpt + // that would generate needless cppgc heap garbage when only the + // backing-store has to change. + ret_objects->storage.clear(); while (i < nNodes) { bool bDataBind = false; if (((dwStyles & XFA_ResolveFlag::kBind) || @@ -844,7 +857,7 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, i = resolve_processor_->IndexForDataBind(rndBind.condition_, nNodes); bDataBind = true; } - rndFind.cur_object_ = findObjects[i++].Get(); + rndFind.cur_object_ = find_objects->storage[i++].Get(); rndFind.level_ = nLevel; rndFind.result_.type = ResolveResult::Type::kNodes; if (!resolve_processor_->Resolve(GetIsolate(), rndFind)) { @@ -863,19 +876,20 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, rndFind.result_.objects.front() = ToObject(GetIsolate(), pValue); } } - if (!up_object_array_.empty()) { - up_object_array_.pop_back(); + if (!up_object_array_->storage.empty()) { + up_object_array_->storage.pop_back(); } - retObjects.insert(retObjects.end(), rndFind.result_.objects.begin(), - rndFind.result_.objects.end()); + ret_objects->storage.insert(ret_objects->storage.end(), + rndFind.result_.objects.begin(), + rndFind.result_.objects.end()); rndFind.result_.objects.clear(); if (bDataBind) { break; } } - findObjects.clear(); + find_objects->storage.clear(); - nNodes = fxcrt::CollectionSize(retObjects); + nNodes = fxcrt::CollectionSize(ret_objects->storage); if (nNodes < 1) { if (dwStyles & XFA_ResolveFlag::kCreateNode) { bNextCreate = true; @@ -893,7 +907,7 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, break; } - findObjects = std::move(retObjects); + find_objects->storage = std::move(ret_objects->storage); rndFind.result_.objects.clear(); if (nLevel == 0) { dwStyles.Clear(XFA_ResolveFlag::kParent); @@ -905,8 +919,8 @@ CFXJSE_Engine::ResolveObjectsWithBindNode(CXFA_Object* refObject, if (!bNextCreate) { result.type = rndFind.result_.type; if (nNodes > 0) { - result.objects.insert(result.objects.end(), findObjects.begin(), - findObjects.end()); + result.objects.insert(result.objects.end(), find_objects->storage.begin(), + find_objects->storage.end()); } if (rndFind.result_.type == ResolveResult::Type::kAttribute) { result.script_attribute = rndFind.result_.script_attribute; @@ -990,8 +1004,12 @@ CXFA_Object* CFXJSE_Engine::ToXFAObject(v8::Local obj) { v8::Local CFXJSE_Engine::NewNormalXFAObject(CXFA_Object* obj) { v8::EscapableHandleScope scope(GetIsolate()); CJX_Object* js_object = obj->JSObject(); - v8::Local binding = js_object->NewBoundV8Object( - GetIsolate(), GetJseNormalClass()->GetTemplate(GetIsolate())); + auto iter = map_object_to_object_.find(js_object); + if (iter != map_object_to_object_.end()) { + return scope.Escape(v8::Local::New(GetIsolate(), iter->second)); + } + v8::Local binding = FXJSE_CreateBoundObject( + GetIsolate(), js_object, GetJseNormalClass()->GetTemplate(GetIsolate())); map_object_to_object_[js_object].Reset(GetIsolate(), binding); return scope.Escape(binding); } diff --git a/fxjs/xfa/cfxjse_engine.h b/fxjs/xfa/cfxjse_engine.h index 683b849d86..f253d6d46b 100644 --- a/fxjs/xfa/cfxjse_engine.h +++ b/fxjs/xfa/cfxjse_engine.h @@ -125,9 +125,9 @@ class CFXJSE_Engine final : public CFX_IsolateWrapper { ~EventParamScope(); private: - UnownedPtr engine_; - UnownedPtr prev_target_; - UnownedPtr prev_event_param_; + const UnownedPtr engine_; + CXFA_Node* const prev_target_ = nullptr; + const UnownedPtr prev_event_param_; }; friend class EventParamScope; @@ -225,7 +225,7 @@ class CFXJSE_Engine final : public CFX_IsolateWrapper { map_variable_to_context_; cppgc::Persistent target_; UnownedPtr event_param_; - std::vector> up_object_array_; + cppgc::Persistent> up_object_array_; cppgc::Persistent> script_node_array_; std::unique_ptr const node_helper_; std::unique_ptr const resolve_processor_; diff --git a/fxjs/xfa/cfxjse_formcalc_context.cpp b/fxjs/xfa/cfxjse_formcalc_context.cpp index 7b1f7912ac..2ea589d117 100644 --- a/fxjs/xfa/cfxjse_formcalc_context.cpp +++ b/fxjs/xfa/cfxjse_formcalc_context.cpp @@ -5112,9 +5112,9 @@ CFXJSE_FormCalcContext::CFXJSE_FormCalcContext(v8::Isolate* pIsolate, CFXJSE_Context* pScriptContext, CXFA_Document* doc) : isolate_(pIsolate), document_(doc) { - value_.Reset(isolate_, - NewBoundV8Object( - isolate_, CFXJSE_Class::Create(pScriptContext, + value_.Reset(isolate_, FXJSE_CreateBoundObject( + isolate_, this, + CFXJSE_Class::Create(pScriptContext, &kFormCalcDescriptor, false) ->GetTemplate(isolate_))); } diff --git a/fxjs/xfa/cfxjse_resolveprocessor.cpp b/fxjs/xfa/cfxjse_resolveprocessor.cpp index b74733d6e4..96cec1b38e 100644 --- a/fxjs/xfa/cfxjse_resolveprocessor.cpp +++ b/fxjs/xfa/cfxjse_resolveprocessor.cpp @@ -15,10 +15,12 @@ #include "core/fxcrt/containers/to_vector.h" #include "core/fxcrt/fx_extension.h" #include "fxjs/fxv8.h" +#include "fxjs/gc/containers.h" #include "fxjs/xfa/cfxjse_engine.h" #include "fxjs/xfa/cfxjse_isolatetracker.h" #include "fxjs/xfa/cfxjse_nodehelper.h" #include "fxjs/xfa/cjx_object.h" +#include "v8/include/cppgc/persistent.h" #include "xfa/fxfa/parser/cxfa_document.h" #include "xfa/fxfa/parser/cxfa_localemgr.h" #include "xfa/fxfa/parser/cxfa_node.h" @@ -763,13 +765,17 @@ void CFXJSE_ResolveProcessor::DoPredicateFilter(v8::Isolate* pIsolate, } else { return; } - WideString wsExpression = wsCondition.Substr(2, wsCondition.GetLength() - 3); + + cppgc::Persistent> candidates = + cppgc::MakeGarbageCollected>( + engine_->GetDocument()->GetHeap()->GetAllocationHandle()); + candidates->storage = std::move(pRnd->result_.objects); for (size_t i = iFoundCount; i > 0; --i) { bool bool_val = false; CFXJSE_Context::ExecutionResult exec_result = engine_->RunScript(eLangType, wsExpression.AsStringView(), - pRnd->result_.objects[i - 1].Get()); + candidates->storage[i - 1].Get()); if (exec_result.status) { CFXJSE_ScopeUtil_IsolateHandleRootContext scope(pIsolate); v8::Local local_val = @@ -777,9 +783,10 @@ void CFXJSE_ResolveProcessor::DoPredicateFilter(v8::Isolate* pIsolate, bool_val = fxv8::ReentrantToBooleanHelper(pIsolate, local_val); } if (!bool_val) { - pRnd->result_.objects.erase(pRnd->result_.objects.begin() + i - 1); + candidates->storage.erase(candidates->storage.begin() + i - 1); } } + pRnd->result_.objects = std::move(candidates->storage); } CFXJSE_ResolveProcessor::NodeData::NodeData() = default; diff --git a/fxjs/xfa/cfxjse_resolveprocessor.h b/fxjs/xfa/cfxjse_resolveprocessor.h index 0b3322133f..d83b1ad96d 100644 --- a/fxjs/xfa/cfxjse_resolveprocessor.h +++ b/fxjs/xfa/cfxjse_resolveprocessor.h @@ -27,7 +27,7 @@ class CFXJSE_ResolveProcessor { NodeData(); ~NodeData(); - UnownedPtr cur_object_; // Ok, stack-only. + CXFA_Object* cur_object_ = nullptr; // Ok, stack-only. WideString name_; WideString condition_; XFA_HashCode hash_name_ = XFA_HASHCODE_None; diff --git a/fxjs/xfa/cjx_tree.cpp b/fxjs/xfa/cjx_tree.cpp index 6d14cca339..74e797b5d1 100644 --- a/fxjs/xfa/cjx_tree.cpp +++ b/fxjs/xfa/cjx_tree.cpp @@ -141,8 +141,7 @@ void CJX_Tree::nodes(v8::Isolate* pIsolate, doc->GetNodeOwner()->PersistList(pNodeList); CFXJSE_Engine* pEngine = doc->GetScriptContext(); - *pValue = pNodeList->JSObject()->NewBoundV8Object( - pIsolate, pEngine->GetJseNormalClass()->GetTemplate(pIsolate)); + *pValue = pEngine->GetOrCreateJSBindingFromMap(pNodeList); } void CJX_Tree::parent(v8::Isolate* pIsolate, @@ -250,6 +249,5 @@ v8::Local CJX_Tree::ResolveNodeList(v8::Isolate* pIsolate, } } } - return pNodeList->JSObject()->NewBoundV8Object( - pIsolate, pScriptContext->GetJseNormalClass()->GetTemplate(pIsolate)); + return pScriptContext->GetOrCreateJSBindingFromMap(pNodeList); } diff --git a/fxjs/xfa/fxjse.cpp b/fxjs/xfa/fxjse.cpp index 72d3ce4f4c..f0a6cbebf1 100644 --- a/fxjs/xfa/fxjse.cpp +++ b/fxjs/xfa/fxjse.cpp @@ -11,7 +11,6 @@ #include "fxjs/xfa/cfxjse_isolatetracker.h" #include "v8/include/v8-isolate.h" #include "v8/include/v8-object.h" -#include "v8/include/v8-template.h" namespace pdfium::fxjse { @@ -41,17 +40,6 @@ CJX_Object* CFXJSE_HostObject::AsCJXObject() { return nullptr; } -v8::Local CFXJSE_HostObject::NewBoundV8Object( - v8::Isolate* pIsolate, - v8::Local tmpl) { - v8::Local hObject = - tmpl->InstanceTemplate() - ->NewInstance(pIsolate->GetCurrentContext()) - .ToLocalChecked(); - FXJSE_UpdateObjectBinding(hObject, this); - return hObject; -} - void FXJSE_ThrowMessage(v8::Isolate* pIsolate, ByteStringView utf8Message) { DCHECK(pIsolate); CFXJSE_ScopeUtil_IsolateHandleRootContext scope(pIsolate); diff --git a/fxjs/xfa/fxjse.h b/fxjs/xfa/fxjse.h index 08ddc3e4f1..8a28ba74f2 100644 --- a/fxjs/xfa/fxjse.h +++ b/fxjs/xfa/fxjse.h @@ -44,9 +44,6 @@ class CFXJSE_HostObject { virtual CFXJSE_FormCalcContext* AsFormCalcContext(); virtual CJX_Object* AsCJXObject(); - v8::Local NewBoundV8Object(v8::Isolate* pIsolate, - v8::Local tmpl); - protected: CFXJSE_HostObject(); }; diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index ea34ac46e6..091166b3b9 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -16,10 +16,10 @@ All/EPDFRedactPageTreeTest.RemovesUnusedPropertiesFromEveryAncestor/0 7 All/EPDFRedactPageTreeTest.RemovesUnusedPropertiesFromEveryAncestor/1 7 All/EPDFRedactPageTreeTest.RemovesUnusedPropertiesFromEveryAncestor/2 7 All/EPDFRedactPageTreeTest.RemovesUnusedPropertiesFromEveryAncestor/3 7 -AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedDictionary 5 -AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedStates 6 -AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedStream 4 -AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/Unshared 4 +AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedDictionary 7 +AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedStates 8 +AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/SharedStream 6 +AppearanceSharing/EPDFStampSaveEmbedderTest.LayerRotationSurvivesIncrementalSaveAndRewrite/Unshared 5 CPDFSecurityHandlerEmbedderTest.OwnerPasswordVersion2Latin1 3 CPDFSecurityHandlerEmbedderTest.OwnerPasswordVersion2UTF8 3 CPDFSecurityHandlerEmbedderTest.OwnerPasswordVersion3Latin1 3 @@ -50,8 +50,8 @@ EPDFActionEmbedderTest.OpenActionDestinationForms 3 EPDFActionEmbedderTest.ResetFormThreeStates 1 EPDFActionEmbedderTest.SetNextChainsActions 3 EPDFAnnotEmbedderTest.AcrobatCommentWrittenBackReadsTheSame 1 -EPDFAnnotEmbedderTest.AnEmptyDashPatternIsASolidLine 15 -EPDFAnnotEmbedderTest.AnnotFontMapStagesEveryNamedFont 16 +EPDFAnnotEmbedderTest.AnEmptyDashPatternIsASolidLine 19 +EPDFAnnotEmbedderTest.AnnotFontMapStagesEveryNamedFont 17 EPDFAnnotEmbedderTest.ApplyPageRedactionsCountsRemovedAnnotations 6 EPDFAnnotEmbedderTest.ApplyPageRedactionsTwoMarksOnOneTextObject 3 EPDFAnnotEmbedderTest.ApplyRedactionBurnsInAutoSizedLabel 9 @@ -75,56 +75,56 @@ EPDFAnnotEmbedderTest.ApplyRedactionSplitsFillAndStrokePathAcrossSave 5 EPDFAnnotEmbedderTest.ApplyRedactionSynthesizesInteriorColorFill 6 EPDFAnnotEmbedderTest.ApplyRedactionSynthesizesOverlayTextLabel 8 EPDFAnnotEmbedderTest.ApplyRedactionWithoutOverlayLeavesRegionClear 3 -EPDFAnnotEmbedderTest.BorderStyleResolutionUsesISOPrecedence 4 -EPDFAnnotEmbedderTest.CalloutRectHoldsItsLineAndArrow 6 -EPDFAnnotEmbedderTest.CffProgramRaisesPdfVersionTo16 11 -EPDFAnnotEmbedderTest.CloudyBumpsReachPastTheBoxIntoRect 9 -EPDFAnnotEmbedderTest.CloudyPolygonRectHoldsItsBumps 4 +EPDFAnnotEmbedderTest.BorderStyleResolutionUsesISOPrecedence 5 +EPDFAnnotEmbedderTest.CalloutRectHoldsItsLineAndArrow 7 +EPDFAnnotEmbedderTest.CffProgramRaisesPdfVersionTo16 12 +EPDFAnnotEmbedderTest.CloudyBumpsReachPastTheBoxIntoRect 13 +EPDFAnnotEmbedderTest.CloudyPolygonRectHoldsItsBumps 5 EPDFAnnotEmbedderTest.ComboBoxKoreanUsesRegisteredDroidFallbackFont 20 -EPDFAnnotEmbedderTest.DashedBorderDrawsItsDashOrTheDefault 7 +EPDFAnnotEmbedderTest.DashedBorderDrawsItsDashOrTheDefault 11 EPDFAnnotEmbedderTest.DefaultAppearanceFontFace 1 -EPDFAnnotEmbedderTest.DefaultAppearancePrefersAnnotationDrThenFallsBackToAcroFormDr 3 +EPDFAnnotEmbedderTest.DefaultAppearancePrefersAnnotationDrThenFallsBackToAcroFormDr 4 EPDFAnnotEmbedderTest.DirectAnnotationObjectNumberStaysZeroAfterRender 1 -EPDFAnnotEmbedderTest.DrawingAnnotationsWithoutAppearancesWritesNone 3 -EPDFAnnotEmbedderTest.DrawingRectIsWhereTheAppearanceIsDrawn 4 +EPDFAnnotEmbedderTest.DrawingAnnotationsWithoutAppearancesWritesNone 7 +EPDFAnnotEmbedderTest.DrawingRectIsWhereTheAppearanceIsDrawn 6 EPDFAnnotEmbedderTest.EmbedMetadata 1 -EPDFAnnotEmbedderTest.EmbedSetRectPreservesRotatedAppearance 2 +EPDFAnnotEmbedderTest.EmbedSetRectPreservesRotatedAppearance 3 EPDFAnnotEmbedderTest.ExplicitGenerateAppearanceAllowed 2 -EPDFAnnotEmbedderTest.FontEmbeddingPolicyGovernsRegisteredResources 51 -EPDFAnnotEmbedderTest.FreeTextAllFallbackTextKeepsRegisteredDaFont 17 -EPDFAnnotEmbedderTest.FreeTextAppearanceFallsBackToRegisteredFont 12 -EPDFAnnotEmbedderTest.FreeTextAppearanceUsesRegisteredMemoryFont 12 -EPDFAnnotEmbedderTest.FreeTextEmptyContentsKeepsRegisteredDaFontAcrossSave 11 -EPDFAnnotEmbedderTest.FreeTextEphemeralAppearanceLeavesDrUntouched 11 -EPDFAnnotEmbedderTest.FreeTextFallbackAliasNeverCollidesWithStaleDaAlias 25 -EPDFAnnotEmbedderTest.FreeTextKoreanUsesRegisteredDroidFallbackFont 12 -EPDFAnnotEmbedderTest.FreeTextLegacyMarkerDrEntryUpgradesToRealFont 11 -EPDFAnnotEmbedderTest.FreeTextPlateFollowsBorderWidth 10 -EPDFAnnotEmbedderTest.FreeTextRegeneratingOneAnnotationLeavesTheOther 26 -EPDFAnnotEmbedderTest.FreeTextRegisteredFontEmbedsSubsetInSavedPdf 12 -EPDFAnnotEmbedderTest.FreeTextRegisteredFontInstallsRealDrEntry 12 -EPDFAnnotEmbedderTest.FreeTextRegisteredFontMarkerSurvivesAliasSuffix 11 -EPDFAnnotEmbedderTest.FreeTextRegisteredFontResolvesByFamilyAfterReregistration 12 -EPDFAnnotEmbedderTest.FreeTextRegistersFontFromFileAccess 12 -EPDFAnnotEmbedderTest.FreeTextStagedFontFailureLeavesDocumentUntouched 18 -EPDFAnnotEmbedderTest.GenerateFileAttachmentAppearance 4 -EPDFAnnotEmbedderTest.GenerateFileAttachmentAppearancePerIcon 8 -EPDFAnnotEmbedderTest.GenerateInkAppearanceSetsRectToWhatItPaints 8 -EPDFAnnotEmbedderTest.GenerateRedactAppearanceBakesLabelIntoOverlay 7 -EPDFAnnotEmbedderTest.GenerateTextAppearanceFillsItsRect 5 -EPDFAnnotEmbedderTest.GenerateTextAppearancePerIcon 12 -EPDFAnnotEmbedderTest.LineRectHoldsItsArrowhead 4 -EPDFAnnotEmbedderTest.LineRectIsWhatItsStrokePaints 5 +EPDFAnnotEmbedderTest.FontEmbeddingPolicyGovernsRegisteredResources 53 +EPDFAnnotEmbedderTest.FreeTextAllFallbackTextKeepsRegisteredDaFont 18 +EPDFAnnotEmbedderTest.FreeTextAppearanceFallsBackToRegisteredFont 13 +EPDFAnnotEmbedderTest.FreeTextAppearanceUsesRegisteredMemoryFont 13 +EPDFAnnotEmbedderTest.FreeTextEmptyContentsKeepsRegisteredDaFontAcrossSave 12 +EPDFAnnotEmbedderTest.FreeTextEphemeralAppearanceLeavesDrUntouched 12 +EPDFAnnotEmbedderTest.FreeTextFallbackAliasNeverCollidesWithStaleDaAlias 26 +EPDFAnnotEmbedderTest.FreeTextKoreanUsesRegisteredDroidFallbackFont 13 +EPDFAnnotEmbedderTest.FreeTextLegacyMarkerDrEntryUpgradesToRealFont 12 +EPDFAnnotEmbedderTest.FreeTextPlateFollowsBorderWidth 15 +EPDFAnnotEmbedderTest.FreeTextRegeneratingOneAnnotationLeavesTheOther 28 +EPDFAnnotEmbedderTest.FreeTextRegisteredFontEmbedsSubsetInSavedPdf 13 +EPDFAnnotEmbedderTest.FreeTextRegisteredFontInstallsRealDrEntry 13 +EPDFAnnotEmbedderTest.FreeTextRegisteredFontMarkerSurvivesAliasSuffix 12 +EPDFAnnotEmbedderTest.FreeTextRegisteredFontResolvesByFamilyAfterReregistration 13 +EPDFAnnotEmbedderTest.FreeTextRegistersFontFromFileAccess 13 +EPDFAnnotEmbedderTest.FreeTextStagedFontFailureLeavesDocumentUntouched 19 +EPDFAnnotEmbedderTest.GenerateFileAttachmentAppearance 5 +EPDFAnnotEmbedderTest.GenerateFileAttachmentAppearancePerIcon 13 +EPDFAnnotEmbedderTest.GenerateInkAppearanceSetsRectToWhatItPaints 9 +EPDFAnnotEmbedderTest.GenerateRedactAppearanceBakesLabelIntoOverlay 8 +EPDFAnnotEmbedderTest.GenerateTextAppearanceFillsItsRect 7 +EPDFAnnotEmbedderTest.GenerateTextAppearancePerIcon 21 +EPDFAnnotEmbedderTest.LineRectHoldsItsArrowhead 5 +EPDFAnnotEmbedderTest.LineRectIsWhatItsStrokePaints 7 EPDFAnnotEmbedderTest.ListBoxKoreanUsesRegisteredDroidFallbackFont 20 -EPDFAnnotEmbedderTest.NoStrokeColorInkPaintsNothing 4 -EPDFAnnotEmbedderTest.NoStrokeColorKeepsTheFillInTheStrokesPlace 11 -EPDFAnnotEmbedderTest.NoStrokeColorLineKeepsItsFilledEndings 5 -EPDFAnnotEmbedderTest.NoSubsettingFontEmbedsWholeProgram 12 -EPDFAnnotEmbedderTest.OpacityIsStoredAsGiven 3 -EPDFAnnotEmbedderTest.PolylineKneePastTheMiterLimitIsBeveled 4 -EPDFAnnotEmbedderTest.PreviewAndPrintFallbackDoesNotAuthorUntilAuthorized 25 -EPDFAnnotEmbedderTest.ReadPurityRenderMarkupAnnotWithContents 1 -EPDFAnnotEmbedderTest.RedactCommentReadsOverTheReadersDefaults 6 +EPDFAnnotEmbedderTest.NoStrokeColorInkPaintsNothing 5 +EPDFAnnotEmbedderTest.NoStrokeColorKeepsTheFillInTheStrokesPlace 14 +EPDFAnnotEmbedderTest.NoStrokeColorLineKeepsItsFilledEndings 6 +EPDFAnnotEmbedderTest.NoSubsettingFontEmbedsWholeProgram 13 +EPDFAnnotEmbedderTest.OpacityIsStoredAsGiven 4 +EPDFAnnotEmbedderTest.PolylineKneePastTheMiterLimitIsBeveled 5 +EPDFAnnotEmbedderTest.PreviewAndPrintFallbackDoesNotAuthorUntilAuthorized 26 +EPDFAnnotEmbedderTest.ReadPurityRenderMarkupAnnotWithContents 4 +EPDFAnnotEmbedderTest.RedactCommentReadsOverTheReadersDefaults 7 EPDFAnnotEmbedderTest.RedactInQuadsMultipleRegionsOnOneTextObject 3 EPDFAnnotEmbedderTest.RedactInQuadsRemovesTextInsideFormXObject 5 EPDFAnnotEmbedderTest.RedactLabelRegisteredFontInstallsRealDrEntry 12 @@ -133,52 +133,52 @@ EPDFAnnotEmbedderTest.RedactRemovesTextWithEmptyGlyphBoxes 3 EPDFAnnotEmbedderTest.RedactVerticalTextLeadingGlyphKeepsRestInPlace 3 EPDFAnnotEmbedderTest.RedactVerticalTextMiddleGlyphsKeepsTailInPlace 3 EPDFAnnotEmbedderTest.RefitWrapsAStampAcrobatTurnedUpright 5 -EPDFAnnotEmbedderTest.RegisteredCffFontEmitsCidFontType0 12 -EPDFAnnotEmbedderTest.RegisteredCidKeyedCffKeepsCidsInAppearance 12 +EPDFAnnotEmbedderTest.RegisteredCffFontEmitsCidFontType0 13 +EPDFAnnotEmbedderTest.RegisteredCidKeyedCffKeepsCidsInAppearance 13 EPDFAnnotEmbedderTest.RegisteredFallbackFontRendersPageMissingGlyph 5 EPDFAnnotEmbedderTest.RegisteredFontResolutionPrefersStoredFamily 9 EPDFAnnotEmbedderTest.RegisteredFontResolutionRefusesConflictingHint 6 -EPDFAnnotEmbedderTest.RegistryHonoursFsTypeEmbeddingPermissions 12 -EPDFAnnotEmbedderTest.RemoveKey 1 -EPDFAnnotEmbedderTest.RichTextAlignmentFollowsTheAnnotation 11 -EPDFAnnotEmbedderTest.RichTextCoversSupplementaryCharactersByScalar 10 -EPDFAnnotEmbedderTest.RichTextDocumentSubsetDrawsOnlyWhatItCovers 21 -EPDFAnnotEmbedderTest.RichTextEmptyBoxNeverNamesACmaplessSubset 5 -EPDFAnnotEmbedderTest.RichTextJsonFromContentsOnly 5 -EPDFAnnotEmbedderTest.RichTextJsonFromRCAndDS 5 -EPDFAnnotEmbedderTest.RichTextLastResortDrawsWhatNoFontHas 20 -EPDFAnnotEmbedderTest.RichTextPicksTheDocumentSubsetThatCoversTheText 16 -EPDFAnnotEmbedderTest.RichTextPreviewAndPrintLastResortWaits 25 -EPDFAnnotEmbedderTest.RichTextResolvesDocumentProgramWhenUnregistered 24 -EPDFAnnotEmbedderTest.RichTextRtlRunCarriesActualTextAndExtracts 14 -EPDFAnnotEmbedderTest.RichTextSkipsDocumentSubsetWithoutCmap 7 -EPDFAnnotEmbedderTest.RichTextWriterFailureLeavesDocumentUntouched 18 -EPDFAnnotEmbedderTest.RotatedCaretAppearanceCarriesTransform 3 -EPDFAnnotEmbedderTest.SetDefaultAppearanceKeepsFontAtAutoSize 5 -EPDFAnnotEmbedderTest.SetNameAcceptsAnyNameAndKeepsAppearance 4 -EPDFAnnotEmbedderTest.SetNoColorWritesAnEmptyColorArray 3 -EPDFAnnotEmbedderTest.SetNumberValueRefusesWithoutWriting 3 -EPDFAnnotEmbedderTest.SetNumberValueStoresTheNumberAsGiven 3 -EPDFAnnotEmbedderTest.SetRichTextJSONRefusesKindsThatArentMarkup 3 -EPDFAnnotEmbedderTest.SetRichTextJSONRejectsInvalidInputUnchanged 5 -EPDFAnnotEmbedderTest.SetRichTextJSONWithRegisteredBodyFont 12 -EPDFAnnotEmbedderTest.SetRichTextJSONWithoutBodyKeepsCurrentBody 7 -EPDFAnnotEmbedderTest.SetRichTextJSONWritesACommentAsAcrobatDoes 3 -EPDFAnnotEmbedderTest.SetRichTextJSONWritesAllFourForms 6 -EPDFAnnotEmbedderTest.SetRichTextXHTMLImportsOverDefaults 6 -EPDFAnnotEmbedderTest.SetSubtypeChangesTheKindInPlace 5 -EPDFAnnotEmbedderTest.StandardFontDefaultAppearanceRoundTripsThroughDr 18 +EPDFAnnotEmbedderTest.RegistryHonoursFsTypeEmbeddingPermissions 13 +EPDFAnnotEmbedderTest.RemoveKey 2 +EPDFAnnotEmbedderTest.RichTextAlignmentFollowsTheAnnotation 15 +EPDFAnnotEmbedderTest.RichTextCoversSupplementaryCharactersByScalar 11 +EPDFAnnotEmbedderTest.RichTextDocumentSubsetDrawsOnlyWhatItCovers 24 +EPDFAnnotEmbedderTest.RichTextEmptyBoxNeverNamesACmaplessSubset 6 +EPDFAnnotEmbedderTest.RichTextJsonFromContentsOnly 6 +EPDFAnnotEmbedderTest.RichTextJsonFromRCAndDS 6 +EPDFAnnotEmbedderTest.RichTextLastResortDrawsWhatNoFontHas 21 +EPDFAnnotEmbedderTest.RichTextPicksTheDocumentSubsetThatCoversTheText 19 +EPDFAnnotEmbedderTest.RichTextPreviewAndPrintLastResortWaits 27 +EPDFAnnotEmbedderTest.RichTextResolvesDocumentProgramWhenUnregistered 26 +EPDFAnnotEmbedderTest.RichTextRtlRunCarriesActualTextAndExtracts 15 +EPDFAnnotEmbedderTest.RichTextSkipsDocumentSubsetWithoutCmap 8 +EPDFAnnotEmbedderTest.RichTextWriterFailureLeavesDocumentUntouched 19 +EPDFAnnotEmbedderTest.RotatedCaretAppearanceCarriesTransform 5 +EPDFAnnotEmbedderTest.SetDefaultAppearanceKeepsFontAtAutoSize 6 +EPDFAnnotEmbedderTest.SetNameAcceptsAnyNameAndKeepsAppearance 6 +EPDFAnnotEmbedderTest.SetNoColorWritesAnEmptyColorArray 4 +EPDFAnnotEmbedderTest.SetNumberValueRefusesWithoutWriting 4 +EPDFAnnotEmbedderTest.SetNumberValueStoresTheNumberAsGiven 4 +EPDFAnnotEmbedderTest.SetRichTextJSONRefusesKindsThatArentMarkup 5 +EPDFAnnotEmbedderTest.SetRichTextJSONRejectsInvalidInputUnchanged 6 +EPDFAnnotEmbedderTest.SetRichTextJSONWithRegisteredBodyFont 13 +EPDFAnnotEmbedderTest.SetRichTextJSONWithoutBodyKeepsCurrentBody 8 +EPDFAnnotEmbedderTest.SetRichTextJSONWritesACommentAsAcrobatDoes 5 +EPDFAnnotEmbedderTest.SetRichTextJSONWritesAllFourForms 7 +EPDFAnnotEmbedderTest.SetRichTextXHTMLImportsOverDefaults 7 +EPDFAnnotEmbedderTest.SetSubtypeChangesTheKindInPlace 8 +EPDFAnnotEmbedderTest.StandardFontDefaultAppearanceRoundTripsThroughDr 19 EPDFAnnotEmbedderTest.TextFieldDrawsItsBorderStyle 2 EPDFAnnotEmbedderTest.TextFieldGenerateAppearanceStreamIsStable 2 EPDFAnnotEmbedderTest.TextFieldKoreanUsesRegisteredDroidFallbackFont 20 -EPDFAnnotEmbedderTest.TurnedBoxRectIsTheUprightBoxAroundIt 2 -EPDFAnnotEmbedderTest.TwoWeightsOfOneFamilyAreTwoFontsByName 19 -EPDFAnnotEmbedderTest.VariableFontIsInstancedAtRegistration 12 +EPDFAnnotEmbedderTest.TurnedBoxRectIsTheUprightBoxAroundIt 3 +EPDFAnnotEmbedderTest.TwoWeightsOfOneFamilyAreTwoFontsByName 21 +EPDFAnnotEmbedderTest.VariableFontIsInstancedAtRegistration 13 EPDFAnnotEmbedderTest.WidgetRegisteredFontInstallsRealDrEntry 25 EPDFAnnotEmbedderTest.WidgetTextAlignment 2 -EPDFAnnotEmbedderTest.WidthZeroDrawsAHairline 6 +EPDFAnnotEmbedderTest.WidthZeroDrawsAHairline 9 EPDFAnnotRawEmbedderTest.FindsANameOnAnAnnotationWrittenInPlace 3 -EPDFAnnotRawEmbedderTest.FindsAnAnnotationByNameOnItsPage 5 +EPDFAnnotRawEmbedderTest.FindsAnAnnotationByNameOnItsPage 9 EPDFAnnotRawEmbedderTest.FindsAnAnnotationByObjectNumber 5 EPDFAnnotRawEmbedderTest.FindsNothingWhereThereIsNothing 3 EPDFAnnotRawEmbedderTest.NewAnnotationsNameTheirPage 6 @@ -187,12 +187,12 @@ EPDFAttachmentEmbedderTest.ExtractFileLargeAttachment 5 EPDFAttachmentEmbedderTest.GetAttachmentIndexByKey 6 EPDFAttachmentEmbedderTest.GetFileHonoursTheBufferContract 5 EPDFFlattenEmbedderTest.CopierFollowsReferencesByWhatTheyResolveTo 3 -EPDFFlattenEmbedderTest.ExportAnnotationsDeduplicatesSharedResources 6 -EPDFFlattenEmbedderTest.ExportAnnotationsMatchesSourceCrop 6 +EPDFFlattenEmbedderTest.ExportAnnotationsDeduplicatesSharedResources 8 +EPDFFlattenEmbedderTest.ExportAnnotationsMatchesSourceCrop 9 EPDFFlattenEmbedderTest.ExportPagesFlattenedCopiesPagesInTheGivenOrder 5 EPDFFlattenEmbedderTest.ExportPagesFlattenedKeepsTheLayersPrintState 6 EPDFFlattenEmbedderTest.ExportPagesFlattenedPrintsAFieldDrawnInMemory 1 -EPDFFlattenEmbedderTest.FlattenAnnotationSetRejectsForeignAnnotation 3 +EPDFFlattenEmbedderTest.FlattenAnnotationSetRejectsForeignAnnotation 4 EPDFFlattenEmbedderTest.FlattenAnnotationSetReportsPerEntry 7 EPDFFlattenEmbedderTest.FlattenDirectAnnotationByHandle 8 EPDFFlattenEmbedderTest.FlattenForDisplayLeavesANoViewAnnotation 1 @@ -201,13 +201,13 @@ EPDFFlattenEmbedderTest.FlattenPageHonorsPrintUsage 10 EPDFFlattenEmbedderTest.FlattenPagePreservesUnpaintedAnnotationsAndDetachesWidget 12 EPDFFlattenEmbedderTest.FlattenPaintsTheAppearanceDrawnInMemory 7 EPDFFlattenEmbedderTest.FlattenSpecificAnnotationByHandle 7 -EPDFFlattenEmbedderTest.InvisibleLeavesOutOnlyAnUnknownType 7 -EPDFFontEmbedderTest.FreeTextReportsCharactersNoFontHas 6 +EPDFFlattenEmbedderTest.InvisibleLeavesOutOnlyAnUnknownType 8 +EPDFFontEmbedderTest.FreeTextReportsCharactersNoFontHas 7 EPDFFontEmbedderTest.ListsADocumentProgramAndHandsOutItsBytes 25 EPDFFontEmbedderTest.PasswordFieldWritesOnlyStars 8 EPDFFontEmbedderTest.RealignsAProgramABrowserWouldRefuse 25 EPDFFontEmbedderTest.ResolvesADocumentProgram 25 -EPDFFontEmbedderTest.RichTextDrawsTheProgramItsStyleNames 22 +EPDFFontEmbedderTest.RichTextDrawsTheProgramItsStyleNames 25 EPDFFontEmbedderTest.SimpleFieldFontWritesThroughItsProgram 13 EPDFFontEmbedderTest.UnauthorizedRegisteredFontDoesNotTakeOverABox 25 EPDFFontEmbedderTest.WidgetDrawsEachClusterInAFontThatHasIt 20 @@ -254,10 +254,10 @@ EPDFFormEmbedderTest.TwoPlaneTwinWidgetsFillTogether 9 EPDFFormEmbedderTest.TypedValueSnapshotPreservesPdfShapes 3 EPDFFormEmbedderTest.WidgetInNoFieldDrawsItsBox 3 EPDFFormEmbedderTest.WidgetRotationTurnsItsAppearance 2 -EPDFInkAppearanceEmbedderTest.AZigzagIsOneCubicPerPair 4 -EPDFInkAppearanceEmbedderTest.DrawsAcrobatsCurves 10 -EPDFInkAppearanceEmbedderTest.OnePointIsAcrobatsDot 4 -EPDFInkAppearanceEmbedderTest.TheCurvesDoNotDependOnTheWidth 11 +EPDFInkAppearanceEmbedderTest.AZigzagIsOneCubicPerPair 5 +EPDFInkAppearanceEmbedderTest.DrawsAcrobatsCurves 17 +EPDFInkAppearanceEmbedderTest.OnePointIsAcrobatsDot 5 +EPDFInkAppearanceEmbedderTest.TheCurvesDoNotDependOnTheWidth 19 EPDFMeasureEmbedderTest.BadArgumentsAndRejectedWrites 5 EPDFMeasureEmbedderTest.CaptionAppearanceGolden 19 EPDFMeasureEmbedderTest.DirectMeasureWithSharedNestedFormatDetachesOnlyItsOwner 5 @@ -284,7 +284,7 @@ EPDFNamedPagesEmbedderTest.DeletingAPageDropsItsRegistrations 9 EPDFNamedPagesEmbedderTest.NewDocumentGrowsATreeOnFirstSet 6 EPDFNamedPagesEmbedderTest.RemoveByKeyKeepsThePage 8 EPDFNamedPagesEmbedderTest.SetReplacesRejectsAndRoundTrips 8 -EPDFObjectNumberEmbedderTest.FullSaveListsUnusedNumbersAsFree 1 +EPDFObjectNumberEmbedderTest.FullSaveListsUnusedNumbersAsFree 2 EPDFOutlineEmbedderTest.ADictionaryThatIsntAnItemEndsTheList 3 EPDFOutlineEmbedderTest.ADirectItemKeepsItsListAsItIs 1 EPDFOutlineEmbedderTest.ALoopEndsTheList 3 @@ -318,8 +318,8 @@ EPDFPpoEmbedderTest.SharesAFontDefinedTheSameWay 19 EPDFRedactEmbedderTest.DirectReplacementTextIsRemovedFromSiblingObjects 3 EPDFRedactEmbedderTest.InheritedPropertiesLeaveNoUnusedOriginalOnPage 5 EPDFRedactEmbedderTest.NestedFormsUseTheRenderersTransformOrder 7 -EPDFRedactEmbedderTest.RedactingAFlattenedStampLeavesAStampSharingItsDrawingAlone 20 -EPDFRedactEmbedderTest.RedactingTheOnlyStampLeavesNothingOfItsDrawing 18 +EPDFRedactEmbedderTest.RedactingAFlattenedStampLeavesAStampSharingItsDrawingAlone 22 +EPDFRedactEmbedderTest.RedactingTheOnlyStampLeavesNothingOfItsDrawing 19 EPDFRedactEmbedderTest.RemovesReplacementTextFromWholeAffectedSpan 8 EPDFRedactEmbedderTest.SharedFormPreservesUnmarkedReplacementText 5 EPDFRedactEmbedderTest.SharedImageAndMaskPreserveOtherPlacements 6 @@ -345,38 +345,38 @@ EPDFSignatureEmbedderTest.ProbeMdpStructuresAreDirect 5 EPDFSignatureEmbedderTest.ProbeSeedValueVersionAndApprovalOnly 3 EPDFSignatureEmbedderTest.SealRejectsDecoysAndBadDer 6 EPDFSignatureEmbedderTest.SignRoundTrip 8 -EPDFStampResizeEmbedderTest.ADrawingFromALayersPageLeavesTheLayerAlone 5 -EPDFStampResizeEmbedderTest.AFormThatChangesItsDrawingIsNotLookedThrough 18 -EPDFStampResizeEmbedderTest.AFormThatOnlyMovesItsDrawingIsLookedThrough 8 -EPDFStampResizeEmbedderTest.ALayerThatDoesNotPaintCAOverOurWrapperIsPartOfTheDrawing 9 -EPDFStampResizeEmbedderTest.ALayerThatDoesNotRepeatCAIsPartOfTheDrawing 7 -EPDFStampResizeEmbedderTest.AStampFromAPageLeavesTheDocumentInfoAlone 10 -EPDFStampResizeEmbedderTest.AnExportIsTheCanonicalDrawingPage 7 -EPDFStampResizeEmbedderTest.AnImportedDrawingExportsItsCanonicalBytes 4 -EPDFStampResizeEmbedderTest.AnOlderExportStillImports 7 -EPDFStampResizeEmbedderTest.AnOpacityLayerRepeatingCAIsReplacedNotNested 8 -EPDFStampResizeEmbedderTest.AnotherToolsArtworkIsOneDrawingAtAnySize 5 -EPDFStampResizeEmbedderTest.BooleanValues 3 -EPDFStampResizeEmbedderTest.CanonicalDrawingIsWhatAStampExports 6 -EPDFStampResizeEmbedderTest.ChangingAStampLeavesAStampSharingItsDrawingAlone 9 -EPDFStampResizeEmbedderTest.CoverCentersBothAxes 9 -EPDFStampResizeEmbedderTest.DetachesSharedDictionariesAndSelectedState 8 -EPDFStampResizeEmbedderTest.EditingOneStampsDrawingLeavesAStampSharingItAlone 10 -EPDFStampResizeEmbedderTest.ExportAndImportAreAFixedPoint 16 -EPDFStampResizeEmbedderTest.ExportAppearanceLeavesAnOpacityLayerOut 5 -EPDFStampResizeEmbedderTest.ExportAppearanceOfOurWrapperIsTheDrawing 7 -EPDFStampResizeEmbedderTest.FailedWrappingLeavesOriginalAppearanceUnchanged 4 -EPDFStampResizeEmbedderTest.OpacityIsAcrobatsLayerOverOurWrapper 10 -EPDFStampResizeEmbedderTest.OurWrapperIsFoundUnderFormsThatOnlyDrawIt 14 -EPDFStampResizeEmbedderTest.RefreshesAlreadyParsedAnnotationObjects 6 -EPDFStampResizeEmbedderTest.RepeatedResizesReuseChildDespiteMissingOrStaleMarker 26 -EPDFStampResizeEmbedderTest.RotatedWrapperStartsAtTheOrigin 7 -EPDFStampResizeEmbedderTest.SetStampOpacityReplacesAcrobatsLayer 7 -EPDFStampResizeEmbedderTest.StaleMarkerDoesNotReplaceArtworkWithMissingDo 6 -EPDFStampResizeEmbedderTest.StampsPlacingOneDrawingShareIt 9 -EPDFStampResizeEmbedderTest.StateSelectionWithoutASMatchesRendering 15 -EPDFStampResizeEmbedderTest.TheSameDrawingExportsToTheSameBytes 6 -EPDFStampResizeEmbedderTest.WrappingMovesTheDrawingsEntriesWithIt 6 +EPDFStampResizeEmbedderTest.ADrawingFromALayersPageLeavesTheLayerAlone 6 +EPDFStampResizeEmbedderTest.AFormThatChangesItsDrawingIsNotLookedThrough 19 +EPDFStampResizeEmbedderTest.AFormThatOnlyMovesItsDrawingIsLookedThrough 9 +EPDFStampResizeEmbedderTest.ALayerThatDoesNotPaintCAOverOurWrapperIsPartOfTheDrawing 10 +EPDFStampResizeEmbedderTest.ALayerThatDoesNotRepeatCAIsPartOfTheDrawing 8 +EPDFStampResizeEmbedderTest.AStampFromAPageLeavesTheDocumentInfoAlone 12 +EPDFStampResizeEmbedderTest.AnExportIsTheCanonicalDrawingPage 8 +EPDFStampResizeEmbedderTest.AnImportedDrawingExportsItsCanonicalBytes 5 +EPDFStampResizeEmbedderTest.AnOlderExportStillImports 8 +EPDFStampResizeEmbedderTest.AnOpacityLayerRepeatingCAIsReplacedNotNested 9 +EPDFStampResizeEmbedderTest.AnotherToolsArtworkIsOneDrawingAtAnySize 6 +EPDFStampResizeEmbedderTest.BooleanValues 4 +EPDFStampResizeEmbedderTest.CanonicalDrawingIsWhatAStampExports 8 +EPDFStampResizeEmbedderTest.ChangingAStampLeavesAStampSharingItsDrawingAlone 11 +EPDFStampResizeEmbedderTest.CoverCentersBothAxes 10 +EPDFStampResizeEmbedderTest.DetachesSharedDictionariesAndSelectedState 10 +EPDFStampResizeEmbedderTest.EditingOneStampsDrawingLeavesAStampSharingItAlone 12 +EPDFStampResizeEmbedderTest.ExportAndImportAreAFixedPoint 19 +EPDFStampResizeEmbedderTest.ExportAppearanceLeavesAnOpacityLayerOut 6 +EPDFStampResizeEmbedderTest.ExportAppearanceOfOurWrapperIsTheDrawing 8 +EPDFStampResizeEmbedderTest.FailedWrappingLeavesOriginalAppearanceUnchanged 5 +EPDFStampResizeEmbedderTest.OpacityIsAcrobatsLayerOverOurWrapper 11 +EPDFStampResizeEmbedderTest.OurWrapperIsFoundUnderFormsThatOnlyDrawIt 15 +EPDFStampResizeEmbedderTest.RefreshesAlreadyParsedAnnotationObjects 7 +EPDFStampResizeEmbedderTest.RepeatedResizesReuseChildDespiteMissingOrStaleMarker 27 +EPDFStampResizeEmbedderTest.RotatedWrapperStartsAtTheOrigin 8 +EPDFStampResizeEmbedderTest.SetStampOpacityReplacesAcrobatsLayer 8 +EPDFStampResizeEmbedderTest.StaleMarkerDoesNotReplaceArtworkWithMissingDo 7 +EPDFStampResizeEmbedderTest.StampsPlacingOneDrawingShareIt 13 +EPDFStampResizeEmbedderTest.StateSelectionWithoutASMatchesRendering 16 +EPDFStampResizeEmbedderTest.TheSameDrawingExportsToTheSameBytes 7 +EPDFStampResizeEmbedderTest.WrappingMovesTheDrawingsEntriesWithIt 7 EPDFViewEmbedderTest.EPDFDocDeletePageByObjectNumber 3 EPDFViewEmbedderTest.EPDFDocDeletePageByObjectNumberDeletesDuplicatePageObjectOccurrence 2 EPDFViewEmbedderTest.EPDFDocSetPageRotationByObjectNumber 1 @@ -385,25 +385,26 @@ EPDFViewEmbedderTest.EPDFGetPageRotateByIndex 2 EPDFViewEmbedderTest.EPDFGetPageTabOrderByIndex 2 EPDFViewEmbedderTest.EPDFGetPageUserUnitByIndex 1 EPDFViewEmbedderTest.ImageOfAnotherDocumentDraws 4 -FPDFAnnotEmbedderTest.AddAndModifyImage 7 -FPDFAnnotEmbedderTest.AddAndModifyPath 9 -FPDFAnnotEmbedderTest.AddAndModifyText 5 -FPDFAnnotEmbedderTest.AddAndSaveLinkAnnotation 1 -FPDFAnnotEmbedderTest.AddAndSaveUnderlineAnnotation 2 -FPDFAnnotEmbedderTest.AddFirstTextAnnotation 1 +FPDFAnnotEmbedderTest.AddAndModifyImage 8 +FPDFAnnotEmbedderTest.AddAndModifyPath 10 +FPDFAnnotEmbedderTest.AddAndModifyText 6 +FPDFAnnotEmbedderTest.AddAndSaveLinkAnnotation 3 +FPDFAnnotEmbedderTest.AddAndSaveUnderlineAnnotation 3 +FPDFAnnotEmbedderTest.AddFirstTextAnnotation 2 FPDFAnnotEmbedderTest.AnnotationBorder 1 FPDFAnnotEmbedderTest.AnnotationBorderRendering 1 -FPDFAnnotEmbedderTest.BadCasesFileAttachmentAnnotation 3 -FPDFAnnotEmbedderTest.Bug1212 2 -FPDFAnnotEmbedderTest.GetAndAddFileAttachmentAnnotation 2 +FPDFAnnotEmbedderTest.BadCasesFileAttachmentAnnotation 5 +FPDFAnnotEmbedderTest.Bug1212 4 +FPDFAnnotEmbedderTest.CreateAnnotSavesIndirectReference 3 +FPDFAnnotEmbedderTest.GetAndAddFileAttachmentAnnotation 3 FPDFAnnotEmbedderTest.GetAndSetQuadPoints 2 FPDFAnnotEmbedderTest.GetSetAP 3 FPDFAnnotEmbedderTest.GetSetStringValue 1 -FPDFAnnotEmbedderTest.InkAnnotation 1 -FPDFAnnotEmbedderTest.LineAnnotation 1 +FPDFAnnotEmbedderTest.InkAnnotation 2 +FPDFAnnotEmbedderTest.LineAnnotation 2 FPDFAnnotEmbedderTest.ModifyAnnotationFlags 1 FPDFAnnotEmbedderTest.ModifyRectQuadpointsWithAP 3 -FPDFAnnotEmbedderTest.PolygonAnnotation 1 +FPDFAnnotEmbedderTest.PolygonAnnotation 2 FPDFAnnotEmbedderTest.RemoveAnnotation 2 FPDFAnnotEmbedderTest.RemoveOptionalAP 3 FPDFAnnotEmbedderTest.RemoveRequiredAP 3 @@ -508,8 +509,11 @@ FPDFSaveWithFontSubsetEmbedderTest.SaveWithSubsetMultipleFontsMultipleTexts 20 FPDFSaveWithFontSubsetEmbedderTest.SaveWithSubsetWithNewText 12 FPDFSaveWithFontSubsetEmbedderTest.SaveWithoutSubsetWithNewText 12 FPDFTransformEmbedderTest.ClipPath 4 +FPDFTransformEmbedderTest.SetArtBox 1 +FPDFTransformEmbedderTest.SetBleedBox 1 FPDFTransformEmbedderTest.SetCropBox 1 FPDFTransformEmbedderTest.SetMediaBox 1 +FPDFTransformEmbedderTest.SetTrimBox 1 FPDFTransformEmbedderTest.TransFormWithClip 9 FPDFTransformEmbedderTest.TransFormWithClipAndSave 5 FPDFTransformEmbedderTest.TransFormWithClipAndSaveWithLocale 5 diff --git a/testing/resources/actual_text_rtl_glyphs.in b/testing/resources/actual_text_rtl_glyphs.in new file mode 100644 index 0000000000..195fa449a2 --- /dev/null +++ b/testing/resources/actual_text_rtl_glyphs.in @@ -0,0 +1,125 @@ +{{header}} +{{object 1 0}} << + /Type /Catalog + /Pages 2 0 R +>> +endobj +{{object 2 0}} << + /Type /Pages + /Count 1 + /Kids [3 0 R] +>> +endobj +{{object 3 0}} << + /Type /Page + /Contents 4 0 R + /Parent 2 0 R + /MediaBox [0 0 200 400] + /Resources << + /Font << + /F1 5 0 R + /F2 6 0 R + >> + >> +>> +endobj +{{object 4 0}} << + {{streamlen}} +>> +stream +BT +/F2 12 Tf +% RTL glyphs without /ActualText. +20 350 Td +<010205> Tj +% RTL glyphs with /ActualText. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% RTL glyphs with /ActualText containing neutral punctuation. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% RTL glyphs with /ActualText containing digits. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% Latin text followed by RTL glyphs with /ActualText. +0 -50 Td +/F1 12 Tf +(Hello world ) Tj +/F2 12 Tf +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +% Numbered list item as RTL glyphs with /ActualText. +0 -50 Td +/Span << + /ActualText +>> BDC +<010205> Tj +EMC +ET +endstream +endobj +{{object 5 0}} << + /Type /Font + /Subtype /Type1 + /BaseFont /Helvetica +>> +endobj +{{object 6 0}} << + /Type /Font + /Subtype /TrueType + /BaseFont /BAAAAA+NotoSansHebrew-Regular + /FirstChar 0 + /FontDescriptor 7 0 R + /LastChar 5 + /ToUnicode 9 0 R + /Widths [600 294 235 645 397 542] +>> +endobj +{{object 7 0}} << + /Type /FontDescriptor + /Ascent 1069 + /CapHeight 869 + /Descent -293 + /Flags 4 + /FontBBox [-210 -252 716 869] + /FontFile2 8 0 R + /FontName /BAAAAA+NotoSansHebrew-Regular + /ItalicAngle 0 + /StemV 80 +>> +endobj +{{object 8 0}} << + /Filter [/ASCII85Decode /FlateDecode] + {{streamlen}} + /Length1 6721 +>> +stream +{{include hebrew_truetype_font.fragment}} +endstream +endobj +{{object 9 0}} << + {{streamlen}} +>> +stream +{{include hebrew_cmap.fragment}} +endstream +endobj +{{xref}} +{{trailer}} +{{startxref}} +%%EOF diff --git a/testing/resources/actual_text_rtl_glyphs.pdf b/testing/resources/actual_text_rtl_glyphs.pdf new file mode 100644 index 0000000000..ea4a5535de Binary files /dev/null and b/testing/resources/actual_text_rtl_glyphs.pdf differ diff --git a/testing/resources/bug_585348292.pdf b/testing/resources/bug_585348292.pdf new file mode 100644 index 0000000000..91fa709058 Binary files /dev/null and b/testing/resources/bug_585348292.pdf differ diff --git a/testing/resources/javascript/app_methods.in b/testing/resources/javascript/app_methods.in index 1c01e84736..8b208bfa2a 100644 --- a/testing/resources/javascript/app_methods.in +++ b/testing/resources/javascript/app_methods.in @@ -54,6 +54,14 @@ try { expect("app.beep(1)", undefined); expectError("app.browseForDoc()"); + expectError("app.clearInterval()"); + expectError("app.clearInterval(1, 2)"); + expect("app.clearInterval(1)", undefined); + expect("app.clearInterval({})", undefined); + expectError("app.clearTimeOut()"); + expectError("app.clearTimeOut(1, 2)"); + expect("app.clearTimeOut(1)", undefined); + expect("app.clearTimeOut({})", undefined); expect("app.execDialog()", undefined); expectError("app.execMenuItem()"); expect("app.findComponent()", undefined); @@ -66,6 +74,18 @@ try { expect("app.openFDF()", undefined); expectError("app.popUpMenuEx()"); expectError("app.popUpMenu()"); + expectError("app.setInterval()"); + expectError("app.setInterval('')"); + expectError("app.setInterval('foo', 100, 200)"); + var testInterval = app.setInterval("42", 1000000); + expect("typeof testInterval", "object"); + expect("app.clearInterval(testInterval)", undefined); + expectError("app.setTimeOut()"); + expectError("app.setTimeOut('')"); + expectError("app.setTimeOut('foo', 100, 200)"); + var testTimeout = app.setTimeOut("42", 1000000); + expect("typeof testTimeout", "object"); + expect("app.clearTimeOut(testTimeout)", undefined); expect("app.mailMsg(true)", undefined); expect("app.mailMsg(false, 'user@example.com')", undefined); diff --git a/testing/resources/javascript/app_methods_expected.txt b/testing/resources/javascript/app_methods_expected.txt index 86fb3a94d4..0d547f4b84 100644 --- a/testing/resources/javascript/app_methods_expected.txt +++ b/testing/resources/javascript/app_methods_expected.txt @@ -26,6 +26,14 @@ Alert: PASS: app.alert({'color': 'red', 'size': 42}) threw app.alert: Incorrect BEEP!!! 1 Alert: PASS: app.beep(1) = undefined Alert: FAIL: app.browseForDoc() = undefined, expected to throw +Alert: PASS: app.clearInterval() threw app.clearInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.clearInterval(1, 2) threw app.clearInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.clearInterval(1) = undefined +Alert: PASS: app.clearInterval({}) = undefined +Alert: PASS: app.clearTimeOut() threw app.clearTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.clearTimeOut(1, 2) threw app.clearTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.clearTimeOut(1) = undefined +Alert: PASS: app.clearTimeOut({}) = undefined Alert: PASS: app.execDialog() = undefined Alert: PASS: app.execMenuItem() threw app.execMenuItem: Operation not supported. Alert: PASS: app.findComponent() = undefined @@ -38,6 +46,16 @@ Alert: PASS: app.openDoc() threw app.openDoc: Operation not supported. Alert: PASS: app.openFDF() = undefined Alert: PASS: app.popUpMenuEx() threw app.popUpMenuEx: Operation not supported. Alert: PASS: app.popUpMenu() threw app.popUpMenu: Operation not supported. +Alert: PASS: app.setInterval() threw app.setInterval: Incorrect number of parameters passed to function. +Alert: PASS: app.setInterval('') threw app.setInterval: The input value is invalid. +Alert: PASS: app.setInterval('foo', 100, 200) threw app.setInterval: Incorrect number of parameters passed to function. +Alert: PASS: typeof testInterval = object +Alert: PASS: app.clearInterval(testInterval) = undefined +Alert: PASS: app.setTimeOut() threw app.setTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: app.setTimeOut('') threw app.setTimeOut: The input value is invalid. +Alert: PASS: app.setTimeOut('foo', 100, 200) threw app.setTimeOut: Incorrect number of parameters passed to function. +Alert: PASS: typeof testTimeout = object +Alert: PASS: app.clearTimeOut(testTimeout) = undefined Mail Msg: 1, to=, cc=, bcc=, subject=, body= Alert: PASS: app.mailMsg(true) = undefined Mail Msg: 0, to=user@example.com, cc=, bcc=, subject=, body= diff --git a/testing/resources/javascript/field_properties.in b/testing/resources/javascript/field_properties.in index 5556e16d24..81e54d68f5 100644 --- a/testing/resources/javascript/field_properties.in +++ b/testing/resources/javascript/field_properties.in @@ -14,6 +14,7 @@ function testProperties() { var badbutton = this.getField("MyField.MyBadPushButton"); var radio = this.getField("MyField.MyRadio"); var list = this.getField("MyField.MyMultiSelect"); + var single = this.getField("MyField.MySingleSelect"); var check = this.getField("MyField.MyCheckBox"); var file = this.getField("MyField.MyFile"); app.alert('Testing properties under delay'); @@ -28,6 +29,7 @@ function testProperties() { testRadioButtonPropertiesCase(radio); testCheckBoxPropertiesCase(check); testListBoxPropertiesCase(list); + testSingleSelectPropertiesCase(single); testFileSelectPropertiesCase(file); } catch (e) { app.alert("Unexpected error: " + e); @@ -44,35 +46,34 @@ function testFieldPropertiesCase(field) { function testTextPropertiesCase(field) { try { - // TODO(tsepez): devise tests and uncomment. testRIProperty(field, "alignment", "left", "center"); testRWProperty(field, "borderStyle", "solid", "inset"); testRIProperty(field, "calcOrderIndex", -1, 100); testRIProperty(field, "charLimit", 0, 100); testRIProperty(field, "comb", false, true); - // testRIProperty(field, "commitOnSelChange", false, true); - // testROProperty(field, "currentValueIndices", "clams"); + testUnreadableProperty(field, "commitOnSelChange"); + testUnreadableProperty(field, "currentValueIndices"); testXXProperty(field, "defaultStyle"); testRIProperty(field, "defaultValue", "grue", "clams"); testRIProperty(field, "doNotScroll", false, true); testRIProperty(field, "doNotSpellCheck", false, true); testRWProperty(field, "display", 2, 3); testROProperty(field, "doc", "[object global]"); - // testROProperty(field, "editable", "clams"); + testUnreadableProperty(field, "editable"); testRWProperty(field, "hidden", false, true); testRIProperty(field, "fileSelect", false, true); testRIProperty(field, "fillColor", "T", ["RGB", 0, 0, 0]); testRWProperty(field, "lineWidth", 1, 4); testRIProperty(field, "multiline", false, true); - // testROProperty(field, "multipleSelection", "clams"); + testUnreadableProperty(field, "multipleSelection"); testROProperty(field, "name", "MyField.MyText"); - // testROProperty(field, "numItems", "clams"); + testXXProperty(field, "numItems"); testROProperty(field, "page", 0); testRIProperty(field, "password", false, 42); testRWProperty(field, "print", true, false); testRWProperty(field, "readonly", false, true); testROProperty(field, "rect", [200,221,220,201]); - // testROProperty(field, "required", "clams"); + testRIProperty(field, "required", false, true); testRIProperty(field, "richText", false, true); testRIProperty(field, "richValue", undefined, "clams"); testRIProperty(field, "rotation", 0, 42); @@ -80,7 +81,7 @@ function testTextPropertiesCase(field) { testRIProperty(field, "strokeColor", "T", ["RGB", 0, 0, 0]); testRIProperty(field, "submitName", undefined, "clams"); testRIProperty(field, "textColor", "T", ["RGB", 0, 0, 0]); - // testROProperty(field, "textFont", "clams"); + testUnreadableProperty(field, "textFont"); testRIProperty(field, "textSize", 0, 32); testROProperty(field, "type", "text"); testRIProperty(field, "userName", ""); @@ -118,6 +119,7 @@ function testRadioButtonPropertiesCase(field) { try { testROProperty(field, "exportValues", "Yes"); testRIProperty(field, "radiosInUnison", false); + testRIProperty(field, "required", false, true); testRIProperty(field, "style", "circle"); testROProperty(field, "type", "radiobutton"); testRIProperty(field, "value", "Off"); @@ -130,6 +132,7 @@ function testRadioButtonPropertiesCase(field) { function testCheckBoxPropertiesCase(field) { try { testROProperty(field, "exportValues", "Yes"); + testRIProperty(field, "required", false, true); testRIProperty(field, "style", "check"); testROProperty(field, "type", "checkbox"); testRIProperty(field, "value", "Off"); @@ -142,6 +145,23 @@ function testCheckBoxPropertiesCase(field) { function testListBoxPropertiesCase(field) { try { testRWProperty(field, "currentValueIndices", 2, 1); + testROProperty(field, "numItems", 3); + testRIProperty(field, "multipleSelection", true, false); + testRIProperty(field, "commitOnSelChange", false, true); + testRIProperty(field, "required", false, true); + testUnreadableProperty(field, "editable"); + } catch (e) { + app.alert("Unexpected error: " + e); + } +} + +function testSingleSelectPropertiesCase(field) { + try { + testROProperty(field, "numItems", 3); + testRIProperty(field, "multipleSelection", false, true); + testRIProperty(field, "commitOnSelChange", false, true); + testRIProperty(field, "required", false, true); + testUnreadableProperty(field, "editable"); } catch (e) { app.alert("Unexpected error: " + e); } diff --git a/testing/resources/javascript/field_properties_expected.txt b/testing/resources/javascript/field_properties_expected.txt index 4b98bcf119..283b7e5189 100644 --- a/testing/resources/javascript/field_properties_expected.txt +++ b/testing/resources/javascript/field_properties_expected.txt @@ -20,6 +20,8 @@ Alert: PASS: charLimit = 0 Alert: PASS: charLimit = 0 Alert: PASS: comb = false Alert: PASS: comb = false +Alert: PASS: commitOnSelChange threw Field.commitOnSelChange: Object is of the wrong type. +Alert: PASS: currentValueIndices threw Field.currentValueIndices: Object is of the wrong type. Alert: PASS: defaultStyle threw Field.defaultStyle: Operation not supported. Alert: PASS: defaultStyle threw Field.defaultStyle: Operation not supported. Alert: PASS: defaultValue = grue @@ -32,6 +34,7 @@ Alert: PASS: display = 2 Alert: PASS: display = 3 Alert: PASS: doc = [object global] Alert: PASS: doc threw Field.doc: Operation not supported. +Alert: PASS: editable threw Field.editable: Object is of the wrong type. Alert: PASS: hidden = false Alert: PASS: hidden = true Alert: PASS: fileSelect = false @@ -42,8 +45,11 @@ Alert: PASS: lineWidth = 1 Alert: PASS: lineWidth = 4 Alert: PASS: multiline = false Alert: PASS: multiline = false +Alert: PASS: multipleSelection threw Field.multipleSelection: Object is of the wrong type. Alert: PASS: name = MyField.MyText Alert: PASS: name threw Field.name: Operation not supported. +Alert: PASS: numItems threw Field.numItems: Object is of the wrong type. +Alert: PASS: numItems threw Field.numItems: Operation not supported. Alert: PASS: page = 0 Alert: PASS: page threw Field.page: Cannot assign to readonly property. Alert: PASS: password = false @@ -54,6 +60,8 @@ Alert: PASS: readonly = false Alert: PASS: readonly = true Alert: PASS: rect = 200,221,220,201 Alert: PASS: rect threw Field.rect: Incorrect parameter value. +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: richText = false Alert: PASS: richText = false Alert: PASS: richValue = undefined @@ -68,6 +76,7 @@ Alert: PASS: submitName = undefined Alert: PASS: submitName = undefined Alert: PASS: textColor = T Alert: PASS: textColor = T +Alert: PASS: textFont threw Field.textFont: Object no longer exists. Alert: PASS: textSize = 0 Alert: PASS: textSize = 0 Alert: PASS: type = text @@ -100,6 +109,8 @@ Alert: PASS: exportValues = Yes Alert: PASS: exportValues threw Field.exportValues: Object no longer exists. Alert: PASS: radiosInUnison = false Alert: PASS: radiosInUnison = false +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: style = circle Alert: PASS: style = circle Alert: PASS: type = radiobutton @@ -110,6 +121,8 @@ Alert: PASS: valueAsString = Off Alert: PASS: valueAsString threw Field.valueAsString: Operation not supported. Alert: PASS: exportValues = Yes Alert: PASS: exportValues threw Field.exportValues: Object no longer exists. +Alert: PASS: required = false +Alert: PASS: required = false Alert: PASS: style = check Alert: PASS: style = check Alert: PASS: type = checkbox @@ -120,5 +133,23 @@ Alert: PASS: valueAsString = Off Alert: PASS: valueAsString threw Field.valueAsString: Operation not supported. Alert: PASS: currentValueIndices = 2 Alert: PASS: currentValueIndices = 1 +Alert: PASS: numItems = 3 +Alert: PASS: numItems threw Field.numItems: Operation not supported. +Alert: PASS: multipleSelection = true +Alert: PASS: multipleSelection = true +Alert: PASS: commitOnSelChange = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: required = false +Alert: PASS: required = false +Alert: PASS: editable threw Field.editable: Object is of the wrong type. +Alert: PASS: numItems = 3 +Alert: PASS: numItems threw Field.numItems: Operation not supported. +Alert: PASS: multipleSelection = false +Alert: PASS: multipleSelection = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: commitOnSelChange = false +Alert: PASS: required = false +Alert: PASS: required = false +Alert: PASS: editable threw Field.editable: Object is of the wrong type. Alert: PASS: fileSelect = true Alert: PASS: fileSelect = true diff --git a/testing/resources/javascript/xfa_specific/bug_1109108.in b/testing/resources/javascript/xfa_specific/bug_1109108.in index 550112e72d..c51488b36e 100644 --- a/testing/resources/javascript/xfa_specific/bug_1109108.in +++ b/testing/resources/javascript/xfa_specific/bug_1109108.in @@ -10,20 +10,6 @@ stream