From 4980d81fbb826f875e71182e718ff6b0b245cba9 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Mon, 23 Nov 2026 13:54:16 +0200 Subject: [PATCH 1/3] Read an annotation's border in one place, for form fields and setters too ISO 32000-1 12.5.2 reads an annotation's border from /BS when it has one, and then /Border is not read at all; else from /Border [h v w [dash]]; else the border is solid and 1 wide. Free text has followed that since pull requests 118 and 121. The rule was then written four times, and two places did not follow it. Every form field drawer read /BS alone: text field, combo box, list box, push button, check box, radio button and the signature box. A field with /Border [0 0 5 [4 2]] and no /BS was drawn 1 wide and solid, and one with /Border [0 0 0] was drawn 1 wide, while EPDFAnnot_GetBorderStyle read 5 and dashed, and 0: what the API read and what a redraw drew did not agree. On an annotation whose border is only in /Border, EPDFAnnot_SetBorderDashPattern made a /BS holding only /D, so the width fell to 1, and with no pattern it changed nothing. EPDFAnnot_SetBorderStyle left the old /Border in the file, where a reader that looks at /Border first (PDFium's form filler does) went on showing the old border. fpdfdoc::ReadAnnotBorder (core/fpdfdoc/cpdf_annot_border) now reads the width, the style and the stored dash pattern by the rule. The generator's GetAnnotBorderStyleInfo, GetBorderWidth and GetDashPatternString, and the C API's EPDFAnnot_GetBorderStyle and dash pattern readers, take the border from it. The reader of a bare /BS dictionary is gone, so a drawer can't read /BS alone again; the form field drawers and the link's style read call GetAnnotBorderStyleInfo. Before a setter changes an annotation that has no /BS, its /Border is written into a new /BS as it reads: its width, and a dashed style with its pattern when the array has one. The setter then changes the part it sets, as it does on any /BS, so the dash setter leaves the style alone there too, and /Border is removed. EPDFAnnot_SetBorderStyle refuses a style that is none before it writes anything. With one reading, three inputs ISO does not define read alike everywhere. A /BS /S that is none of its five names is solid: the form fields, the plain free text box and the link took its first letter. A /Border with more than four entries has no dash for the API either. A /BS /S written as a string is the style for the API too. Tests: CPDFGenerateAPTest.BorderArrayDrawsAsBorderStyleForEveryKind draws all seventeen kinds that have a border from /BS and from /Border and compares the streams. CPDFAnnotBorderTest covers the reader. Three EPDFAnnotEmbedderTest cases cover the setters and one a text field through the C API; the four are listed as layer-mode writers. --- core/fpdfdoc/BUILD.gn | 5 + core/fpdfdoc/cpdf_annot_border.cpp | 51 +++ core/fpdfdoc/cpdf_annot_border.h | 43 +++ core/fpdfdoc/cpdf_annot_border_unittest.cpp | 217 ++++++++++++ .../cpdf_appearancegenerator_common.cpp | 134 +++---- .../cpdf_appearancegenerator_forms.cpp | 18 +- .../cpdf_appearancegenerator_icons.cpp | 5 +- .../cpdf_appearancegenerator_internal.h | 5 +- .../cpdf_appearancegenerator_unittest.cpp | 326 ++++++++++++++++++ docs/embedpdf/fork-ledger.md | 19 +- fpdfsdk/epdf_annot.cpp | 118 +++---- fpdfsdk/epdf_annot_embeddertest.cpp | 276 +++++++++++++++ public/epdf_annot.h | 29 +- testing/embedpdf_layer_mode_writers.txt | 4 + 14 files changed, 1063 insertions(+), 187 deletions(-) create mode 100644 core/fpdfdoc/cpdf_annot_border.cpp create mode 100644 core/fpdfdoc/cpdf_annot_border.h create mode 100644 core/fpdfdoc/cpdf_annot_border_unittest.cpp diff --git a/core/fpdfdoc/BUILD.gn b/core/fpdfdoc/BUILD.gn index 1d311120b0..e25958a848 100644 --- a/core/fpdfdoc/BUILD.gn +++ b/core/fpdfdoc/BUILD.gn @@ -13,6 +13,10 @@ source_set("fpdfdoc") { "cpdf_action.h", "cpdf_annot.cpp", "cpdf_annot.h", + # EmbedPDF: the one reading of an annotation's border (/BS, or else + # /Border), for the appearance generator and the EPDFAnnot_* readers. + "cpdf_annot_border.cpp", + "cpdf_annot_border.h", "cpdf_annot_rotation.cpp", "cpdf_annot_rotation.h", "cpdf_embed_metadata.cpp", @@ -156,6 +160,7 @@ source_set("fpdfdoc") { pdfium_unittest_source_set("unittests") { sources = [ "cpdf_action_unittest.cpp", + "cpdf_annot_border_unittest.cpp", "cpdf_annot_unittest.cpp", "cpdf_annotlist_unittest.cpp", "cpdf_bafontmap_unittest.cpp", diff --git a/core/fpdfdoc/cpdf_annot_border.cpp b/core/fpdfdoc/cpdf_annot_border.cpp new file mode 100644 index 0000000000..3b409da18e --- /dev/null +++ b/core/fpdfdoc/cpdf_annot_border.cpp @@ -0,0 +1,51 @@ +// Copyright 2026 CloudPDF LTD +// SPDX-License-Identifier: Apache-2.0 + +#include "core/fpdfdoc/cpdf_annot_border.h" + +#include "constants/annotation_common.h" +#include "core/fpdfapi/parser/cpdf_array.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" + +namespace fpdfdoc { + +AnnotBorder ReadAnnotBorder(const CPDF_Dictionary* annot_dict) { + AnnotBorder border; + + RetainPtr border_style = annot_dict->GetDictFor("BS"); + if (border_style) { + if (border_style->KeyExist("W")) { + border.width = border_style->GetFloatFor("W"); + } + const CPDF_Annot::BorderStyle style = + CPDF_Annot::StringToBorderStyle(border_style->GetByteStringFor("S")); + if (style != CPDF_Annot::BorderStyle::kUnknown) { + border.style = style; + } + border.dash_array = border_style->GetArrayFor("D"); + if (border.style == CPDF_Annot::BorderStyle::kDashed && border.dash_array && + border.dash_array->IsEmpty()) { + border.style = CPDF_Annot::BorderStyle::kSolid; + } + return border; + } + + RetainPtr border_array = + annot_dict->GetArrayFor(pdfium::annotation::kBorder); + if (!border_array) { + return border; + } + if (border_array->size() > 2) { + border.width = border_array->GetFloatAt(2); + } + // The dash array is the fourth and last entry. + if (border_array->size() == 4) { + border.dash_array = border_array->GetArrayAt(3); + if (border.dash_array && !border.dash_array->IsEmpty()) { + border.style = CPDF_Annot::BorderStyle::kDashed; + } + } + return border; +} + +} // namespace fpdfdoc diff --git a/core/fpdfdoc/cpdf_annot_border.h b/core/fpdfdoc/cpdf_annot_border.h new file mode 100644 index 0000000000..4cd0cb7022 --- /dev/null +++ b/core/fpdfdoc/cpdf_annot_border.h @@ -0,0 +1,43 @@ +// Copyright 2026 CloudPDF LTD +// SPDX-License-Identifier: Apache-2.0 + +#ifndef CORE_FPDFDOC_CPDF_ANNOT_BORDER_H_ +#define CORE_FPDFDOC_CPDF_ANNOT_BORDER_H_ + +#include "core/fpdfapi/parser/cpdf_array.h" +#include "core/fpdfdoc/cpdf_annot.h" +#include "core/fxcrt/retain_ptr.h" + +class CPDF_Dictionary; + +namespace fpdfdoc { + +// An annotation's border, read by the one rule of ISO 32000-1 12.5.2: its +// /BS when it has one, and /Border is then not read at all; else +// /Border [h v w [dash]]; else a solid border 1 wide. +// +// Our code reads a border here and nowhere else: the appearance generator +// draws every kind from this reading, and EPDFAnnot_GetBorderStyle() and the +// dash pattern readers report it. So a border is drawn as it reads, +// whichever key holds it. +struct AnnotBorder { + // /BS /W, or /Border's third number; 1 when the key that is read has none. + float width = 1.0f; + + // /BS /S, solid when it is left out or is no name ISO 32000 defines. A + // /Border is dashed when its dash array holds a pattern. A dashed border + // whose pattern is an empty array draws a solid line (8.4.3.6) and is + // solid here. Never kUnknown. + CPDF_Annot::BorderStyle style = CPDF_Annot::BorderStyle::kSolid; + + // The pattern as stored, whatever the style: /BS /D, or /Border's dash + // array. Null when none is stored; a dashed border then draws ISO's + // default dash. + RetainPtr dash_array; +}; + +AnnotBorder ReadAnnotBorder(const CPDF_Dictionary* annot_dict); + +} // namespace fpdfdoc + +#endif // CORE_FPDFDOC_CPDF_ANNOT_BORDER_H_ diff --git a/core/fpdfdoc/cpdf_annot_border_unittest.cpp b/core/fpdfdoc/cpdf_annot_border_unittest.cpp new file mode 100644 index 0000000000..b168f94a7a --- /dev/null +++ b/core/fpdfdoc/cpdf_annot_border_unittest.cpp @@ -0,0 +1,217 @@ +// Copyright 2026 CloudPDF LTD +// SPDX-License-Identifier: Apache-2.0 + +#include "core/fpdfdoc/cpdf_annot_border.h" + +#include +#include +#include + +#include "constants/annotation_common.h" +#include "core/fpdfapi/parser/cpdf_array.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_name.h" +#include "core/fpdfapi/parser/cpdf_number.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +using BorderStyle = CPDF_Annot::BorderStyle; + +RetainPtr Numbers(std::initializer_list values) { + auto array = pdfium::MakeRetain(); + for (float value : values) { + array->AppendNew(value); + } + return array; +} + +// /BS on a new annotation: /W |width|, /S |style| and /D |dash|, each when +// given. +RetainPtr WithBorderStyle( + std::optional width, + const char* style, + std::optional> dash) { + auto annot_dict = pdfium::MakeRetain(); + auto border_style = annot_dict->SetNewFor("BS"); + if (width.has_value()) { + border_style->SetNewFor("W", width.value()); + } + if (style) { + border_style->SetNewFor("S", style); + } + if (dash.has_value()) { + auto dash_array = border_style->SetNewFor("D"); + for (float value : dash.value()) { + dash_array->AppendNew(value); + } + } + return annot_dict; +} + +// /Border |border| on a new annotation. +RetainPtr WithBorderArray(RetainPtr border) { + auto annot_dict = pdfium::MakeRetain(); + annot_dict->SetFor(pdfium::annotation::kBorder, std::move(border)); + return annot_dict; +} + +// The pattern |border| stores; empty when it stores none or an empty one. +std::vector StoredPattern(const fpdfdoc::AnnotBorder& border) { + std::vector values; + if (border.dash_array) { + for (size_t i = 0; i < border.dash_array->size(); ++i) { + values.push_back(border.dash_array->GetFloatAt(i)); + } + } + return values; +} + +} // namespace + +TEST(CPDFAnnotBorderTest, NeitherKeyIsSolidAndOneWide) { + auto annot_dict = pdfium::MakeRetain(); + const fpdfdoc::AnnotBorder border = + fpdfdoc::ReadAnnotBorder(annot_dict.Get()); + EXPECT_EQ(1.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + EXPECT_FALSE(border.dash_array); +} + +TEST(CPDFAnnotBorderTest, BorderStyleWidthAndNames) { + // What /BS leaves out takes its default: 1 wide, solid. + fpdfdoc::AnnotBorder border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(std::nullopt, nullptr, std::nullopt).Get()); + EXPECT_EQ(1.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + + border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(0.0f, nullptr, std::nullopt).Get()); + EXPECT_EQ(0.0f, border.width); + + struct NameCase { + const char* name; + BorderStyle style; + }; + static constexpr NameCase kNames[] = { + {"S", BorderStyle::kSolid}, + {"D", BorderStyle::kDashed}, + {"B", BorderStyle::kBeveled}, + {"I", BorderStyle::kInset}, + {"U", BorderStyle::kUnderline}, + // A name ISO 32000 doesn't define is the default, solid, whatever its + // first letter. + {"Dashed", BorderStyle::kSolid}, + {"Underline", BorderStyle::kSolid}, + {"X", BorderStyle::kSolid}, + }; + for (const NameCase& name_case : kNames) { + SCOPED_TRACE(name_case.name); + border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(2.5f, name_case.name, std::nullopt).Get()); + EXPECT_EQ(name_case.style, border.style); + // The width as written, for a beveled or inset border too. + EXPECT_EQ(2.5f, border.width); + } +} + +TEST(CPDFAnnotBorderTest, BorderStylePattern) { + // Dashed without /D: no pattern stored, and it draws the default dash. + fpdfdoc::AnnotBorder border = + fpdfdoc::ReadAnnotBorder(WithBorderStyle(2, "D", std::nullopt).Get()); + EXPECT_EQ(BorderStyle::kDashed, border.style); + EXPECT_FALSE(border.dash_array); + + border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(2, "D", std::vector{4, 2}).Get()); + EXPECT_EQ(BorderStyle::kDashed, border.style); + EXPECT_EQ((std::vector{4, 2}), StoredPattern(border)); + + // An empty pattern is a solid line (ISO 32000 8.4.3.6). + border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(2, "D", std::vector{}).Get()); + EXPECT_EQ(BorderStyle::kSolid, border.style); + ASSERT_TRUE(border.dash_array); + EXPECT_TRUE(border.dash_array->IsEmpty()); + + // A pattern is stored whatever the style; only a dashed border draws it. + for (const char* style : {"S", "B", "I", "U"}) { + SCOPED_TRACE(style); + border = fpdfdoc::ReadAnnotBorder( + WithBorderStyle(2, style, std::vector{4, 2}).Get()); + EXPECT_NE(BorderStyle::kDashed, border.style); + EXPECT_EQ((std::vector{4, 2}), StoredPattern(border)); + } +} + +TEST(CPDFAnnotBorderTest, BorderArray) { + fpdfdoc::AnnotBorder border = + fpdfdoc::ReadAnnotBorder(WithBorderArray(Numbers({0, 0, 5})).Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + EXPECT_FALSE(border.dash_array); + + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(Numbers({0, 0, 0})).Get()); + EXPECT_EQ(0.0f, border.width); + + // The corner radii are not part of what is read. + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(Numbers({3, 3, 5})).Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + + // Too short to hold a width: the default. + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(Numbers({0, 0})).Get()); + EXPECT_EQ(1.0f, border.width); + + // A dash array with a pattern makes the border dashed. + RetainPtr dashed = Numbers({0, 0, 5}); + dashed->Append(Numbers({4, 2})); + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(dashed).Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kDashed, border.style); + EXPECT_EQ((std::vector{4, 2}), StoredPattern(border)); + + // An empty one is a solid line. + RetainPtr empty_dash = Numbers({0, 0, 5}); + empty_dash->Append(Numbers({})); + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(empty_dash).Get()); + EXPECT_EQ(BorderStyle::kSolid, border.style); + ASSERT_TRUE(border.dash_array); + EXPECT_TRUE(border.dash_array->IsEmpty()); + + // A fourth entry that is no array is no dash. + border = + fpdfdoc::ReadAnnotBorder(WithBorderArray(Numbers({0, 0, 5, 7})).Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + EXPECT_FALSE(border.dash_array); + + // The dash array is the last of four entries: with more, the width is + // still read and no dash is. + RetainPtr five = Numbers({0, 0, 5}); + five->Append(Numbers({4, 2})); + five->AppendNew(9); + border = fpdfdoc::ReadAnnotBorder(WithBorderArray(five).Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + EXPECT_FALSE(border.dash_array); +} + +TEST(CPDFAnnotBorderTest, BorderStyleWinsOverBorderArray) { + // An empty /BS is the default border; /Border beside it is not read. + RetainPtr dashed = Numbers({0, 0, 5}); + dashed->Append(Numbers({4, 2})); + RetainPtr annot_dict = + WithBorderStyle(std::nullopt, nullptr, std::nullopt); + annot_dict->SetFor(pdfium::annotation::kBorder, dashed); + fpdfdoc::AnnotBorder border = fpdfdoc::ReadAnnotBorder(annot_dict.Get()); + EXPECT_EQ(1.0f, border.width); + EXPECT_EQ(BorderStyle::kSolid, border.style); + EXPECT_FALSE(border.dash_array); + + // A /BS that is no dictionary is no /BS. + annot_dict->SetNewFor("BS", 4); + border = fpdfdoc::ReadAnnotBorder(annot_dict.Get()); + EXPECT_EQ(5.0f, border.width); + EXPECT_EQ(BorderStyle::kDashed, border.style); +} diff --git a/core/fpdfdoc/cpdf_appearancegenerator_common.cpp b/core/fpdfdoc/cpdf_appearancegenerator_common.cpp index db129751a5..735fcc8cea 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_common.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_common.cpp @@ -32,6 +32,7 @@ #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfdoc/cpdf_annot.h" +#include "core/fpdfdoc/cpdf_annot_border.h" #include "core/fpdfdoc/cpdf_annot_rotation.h" #include "core/fpdfdoc/cpdf_appearancegenerator_internal.h" #include "core/fpdfdoc/cpdf_color_utils.h" @@ -66,14 +67,17 @@ std::vector DashValues(const CPDF_Array* dash_array) { return values; } -// A dashed /BS's pattern (ISO 32000 table 168): its /D, or the default [3] -// when it names none. An empty /D is a solid line (8.4.3.6): no pattern. -std::vector BorderStyleDash(const CPDF_Dictionary* border_style_dict) { - RetainPtr dash_array = border_style_dict->GetArrayFor("D"); - if (!dash_array) { +// The pattern |border| draws its line with: a dashed border's stored one, or +// the default [3] when it stores none (ISO 32000 table 168). None for a +// border that draws a solid line. +std::vector BorderDash(const fpdfdoc::AnnotBorder& border) { + if (border.style != CPDF_Annot::BorderStyle::kDashed) { + return {}; + } + if (!border.dash_array) { return {kDefaultDash}; } - return DashValues(dash_array.Get()); + return DashValues(border.dash_array.Get()); } // The dash operator for |values|; empty when there are none. @@ -278,71 +282,34 @@ BlendMode DefaultBlendModeFor(CPDF_Annot::Subtype subtype) { } } -BorderStyleInfo GetBorderStyleInfo(const CPDF_Dictionary* border_style_dict) { - BorderStyleInfo border_style_info; - if (!border_style_dict) { - return border_style_info; - } - - if (border_style_dict->KeyExist("W")) { - border_style_info.width = border_style_dict->GetFloatFor("W"); - } - - const ByteString border_style_string = - border_style_dict->GetByteStringFor("S"); - if (border_style_string.GetLength()) { - switch (border_style_string[0]) { - case 'S': - border_style_info.style = BorderStyle::kSolid; - break; - case 'D': - border_style_info.style = BorderStyle::kDash; - break; - case 'B': - border_style_info.style = BorderStyle::kBeveled; - border_style_info.width *= 2; - break; - case 'I': - border_style_info.style = BorderStyle::kInset; - border_style_info.width *= 2; - break; - case 'U': - border_style_info.style = BorderStyle::kUnderline; - break; - } - } - - // A dashed border with an empty pattern draws a solid line. - std::vector dash = BorderStyleDash(border_style_dict); - if (!dash.empty()) { - border_style_info.dash_pattern = std::move(dash); - } else if (border_style_info.style == BorderStyle::kDash) { - border_style_info.style = BorderStyle::kSolid; - } - - return border_style_info; -} - -// An annotation's border as ISO 32000-1 12.5.2 reads it: its /BS, or else -// its /Border array, whose width (default 1) and dash array draw as -// GetBorderWidth and GetDashPatternString take them; an empty dash array -// draws a solid line. +// An annotation's border as a box draws it, from the one reading of a border +// (fpdfdoc::ReadAnnotBorder): its /BS, or else its /Border, or else 1 wide +// and solid. Every drawer that takes a border's style calls this; none reads +// /BS itself. A beveled or inset border is twice as wide as it says: the +// line, and the lit and shaded edges inside it. BorderStyleInfo GetAnnotBorderStyleInfo(const CPDF_Dictionary* annot_dict) { - RetainPtr border_style_dict = - annot_dict->GetDictFor("BS"); - if (border_style_dict) { - return GetBorderStyleInfo(border_style_dict.Get()); - } + const fpdfdoc::AnnotBorder border = fpdfdoc::ReadAnnotBorder(annot_dict); BorderStyleInfo border_style_info; - border_style_info.width = GetBorderWidth(annot_dict); - RetainPtr border_array = - annot_dict->GetArrayFor(pdfium::annotation::kBorder); - if (border_array && border_array->size() == 4) { - std::vector dash = DashValues(border_array->GetArrayAt(3).Get()); - if (!dash.empty()) { + border_style_info.width = border.width; + switch (border.style) { + case CPDF_Annot::BorderStyle::kUnknown: + case CPDF_Annot::BorderStyle::kSolid: + break; + case CPDF_Annot::BorderStyle::kDashed: border_style_info.style = BorderStyle::kDash; - border_style_info.dash_pattern = std::move(dash); - } + border_style_info.dash_pattern = BorderDash(border); + break; + case CPDF_Annot::BorderStyle::kBeveled: + border_style_info.style = BorderStyle::kBeveled; + border_style_info.width *= 2; + break; + case CPDF_Annot::BorderStyle::kInset: + border_style_info.style = BorderStyle::kInset; + border_style_info.width *= 2; + break; + case CPDF_Annot::BorderStyle::kUnderline: + border_style_info.style = BorderStyle::kUnderline; + break; } return border_style_info; } @@ -571,40 +538,17 @@ std::optional GetStrokeColorString(const CPDF_Dictionary* dict) { return GenerateColorAP(color, PaintOperation::kStroke); } +// The width a border's line is drawn with: /BS /W, or else /Border's, or +// else 1. float GetBorderWidth(const CPDF_Dictionary* dict) { - RetainPtr border_style_dict = dict->GetDictFor("BS"); - if (border_style_dict) { - return border_style_dict->KeyExist("W") - ? border_style_dict->GetFloatFor("W") - : 1.0f; - } - - auto border_array = dict->GetArrayFor(pdfium::annotation::kBorder); - if (border_array && border_array->size() > 2) { - return border_array->GetFloatAt(2); - } - - return 1.0f; + return fpdfdoc::ReadAnnotBorder(dict).width; } // The dash operator a border draws with, as ISO 32000 reads it: a dashed /BS // draws its /D, or the default dash when it names none, and nothing (a solid // line) for an empty one; a /Border draws its own dash array. ByteString GetDashPatternString(const CPDF_Dictionary* dict) { - RetainPtr border_style_dict = dict->GetDictFor("BS"); - if (border_style_dict) { - if (border_style_dict->GetByteStringFor("S") != "D") { - return ByteString(); - } - return DashOperator(BorderStyleDash(border_style_dict.Get())); - } - - RetainPtr border_array = - dict->GetArrayFor(pdfium::annotation::kBorder); - if (border_array && border_array->size() == 4) { - return DashOperator(DashValues(border_array->GetArrayAt(3).Get())); - } - return ByteString(); + return DashOperator(BorderDash(fpdfdoc::ReadAnnotBorder(dict))); } ByteString GetPaintOperatorString(bool is_stroke_rect, bool is_fill_rect) { diff --git a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp index 57eec08c92..11e0005bdb 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp @@ -60,8 +60,8 @@ using appearance_generator::GenerateEphemeralDefaultAcroFormDict; using appearance_generator::GenerateExtGStateDict; using appearance_generator::GenerateResourcesDict; using appearance_generator::GetAnnotationDimensionsAndColor; +using appearance_generator::GetAnnotBorderStyleInfo; using appearance_generator::GetAppearanceCharacteristics; -using appearance_generator::GetBorderStyleInfo; using appearance_generator::GetDefaultAppearanceInfo; using appearance_generator::PaintOperation; using appearance_generator::ResolveDaFontForEphemeralTarget; @@ -300,7 +300,7 @@ void GenerateTextFieldFormAP(fxcrt::ostringstream& app_stream, const WideString* value_override) { const AppearanceCharacteristics mk = GetAppearanceCharacteristics(annot_dict->GetDictFor("MK")); - const BorderStyleInfo bs = GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const float bw = bs.width; CFX_FloatRect body_rect = bbox; @@ -340,8 +340,7 @@ void GenerateComboBoxFormAP(fxcrt::ostringstream& app_stream, const WideString* value_override) { const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); - const BorderStyleInfo border_info = - GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo border_info = GetAnnotBorderStyleInfo(annot_dict); const ByteString background = GenerateColorAP(dims.background_color, PaintOperation::kFill); @@ -372,8 +371,7 @@ void GenerateListBoxFormAP(fxcrt::ostringstream& app_stream, const CPDF_RichTextLayout::Options& options) { const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); - const BorderStyleInfo border_info = - GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo border_info = GetAnnotBorderStyleInfo(annot_dict); const ByteString background = GenerateColorAP(dims.background_color, PaintOperation::kFill); @@ -490,7 +488,7 @@ void GeneratePushButtonFormAP(fxcrt::ostringstream& app_stream, const CPDF_RichTextLayout::Options& options) { const AppearanceCharacteristics mk = GetAppearanceCharacteristics(annot_dict->GetDictFor("MK")); - const BorderStyleInfo bs = GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const float bw = bs.width; app_stream << "q\n"; @@ -1002,7 +1000,7 @@ void CPDF_AppearanceGenerator::GenerateBoxFormAP(CPDF_Document* doc, CPDF_Dictionary* annot_dict) { const AppearanceCharacteristics mk = GetAppearanceCharacteristics(annot_dict->GetDictFor("MK")); - const BorderStyleInfo bs = GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); @@ -1022,7 +1020,7 @@ void CPDF_AppearanceGenerator::GenerateCheckboxFormAP( CPDF_Dictionary* annot_dict) { const AppearanceCharacteristics mk = GetAppearanceCharacteristics(annot_dict->GetDictFor("MK")); - const BorderStyleInfo bs = GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); @@ -1080,7 +1078,7 @@ void CPDF_AppearanceGenerator::GenerateRadioButtonFormAP( CPDF_Dictionary* annot_dict) { const AppearanceCharacteristics mk = GetAppearanceCharacteristics(annot_dict->GetDictFor("MK")); - const BorderStyleInfo bs = GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); diff --git a/core/fpdfdoc/cpdf_appearancegenerator_icons.cpp b/core/fpdfdoc/cpdf_appearancegenerator_icons.cpp index bc5a48de5e..303411b0a7 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_icons.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_icons.cpp @@ -41,7 +41,7 @@ using appearance_generator::GenerateExtGStateDict; using appearance_generator::GenerateFallbackFontDict; using appearance_generator::GenerateResourceFontDict; using appearance_generator::GenerateResourcesDict; -using appearance_generator::GetBorderStyleInfo; +using appearance_generator::GetAnnotBorderStyleInfo; using appearance_generator::GetBorderWidth; using appearance_generator::GetColorStringWithDefault; using appearance_generator::GetDashPatternString; @@ -575,8 +575,7 @@ bool GenerateLinkAP(APGenerationTarget* target, app_stream << GetDashPatternString(annot_dict); // Determine border style - BorderStyleInfo border_info = - GetBorderStyleInfo(annot_dict->GetDictFor("BS")); + const BorderStyleInfo border_info = GetAnnotBorderStyleInfo(annot_dict); switch (border_info.style) { case BorderStyle::kUnderline: { diff --git a/core/fpdfdoc/cpdf_appearancegenerator_internal.h b/core/fpdfdoc/cpdf_appearancegenerator_internal.h index 0675e36a55..f4d127b725 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_internal.h +++ b/core/fpdfdoc/cpdf_appearancegenerator_internal.h @@ -146,7 +146,10 @@ bool IsFinitePoint(const CFX_PointF& point); CFX_PointF Midpoint(const CFX_PointF& first, const CFX_PointF& second); ByteString BlendModeToPDFName(BlendMode bm); BlendMode DefaultBlendModeFor(CPDF_Annot::Subtype subtype); -BorderStyleInfo GetBorderStyleInfo(const CPDF_Dictionary* border_style_dict); +// An annotation's border, for a drawer: /BS, or else /Border, or else 1 wide +// and solid (fpdfdoc::ReadAnnotBorder). A drawer takes its border from this, +// or from GetBorderWidth() and GetDashPatternString(), which read the same; +// it never reads /BS or /Border itself. BorderStyleInfo GetAnnotBorderStyleInfo(const CPDF_Dictionary* annot_dict); AnnotationDimensionsAndColor GetAnnotationDimensionsAndColor( const CPDF_Dictionary* annot_dict); diff --git a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp index fd91f30472..985f59fd34 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp @@ -3,12 +3,14 @@ #include "core/fpdfdoc/cpdf_appearancegenerator.h" +#include #include #include #include "constants/annotation_common.h" #include "constants/font_encodings.h" #include "constants/form_fields.h" +#include "constants/form_flags.h" #include "core/fpdfapi/page/test_with_page_module.h" #include "core/fpdfapi/parser/cpdf_array.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" @@ -365,6 +367,330 @@ TEST_F(CPDFGenerateAPTest, FreeTextCalloutBorderDash) { GenerateFreeTextAPContent(solid_callout.Get()).Contains(" 0 d\n")); } +namespace { + +// A kind of annotation the generator draws with its border. +enum class BorderedKind { + kSquare, + kCircle, + kLine, + kPolygon, + kPolyLine, + kInk, + kFreeText, + kCallout, + kLink, + kRedact, + kTextField, + kComboBox, + kListBox, + kCheckBox, + kRadioButton, + kPushButton, + kSignature, +}; + +struct BorderedKindCase { + const char* name; + BorderedKind kind; + // False for a check box, a radio button and a push button, which draw one + // solid box for every border style. + bool draws_dashes; +}; + +constexpr BorderedKindCase kBorderedKinds[] = { + {"square", BorderedKind::kSquare, true}, + {"circle", BorderedKind::kCircle, true}, + {"line", BorderedKind::kLine, true}, + {"polygon", BorderedKind::kPolygon, true}, + {"polyline", BorderedKind::kPolyLine, true}, + {"ink", BorderedKind::kInk, true}, + {"free text", BorderedKind::kFreeText, true}, + {"free text callout", BorderedKind::kCallout, true}, + {"link", BorderedKind::kLink, true}, + {"redaction", BorderedKind::kRedact, true}, + {"text field", BorderedKind::kTextField, true}, + {"combo box", BorderedKind::kComboBox, true}, + {"list box", BorderedKind::kListBox, true}, + {"check box", BorderedKind::kCheckBox, false}, + {"radio button", BorderedKind::kRadioButton, false}, + {"push button", BorderedKind::kPushButton, false}, + {"signature", BorderedKind::kSignature, true}, +}; + +// An annotation of |kind|, 120 by 60, with what the kind needs to be drawn +// (a colour, its points, its text) and neither /BS nor /Border. +RetainPtr MakeBorderedDict(BorderedKind kind) { + const CFX_FloatRect rect(50, 50, 170, 110); + auto shape = [&rect](const ByteString& subtype) { + auto annot_dict = MakeAnnotDict(subtype, rect); + annot_dict->SetFor(pdfium::annotation::kC, MakeNumberArray({1, 0, 0})); + return annot_dict; + }; + auto widget = [&rect](const ByteString& field_type, uint32_t field_flags) { + auto annot_dict = MakeAnnotDict("Widget", rect); + annot_dict->SetNewFor(pdfium::form_fields::kFT, field_type); + annot_dict->SetNewFor(pdfium::form_fields::kFf, + static_cast(field_flags)); + annot_dict->SetNewFor("DA", "/Helv 12 Tf 0 g"); + auto mk = annot_dict->SetNewFor("MK"); + mk->SetFor("BC", MakeNumberArray({0, 1, 0})); + mk->SetFor("BG", MakeNumberArray({1, 1, 0.8f})); + return annot_dict; + }; + auto options = [] { + auto array = pdfium::MakeRetain(); + array->AppendNew("one"); + array->AppendNew("two"); + return array; + }; + + switch (kind) { + case BorderedKind::kSquare: + return shape("Square"); + case BorderedKind::kCircle: + return shape("Circle"); + case BorderedKind::kLine: { + auto annot_dict = shape("Line"); + annot_dict->SetFor("L", MakeNumberArray({60, 60, 160, 100})); + return annot_dict; + } + case BorderedKind::kPolygon: { + auto annot_dict = shape("Polygon"); + annot_dict->SetFor(pdfium::annotation::kVertices, + MakeNumberArray({60, 60, 160, 60, 110, 100})); + return annot_dict; + } + case BorderedKind::kPolyLine: { + auto annot_dict = shape("PolyLine"); + annot_dict->SetFor(pdfium::annotation::kVertices, + MakeNumberArray({60, 60, 110, 100, 160, 60})); + return annot_dict; + } + case BorderedKind::kInk: { + auto annot_dict = shape("Ink"); + auto ink_list = pdfium::MakeRetain(); + ink_list->Append(MakeNumberArray({60, 60, 110, 100, 160, 60})); + annot_dict->SetFor("InkList", std::move(ink_list)); + return annot_dict; + } + case BorderedKind::kFreeText: + return MakeFreeTextDict(rect); + case BorderedKind::kCallout: { + auto annot_dict = MakeFreeTextDict(rect); + annot_dict->SetNewFor("IT", "FreeTextCallout"); + annot_dict->SetFor("CL", MakeNumberArray({10, 10, 30, 80, 50, 80})); + annot_dict->SetNewFor("LE", "OpenArrow"); + return annot_dict; + } + case BorderedKind::kLink: + return MakeAnnotDict("Link", rect); + case BorderedKind::kRedact: + return shape("Redact"); + case BorderedKind::kTextField: { + auto annot_dict = widget(pdfium::form_fields::kTx, 0); + annot_dict->SetNewFor(pdfium::form_fields::kV, "hello"); + return annot_dict; + } + case BorderedKind::kComboBox: { + auto annot_dict = + widget(pdfium::form_fields::kCh, pdfium::form_flags::kChoiceCombo); + annot_dict->SetFor("Opt", options()); + annot_dict->SetNewFor(pdfium::form_fields::kV, "one"); + return annot_dict; + } + case BorderedKind::kListBox: { + auto annot_dict = widget(pdfium::form_fields::kCh, 0); + annot_dict->SetFor("Opt", options()); + return annot_dict; + } + case BorderedKind::kCheckBox: + return widget(pdfium::form_fields::kBtn, 0); + case BorderedKind::kRadioButton: + return widget(pdfium::form_fields::kBtn, + pdfium::form_flags::kButtonRadio); + case BorderedKind::kPushButton: { + auto annot_dict = widget(pdfium::form_fields::kBtn, + pdfium::form_flags::kButtonPushbutton); + annot_dict->GetMutableDictFor("MK")->SetNewFor("CA", "Go"); + return annot_dict; + } + case BorderedKind::kSignature: + return widget(pdfium::form_fields::kSig, 0); + } + return nullptr; +} + +// What a stream written into a document holds. +ByteString WrittenContent(RetainPtr stream) { + if (!stream || !stream->IsMemoryBased()) { + return ByteString(); + } + const pdfium::span data = stream->GetInMemoryRawData(); + return ByteString(data.data(), data.size()); +} + +// All that /AP /N of |annot_dict| draws: its stream, or each of its states' +// streams in the order of their names. Empty when there is no appearance. +ByteString NormalAppearanceContent(const CPDF_Dictionary* annot_dict) { + RetainPtr ap_dict = + annot_dict->GetDictFor(pdfium::annotation::kAP); + if (!ap_dict) { + return ByteString(); + } + // A stream first: asked for a dictionary, a stream gives its own. + if (RetainPtr stream = ap_dict->GetStreamFor("N")) { + return WrittenContent(std::move(stream)); + } + RetainPtr states = ap_dict->GetDictFor("N"); + if (!states) { + return ByteString(); + } + ByteString content; + for (const ByteString& state : states->GetKeys()) { + content += "[" + state + "]\n" + + WrittenContent(states->GetStreamFor(state.AsStringView())); + } + return content; +} + +// The appearance the generator writes for a new annotation of |kind| whose +// border |write_border| has written, each in a document of its own. +ByteString DrawBorderedKind( + BorderedKind kind, + const std::function& write_border) { + CPDF_TestDocument doc; + AddAcroFormWithHelvetica(&doc); + RetainPtr annot_dict = MakeBorderedDict(kind); + write_border(annot_dict.Get()); + + auto draw_annot = [&](CPDF_Annot::Subtype subtype) { + EXPECT_TRUE(CPDF_AppearanceGenerator::GenerateAnnotAP( + &doc, annot_dict.Get(), subtype)); + }; + switch (kind) { + case BorderedKind::kSquare: + draw_annot(CPDF_Annot::Subtype::SQUARE); + break; + case BorderedKind::kCircle: + draw_annot(CPDF_Annot::Subtype::CIRCLE); + break; + case BorderedKind::kLine: + draw_annot(CPDF_Annot::Subtype::LINE); + break; + case BorderedKind::kPolygon: + draw_annot(CPDF_Annot::Subtype::POLYGON); + break; + case BorderedKind::kPolyLine: + draw_annot(CPDF_Annot::Subtype::POLYLINE); + break; + case BorderedKind::kInk: + draw_annot(CPDF_Annot::Subtype::INK); + break; + case BorderedKind::kFreeText: + case BorderedKind::kCallout: + draw_annot(CPDF_Annot::Subtype::FREETEXT); + break; + case BorderedKind::kLink: + draw_annot(CPDF_Annot::Subtype::LINK); + break; + case BorderedKind::kRedact: + draw_annot(CPDF_Annot::Subtype::REDACT); + break; + case BorderedKind::kTextField: + CPDF_AppearanceGenerator::GenerateFormAP( + &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kTextField); + break; + case BorderedKind::kComboBox: + CPDF_AppearanceGenerator::GenerateFormAP( + &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kComboBox); + break; + case BorderedKind::kListBox: + CPDF_AppearanceGenerator::GenerateFormAP( + &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kListBox); + break; + case BorderedKind::kCheckBox: + CPDF_AppearanceGenerator::GenerateCheckboxFormAP(&doc, annot_dict.Get()); + break; + case BorderedKind::kRadioButton: + CPDF_AppearanceGenerator::GenerateRadioButtonFormAP(&doc, + annot_dict.Get()); + break; + case BorderedKind::kPushButton: + CPDF_AppearanceGenerator::GenerateFormAP( + &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kPushButton); + break; + case BorderedKind::kSignature: + CPDF_AppearanceGenerator::GenerateBoxFormAP(&doc, annot_dict.Get()); + break; + } + return NormalAppearanceContent(annot_dict.Get()); +} + +} // namespace + +// The one border rule (ISO 32000-1 12.5.2), for every kind the generator +// draws with a border: a border kept in /Border [h v w [dash]] draws exactly +// what the same border kept in /BS draws; with neither key the border is +// solid and 1 wide; and beside a /BS, /Border is not read at all. +TEST_F(CPDFGenerateAPTest, BorderArrayDrawsAsBorderStyleForEveryKind) { + const std::vector pattern = {4, 2}; + for (const BorderedKindCase& kind_case : kBorderedKinds) { + SCOPED_TRACE(kind_case.name); + const BorderedKind kind = kind_case.kind; + auto with_border_style = [kind](float width, + std::optional> dash = + std::nullopt) { + return DrawBorderedKind(kind, [&](CPDF_Dictionary* annot_dict) { + SetBorderStyle(annot_dict, width, dash); + }); + }; + auto with_border_array = [kind](float width, + std::optional> dash = + std::nullopt) { + return DrawBorderedKind(kind, [&](CPDF_Dictionary* annot_dict) { + SetBorderArray(annot_dict, width, dash); + }); + }; + + // A width: the kind draws it, and draws it from /Border alike. + const ByteString wide = with_border_style(5); + ASSERT_FALSE(wide.IsEmpty()); + EXPECT_NE(with_border_style(1), wide); + EXPECT_EQ(with_border_array(5), wide); + + // A dash. + const ByteString dashed = with_border_style(5, pattern); + EXPECT_EQ(kind_case.draws_dashes, dashed.Contains("[4 2 ] 0 d\n")); + EXPECT_EQ(kind_case.draws_dashes, dashed != wide); + EXPECT_EQ(with_border_array(5, pattern), dashed); + + // No border. + const ByteString none = with_border_style(0); + EXPECT_NE(none, wide); + EXPECT_EQ(with_border_array(0), none); + + // Neither key: solid and 1 wide. + EXPECT_EQ(DrawBorderedKind(kind, [](CPDF_Dictionary*) {}), + with_border_style(1)); + + // /BS wins, whatever the /Border beside it says. + EXPECT_EQ(DrawBorderedKind(kind, + [](CPDF_Dictionary* annot_dict) { + SetBorderArray(annot_dict, 2, + std::vector{1, 1}); + SetBorderStyle(annot_dict, 5); + }), + wide); + EXPECT_EQ(DrawBorderedKind(kind, + [&pattern](CPDF_Dictionary* annot_dict) { + SetBorderArray(annot_dict, 2); + SetBorderStyle(annot_dict, 5, pattern); + }), + dashed); + } +} + TEST_F(CPDFGenerateAPTest, GeneratePersistentFreeTextAPAfterDefaultAppearanceColorUpdate) { CPDF_TestDocument doc; diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index a04c153b09..b7a2a6a53f 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -334,19 +334,28 @@ matrix. `cpdf_appearancegenerator_.cpp` per family and what they share in `cpdf_appearancegenerator_internal.h`). None of our code calls upstream's `CPDF_GenerateAP`, and upstream's `core/fpdfdoc/cpdf_generateap.{h,cpp}` stay byte-identical to upstream, compiled and -unused. +unused. An annotation's border is read in one place, `fpdfdoc::ReadAnnotBorder`, as ISO 32000-1 +12.5.2 says: its `/BS`, and then `/Border` is not read at all; or else its `/Border`; or else solid +and 1 wide. Every drawer takes its border from that reading, the `EPDFAnnot_*` border readers +report it, and the border setters leave the border in `/BS` alone. **Why.** We rewrote most of the generator: appearances built in memory, rich text, rotation, measurement, redaction overlays, form fields. Mixed into upstream's file, it was the worst conflict -file. Apart, upstream's file merges cleanly. +file. Apart, upstream's file merges cleanly. With one reading of a border, an annotation is drawn +with the border the API reads for it, whichever key holds it. **Where.** `cpdf_appearancegenerator*` and its unit test; the calls in `cpdf_annot.cpp`, upstream's `FPDFAnnot_AppendObject` and `FPDFAnnot_SetFontColor` in `fpdf_annot.cpp`, -`epdf_annot.cpp`, `epdf_form.cpp`, `epdf_redact.cpp` and the rich text writer. +`epdf_annot.cpp`, `epdf_form.cpp`, `epdf_redact.cpp` and the rich text writer. The border: +`cpdf_annot_border.{h,cpp}`, its drawers' view of it in `cpdf_appearancegenerator_common.cpp` +(`GetAnnotBorderStyleInfo`, `GetBorderWidth`, `GetDashPatternString`), and +`BorderStyleDictForWrite` in `epdf_annot.cpp`. **Guarded by.** `check-fork-tags.py` fails when upstream's files differ from upstream (`fork-pristine.txt`); `upstream-preview.py` lists new upstream callers of `CPDF_GenerateAP::`, and -upstream's commits to its generator. +upstream's commits to its generator. `CPDFGenerateAPTest.BorderArrayDrawsAsBorderStyleForEveryKind` +draws every kind that has a border from both keys. **When upstream touches this.** A commit to `cpdf_generateap.*`: port it to ours or skip it, with the reason in the sync report. A new upstream caller of `CPDF_GenerateAP::`: route it to ours, or -accept it in the report. +accept it in the report. A drawer ported from upstream reads `/BS` alone, as upstream's form fields +do: give it our reading, and a row in that test. ## Text diff --git a/fpdfsdk/epdf_annot.cpp b/fpdfsdk/epdf_annot.cpp index 27281cf708..907c8caa6d 100644 --- a/fpdfsdk/epdf_annot.cpp +++ b/fpdfsdk/epdf_annot.cpp @@ -42,6 +42,7 @@ #include "core/fpdfapi/parser/cpdf_stream_acc.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "core/fpdfdoc/cpdf_annot.h" +#include "core/fpdfdoc/cpdf_annot_border.h" #include "core/fpdfdoc/cpdf_annot_rotation.h" #include "core/fpdfdoc/cpdf_appearancegenerator.h" #include "core/fpdfdoc/cpdf_color_utils.h" @@ -1384,21 +1385,34 @@ EPDFAnnot_ClearRectangleDifferences(FPDF_ANNOTATION annot) { namespace { -RetainPtr GetExplicitBorderDashArray( - const CPDF_Dictionary* pAnnotDict) { - RetainPtr pBSDict = pAnnotDict->GetDictFor("BS"); - if (pBSDict) { - // /BS takes precedence over /Border. Its /D is the pattern as stored, - // whatever /S says: only a dashed border draws it. - return pBSDict->GetArrayFor("D"); - } - - RetainPtr pBorderArray = - pAnnotDict->GetArrayFor(pdfium::annotation::kBorder); - if (!pBorderArray || pBorderArray->size() < 4) { - return nullptr; +// The /BS a border setter writes into. An annotation that keeps its border in +// /Border alone is given that border as a /BS first: its width, and a dashed +// style with its pattern when the array has one. The setter then changes the +// part it sets, and the rest stays as it read. /Border is removed: with a /BS +// beside it a reader that follows ISO 32000-1 12.5.2 no longer looks at it, +// and one that reads /Border first (PDFium's form filler does) would go on +// showing the old border. +RetainPtr BorderStyleDictForWrite( + CPDF_Dictionary* annot_dict) { + RetainPtr bs_dict = annot_dict->GetMutableDictFor("BS"); + if (!bs_dict) { + const bool has_border_array = + !!annot_dict->GetArrayFor(pdfium::annotation::kBorder); + const fpdfdoc::AnnotBorder border = fpdfdoc::ReadAnnotBorder(annot_dict); + bs_dict = annot_dict->SetNewFor("BS"); + if (has_border_array) { + bs_dict->SetNewFor("W", border.width); + if (border.style == CPDF_Annot::BorderStyle::kDashed) { + bs_dict->SetNewFor("S", "D"); + RetainPtr dash = bs_dict->SetNewFor("D"); + for (size_t i = 0; i < border.dash_array->size(); ++i) { + dash->AppendNew(border.dash_array->GetFloatAt(i)); + } + } + } } - return pBorderArray->GetArrayAt(3); + annot_dict->RemoveFor(pdfium::annotation::kBorder); + return bs_dict; } } // namespace @@ -1412,7 +1426,7 @@ EPDFAnnot_GetBorderDashPatternCount(FPDF_ANNOTATION annot) { } RetainPtr pDashArray = - GetExplicitBorderDashArray(pAnnotDict); + fpdfdoc::ReadAnnotBorder(pAnnotDict).dash_array; return pDashArray ? pDashArray->size() : 0; } @@ -1427,7 +1441,7 @@ EPDFAnnot_GetBorderDashPattern(FPDF_ANNOTATION annot, } RetainPtr pDashArray = - GetExplicitBorderDashArray(pAnnotDict); + fpdfdoc::ReadAnnotBorder(pAnnotDict).dash_array; if (!pDashArray || pDashArray->size() < count) { return false; } @@ -1454,10 +1468,8 @@ EPDFAnnot_SetBorderDashPattern(FPDF_ANNOTATION annot, return false; } - RetainPtr bs_dict = annot_dict->GetMutableDictFor("BS"); - if (!bs_dict) { - bs_dict = annot_dict->SetNewFor("BS"); - } + RetainPtr bs_dict = + BorderStyleDictForWrite(annot_dict.Get()); // --- Removal branch (PDFium style) --- if (!dash_array || count == 0) { @@ -1498,41 +1510,13 @@ EPDFAnnot_GetBorderStyle(FPDF_ANNOTATION annot, float* width) { return FPDF_ANNOT_BS_UNKNOWN; } - RetainPtr pBSDict = pAnnotDict->GetDictFor("BS"); - if (pBSDict) { - if (width) { - *width = pBSDict->KeyExist("W") ? pBSDict->GetFloatFor("W") : 1.0f; - } - - CPDF_Annot::BorderStyle nStyle = - CPDF_Annot::StringToBorderStyle(pBSDict->GetNameFor("S")); - if (nStyle == CPDF_Annot::BorderStyle::kUnknown) { - nStyle = CPDF_Annot::BorderStyle::kSolid; - } - // A dashed border with an empty pattern draws a solid line (ISO 32000 - // 8.4.3.6), so it reads solid, as a /Border with an empty dash array does. - RetainPtr pDashArray = pBSDict->GetArrayFor("D"); - if (nStyle == CPDF_Annot::BorderStyle::kDashed && pDashArray && - pDashArray->IsEmpty()) { - nStyle = CPDF_Annot::BorderStyle::kSolid; - } - return static_cast(nStyle); - } - - RetainPtr pBorderArray = - pAnnotDict->GetArrayFor(pdfium::annotation::kBorder); + // The one reading of a border, which the appearance generator draws from: + // /BS, or else /Border, or else solid and 1 wide. + const fpdfdoc::AnnotBorder border = fpdfdoc::ReadAnnotBorder(pAnnotDict); if (width) { - *width = pBorderArray && pBorderArray->size() >= 3 - ? pBorderArray->GetFloatAt(2) - : 1.0f; - } - - RetainPtr pDashArray = - GetExplicitBorderDashArray(pAnnotDict); - if (pDashArray && !pDashArray->IsEmpty()) { - return FPDF_ANNOT_BS_DASHED; + *width = border.width; } - return FPDF_ANNOT_BS_SOLID; + return static_cast(border.style); } FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV @@ -1546,30 +1530,28 @@ EPDFAnnot_SetBorderStyle(FPDF_ANNOTATION annot, return false; } - RetainPtr pBSDict = pAnnotDict->GetMutableDictFor("BS"); - if (!pBSDict) { - pBSDict = pAnnotDict->SetNewFor("BS"); + // A style that is none of ours is refused before anything is written. + ByteString style_name; + if (style != FPDF_ANNOT_BS_UNKNOWN) { + style_name = CPDF_Annot::BorderStyleToString( + static_cast(style)); + if (style_name.IsEmpty()) { + return false; + } } + RetainPtr pBSDict = + BorderStyleDictForWrite(pAnnotDict.Get()); if (width >= 0) { pBSDict->SetNewFor("W", width); } else { pBSDict->RemoveFor("W"); } - - if (style == FPDF_ANNOT_BS_UNKNOWN) { - pBSDict->RemoveFor("S"); - return true; - } - - auto internal_style = static_cast(style); - ByteString style_name = CPDF_Annot::BorderStyleToString(internal_style); - if (style_name.IsEmpty()) { - return false; + pBSDict->RemoveFor("S"); + } else { + pBSDict->SetNewFor("S", style_name); } - - pBSDict->SetNewFor("S", style_name); return true; } diff --git a/fpdfsdk/epdf_annot_embeddertest.cpp b/fpdfsdk/epdf_annot_embeddertest.cpp index 5e48587db0..584958d1dd 100644 --- a/fpdfsdk/epdf_annot_embeddertest.cpp +++ b/fpdfsdk/epdf_annot_embeddertest.cpp @@ -86,6 +86,7 @@ #include "testing/utils/path_service.h" using pdfium::kAnnotationStampWithApPng; +using testing::ElementsAre; using testing::HasSubstr; namespace { @@ -7855,6 +7856,281 @@ TEST_F(EPDFAnnotEmbedderTest, AnEmptyDashPatternIsASolidLine) { } } +namespace { + +// What the API reads of an annotation's border, and the keys that hold it. +struct BorderRead { + FPDF_ANNOT_BORDER_STYLE style = FPDF_ANNOT_BS_UNKNOWN; + float width = -1; + std::vector pattern; + bool has_border_style = false; // /BS + bool has_border_array = false; // /Border +}; + +BorderRead ReadBorder(FPDF_ANNOTATION annot) { + BorderRead read; + read.style = EPDFAnnot_GetBorderStyle(annot, &read.width); + read.pattern.resize(EPDFAnnot_GetBorderDashPatternCount(annot)); + if (!read.pattern.empty()) { + EXPECT_TRUE(EPDFAnnot_GetBorderDashPattern(annot, read.pattern.data(), + read.pattern.size())); + } + const CPDF_Dictionary* annot_dict = + CPDFAnnotContextFromFPDFAnnotation(annot)->GetAnnotDict(); + read.has_border_style = annot_dict->KeyExist("BS"); + read.has_border_array = annot_dict->KeyExist(pdfium::annotation::kBorder); + return read; +} + +// Gives |annot| the border /Border [0 0 |width|], with |pattern| as its dash +// array when given, and no /BS. +void WriteBorderArray( + FPDF_ANNOTATION annot, + float width, + std::optional> pattern = std::nullopt) { + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(annot)->GetMutableAnnotDict(); + annot_dict->RemoveFor("BS"); + RetainPtr border = + annot_dict->SetNewFor(pdfium::annotation::kBorder); + border->AppendNew(0); + border->AppendNew(0); + border->AppendNew(width); + if (pattern.has_value()) { + RetainPtr dash = border->AppendNew(); + for (float value : pattern.value()) { + dash->AppendNew(value); + } + } +} + +// A black square on |page| whose border is /Border [0 0 |width|], with +// |pattern| as its dash array when given. +ScopedFPDFAnnotation NewSquareWithBorderArray( + FPDF_PAGE page, + float width, + std::optional> pattern = std::nullopt) { + ScopedFPDFAnnotation annot(FPDFPage_CreateAnnot(page, FPDF_ANNOT_SQUARE)); + EXPECT_TRUE(annot); + const FS_RECTF rect{/*left=*/10.0f, /*top=*/90.0f, /*right=*/90.0f, + /*bottom=*/10.0f}; + EXPECT_TRUE(FPDFAnnot_SetRect(annot.get(), &rect)); + EXPECT_TRUE( + EPDFAnnot_SetColor(annot.get(), FPDFANNOT_COLORTYPE_Color, 0, 0, 0)); + WriteBorderArray(annot.get(), width, std::move(pattern)); + return annot; +} + +// The appearance |annot| is drawn with, generated now. +ByteString DrawnNow(FPDF_ANNOTATION annot) { + EXPECT_TRUE(EPDFAnnot_GenerateAppearance(annot)); + return GetNormalAppearanceStreamBytes(annot); +} + +} // namespace + +// A dash pattern set on an annotation that keeps its border in /Border: the +// border becomes a /BS first, so its width stays (it fell to 1), and so does +// its style, which the setter never changes. /Border is removed. +TEST_F(EPDFAnnotEmbedderTest, SettingADashOnABorderArrayKeepsItsWidth) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + static constexpr float kPattern[] = {4, 2}; + + { + // /Border [0 0 5] is a solid border, and stays one: the pattern is stored + // and waits for a dashed style, as on a border that began as a /BS. + ScopedFPDFAnnotation square = NewSquareWithBorderArray(page.get(), 5); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), kPattern, 2)); + BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_SOLID, read.style); + EXPECT_FLOAT_EQ(5, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + ByteString look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("5 w ")); + EXPECT_FALSE(look.Contains("] 0 d")); + + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_DASHED, 5)); + read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("5 w ")); + EXPECT_TRUE(look.Contains("[4 2 ] 0 d")); + } + { + // /Border [0 0 5 [1 3]] is a dashed border: it draws the new pattern. + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 5, std::vector{1, 3}); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), kPattern, 2)); + const BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(5, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + const ByteString look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("5 w ")); + EXPECT_TRUE(look.Contains("[4 2 ] 0 d")); + } +} + +// The dash pattern removed from an annotation that keeps its border in +// /Border: the pattern goes (it stayed), the width stays, and so does the +// style, so a border that was dashed draws ISO's default dash, as one that +// began as a /BS does. /Border is removed. +TEST_F(EPDFAnnotEmbedderTest, RemovingTheDashOfABorderArrayKeepsItsWidth) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + + { + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 5, std::vector{4, 2}); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), nullptr, 0)); + const BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(5, read.width); + EXPECT_TRUE(read.pattern.empty()); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + const ByteString look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("5 w ")); + EXPECT_TRUE(look.Contains("[3 ] 0 d")); + EXPECT_FALSE(look.Contains("[4 2 ] 0 d")); + + // Solid is a style, set as one. + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_SOLID, 5)); + EXPECT_FALSE(DrawnNow(square.get()).Contains("] 0 d")); + } + { + // A solid /Border has no pattern to remove: it is the same border, in + // /BS. + ScopedFPDFAnnotation square = NewSquareWithBorderArray(page.get(), 5); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), nullptr, 0)); + const BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_SOLID, read.style); + EXPECT_FLOAT_EQ(5, read.width); + EXPECT_TRUE(read.pattern.empty()); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + const ByteString look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("5 w ")); + EXPECT_FALSE(look.Contains("] 0 d")); + } +} + +// A style and width set on an annotation that has a /Border leave none +// behind: a reader that looks at /Border before /BS would show the old +// border. What the call does not set, the pattern, stays stored. +TEST_F(EPDFAnnotEmbedderTest, SettingABorderStyleRemovesTheBorderArray) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + + { + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 5, std::vector{4, 2}); + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_SOLID, 3)); + BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_SOLID, read.style); + EXPECT_FLOAT_EQ(3, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + float horizontal = -1; + float vertical = -1; + float array_width = -1; + EXPECT_FALSE(FPDFAnnot_GetBorder(square.get(), &horizontal, &vertical, + &array_width)); + ByteString look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("3 w ")); + EXPECT_FALSE(look.Contains("] 0 d")); + + // Dashed again, it draws the pattern it came with. + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_DASHED, 3)); + look = DrawnNow(square.get()); + EXPECT_TRUE(look.Contains("3 w ")); + EXPECT_TRUE(look.Contains("[4 2 ] 0 d")); + } + { + // A /Border beside a /BS was not read; it goes all the same. + ScopedFPDFAnnotation square = NewSquareWithBorderArray(page.get(), 9); + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(square.get())->GetMutableAnnotDict(); + annot_dict->SetNewFor("BS")->SetNewFor("W", + 2); + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_DASHED, 4)); + const BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(4, read.width); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + } + { + // A style that is none is refused, and nothing is written. + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 5, std::vector{4, 2}); + EXPECT_FALSE(EPDFAnnot_SetBorderStyle( + square.get(), static_cast(99), 3)); + const BorderRead read = ReadBorder(square.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(5, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + EXPECT_FALSE(read.has_border_style); + EXPECT_TRUE(read.has_border_array); + } +} + +// A form field is drawn with the border the API reads for it, whichever key +// holds it: /Border [0 0 4 [3 1]] without a /BS reads, and draws, as the same +// border in /BS does. (It drew 1 wide and solid.) +TEST_F(EPDFAnnotEmbedderTest, AFormFieldDrawsTheBorderItReads) { + ASSERT_TRUE(OpenDocument("text_form.pdf")); + ScopedPage page = LoadScopedPage(0); + ASSERT_TRUE(page); + ScopedFPDFAnnotation annot(FPDFPage_GetAnnot(page.get(), 0)); + ASSERT_TRUE(annot); + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(annot.get())->GetMutableAnnotDict(); + ASSERT_TRUE(annot_dict); + RetainPtr border_color = + annot_dict->SetNewFor("MK")->SetNewFor("BC"); + border_color->AppendNew(0); + border_color->AppendNew(0); + border_color->AppendNew(1); + + RetainPtr bs = annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", 4); + bs->SetNewFor("S", "D"); + RetainPtr dash = bs->SetNewFor("D"); + dash->AppendNew(3); + dash->AppendNew(1); + const BorderRead in_border_style = ReadBorder(annot.get()); + ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(annot.get())); + const ByteString from_border_style = + GetNormalAppearanceStreamBytes(annot.get()); + EXPECT_TRUE(from_border_style.Contains("4 w\n[3 1 ] 0 d\n")); + + WriteBorderArray(annot.get(), 4, std::vector{3, 1}); + const BorderRead in_border_array = ReadBorder(annot.get()); + EXPECT_FALSE(in_border_array.has_border_style); + EXPECT_EQ(in_border_style.style, in_border_array.style); + EXPECT_FLOAT_EQ(in_border_style.width, in_border_array.width); + EXPECT_EQ(in_border_style.pattern, in_border_array.pattern); + ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(annot.get())); + EXPECT_EQ(from_border_style, GetNormalAppearanceStreamBytes(annot.get())); +} + TEST_F(EPDFAnnotEmbedderTest, SetNameAcceptsAnyNameAndKeepsAppearance) { embedpdf_test::ScopedTestDocument doc(NewTestDocument()); ASSERT_TRUE(doc); diff --git a/public/epdf_annot.h b/public/epdf_annot.h index 9a70f5d6c5..41149ce08a 100644 --- a/public/epdf_annot.h +++ b/public/epdf_annot.h @@ -305,8 +305,11 @@ FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV EPDFAnnot_SetNoColor(FPDF_ANNOTATION annot, FPDFANNOT_COLORTYPE type); // Experimental EmbedPDF Extension API. -// Get the border style and width of an annotation. This function handles both -// the modern /BS dictionary and the legacy /Border array. A border is dashed +// Get the border style and width of an annotation, as ISO 32000-1 12.5.2 +// reads a border: from its /BS dictionary when it has one, and the legacy +// /Border array is then not read at all; else from /Border; else a solid +// border 1 wide. Every kind of annotation whose appearance is generated, +// form fields included, is drawn from this same reading. A border is dashed // when it draws dashes: a dashed /BS whose /D is an empty array, like a // /Border whose dash array is empty, draws a solid line and reads solid. // @@ -318,12 +321,23 @@ FPDF_EXPORT FPDF_ANNOT_BORDER_STYLE FPDF_CALLCONV EPDFAnnot_GetBorderStyle(FPDF_ANNOTATION annot, float* width); // Experimental EmbedPDF Extension API. -// Set the border style and width of an annotation. +// Set the border style and width of an annotation, in its /BS dictionary. +// +// An annotation that keeps its border in the legacy /Border array is given +// that border as a /BS first (its width, and a dashed style with its dash +// pattern when the array has one), so what this call does not set stays as +// it read: a pattern stays stored. /Border is then removed. With a /BS +// beside it, it is no longer read, and a reader that looks at /Border first +// would go on showing the old border. // // annot - handle to an annotation. -// width - the border width to be set. +// style - the border style to be set. FPDF_ANNOT_BS_UNKNOWN removes +// /BS /S, which leaves a solid border. +// width - the border width to be set. A negative width removes /BS /W, +// which leaves a border 1 wide. // -// Returns true if successful. +// Returns true if successful. A |style| that is no border style is refused +// and nothing is written. FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV EPDFAnnot_SetBorderStyle(FPDF_ANNOTATION annot, FPDF_ANNOT_BORDER_STYLE style, @@ -422,6 +436,11 @@ EPDFAnnot_GetBorderDashPattern(FPDF_ANNOTATION annot, // pattern. A NULL |dash_array| or a |count| of 0 removes the pattern, and a // dashed border then draws the default dash [3]. // +// An annotation that keeps its border in the legacy /Border array is given +// that border as a /BS first, and /Border is removed, as +// EPDFAnnot_SetBorderStyle() does. Its width stays, and so does its style: a +// /Border with a dash array is a dashed border, one without is solid. +// // annot - handle to an annotation. // dash_array - the dash pattern to be set. // count - the number of entries in the buffer, obtained from diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 8b7ffc529e..60307bcfac 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -49,6 +49,7 @@ EPDFActionEmbedderTest.NodeFilePathAndNamePayloadsFromSyntheticDicts 2 EPDFActionEmbedderTest.OpenActionDestinationForms 3 EPDFActionEmbedderTest.ResetFormThreeStates 1 EPDFActionEmbedderTest.SetNextChainsActions 3 +EPDFAnnotEmbedderTest.AFormFieldDrawsTheBorderItReads 2 EPDFAnnotEmbedderTest.AcrobatCommentWrittenBackReadsTheSame 1 EPDFAnnotEmbedderTest.AnEmptyDashPatternIsASolidLine 19 EPDFAnnotEmbedderTest.AnnotFontMapStagesEveryNamedFont 17 @@ -140,6 +141,7 @@ EPDFAnnotEmbedderTest.RegisteredFontResolutionPrefersStoredFamily 9 EPDFAnnotEmbedderTest.RegisteredFontResolutionRefusesConflictingHint 6 EPDFAnnotEmbedderTest.RegistryHonoursFsTypeEmbeddingPermissions 13 EPDFAnnotEmbedderTest.RemoveKey 2 +EPDFAnnotEmbedderTest.RemovingTheDashOfABorderArrayKeepsItsWidth 8 EPDFAnnotEmbedderTest.RichTextAlignmentFollowsTheAnnotation 15 EPDFAnnotEmbedderTest.RichTextCoversSupplementaryCharactersByScalar 11 EPDFAnnotEmbedderTest.RichTextDocumentSubsetDrawsOnlyWhatItCovers 24 @@ -167,6 +169,8 @@ EPDFAnnotEmbedderTest.SetRichTextJSONWritesACommentAsAcrobatDoes 5 EPDFAnnotEmbedderTest.SetRichTextJSONWritesAllFourForms 7 EPDFAnnotEmbedderTest.SetRichTextXHTMLImportsOverDefaults 7 EPDFAnnotEmbedderTest.SetSubtypeChangesTheKindInPlace 8 +EPDFAnnotEmbedderTest.SettingABorderStyleRemovesTheBorderArray 8 +EPDFAnnotEmbedderTest.SettingADashOnABorderArrayKeepsItsWidth 8 EPDFAnnotEmbedderTest.StandardFontDefaultAppearanceRoundTripsThroughDr 19 EPDFAnnotEmbedderTest.TextFieldDrawsItsBorderStyle 2 EPDFAnnotEmbedderTest.TextFieldGenerateAppearanceStreamIsStable 2 From 760da5e349cf6c6ba18db7fec2b7472e0532ec5d Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Tue, 24 Nov 2026 22:54:33 +0200 Subject: [PATCH 2/3] Write a border only when a call changes it, and never into a shared /BS A review of pull request 130 found three things in the border setters. A call that asked for what the border already was still turned a /Border into a /BS and removed it. On /Border [6 4 2], removing a dash pattern that is not there left /BS << /W 2 >>, and the corner radii, which a /BS cannot hold, were gone. Setting the style and width it has, the pattern it has, or dashed on a dashed one did the same. EPDFAnnot_SetBorderStyle and EPDFAnnot_SetBorderDashPattern now read what the border states first (ReadStatedBorder) and write nothing when that is what the call asks for. A /BS states its entries, so a call for an entry it leaves out still writes it. A /Border states width, style and pattern by its form. Only a key that is well formed states anything: a name where the width goes reads as 0, and is written anew. A call that changes the border still moves a /Border into /BS and removes it. A style that is none was refused after the annotation had been taken for writing, so on a layer the annotation was copied in for nothing. The check is above that now, and a call that changes nothing copies nothing either. A /BS that is an indirect object may be another annotation's too, and so may its /D. The setters wrote into both. The annotation now gets a /BS of its own first (OwnDictEntry, which OwnMKForWriting uses for /MK too), and a pattern goes into a new array under /D. The table test over every kind that has a border gains a row for a push button that shows its icon, whose drawer reads the border through the one reader since the merge. Tests, in EPDFAnnotEmbedderTest and listed as layer-mode writers: ABorderCallThatChangesNothingWritesNothing, ABorderCallThatChangesNothingLeavesALayerAsItWas, AMalformedBorderThatReadsAsAskedIsWrittenAnew, ARefusedBorderStyleLeavesALayerAsItWas and ASharedBorderStyleIsNotWrittenInto. RemovingTheDashOfABorderArrayKeepsItsWidth now expects a solid /Border to stay when its absent pattern is removed. --- .../cpdf_appearancegenerator_unittest.cpp | 30 +- docs/embedpdf/fork-ledger.md | 18 +- fpdfsdk/epdf_annot.cpp | 259 +++++++-- fpdfsdk/epdf_annot_embeddertest.cpp | 498 +++++++++++++++++- public/epdf_annot.h | 40 +- testing/embedpdf_layer_mode_writers.txt | 5 + 6 files changed, 769 insertions(+), 81 deletions(-) diff --git a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp index 985f59fd34..92ada5cc3d 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp @@ -387,14 +387,15 @@ enum class BorderedKind { kCheckBox, kRadioButton, kPushButton, + kIconButton, kSignature, }; struct BorderedKindCase { const char* name; BorderedKind kind; - // False for a check box, a radio button and a push button, which draw one - // solid box for every border style. + // False for a check box, a radio button and a push button (with a caption + // or an icon), which draw one solid box for every border style. bool draws_dashes; }; @@ -415,12 +416,15 @@ constexpr BorderedKindCase kBorderedKinds[] = { {"check box", BorderedKind::kCheckBox, false}, {"radio button", BorderedKind::kRadioButton, false}, {"push button", BorderedKind::kPushButton, false}, + {"push button with an icon", BorderedKind::kIconButton, false}, {"signature", BorderedKind::kSignature, true}, }; // An annotation of |kind|, 120 by 60, with what the kind needs to be drawn -// (a colour, its points, its text) and neither /BS nor /Border. -RetainPtr MakeBorderedDict(BorderedKind kind) { +// (a colour, its points, its text, an icon in |doc|) and neither /BS nor +// /Border. +RetainPtr MakeBorderedDict(CPDF_Document* doc, + BorderedKind kind) { const CFX_FloatRect rect(50, 50, 170, 110); auto shape = [&rect](const ByteString& subtype) { auto annot_dict = MakeAnnotDict(subtype, rect); @@ -515,6 +519,21 @@ RetainPtr MakeBorderedDict(BorderedKind kind) { annot_dict->GetMutableDictFor("MK")->SetNewFor("CA", "Go"); return annot_dict; } + case BorderedKind::kIconButton: { + // An image field: its icon alone (/MK /TP 1), fitted inside the border. + auto icon_dict = pdfium::MakeRetain(); + icon_dict->SetNewFor("Type", "XObject"); + icon_dict->SetNewFor("Subtype", "Form"); + icon_dict->SetRectFor("BBox", CFX_FloatRect(0, 0, 10, 10)); + auto icon = doc->NewIndirect(std::move(icon_dict)); + icon->SetData(ByteStringView("0 0 10 10 re f").unsigned_span()); + auto annot_dict = widget(pdfium::form_fields::kBtn, + pdfium::form_flags::kButtonPushbutton); + RetainPtr mk = annot_dict->GetMutableDictFor("MK"); + mk->SetNewFor("I", doc, icon->GetObjNum()); + mk->SetNewFor("TP", 1); + return annot_dict; + } case BorderedKind::kSignature: return widget(pdfium::form_fields::kSig, 0); } @@ -561,7 +580,7 @@ ByteString DrawBorderedKind( const std::function& write_border) { CPDF_TestDocument doc; AddAcroFormWithHelvetica(&doc); - RetainPtr annot_dict = MakeBorderedDict(kind); + RetainPtr annot_dict = MakeBorderedDict(&doc, kind); write_border(annot_dict.Get()); auto draw_annot = [&](CPDF_Annot::Subtype subtype) { @@ -617,6 +636,7 @@ ByteString DrawBorderedKind( annot_dict.Get()); break; case BorderedKind::kPushButton: + case BorderedKind::kIconButton: CPDF_AppearanceGenerator::GenerateFormAP( &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kPushButton); break; diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index 03441034e5..49730a1790 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -336,8 +336,12 @@ matrix. upstream's `core/fpdfdoc/cpdf_generateap.{h,cpp}` stay byte-identical to upstream, compiled and unused. An annotation's border is read in one place, `fpdfdoc::ReadAnnotBorder`, as ISO 32000-1 12.5.2 says: its `/BS`, and then `/Border` is not read at all; or else its `/Border`; or else solid -and 1 wide. Every drawer takes its border from that reading, the `EPDFAnnot_*` border readers -report it, and the border setters leave the border in `/BS` alone. +and 1 wide. Every drawer takes its border from that reading, and the `EPDFAnnot_*` border readers +report it. A border setter that changes the border leaves it in a `/BS` of the annotation's own: +a `/Border` is moved into it and removed, and a `/BS` or a `/D` that is an indirect object, which +another annotation may name too, is never written into. A setter that asks for what the border +already states writes nothing, so a `/Border` stays as it is, with the corner radii a `/BS` +cannot hold; a malformed border that only reads as the values is written anew. **Why.** We rewrote most of the generator: appearances built in memory, rich text, rotation, measurement, redaction overlays, form fields. Mixed into upstream's file, it was the worst conflict file. Apart, upstream's file merges cleanly. With one reading of a border, an annotation is drawn @@ -359,21 +363,23 @@ middle, and reads an icon narrower than one unit as one unit wide. A push button a new stream on every redraw, as a check box's are: the stream it had may be another widget's or a picture the button showed, so it is never written into, and the icon its resources named goes with it. Before a form drawer replaces an appearance, a widget whose `/AP` is an indirect object -gets a copy of its own (`OwnAppearanceDict`), and `epdf_annot.cpp` does the same for `/MK` before -a setter writes it (`OwnMKForWriting`): another widget may name the same dictionary. A colour is +gets a copy of its own (`OwnAppearanceDict`), and `epdf_annot.cpp` does the same for `/MK` and +`/BS` before a setter writes one (`OwnMKForWriting` and `BorderStyleDictForWrite`, both through +`OwnDictEntry`): another annotation may name the same dictionary. A colour is set as a new array, never written into the one the entry named, which may be an object another `/MK` names too. An `/MK` setter that changes nothing writes nothing, and it changes nothing only when the entry is well formed and reads as the value (three numbers from 0 to 1, a string, an integer): a malformed entry that reads the same is written anew. An icon is a form XObject everywhere (`ButtonIconOf`, `MKIconForm`). The border: `cpdf_annot_border.{h,cpp}`, its drawers' view of it in `cpdf_appearancegenerator_common.cpp` (`GetAnnotBorderStyleInfo`, `GetBorderWidth`, -`GetDashPatternString`), and `BorderStyleDictForWrite` in `epdf_annot.cpp`. +`GetDashPatternString`), and `ReadStatedBorder` and `BorderStyleDictForWrite` in `epdf_annot.cpp`. **Guarded by.** `check-fork-tags.py` fails when upstream's files differ from upstream (`fork-pristine.txt`); `upstream-preview.py` lists new upstream callers of `CPDF_GenerateAP::`, and upstream's commits to its generator. `epdf_widget_drawing_embeddertest.cpp` for a button's icon; its `AButtonIsSharedAsTheFormFillerSharesIt` runs upstream's form filler on the same buttons and compares the two. `CPDFGenerateAPTest.BorderArrayDrawsAsBorderStyleForEveryKind` draws every kind -that has a border from both keys. +that has a border from both keys; the border setters' tests are in `epdf_annot_embeddertest.cpp` +(`ABorderCallThatChangesNothingWritesNothing`, `ASharedBorderStyleIsNotWrittenInto`). **When upstream touches this.** A commit to `cpdf_generateap.*`: port it to ours or skip it, with the reason in the sync report. A new upstream caller of `CPDF_GenerateAP::`: route it to ours, or accept it in the report. A change to what `CPDF_IconFit`'s readers return (`GetScaleMethod`, diff --git a/fpdfsdk/epdf_annot.cpp b/fpdfsdk/epdf_annot.cpp index 9dcc9d6d28..69e403449f 100644 --- a/fpdfsdk/epdf_annot.cpp +++ b/fpdfsdk/epdf_annot.cpp @@ -1385,15 +1385,180 @@ EPDFAnnot_ClearRectangleDifferences(FPDF_ANNOTATION annot) { namespace { -// The /BS a border setter writes into. An annotation that keeps its border in -// /Border alone is given that border as a /BS first: its width, and a dashed -// style with its pattern when the array has one. The setter then changes the -// part it sets, and the rest stays as it read. /Border is removed: with a /BS -// beside it a reader that follows ISO 32000-1 12.5.2 no longer looks at it, -// and one that reads /Border first (PDFium's form filler does) would go on -// showing the old border. +// Gives |annot_dict| a dictionary of its own under |key| when the entry +// names an indirect object: a copy with the same entries. Another annotation +// may name that object too, and a change to it would show there as well. +void OwnDictEntry(FPDF_ANNOTATION annot, + CPDF_Dictionary* annot_dict, + ByteStringView key) { + RetainPtr entry = annot_dict->GetObjectFor(key); + if (!entry || !entry->IsReference()) { + return; + } + RetainPtr shared = annot_dict->GetDictFor(key); + if (!shared) { + return; + } + CPDF_AnnotContext* context = CPDFAnnotContextFromFPDFAnnotation(annot); + CPDF_Document* doc = context && context->GetPage() + ? context->GetPage()->GetDocument() + : nullptr; + annot_dict->SetFor(ByteString(key), + doc ? shared->CloneForHolder(doc) : shared->Clone()); +} + +// The entries of |array| when every one is a number. +std::optional> NumbersOf(const CPDF_Array* array) { + std::vector numbers; + for (size_t i = 0; i < array->size(); ++i) { + RetainPtr entry = array->GetDirectObjectAt(i); + if (!entry || !entry->IsNumber()) { + return std::nullopt; + } + numbers.push_back(entry->GetNumber()); + } + return numbers; +} + +// What the key an annotation's border is read from states, for a setter to +// see whether a call would change anything. +// +// A /BS states what its entries say, and an entry it leaves out is not +// stated. A /Border has no entry to leave out: its form states all three, +// the width as its third number, and dashed with the pattern its dash array +// holds or solid without one. +struct StatedBorder { + // False for a border kept in /Border. + bool in_border_style = true; + std::optional width; + // The style's name: /BS /S, or S or D for a /Border. + std::optional style; + // /BS /D, or the pattern of a /Border that has one. + std::optional> pattern; +}; + +// What |annot_dict|'s border states, by the rule fpdfdoc::ReadAnnotBorder +// reads it with: /BS, or else /Border, or else nothing. Nothing is returned +// when that key is not written as ISO 32000 writes a border: a /BS that is +// no dictionary, a name where a number goes, a /Border that is not three +// numbers and at most a dash array. Such a border may read as what a call +// asks for (a name reads as 0) without stating it, so a setter writes it +// anew. +std::optional ReadStatedBorder( + const CPDF_Dictionary* annot_dict) { + StatedBorder stated; + if (RetainPtr entry = + annot_dict->GetDirectObjectFor("BS")) { + const CPDF_Dictionary* border_style = entry->AsDictionary(); + if (!border_style) { + return std::nullopt; + } + if (RetainPtr width = + border_style->GetDirectObjectFor("W")) { + if (!width->IsNumber()) { + return std::nullopt; + } + stated.width = width->GetNumber(); + } + if (RetainPtr style = + border_style->GetDirectObjectFor("S")) { + if (!style->IsName()) { + return std::nullopt; + } + stated.style = style->GetString(); + } + if (RetainPtr dash = + border_style->GetDirectObjectFor("D")) { + if (!dash->IsArray()) { + return std::nullopt; + } + stated.pattern = NumbersOf(dash->AsArray()); + if (!stated.pattern.has_value()) { + return std::nullopt; + } + } + return stated; + } + + RetainPtr entry = + annot_dict->GetDirectObjectFor(pdfium::annotation::kBorder); + if (!entry) { + return stated; + } + const CPDF_Array* border = entry->AsArray(); + if (!border || border->size() < 3 || border->size() > 4) { + return std::nullopt; + } + for (size_t i = 0; i < 3; ++i) { + RetainPtr number = border->GetDirectObjectAt(i); + if (!number || !number->IsNumber()) { + return std::nullopt; + } + } + stated.in_border_style = false; + stated.width = border->GetFloatAt(2); + stated.style = "S"; + if (border->size() == 4) { + RetainPtr dash = border->GetDirectObjectAt(3); + if (!dash || !dash->IsArray()) { + return std::nullopt; + } + std::optional> pattern = NumbersOf(dash->AsArray()); + if (!pattern.has_value()) { + return std::nullopt; + } + // An empty dash array is a solid line, and no pattern. + if (!pattern->empty()) { + stated.style = "D"; + stated.pattern = std::move(pattern); + } + } + return stated; +} + +// Whether |stated| already is the style and width a call asks for: the name +// |style_name|, or no /S when it is empty; |width|, or no /W when it is +// negative. In a /Border, which leaves nothing out, no /S is solid and no /W +// is 1 wide. +bool StatesStyleAndWidth(const StatedBorder& stated, + const ByteString& style_name, + float width) { + if (!stated.in_border_style) { + return stated.style == + (style_name.IsEmpty() ? ByteString("S") : style_name) && + stated.width == (width >= 0 ? width : 1.0f); + } + const bool states_style = style_name.IsEmpty() ? !stated.style.has_value() + : stated.style == style_name; + const bool states_width = + width >= 0 ? stated.width == width : !stated.width.has_value(); + return states_style && states_width; +} + +// Whether |stated| already has the dash pattern |pattern|, or none when it +// is empty. +bool StatesPattern(const StatedBorder& stated, + const std::vector& pattern) { + return pattern.empty() ? !stated.pattern.has_value() + : stated.pattern == pattern; +} + +// The /BS a border setter writes into: a dictionary of the annotation's own +// (OwnDictEntry()), since a /BS that is an indirect object may be another +// annotation's too. +// +// An annotation that keeps its border in /Border alone is given that border +// as a /BS first: its width, and a dashed style with its pattern when the +// array has one. The setter then changes the part it sets, and the rest +// stays as it read. /Border is removed: with a /BS beside it a reader that +// follows ISO 32000-1 12.5.2 no longer looks at it, and one that reads +// /Border first (PDFium's form filler does) would go on showing the old +// border. Its corner radii go with it, which a /BS cannot hold, so a setter +// comes here only for a call that changes the border. RetainPtr BorderStyleDictForWrite( + FPDF_ANNOTATION annot, CPDF_Dictionary* annot_dict) { + OwnDictEntry(annot, annot_dict, "BS"); RetainPtr bs_dict = annot_dict->GetMutableDictFor("BS"); if (!bs_dict) { const bool has_border_array = @@ -1458,44 +1623,50 @@ EPDFAnnot_SetBorderDashPattern(FPDF_ANNOTATION annot, const float* dash_array, unsigned long count) { ScopedFPDFAnnotationView annot_view(annot); - if (!annot) { + const CPDF_Dictionary* stored_dict = GetAnnotDictFromFPDFAnnotation(annot); + if (!stored_dict) { return false; } + // The pattern asked for; none removes it. + std::vector pattern; + if (dash_array) { + // SAFETY: caller guarantees `dash_array` has `count` elements. + for (unsigned long i = 0; i < count; ++i) { + pattern.push_back(dash_array[i]); + } + } + + // Nothing to change: no write, and a /Border stays a /Border. + const std::optional stated = ReadStatedBorder(stored_dict); + if (stated.has_value() && StatesPattern(stated.value(), pattern)) { + return true; + } + RetainPtr annot_dict = GetMutableAnnotDictFromFPDFAnnotation(annot); if (!annot_dict) { return false; } - RetainPtr bs_dict = - BorderStyleDictForWrite(annot_dict.Get()); + BorderStyleDictForWrite(annot, annot_dict.Get()); - // --- Removal branch (PDFium style) --- - if (!dash_array || count == 0) { + // The pattern only: /S stays as it is, so a solid border with a pattern + // still draws solid, and a dashed one without draws the default dash. + if (pattern.empty()) { bs_dict->RemoveFor("D"); - // Optional: if style was dashed only because of the array, you can revert. - // Leaving it unchanged matches PDFium's permissive style. if (bs_dict->size() == 0) { annot_dict->RemoveFor("BS"); } return true; } - // --- Set branch --- (the pattern only: /S stays as it is, so a solid - // border with a pattern still draws solid) - RetainPtr d_array = bs_dict->GetMutableArrayFor("D"); - if (d_array) { - d_array->Clear(); - } else { - d_array = bs_dict->SetNewFor("D"); - } - - // SAFETY: caller guarantees `dash_array` has `count` elements. - for (unsigned long i = 0; i < count; ++i) { - d_array->AppendNew(dash_array[i]); + // A new array under the key. The one the entry named is not written into: + // it may be an object of its own, which another /BS names too. + RetainPtr d_array = bs_dict->SetNewFor("D"); + for (float value : pattern) { + d_array->AppendNew(value); } - return true; } @@ -1524,13 +1695,13 @@ EPDFAnnot_SetBorderStyle(FPDF_ANNOTATION annot, FPDF_ANNOT_BORDER_STYLE style, float width) { ScopedFPDFAnnotationView annot_view(annot); - RetainPtr pAnnotDict = - GetMutableAnnotDictFromFPDFAnnotation(annot); - if (!pAnnotDict) { + const CPDF_Dictionary* stored_dict = GetAnnotDictFromFPDFAnnotation(annot); + if (!stored_dict) { return false; } - // A style that is none of ours is refused before anything is written. + // A style that is none of ours is refused before the annotation is taken + // for writing. ByteString style_name; if (style != FPDF_ANNOT_BS_UNKNOWN) { style_name = CPDF_Annot::BorderStyleToString( @@ -1540,8 +1711,20 @@ EPDFAnnot_SetBorderStyle(FPDF_ANNOTATION annot, } } + // Nothing to change: no write, and a /Border stays a /Border. + const std::optional stated = ReadStatedBorder(stored_dict); + if (stated.has_value() && + StatesStyleAndWidth(stated.value(), style_name, width)) { + return true; + } + + RetainPtr pAnnotDict = + GetMutableAnnotDictFromFPDFAnnotation(annot); + if (!pAnnotDict) { + return false; + } RetainPtr pBSDict = - BorderStyleDictForWrite(pAnnotDict.Get()); + BorderStyleDictForWrite(annot, pAnnotDict.Get()); if (width >= 0) { pBSDict->SetNewFor("W", width); } else { @@ -4377,17 +4560,7 @@ namespace { RetainPtr OwnMKForWriting(FPDF_ANNOTATION annot, CPDF_Dictionary* annot_dict, bool create) { - RetainPtr entry = annot_dict->GetObjectFor("MK"); - if (entry && entry->IsReference()) { - RetainPtr shared = annot_dict->GetDictFor("MK"); - CPDF_AnnotContext* ctx = CPDFAnnotContextFromFPDFAnnotation(annot); - CPDF_Document* doc = - ctx && ctx->GetPage() ? ctx->GetPage()->GetDocument() : nullptr; - if (shared) { - annot_dict->SetFor("MK", - doc ? shared->CloneForHolder(doc) : shared->Clone()); - } - } + OwnDictEntry(annot, annot_dict, "MK"); return create ? annot_dict->GetOrCreateDictFor("MK") : annot_dict->GetMutableDictFor("MK"); } diff --git a/fpdfsdk/epdf_annot_embeddertest.cpp b/fpdfsdk/epdf_annot_embeddertest.cpp index 0558f01efc..bceca2ac3b 100644 --- a/fpdfsdk/epdf_annot_embeddertest.cpp +++ b/fpdfsdk/epdf_annot_embeddertest.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -7882,19 +7883,19 @@ BorderRead ReadBorder(FPDF_ANNOTATION annot) { return read; } -// Gives |annot| the border /Border [0 0 |width|], with |pattern| as its dash -// array when given, and no /BS. -void WriteBorderArray( - FPDF_ANNOTATION annot, - float width, - std::optional> pattern = std::nullopt) { +// Gives |annot| the border /Border [|radii| |width|], with |pattern| as its +// dash array when given, and no /BS. The corner radii are 0 unless given. +void WriteBorderArray(FPDF_ANNOTATION annot, + float width, + std::optional> pattern = std::nullopt, + FS_SIZEF radii = {0, 0}) { RetainPtr annot_dict = CPDFAnnotContextFromFPDFAnnotation(annot)->GetMutableAnnotDict(); annot_dict->RemoveFor("BS"); RetainPtr border = annot_dict->SetNewFor(pdfium::annotation::kBorder); - border->AppendNew(0); - border->AppendNew(0); + border->AppendNew(radii.width); + border->AppendNew(radii.height); border->AppendNew(width); if (pattern.has_value()) { RetainPtr dash = border->AppendNew(); @@ -7904,12 +7905,13 @@ void WriteBorderArray( } } -// A black square on |page| whose border is /Border [0 0 |width|], with +// A black square on |page| whose border is /Border [|radii| |width|], with // |pattern| as its dash array when given. ScopedFPDFAnnotation NewSquareWithBorderArray( FPDF_PAGE page, float width, - std::optional> pattern = std::nullopt) { + std::optional> pattern = std::nullopt, + FS_SIZEF radii = {0, 0}) { ScopedFPDFAnnotation annot(FPDFPage_CreateAnnot(page, FPDF_ANNOT_SQUARE)); EXPECT_TRUE(annot); const FS_RECTF rect{/*left=*/10.0f, /*top=*/90.0f, /*right=*/90.0f, @@ -7917,7 +7919,7 @@ ScopedFPDFAnnotation NewSquareWithBorderArray( EXPECT_TRUE(FPDFAnnot_SetRect(annot.get(), &rect)); EXPECT_TRUE( EPDFAnnot_SetColor(annot.get(), FPDFANNOT_COLORTYPE_Color, 0, 0, 0)); - WriteBorderArray(annot.get(), width, std::move(pattern)); + WriteBorderArray(annot.get(), width, std::move(pattern), radii); return annot; } @@ -7927,6 +7929,51 @@ ByteString DrawnNow(FPDF_ANNOTATION annot) { return GetNormalAppearanceStreamBytes(annot); } +// |object| as it is stored, to compare before and after a call. A reference +// shows its number and the object it names. +std::string StoredText(const CPDF_Object* object) { + if (!object) { + return "-"; + } + std::ostringstream text; + if (object->IsReference()) { + text << object->AsReference()->GetRefObjNum() + << " 0 R = " << StoredText(object->GetDirect().Get()); + } else if (const CPDF_Array* array = object->AsArray()) { + text << "["; + for (size_t i = 0; i < array->size(); ++i) { + text << " " << StoredText(array->GetObjectAt(i).Get()); + } + text << " ]"; + } else if (const CPDF_Dictionary* dict = object->AsDictionary()) { + text << "<<"; + for (const ByteString& key : dict->GetKeys()) { + text << " /" << key.c_str() << " " + << StoredText(dict->GetObjectFor(key.AsStringView()).Get()); + } + text << " >>"; + } else if (object->IsNumber()) { + text << object->GetNumber(); + } else if (object->IsName()) { + text << "/" << object->GetString().c_str(); + } else if (object->IsString()) { + text << "(" << object->GetString().c_str() << ")"; + } else { + text << "?"; + } + return text.str(); +} + +// The two keys that can hold |annot|'s border, as they are stored. +std::string StoredBorderKeys(FPDF_ANNOTATION annot) { + const CPDF_Dictionary* annot_dict = + CPDFAnnotContextFromFPDFAnnotation(annot)->GetAnnotDict(); + return "/Border " + + StoredText( + annot_dict->GetObjectFor(pdfium::annotation::kBorder).Get()) + + " /BS " + StoredText(annot_dict->GetObjectFor("BS").Get()); +} + } // namespace // A dash pattern set on an annotation that keeps its border in /Border: the @@ -8010,16 +8057,16 @@ TEST_F(EPDFAnnotEmbedderTest, RemovingTheDashOfABorderArrayKeepsItsWidth) { EXPECT_FALSE(DrawnNow(square.get()).Contains("] 0 d")); } { - // A solid /Border has no pattern to remove: it is the same border, in - // /BS. + // A solid /Border has no pattern to remove: nothing is written, and it + // stays the /Border it was. ScopedFPDFAnnotation square = NewSquareWithBorderArray(page.get(), 5); ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), nullptr, 0)); const BorderRead read = ReadBorder(square.get()); EXPECT_EQ(FPDF_ANNOT_BS_SOLID, read.style); EXPECT_FLOAT_EQ(5, read.width); EXPECT_TRUE(read.pattern.empty()); - EXPECT_TRUE(read.has_border_style); - EXPECT_FALSE(read.has_border_array); + EXPECT_FALSE(read.has_border_style); + EXPECT_TRUE(read.has_border_array); const ByteString look = DrawnNow(square.get()); EXPECT_TRUE(look.Contains("5 w ")); EXPECT_FALSE(look.Contains("] 0 d")); @@ -8091,6 +8138,427 @@ TEST_F(EPDFAnnotEmbedderTest, SettingABorderStyleRemovesTheBorderArray) { } } +// A border setter call that asks for what the border already states writes +// nothing. A /Border stays a /Border, with its corner radii, which a /BS +// cannot hold. (Every call turned it into a /BS and removed it.) A call that +// changes the border still moves it into /BS. +TEST_F(EPDFAnnotEmbedderTest, ABorderCallThatChangesNothingWritesNothing) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + static constexpr float kPattern[] = {3, 1}; + const FS_SIZEF radii = {6, 4}; + + struct Case { + const char* name; + // The dash array of /Border [6 4 2 ...], when it has one. + std::optional> pattern; + std::function call; + }; + const Case kNoChange[] = { + {"no pattern, removed from a solid border", std::nullopt, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, nullptr, 0); + }}, + {"an empty pattern, removed", std::vector{}, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, nullptr, 0); + }}, + {"solid and 2 wide, set on a solid border 2 wide", std::nullopt, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_SOLID, 2); + }}, + {"no style and 2 wide, set on a solid border 2 wide", std::nullopt, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_UNKNOWN, 2); + }}, + {"the pattern it has, set again", std::vector{3, 1}, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, kPattern, 2); + }}, + {"dashed and 2 wide, set on a dashed border 2 wide", + std::vector{3, 1}, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_DASHED, 2); + }}, + }; + for (const Case& no_change : kNoChange) { + SCOPED_TRACE(no_change.name); + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 2, no_change.pattern, radii); + const std::string stored = StoredBorderKeys(square.get()); + ASSERT_TRUE(no_change.call(square.get())); + EXPECT_EQ(stored, StoredBorderKeys(square.get())); + float horizontal = -1; + float vertical = -1; + float width = -1; + ASSERT_TRUE( + FPDFAnnot_GetBorder(square.get(), &horizontal, &vertical, &width)); + EXPECT_EQ(6, horizontal); + EXPECT_EQ(4, vertical); + EXPECT_EQ(2, width); + } + + const Case kChange[] = { + {"the pattern removed from a dashed border", std::vector{3, 1}, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, nullptr, 0); + }}, + {"another pattern", std::vector{3, 1}, + [](FPDF_ANNOTATION annot) { + static constexpr float kOther[] = {3, 2}; + return !!EPDFAnnot_SetBorderDashPattern(annot, kOther, 2); + }}, + {"another width", std::nullopt, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_SOLID, 3); + }}, + {"another style", std::nullopt, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_DASHED, 2); + }}, + {"no style, on a dashed border", std::vector{3, 1}, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_UNKNOWN, 2); + }}, + }; + for (const Case& change : kChange) { + SCOPED_TRACE(change.name); + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 2, change.pattern, radii); + ASSERT_TRUE(change.call(square.get())); + const BorderRead read = ReadBorder(square.get()); + EXPECT_TRUE(read.has_border_style); + EXPECT_FALSE(read.has_border_array); + } + + { + // A /BS, asked for the entries it has: left as it is. An entry it does + // not have is still written, though the border reads the same without. + ScopedFPDFAnnotation square = + NewSquareWithBorderArray(page.get(), 9, std::nullopt, radii); + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(square.get())->GetMutableAnnotDict(); + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", 2); + bs->SetNewFor("S", "D"); + RetainPtr dash = bs->SetNewFor("D"); + dash->AppendNew(3); + dash->AppendNew(1); + const std::string stored = StoredBorderKeys(square.get()); + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_DASHED, 2)); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), kPattern, 2)); + // The /Border beside it was not read, and stays too. + EXPECT_EQ(stored, StoredBorderKeys(square.get())); + + bs->RemoveFor("S"); + bs->RemoveFor("D"); + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_SOLID, 2)); + EXPECT_EQ("/Border - /BS << /S /S /W 2 >>", StoredBorderKeys(square.get())); + } + { + // Neither key: there is nothing to remove, and no empty /BS is left. A + // border that is set is written, the default one too. + ScopedFPDFAnnotation square( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_SQUARE)); + ASSERT_TRUE(square); + ASSERT_EQ("/Border - /BS -", StoredBorderKeys(square.get())); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), nullptr, 0)); + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_UNKNOWN, -1)); + EXPECT_EQ("/Border - /BS -", StoredBorderKeys(square.get())); + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_SOLID, 1)); + EXPECT_EQ("/Border - /BS << /S /S /W 1 >>", StoredBorderKeys(square.get())); + } +} + +// On a layer, a border call that changes nothing copies nothing into the +// layer, and the layer saves nothing. +TEST_F(EPDFAnnotEmbedderTest, + ABorderCallThatChangesNothingLeavesALayerAsItWas) { + std::string bytes; + { + embedpdf_test::ScopedTestDocument source(NewTestDocument()); + ASSERT_TRUE(source); + { + ScopedFPDFPage page(FPDFPage_New(source.get(), 0, 200, 200)); + ASSERT_TRUE(page); + ScopedFPDFAnnotation square = NewSquareWithBorderArray( + page.get(), 2, std::vector{3, 1}, {6, 4}); + ASSERT_TRUE(square); + } + ClearString(); + ASSERT_TRUE(FPDF_SaveAsCopy(source.get(), this, 0)); + bytes = GetString(); + } + embedpdf_test::LayerFixture opened; + ASSERT_TRUE(opened.OpenBytes({bytes.begin(), bytes.end()})); + ScopedFPDFPage page(FPDF_LoadPage(opened.layer, 0)); + ASSERT_TRUE(page); + ScopedFPDFAnnotation square(FPDFPage_GetAnnot(page.get(), 0)); + ASSERT_TRUE(square); + ASSERT_EQ("/Border [ 6 4 2 [ 3 1 ] ] /BS -", StoredBorderKeys(square.get())); + ASSERT_EQ(0u, EPDFLayer_GetPromotedObjectCount(opened.layer)); + + static constexpr float kPattern[] = {3, 1}; + ASSERT_TRUE(EPDFLayer_BeginTransaction(opened.layer)); + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_DASHED, 2)); + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(square.get(), kPattern, 2)); + ASSERT_TRUE(EPDFLayer_CommitTransaction(opened.layer)); + + EXPECT_EQ(0u, EPDFLayer_GetPromotedObjectCount(opened.layer)); + EXPECT_TRUE(opened.SaveDelta().empty()); +} + +// A setter leaves a border alone only when the key it is read from is well +// formed and states what the call asks for. One that merely reads as it (a +// name where the width goes reads as 0, a /Border too short to hold a width +// reads as 1 wide) is written anew, as a /BS. +TEST_F(EPDFAnnotEmbedderTest, AMalformedBorderThatReadsAsAskedIsWrittenAnew) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + static constexpr float kThreeNought[] = {3, 0}; + + struct Case { + const char* name; + // Stores the malformed border in the annotation's dictionary. + std::function store; + // Asks for what it reads as. + std::function call; + const char* stored_after; + }; + auto solid = [](float width) { + return [width](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_SOLID, width); + }; + }; + const Case kCases[] = { + {"/Border with a name for its width", + [](CPDF_Dictionary* annot_dict) { + RetainPtr border = + annot_dict->SetNewFor(pdfium::annotation::kBorder); + border->AppendNew(6); + border->AppendNew(4); + border->AppendNew("X"); + }, + solid(0), "/Border - /BS << /S /S /W 0 >>"}, + {"/Border of two numbers", + [](CPDF_Dictionary* annot_dict) { + RetainPtr border = + annot_dict->SetNewFor(pdfium::annotation::kBorder); + border->AppendNew(6); + border->AppendNew(4); + }, + solid(1), "/Border - /BS << /S /S /W 1 >>"}, + {"/Border with a name in its dash array", + [](CPDF_Dictionary* annot_dict) { + RetainPtr border = + annot_dict->SetNewFor(pdfium::annotation::kBorder); + border->AppendNew(6); + border->AppendNew(4); + border->AppendNew(2); + RetainPtr dash = border->AppendNew(); + dash->AppendNew(3); + dash->AppendNew("X"); + }, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, kThreeNought, 2); + }, + "/Border - /BS << /D [ 3 0 ] /S /D /W 2 >>"}, + {"/BS with a name for /W", + [](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", "X"); + bs->SetNewFor("S", "S"); + }, + solid(0), "/Border - /BS << /S /S /W 0 >>"}, + {"/BS with a string for /S", + [](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", 2); + bs->SetNewFor("S", "S"); + }, + solid(2), "/Border - /BS << /S /S /W 2 >>"}, + {"/BS with a name in /D", + [](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + RetainPtr dash = bs->SetNewFor("D"); + dash->AppendNew(3); + dash->AppendNew("X"); + }, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, kThreeNought, 2); + }, + "/Border - /BS << /D [ 3 0 ] >>"}, + }; + for (const Case& malformed : kCases) { + SCOPED_TRACE(malformed.name); + ScopedFPDFAnnotation square( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_SQUARE)); + ASSERT_TRUE(square); + malformed.store(CPDFAnnotContextFromFPDFAnnotation(square.get()) + ->GetMutableAnnotDict() + .Get()); + ASSERT_TRUE(malformed.call(square.get())); + EXPECT_EQ(malformed.stored_after, StoredBorderKeys(square.get())); + } +} + +// A style that is none is refused before the annotation is taken for +// writing: on a layer nothing is copied into the layer. (The annotation was +// copied in, and the copy stayed in memory.) +TEST_F(EPDFAnnotEmbedderTest, ARefusedBorderStyleLeavesALayerAsItWas) { + std::string bytes; + { + embedpdf_test::ScopedTestDocument source(NewTestDocument()); + ASSERT_TRUE(source); + { + ScopedFPDFPage page(FPDFPage_New(source.get(), 0, 200, 200)); + ASSERT_TRUE(page); + ScopedFPDFAnnotation square = NewSquareWithBorderArray(page.get(), 5); + ASSERT_TRUE(square); + } + ClearString(); + ASSERT_TRUE(FPDF_SaveAsCopy(source.get(), this, 0)); + bytes = GetString(); + } + embedpdf_test::LayerFixture opened; + ASSERT_TRUE(opened.OpenBytes({bytes.begin(), bytes.end()})); + ScopedFPDFPage page(FPDF_LoadPage(opened.layer, 0)); + ASSERT_TRUE(page); + ScopedFPDFAnnotation square(FPDFPage_GetAnnot(page.get(), 0)); + ASSERT_TRUE(square); + ASSERT_EQ(0u, EPDFLayer_GetPromotedObjectCount(opened.layer)); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(opened.layer)); + EXPECT_FALSE(EPDFAnnot_SetBorderStyle( + square.get(), static_cast(99), 3)); + ASSERT_TRUE(EPDFLayer_CommitTransaction(opened.layer)); + + EXPECT_EQ(0u, EPDFLayer_GetPromotedObjectCount(opened.layer)); + EXPECT_TRUE(opened.SaveDelta().empty()); + EXPECT_EQ("/Border [ 0 0 5 ] /BS -", StoredBorderKeys(square.get())); +} + +// A /BS may be an object of its own that another annotation names too, and +// so may its /D. A border setter writes into neither: the annotation gets a +// /BS of its own first, and a pattern goes into a new array. The other +// annotation keeps its border. (The setter wrote into the objects it found.) +TEST_F(EPDFAnnotEmbedderTest, ASharedBorderStyleIsNotWrittenInto) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + CPDF_Document* pdf = CPDFDocumentFromFPDFDocument(doc.get()); + ASSERT_TRUE(pdf); + static constexpr float kPattern[] = {8, 1}; + + for (bool one_style : {true, false}) { + SCOPED_TRACE(one_style ? "one /BS for both annotations" + : "a /BS each, and one /D for both"); + ScopedFPDFAnnotation first = NewSquareWithBorderArray(page.get(), 9); + ScopedFPDFAnnotation second = NewSquareWithBorderArray(page.get(), 9); + ASSERT_TRUE(first); + ASSERT_TRUE(second); + RetainPtr shared_pattern = pdf->NewIndirect(); + shared_pattern->AppendNew(4); + shared_pattern->AppendNew(2); + RetainPtr shared_style = + pdf->NewIndirect(); + for (FPDF_ANNOTATION square : {first.get(), second.get()}) { + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(square)->GetMutableAnnotDict(); + annot_dict->RemoveFor(pdfium::annotation::kBorder); + RetainPtr bs = shared_style; + if (one_style) { + annot_dict->SetNewFor("BS", pdf, + shared_style->GetObjNum()); + } else { + bs = annot_dict->SetNewFor("BS"); + } + bs->SetNewFor("W", 4); + bs->SetNewFor("S", "D"); + bs->SetNewFor("D", pdf, shared_pattern->GetObjNum()); + } + const std::string other_stored = StoredBorderKeys(second.get()); + const std::string pattern_stored = StoredText(shared_pattern.Get()); + const std::string style_stored = StoredText(shared_style.Get()); + auto expect_the_other_as_it_was = [&] { + EXPECT_EQ(other_stored, StoredBorderKeys(second.get())); + EXPECT_EQ(pattern_stored, StoredText(shared_pattern.Get())); + if (one_style) { + EXPECT_EQ(style_stored, StoredText(shared_style.Get())); + } + const BorderRead read = ReadBorder(second.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(4, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + }; + const CPDF_Dictionary* first_dict = + CPDFAnnotContextFromFPDFAnnotation(first.get())->GetAnnotDict(); + + // A pattern: in an array of the annotation's own, in a /BS of its own. + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(first.get(), kPattern, 2)); + expect_the_other_as_it_was(); + BorderRead read = ReadBorder(first.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(4, read.width); + EXPECT_THAT(read.pattern, ElementsAre(8, 1)); + EXPECT_FALSE(first_dict->GetObjectFor("BS")->IsReference()); + EXPECT_FALSE( + first_dict->GetDictFor("BS")->GetObjectFor("D")->IsReference()); + + // A style and a width. + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(first.get(), FPDF_ANNOT_BS_SOLID, 7)); + expect_the_other_as_it_was(); + read = ReadBorder(first.get()); + EXPECT_EQ(FPDF_ANNOT_BS_SOLID, read.style); + EXPECT_FLOAT_EQ(7, read.width); + + // The pattern removed. + ASSERT_TRUE(EPDFAnnot_SetBorderDashPattern(first.get(), nullptr, 0)); + expect_the_other_as_it_was(); + EXPECT_TRUE(ReadBorder(first.get()).pattern.empty()); + } + { + // A style and a width set first, on a /BS that names the shared pattern: + // the copy goes on naming it, and it is still not written into. + ScopedFPDFAnnotation first = NewSquareWithBorderArray(page.get(), 9); + ScopedFPDFAnnotation second = NewSquareWithBorderArray(page.get(), 9); + RetainPtr shared_pattern = pdf->NewIndirect(); + shared_pattern->AppendNew(4); + shared_pattern->AppendNew(2); + RetainPtr shared_style = + pdf->NewIndirect(); + shared_style->SetNewFor("W", 4); + shared_style->SetNewFor("S", "D"); + shared_style->SetNewFor("D", pdf, + shared_pattern->GetObjNum()); + for (FPDF_ANNOTATION square : {first.get(), second.get()}) { + RetainPtr annot_dict = + CPDFAnnotContextFromFPDFAnnotation(square)->GetMutableAnnotDict(); + annot_dict->RemoveFor(pdfium::annotation::kBorder); + annot_dict->SetNewFor("BS", pdf, + shared_style->GetObjNum()); + } + const std::string other_stored = StoredBorderKeys(second.get()); + ASSERT_TRUE(EPDFAnnot_SetBorderStyle(first.get(), FPDF_ANNOT_BS_DASHED, 7)); + EXPECT_EQ(other_stored, StoredBorderKeys(second.get())); + const BorderRead read = ReadBorder(first.get()); + EXPECT_EQ(FPDF_ANNOT_BS_DASHED, read.style); + EXPECT_FLOAT_EQ(7, read.width); + EXPECT_THAT(read.pattern, ElementsAre(4, 2)); + } +} + // A form field is drawn with the border the API reads for it, whichever key // holds it: /Border [0 0 4 [3 1]] without a /BS reads, and draws, as the same // border in /BS does. (It drew 1 wide and solid.) diff --git a/public/epdf_annot.h b/public/epdf_annot.h index d024886553..575b9b0b6b 100644 --- a/public/epdf_annot.h +++ b/public/epdf_annot.h @@ -323,12 +323,22 @@ EPDFAnnot_GetBorderStyle(FPDF_ANNOTATION annot, float* width); // Experimental EmbedPDF Extension API. // Set the border style and width of an annotation, in its /BS dictionary. // -// An annotation that keeps its border in the legacy /Border array is given -// that border as a /BS first (its width, and a dashed style with its dash -// pattern when the array has one), so what this call does not set stays as -// it read: a pattern stays stored. /Border is then removed. With a /BS -// beside it, it is no longer read, and a reader that looks at /Border first -// would go on showing the old border. +// A call that asks for what the border already states writes nothing: the +// /BS has these entries, or the annotation keeps its border in the legacy +// /Border array and that reads as this style and width. Such a /Border stays +// as it is, with its corner radii. A border that only reads as the values +// without stating them (a name where the width goes reads as 0) is written. +// +// A call that changes a border kept in /Border gives the annotation that +// border as a /BS first (its width, and a dashed style with its dash pattern +// when the array has one), so what this call does not set stays as it read: +// a pattern stays stored. /Border is then removed, and its corner radii with +// it, which a /BS cannot hold. With a /BS beside it, it is no longer read, +// and a reader that looks at /Border first would go on showing the old +// border. +// +// The /BS written into is the annotation's own. One that is an indirect +// object, which another annotation may name too, is copied first. // // annot - handle to an annotation. // style - the border style to be set. FPDF_ANNOT_BS_UNKNOWN removes @@ -336,8 +346,8 @@ EPDFAnnot_GetBorderStyle(FPDF_ANNOTATION annot, float* width); // width - the border width to be set. A negative width removes /BS /W, // which leaves a border 1 wide. // -// Returns true if successful. A |style| that is no border style is refused -// and nothing is written. +// Returns true if successful, also when there was nothing to write. A +// |style| that is no border style is refused, and nothing is written. FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV EPDFAnnot_SetBorderStyle(FPDF_ANNOTATION annot, FPDF_ANNOT_BORDER_STYLE style, @@ -436,10 +446,16 @@ EPDFAnnot_GetBorderDashPattern(FPDF_ANNOTATION annot, // pattern. A NULL |dash_array| or a |count| of 0 removes the pattern, and a // dashed border then draws the default dash [3]. // -// An annotation that keeps its border in the legacy /Border array is given -// that border as a /BS first, and /Border is removed, as -// EPDFAnnot_SetBorderStyle() does. Its width stays, and so does its style: a -// /Border with a dash array is a dashed border, one without is solid. +// As with EPDFAnnot_SetBorderStyle(), a call that asks for the pattern the +// border already has, or removes one it does not have, writes nothing, and a +// legacy /Border array stays as it is. A call that changes the pattern of a +// border kept in /Border gives the annotation that border as a /BS first, +// and /Border is removed. Its width stays, and so does its style: a /Border +// with a dash array is a dashed border, one without is solid. +// +// The pattern is written as a new array, in a /BS of the annotation's own. +// An array or a /BS that is an indirect object, which another annotation may +// name too, is not written into. // // annot - handle to an annotation. // dash_array - the dash pattern to be set. diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 9891594488..f1d130c314 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -49,7 +49,12 @@ EPDFActionEmbedderTest.NodeFilePathAndNamePayloadsFromSyntheticDicts 2 EPDFActionEmbedderTest.OpenActionDestinationForms 3 EPDFActionEmbedderTest.ResetFormThreeStates 1 EPDFActionEmbedderTest.SetNextChainsActions 3 +EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingLeavesALayerAsItWas 4 +EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingWritesNothing 16 EPDFAnnotEmbedderTest.AFormFieldDrawsTheBorderItReads 2 +EPDFAnnotEmbedderTest.AMalformedBorderThatReadsAsAskedIsWrittenAnew 9 +EPDFAnnotEmbedderTest.ARefusedBorderStyleLeavesALayerAsItWas 4 +EPDFAnnotEmbedderTest.ASharedBorderStyleIsNotWrittenInto 15 EPDFAnnotEmbedderTest.AcrobatCommentWrittenBackReadsTheSame 1 EPDFAnnotEmbedderTest.AnEmptyDashPatternIsASolidLine 19 EPDFAnnotEmbedderTest.AnnotFontMapStagesEveryNamedFont 17 From a3af442e59a5262774fd9b9dfceacc8f6d628ceb Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Tue, 24 Nov 2026 23:39:08 +0200 Subject: [PATCH 3/3] Take a border entry that names nothing as malformed, not as left out The border setters skip a call that asks for what the border already states. To see what it states they looked each entry up by the object it names, which is nothing both for a key that is left out and for a reference to an object the file does not have. The reader goes by the key, and reads such a /W as 0. So on /BS << /S /S /W 9 0 R >> with no object 9, a call that leaves the width out (a negative width) found nothing to do and returned true, and the border went on reading 0 wide where the call's contract says 1. A /S or a /D that names nothing was left in place the same way, and so was a /BS or a /Border that names nothing, though without a wrong reading. ReadStatedBorder now looks for each entry by its key. One that is there and does not name a number, a name or an array of numbers is malformed, as a name where a number goes already was, and the setter writes the border anew. Test: EPDFAnnotEmbedderTest.ABorderEntryThatNamesNothingIsNotLeftOut, listed as a layer-mode writer. Five of its six cases fail without the change. --- fpdfsdk/epdf_annot.cpp | 44 +++++----- fpdfsdk/epdf_annot_embeddertest.cpp | 112 ++++++++++++++++++++++++ testing/embedpdf_layer_mode_writers.txt | 1 + 3 files changed, 137 insertions(+), 20 deletions(-) diff --git a/fpdfsdk/epdf_annot.cpp b/fpdfsdk/epdf_annot.cpp index 69e403449f..175f2464b3 100644 --- a/fpdfsdk/epdf_annot.cpp +++ b/fpdfsdk/epdf_annot.cpp @@ -1441,38 +1441,43 @@ struct StatedBorder { // reads it with: /BS, or else /Border, or else nothing. Nothing is returned // when that key is not written as ISO 32000 writes a border: a /BS that is // no dictionary, a name where a number goes, a /Border that is not three -// numbers and at most a dash array. Such a border may read as what a call -// asks for (a name reads as 0) without stating it, so a setter writes it -// anew. +// numbers and at most a dash array, an entry that names an object the file +// does not have. Such a border may read as what a call asks for (a name +// reads as 0) without stating it, so a setter writes it anew. +// +// An entry is looked for by its key: one that is there and names nothing is +// not one that is left out. std::optional ReadStatedBorder( const CPDF_Dictionary* annot_dict) { StatedBorder stated; - if (RetainPtr entry = - annot_dict->GetDirectObjectFor("BS")) { - const CPDF_Dictionary* border_style = entry->AsDictionary(); + if (annot_dict->KeyExist("BS")) { + RetainPtr border_style = + annot_dict->GetDictFor("BS"); if (!border_style) { return std::nullopt; } - if (RetainPtr width = - border_style->GetDirectObjectFor("W")) { - if (!width->IsNumber()) { + if (border_style->KeyExist("W")) { + RetainPtr width = + border_style->GetDirectObjectFor("W"); + if (!width || !width->IsNumber()) { return std::nullopt; } stated.width = width->GetNumber(); } - if (RetainPtr style = - border_style->GetDirectObjectFor("S")) { - if (!style->IsName()) { + if (border_style->KeyExist("S")) { + RetainPtr style = + border_style->GetDirectObjectFor("S"); + if (!style || !style->IsName()) { return std::nullopt; } stated.style = style->GetString(); } - if (RetainPtr dash = - border_style->GetDirectObjectFor("D")) { - if (!dash->IsArray()) { + if (border_style->KeyExist("D")) { + RetainPtr dash = border_style->GetArrayFor("D"); + if (!dash) { return std::nullopt; } - stated.pattern = NumbersOf(dash->AsArray()); + stated.pattern = NumbersOf(dash.Get()); if (!stated.pattern.has_value()) { return std::nullopt; } @@ -1480,12 +1485,11 @@ std::optional ReadStatedBorder( return stated; } - RetainPtr entry = - annot_dict->GetDirectObjectFor(pdfium::annotation::kBorder); - if (!entry) { + if (!annot_dict->KeyExist(pdfium::annotation::kBorder)) { return stated; } - const CPDF_Array* border = entry->AsArray(); + RetainPtr border = + annot_dict->GetArrayFor(pdfium::annotation::kBorder); if (!border || border->size() < 3 || border->size() > 4) { return std::nullopt; } diff --git a/fpdfsdk/epdf_annot_embeddertest.cpp b/fpdfsdk/epdf_annot_embeddertest.cpp index bceca2ac3b..c02c76d427 100644 --- a/fpdfsdk/epdf_annot_embeddertest.cpp +++ b/fpdfsdk/epdf_annot_embeddertest.cpp @@ -8412,6 +8412,118 @@ TEST_F(EPDFAnnotEmbedderTest, AMalformedBorderThatReadsAsAskedIsWrittenAnew) { } } +// A border entry may be a reference to an object the file does not have. It +// is there, and it states nothing: the reader takes such a /W as 0. A setter +// does not take it as left out. (Asked to leave the width out, it found +// nothing to do, and the border went on reading 0 wide where it says 1.) +TEST_F(EPDFAnnotEmbedderTest, ABorderEntryThatNamesNothingIsNotLeftOut) { + embedpdf_test::ScopedTestDocument doc(NewTestDocument()); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDFPage_New(doc.get(), 0, 200, 200)); + ASSERT_TRUE(page); + CPDF_Document* pdf = CPDFDocumentFromFPDFDocument(doc.get()); + ASSERT_TRUE(pdf); + // No object of the document has this number. + static constexpr uint32_t kMissing = 9999; + + struct Case { + const char* name; + std::function store; + // Asks for the entry to be left out, or for what the border reads as. + std::function call; + const char* stored_after; + }; + auto no_pattern = [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderDashPattern(annot, nullptr, 0); + }; + const Case kCases[] = { + {"/BS /W", + [pdf](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("S", "S"); + bs->SetNewFor("W", pdf, kMissing); + }, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_SOLID, -1); + }, + "/Border - /BS << /S /S >>"}, + {"/BS /S", + [pdf](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", 2); + bs->SetNewFor("S", pdf, kMissing); + }, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_UNKNOWN, 2); + }, + "/Border - /BS << /W 2 >>"}, + {"/BS /D", + [pdf](CPDF_Dictionary* annot_dict) { + RetainPtr bs = + annot_dict->SetNewFor("BS"); + bs->SetNewFor("W", 2); + bs->SetNewFor("D", pdf, kMissing); + }, + no_pattern, "/Border - /BS << /W 2 >>"}, + {"/BS itself", + [pdf](CPDF_Dictionary* annot_dict) { + annot_dict->SetNewFor("BS", pdf, kMissing); + }, + no_pattern, "/Border - /BS -"}, + {"/Border itself", + [pdf](CPDF_Dictionary* annot_dict) { + annot_dict->SetNewFor(pdfium::annotation::kBorder, pdf, + kMissing); + }, + no_pattern, "/Border - /BS -"}, + {"the width of /Border", + [pdf](CPDF_Dictionary* annot_dict) { + RetainPtr border = + annot_dict->SetNewFor(pdfium::annotation::kBorder); + border->AppendNew(6); + border->AppendNew(4); + border->AppendNew(pdf, kMissing); + }, + [](FPDF_ANNOTATION annot) { + return !!EPDFAnnot_SetBorderStyle(annot, FPDF_ANNOT_BS_SOLID, 0); + }, + "/Border - /BS << /S /S /W 0 >>"}, + }; + for (const Case& names_nothing : kCases) { + SCOPED_TRACE(names_nothing.name); + ScopedFPDFAnnotation square( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_SQUARE)); + ASSERT_TRUE(square); + names_nothing.store(CPDFAnnotContextFromFPDFAnnotation(square.get()) + ->GetMutableAnnotDict() + .Get()); + ASSERT_TRUE(names_nothing.call(square.get())); + EXPECT_EQ(names_nothing.stored_after, StoredBorderKeys(square.get())); + } + + { + // The width, read: 0 while /W names nothing, and 1 once it is left out. + ScopedFPDFAnnotation square( + FPDFPage_CreateAnnot(page.get(), FPDF_ANNOT_SQUARE)); + ASSERT_TRUE(square); + CPDFAnnotContextFromFPDFAnnotation(square.get()) + ->GetMutableAnnotDict() + ->SetNewFor("BS") + ->SetNewFor("W", pdf, kMissing); + float width = -1; + ASSERT_EQ(FPDF_ANNOT_BS_SOLID, + EPDFAnnot_GetBorderStyle(square.get(), &width)); + ASSERT_EQ(0, width); + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(square.get(), FPDF_ANNOT_BS_UNKNOWN, -1)); + EXPECT_EQ(FPDF_ANNOT_BS_SOLID, + EPDFAnnot_GetBorderStyle(square.get(), &width)); + EXPECT_EQ(1, width); + } +} + // A style that is none is refused before the annotation is taken for // writing: on a layer nothing is copied into the layer. (The annotation was // copied in, and the copy stayed in memory.) diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index f1d130c314..0d765ca099 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -51,6 +51,7 @@ EPDFActionEmbedderTest.ResetFormThreeStates 1 EPDFActionEmbedderTest.SetNextChainsActions 3 EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingLeavesALayerAsItWas 4 EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingWritesNothing 16 +EPDFAnnotEmbedderTest.ABorderEntryThatNamesNothingIsNotLeftOut 10 EPDFAnnotEmbedderTest.AFormFieldDrawsTheBorderItReads 2 EPDFAnnotEmbedderTest.AMalformedBorderThatReadsAsAskedIsWrittenAnew 9 EPDFAnnotEmbedderTest.ARefusedBorderStyleLeavesALayerAsItWas 4