From 15099239945327aeea6061e6aebb242f72225e24 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Sun, 29 Nov 2026 20:59:09 +0200 Subject: [PATCH 1/2] Give every redrawn form field a new appearance stream An undo of a form write puts the field's and its widgets' dictionaries back from a capture taken before the write. An import never replaces an object the layer holds a version of, since that version may be newer. So a widget gets the appearance it had back only when the write left that stream as it read. A text field, a combo box and a list box were drawn into the stream the widget already named. After a second value, a reset, a shown text or a restyle, the undo put /V and the widget's keys back, and the widget still named the same stream, which drew what the write had drawn: the page and a saved file showed the undone value. The stream was also written into when the file held it, or when another widget named it too. GenerateFormAPToTarget now makes a new stream for every kind, as it did for a push button and as the check box, radio button and box drawers do, under an /AP of the widget's own (OwnAppearanceDict). The old stream is not opened for writing, so nothing of it is copied into a layer, and a save writes only what the document still reaches. Tests: EPDFCaptureEmbedderTest.RedrawnFieldComesBackWithItsAppearance and RedrawnFieldLeavesTheFilesAppearanceAlone, EPDFFormEmbedderTest.RedrawIsANewStreamEveryTime and RedrawLeavesASharedAppearanceAlone. All four fail without the change. The two form tests are listed as layer-mode writers, and 21 tests that redraw a text or choice field leave one to six more objects in a layer, one for each redraw. --- .../cpdf_appearancegenerator_forms.cpp | 30 ++-- docs/embedpdf/fork-ledger.md | 17 +- fpdfsdk/epdf_capture_embeddertest.cpp | 91 +++++++++++ fpdfsdk/epdf_form_embeddertest.cpp | 147 ++++++++++++++++++ public/epdf_annot.h | 17 +- testing/embedpdf_layer_mode_writers.txt | 44 +++--- 6 files changed, 292 insertions(+), 54 deletions(-) diff --git a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp index b47aae521..d46b4e24f 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp @@ -1209,25 +1209,19 @@ bool GenerateFormAPToTarget(APGenerationTarget* target, if (!resource_font_dict) { return false; // registered /DA font without a resource: no appearance } - // A push button's appearance is a new stream every time, as a check box's - // are. The stream it had may be another widget's too; it may be a picture - // (the button's icon, now or before it was cleared), which is never drawn + // A field's appearance is a new stream every time, as a check box's are. + // The stream it had may be another widget's too; it may be a picture (a + // push button's icon, now or before it was cleared), which is never drawn // over; and its resources may still name an icon the button no longer - // shows, which would keep that picture in the file. The old stream is not - // opened for writing, so nothing of it is copied into a layer. The other - // fields write into the stream they have. - RetainPtr normal_stream; - if (type != CPDF_AppearanceGenerator::kPushButton) { - RetainPtr ap_dict = - annot_dict->GetMutableDictFor(pdfium::annotation::kAP); - normal_stream = ap_dict ? ap_dict->GetMutableStreamFor("N") : nullptr; - } - if (!normal_stream) { - normal_stream = - doc->NewIndirect(pdfium::MakeRetain()); - OwnAppearanceDict(doc, annot_dict) - ->SetNewFor("N", doc, normal_stream->GetObjNum()); - } + // shows, which would keep that picture in the file. It also stays as it + // reads: a capture taken before the write (public/epdf_capture.h) puts the + // widget back with the appearance it named, and an import never replaces a + // stream the layer holds. The old stream is not opened for writing, so + // nothing of it is copied into a layer. + RetainPtr normal_stream = + doc->NewIndirect(pdfium::MakeRetain()); + OwnAppearanceDict(doc, annot_dict) + ->SetNewFor("N", doc, normal_stream->GetObjNum()); normal_stream->SetDataFromStringstreamAndRemoveFilter(&app_stream); RetainPtr stream_dict = normal_stream->GetMutableDict(); // A form XObject, said so: a stream made here has no type yet, and diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index 2635fb7b5..66e4f8271 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -359,13 +359,16 @@ met only in buttons other apps made. Either way the icon fit (`/MK /IF`) is read upstream's `CPDF_IconFit` and the icon is placed by our own `IconPlacement`, by ISO 32000-2 Table 250: upstream's own placement (`CPDF_IconFit::GetScale` and `GetImageOffset`, used by its form filler) puts an icon whose fit names no `/A` at the bottom left, where the table's default is the -middle, and reads an icon narrower than one unit as one unit wide. A push button's appearance is -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` and -`/BS` before a setter writes one (`OwnMKForWriting` and `BorderStyleDictForWrite`, both through -`OwnDictEntry`): another annotation may name the same dictionary. A colour is +middle, and reads an icon narrower than one unit as one unit wide. A field's appearance is a new +stream on every redraw, whatever kind the field is: the stream it had may be another widget's or +a picture a push button showed, so it is never written into, and the icon its resources named +goes with it. It also stays as it reads, so a capture taken before the redraw +(`public/epdf_capture.h`) brings the widget back with the appearance it named: an import never +replaces a stream the layer holds. 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` 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 diff --git a/fpdfsdk/epdf_capture_embeddertest.cpp b/fpdfsdk/epdf_capture_embeddertest.cpp index 9fcea91a6..e84c7cac3 100644 --- a/fpdfsdk/epdf_capture_embeddertest.cpp +++ b/fpdfsdk/epdf_capture_embeddertest.cpp @@ -286,6 +286,16 @@ uint32_t CreateSquare(FPDF_DOCUMENT doc, int page_index, uint32_t objnum) { return Recolor(doc, objnum, 0, 1, 0); } +// Writes |text| as the text field |field_objnum|'s value and draws its +// widgets again, as a value write does. +bool Fill(FPDF_DOCUMENT doc, uint32_t field_objnum, const std::wstring& text) { + ScopedFPDFWideString value = GetFPDFWideString(text); + FPDF_WIDESTRING values[] = {value.get()}; + return EPDFForm_SetFieldValue(doc, field_objnum, EPDF_FORM_VALUE_SCALAR, + values, 1) && + EPDFForm_RedrawFieldWidgets(doc, field_objnum, nullptr, 0, nullptr); +} + // The objects of the document of pages below. constexpr uint32_t kPageTree = 2; constexpr uint32_t kCover = 3; @@ -753,6 +763,87 @@ TEST_F(EPDFCaptureEmbedderTest, DroppedDictionaryComesBackWhole) { EXPECT_EQ(bytes, RawBytesOf(reopened.get(), appearance)); } +// A field filled in a second time comes back as its first fill left it: the +// redraw gave its widget a new appearance and left the one it had as it +// read, so the capture taken before the write brings the widget back naming +// that one, with its bytes, also after a save and reopen dropped it. +TEST_F(EPDFCaptureEmbedderTest, RedrawnFieldComesBackWithItsAppearance) { + for (bool reopen : {false, true}) { + SCOPED_TRACE(reopen ? "reopened between redraw and import" + : "same session"); + ScopedFPDFDocument layer = OpenLayer(); + ASSERT_TRUE(layer); + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + ASSERT_TRUE(Fill(layer.get(), kMergedField, L"Bea")); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + const uint32_t before_ap = NormalAppearanceOf(layer.get(), kMergedField); + ASSERT_NE(0u, before_ap); + const std::string before_bytes = RawBytesOf(layer.get(), before_ap); + ASSERT_FALSE(before_bytes.empty()); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + const std::vector capture = + ExportDict(layer.get(), kMergedField, "AP MK"); + ASSERT_FALSE(capture.empty()); + ASSERT_TRUE(Fill(layer.get(), kMergedField, L"Cyrus")); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + const uint32_t after_ap = NormalAppearanceOf(layer.get(), kMergedField); + ASSERT_NE(0u, after_ap); + EXPECT_NE(before_ap, after_ap); + EXPECT_NE(before_bytes, RawBytesOf(layer.get(), after_ap)); + EXPECT_EQ(before_bytes, RawBytesOf(layer.get(), before_ap)); + + ScopedFPDFDocument target = reopen ? Reopen(layer.get()) : std::move(layer); + ASSERT_TRUE(target); + if (reopen) { + EXPECT_TRUE(RawBytesOf(target.get(), before_ap).empty()); + } + ASSERT_TRUE(EPDFLayer_BeginTransaction(target.get())); + ASSERT_TRUE(ImportDict(target.get(), capture)); + ASSERT_TRUE(EPDFLayer_CommitTransaction(target.get())); + EXPECT_EQ(L"Bea", + DictOf(target.get(), kMergedField)->GetUnicodeTextFor("V")); + EXPECT_EQ(before_ap, NormalAppearanceOf(target.get(), kMergedField)); + EXPECT_EQ(before_bytes, RawBytesOf(target.get(), before_ap)); + } +} + +// A widget may name a stream the file holds, which another annotation names +// too. A redraw never opens it for writing, so the layer holds no version of +// it, and the capture taken before the write brings the widget back naming it. +TEST_F(EPDFCaptureEmbedderTest, RedrawnFieldLeavesTheFilesAppearanceAlone) { + ScopedFPDFDocument layer = OpenLayer(); + ASSERT_TRUE(layer); + const std::string file_bytes = RawBytesOf(layer.get(), kFileSquareAp); + ASSERT_FALSE(file_bytes.empty()); + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + WritableDict(layer.get(), kMergedField) + ->SetNewFor("AP") + ->SetNewFor( + "N", CPDFDocumentFromFPDFDocument(layer.get()), kFileSquareAp); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + const std::vector capture = + ExportDict(layer.get(), kMergedField, "AP MK"); + ASSERT_FALSE(capture.empty()); + ASSERT_TRUE(Fill(layer.get(), kMergedField, L"Bea")); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + const uint32_t drawn = NormalAppearanceOf(layer.get(), kMergedField); + EXPECT_NE(0u, drawn); + EXPECT_NE(kFileSquareAp, drawn); + EXPECT_FALSE(LayerOf(layer.get())->FindLayerVersion(kFileSquareAp)); + EXPECT_EQ(kFileSquareAp, NormalAppearanceOf(layer.get(), kFileSquare)); + EXPECT_EQ(file_bytes, RawBytesOf(layer.get(), kFileSquareAp)); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + ASSERT_TRUE(ImportDict(layer.get(), capture)); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + EXPECT_EQ(L"Ann", DictOf(layer.get(), kMergedField)->GetUnicodeTextFor("V")); + EXPECT_EQ(kFileSquareAp, NormalAppearanceOf(layer.get(), kMergedField)); + EXPECT_EQ(file_bytes, RawBytesOf(layer.get(), kFileSquareAp)); +} + // A dictionary captured without deep keys holds no objects: what it refers // to is kept as it is. TEST_F(EPDFCaptureEmbedderTest, ShallowDictionaryHoldsNoObjects) { diff --git a/fpdfsdk/epdf_form_embeddertest.cpp b/fpdfsdk/epdf_form_embeddertest.cpp index 4a5488728..1c876e402 100644 --- a/fpdfsdk/epdf_form_embeddertest.cpp +++ b/fpdfsdk/epdf_form_embeddertest.cpp @@ -3,6 +3,7 @@ #include "public/epdf_form.h" +#include #include #include @@ -14,7 +15,9 @@ #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_name.h" #include "core/fpdfapi/parser/cpdf_number.h" +#include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/cpdf_stream.h" +#include "core/fpdfapi/parser/cpdf_stream_acc.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "fpdfsdk/cpdfsdk_helpers.h" #include "public/epdf_action.h" @@ -2280,6 +2283,150 @@ TEST_F(EPDFFormEmbedderTest, NewFieldAppearanceIsAFormXObject) { UnloadPage(page); } +namespace { + +// The number of the stream the widget |widget| names as its normal +// appearance, or 0. +uint32_t NormalStreamOf(CPDF_Document* doc, uint32_t widget) { + RetainPtr dict = + ToDictionary(doc->GetIndirectObject(widget)); + RetainPtr ap = dict ? dict->GetDictFor("AP") : nullptr; + RetainPtr normal = ap ? ap->GetStreamFor("N") : nullptr; + return normal ? normal->GetObjNum() : 0; +} + +// What the stream |objnum| draws. +std::string ContentOf(CPDF_Document* doc, uint32_t objnum) { + RetainPtr stream = + ToStream(doc->GetIndirectObject(objnum)); + if (!stream) { + return std::string(); + } + auto acc = pdfium::MakeRetain(std::move(stream)); + acc->LoadAllDataFiltered(); + const ByteStringView bytes(acc->GetSpan()); + return std::string(bytes.unterminated_c_str(), bytes.GetLength()); +} + +} // namespace + +// A field's redraw is a new stream every time, for a text field, a combo box +// and a list box as for the other kinds: the stream its widget named is not +// written into, so it still draws what it drew. +TEST_F(EPDFFormEmbedderTest, RedrawIsANewStreamEveryTime) { + ASSERT_TRUE(OpenDocument("hello_world.pdf")); + FPDF_PAGE page = LoadPage(0); + ASSERT_TRUE(page); + CPDF_Document* doc = CPDFDocumentFromFPDFDocument(document()); + ScopedFPDFWideString one = GetFPDFWideString(L"One"); + ScopedFPDFWideString two = GetFPDFWideString(L"Two"); + FPDF_WIDESTRING options[] = {one.get(), two.get()}; + float bottom = 200; + for (int family : {EPDF_FORMFIELD_FAMILY_TEXT, EPDF_FORMFIELD_FAMILY_COMBOBOX, + EPDF_FORMFIELD_FAMILY_LISTBOX}) { + SCOPED_TRACE(testing::Message() << "field family " << family); + const std::wstring name = L"field" + std::to_wstring(family); + const uint32_t field = EPDFForm_CreateField( + document(), family, GetFPDFWideString(name).get(), 0); + ASSERT_GT(field, 0u); + const uint32_t widget = + CreateWidgetAnnot(page, 20, bottom, 180, bottom + 30); + ASSERT_GT(widget, 0u); + bottom += 40; + ASSERT_TRUE(EPDFForm_AttachWidget(document(), field, widget, nullptr, 0)); + if (family != EPDF_FORMFIELD_FAMILY_TEXT) { + ASSERT_TRUE( + EPDFForm_SetFieldOptions(document(), field, options, options, 2)); + } + ASSERT_TRUE( + EPDFForm_RedrawFieldWidgets(document(), field, nullptr, 0, nullptr)); + const uint32_t first = NormalStreamOf(doc, widget); + ASSERT_GT(first, 0u); + const std::string first_content = ContentOf(doc, first); + ASSERT_FALSE(first_content.empty()); + + // A text field and a combo box draw their value, a list box its options. + if (family == EPDF_FORMFIELD_FAMILY_LISTBOX) { + ASSERT_TRUE(EPDFForm_SetFieldOptions(document(), field, options + 1, + options + 1, 1)); + } else { + ASSERT_TRUE(SetOneValue(document(), field, L"Two")); + } + ASSERT_TRUE( + EPDFForm_RedrawFieldWidgets(document(), field, nullptr, 0, nullptr)); + const uint32_t second = NormalStreamOf(doc, widget); + ASSERT_GT(second, 0u); + EXPECT_NE(first, second); + EXPECT_NE(first_content, ContentOf(doc, second)); + EXPECT_EQ(first_content, ContentOf(doc, first)); + } + UnloadPage(page); +} + +// Two widgets may name one /AP dictionary and one stream, as a file may hold +// them. A redraw gives each an /AP and a stream of its own, and writes into +// neither of the two they shared. +TEST_F(EPDFFormEmbedderTest, RedrawLeavesASharedAppearanceAlone) { + ASSERT_TRUE(OpenDocument("hello_world.pdf")); + FPDF_PAGE page = LoadPage(0); + ASSERT_TRUE(page); + const uint32_t field = + EPDFForm_CreateField(document(), EPDF_FORMFIELD_FAMILY_TEXT, + GetFPDFWideString(L"name").get(), 0); + ASSERT_GT(field, 0u); + const uint32_t widgets[] = {CreateWidgetAnnot(page, 20, 200, 180, 230), + CreateWidgetAnnot(page, 20, 240, 180, 270)}; + for (uint32_t widget : widgets) { + ASSERT_GT(widget, 0u); + ASSERT_TRUE(EPDFForm_AttachWidget(document(), field, widget, nullptr, 0)); + } + + // One stream, and one /AP naming it that both widgets name. + static constexpr char kShared[] = "0 0 1 rg 0 0 9 9 re f"; + CPDF_Document* doc = CPDFDocumentFromFPDFDocument(document()); + auto stream_dict = pdfium::MakeRetain(); + stream_dict->SetNewFor("Type", "XObject"); + stream_dict->SetNewFor("Subtype", "Form"); + RetainPtr stream = doc->NewIndirect(stream_dict); + stream->SetData(ByteStringView(kShared).unsigned_span()); + const uint32_t shared_stream = stream->GetObjNum(); + RetainPtr ap = doc->NewIndirect(); + ap->SetNewFor("N", doc, shared_stream); + const uint32_t shared_ap = ap->GetObjNum(); + for (uint32_t widget : widgets) { + ToDictionary(doc->GetMutableIndirectObject(widget)) + ->SetNewFor("AP", doc, shared_ap); + ASSERT_EQ(shared_stream, NormalStreamOf(doc, widget)); + } + + ASSERT_TRUE(SetOneValue(document(), field, L"Bea")); + ASSERT_TRUE( + EPDFForm_RedrawFieldWidgets(document(), field, nullptr, 0, nullptr)); + + std::set drawn; + for (uint32_t widget : widgets) { + RetainPtr dict = + ToDictionary(doc->GetIndirectObject(widget)); + ASSERT_TRUE(dict); + RetainPtr own_ap = dict->GetObjectFor("AP"); + ASSERT_TRUE(own_ap); + EXPECT_TRUE(own_ap->IsDictionary()); + const uint32_t normal = NormalStreamOf(doc, widget); + EXPECT_NE(0u, normal); + EXPECT_NE(shared_stream, normal); + drawn.insert(normal); + } + EXPECT_EQ(2u, drawn.size()); + EXPECT_EQ(kShared, ContentOf(doc, shared_stream)); + RetainPtr kept_ap = + ToDictionary(doc->GetIndirectObject(shared_ap)); + ASSERT_TRUE(kept_ap); + RetainPtr kept_normal = kept_ap->GetStreamFor("N"); + ASSERT_TRUE(kept_normal); + EXPECT_EQ(shared_stream, kept_normal->GetObjNum()); + UnloadPage(page); +} + TEST_F(EPDFFormEmbedderTest, PushButtonIsAuthorableAndShowsItsCaption) { ASSERT_TRUE(OpenDocument("hello_world.pdf")); FPDF_PAGE page = LoadPage(0); diff --git a/public/epdf_annot.h b/public/epdf_annot.h index 575b9b0b6..684bffde5 100644 --- a/public/epdf_annot.h +++ b/public/epdf_annot.h @@ -1780,14 +1780,15 @@ FPDF_EXPORT int FPDF_CALLCONV EPDFAnnot_GetMKRotation(FPDF_ANNOTATION annot); // as a text field draws them. It replaces whatever the widget // shows, a signature drawn into it included. // -// A push button, a check box, a radio button and a box get new appearance -// streams every time. The ones they had are not written into and not -// deleted: one may be another widget's too, or a picture the widget showed, -// and a save writes only what the document still reaches. So a picture a -// button no longer names or draws is in no file saved in full afterwards. A -// text field, a combo box and a list box write into the stream they have. -// A widget whose /AP is an indirect object, which another widget may name -// too, gets a copy of its own before an appearance in it is replaced. +// Every kind gets new appearance streams every time. The ones the widget had +// are not written into and not deleted: one may be another widget's too, or +// a picture the widget showed, and a save writes only what the document +// still reaches. So a picture a button no longer names or draws is in no +// file saved in full afterwards, and a widget put back from a capture taken +// before the redraw (public/epdf_capture.h) names an appearance that reads +// as it did. A widget whose /AP is an indirect object, which another widget +// may name too, gets a copy of its own before an appearance in it is +// replaced. // // annot - handle to a widget annotation. // diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 474b5cf50..334891394 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -52,7 +52,7 @@ EPDFActionEmbedderTest.SetNextChainsActions 3 EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingLeavesALayerAsItWas 4 EPDFAnnotEmbedderTest.ABorderCallThatChangesNothingWritesNothing 16 EPDFAnnotEmbedderTest.ABorderEntryThatNamesNothingIsNotLeftOut 10 -EPDFAnnotEmbedderTest.AFormFieldDrawsTheBorderItReads 2 +EPDFAnnotEmbedderTest.AFormFieldDrawsTheBorderItReads 3 EPDFAnnotEmbedderTest.AMalformedBorderThatReadsAsAskedIsWrittenAnew 9 EPDFAnnotEmbedderTest.ARefusedBorderStyleLeavesALayerAsItWas 4 EPDFAnnotEmbedderTest.ASharedBorderStyleIsNotWrittenInto 15 @@ -87,7 +87,7 @@ EPDFAnnotEmbedderTest.CalloutRectHoldsItsLineAndArrow 7 EPDFAnnotEmbedderTest.CffProgramRaisesPdfVersionTo16 12 EPDFAnnotEmbedderTest.CloudyBumpsReachPastTheBoxIntoRect 13 EPDFAnnotEmbedderTest.CloudyPolygonRectHoldsItsBumps 5 -EPDFAnnotEmbedderTest.ComboBoxKoreanUsesRegisteredDroidFallbackFont 20 +EPDFAnnotEmbedderTest.ComboBoxKoreanUsesRegisteredDroidFallbackFont 22 EPDFAnnotEmbedderTest.DashedBorderDrawsItsDashOrTheDefault 11 EPDFAnnotEmbedderTest.DefaultAppearanceFontFace 1 EPDFAnnotEmbedderTest.DefaultAppearancePrefersAnnotationDrThenFallsBackToAcroFormDr 4 @@ -97,7 +97,7 @@ EPDFAnnotEmbedderTest.DrawingRectIsWhereTheAppearanceIsDrawn 6 EPDFAnnotEmbedderTest.EmbedMetadata 1 EPDFAnnotEmbedderTest.EmbedSetRectPreservesRotatedAppearance 3 EPDFAnnotEmbedderTest.ExplicitGenerateAppearanceAllowed 2 -EPDFAnnotEmbedderTest.FontEmbeddingPolicyGovernsRegisteredResources 53 +EPDFAnnotEmbedderTest.FontEmbeddingPolicyGovernsRegisteredResources 55 EPDFAnnotEmbedderTest.FreeTextAllFallbackTextKeepsRegisteredDaFont 18 EPDFAnnotEmbedderTest.FreeTextAppearanceFallsBackToRegisteredFont 13 EPDFAnnotEmbedderTest.FreeTextAppearanceUsesRegisteredMemoryFont 13 @@ -122,7 +122,7 @@ EPDFAnnotEmbedderTest.GenerateTextAppearanceFillsItsRect 7 EPDFAnnotEmbedderTest.GenerateTextAppearancePerIcon 21 EPDFAnnotEmbedderTest.LineRectHoldsItsArrowhead 5 EPDFAnnotEmbedderTest.LineRectIsWhatItsStrokePaints 7 -EPDFAnnotEmbedderTest.ListBoxKoreanUsesRegisteredDroidFallbackFont 20 +EPDFAnnotEmbedderTest.ListBoxKoreanUsesRegisteredDroidFallbackFont 22 EPDFAnnotEmbedderTest.NoStrokeColorInkPaintsNothing 5 EPDFAnnotEmbedderTest.NoStrokeColorKeepsTheFillInTheStrokesPlace 14 EPDFAnnotEmbedderTest.NoStrokeColorLineKeepsItsFilledEndings 6 @@ -179,13 +179,13 @@ EPDFAnnotEmbedderTest.SetSubtypeChangesTheKindInPlace 8 EPDFAnnotEmbedderTest.SettingABorderStyleRemovesTheBorderArray 8 EPDFAnnotEmbedderTest.SettingADashOnABorderArrayKeepsItsWidth 8 EPDFAnnotEmbedderTest.StandardFontDefaultAppearanceRoundTripsThroughDr 19 -EPDFAnnotEmbedderTest.TextFieldDrawsItsBorderStyle 2 +EPDFAnnotEmbedderTest.TextFieldDrawsItsBorderStyle 5 EPDFAnnotEmbedderTest.TextFieldGenerateAppearanceStreamIsStable 2 -EPDFAnnotEmbedderTest.TextFieldKoreanUsesRegisteredDroidFallbackFont 20 +EPDFAnnotEmbedderTest.TextFieldKoreanUsesRegisteredDroidFallbackFont 22 EPDFAnnotEmbedderTest.TurnedBoxRectIsTheUprightBoxAroundIt 3 EPDFAnnotEmbedderTest.TwoWeightsOfOneFamilyAreTwoFontsByName 21 EPDFAnnotEmbedderTest.VariableFontIsInstancedAtRegistration 13 -EPDFAnnotEmbedderTest.WidgetRegisteredFontInstallsRealDrEntry 25 +EPDFAnnotEmbedderTest.WidgetRegisteredFontInstallsRealDrEntry 27 EPDFAnnotEmbedderTest.WidgetTextAlignment 2 EPDFAnnotEmbedderTest.WidthZeroDrawsAHairline 9 EPDFAnnotRawEmbedderTest.ALinkedHandleSharesThePage 5 @@ -216,18 +216,18 @@ EPDFFlattenEmbedderTest.FlattenPaintsTheAppearanceDrawnInMemory 7 EPDFFlattenEmbedderTest.FlattenSpecificAnnotationByHandle 7 EPDFFlattenEmbedderTest.InvisibleLeavesOutOnlyAnUnknownType 8 EPDFFontEmbedderTest.FreeTextReportsCharactersNoFontHas 7 -EPDFFontEmbedderTest.ListsADocumentProgramAndHandsOutItsBytes 25 -EPDFFontEmbedderTest.PasswordFieldWritesOnlyStars 8 -EPDFFontEmbedderTest.RealignsAProgramABrowserWouldRefuse 25 -EPDFFontEmbedderTest.ResolvesADocumentProgram 25 +EPDFFontEmbedderTest.ListsADocumentProgramAndHandsOutItsBytes 27 +EPDFFontEmbedderTest.PasswordFieldWritesOnlyStars 11 +EPDFFontEmbedderTest.RealignsAProgramABrowserWouldRefuse 27 +EPDFFontEmbedderTest.ResolvesADocumentProgram 27 EPDFFontEmbedderTest.RichTextDrawsTheProgramItsStyleNames 25 -EPDFFontEmbedderTest.SimpleFieldFontWritesThroughItsProgram 13 -EPDFFontEmbedderTest.UnauthorizedRegisteredFontDoesNotTakeOverABox 25 -EPDFFontEmbedderTest.WidgetDrawsEachClusterInAFontThatHasIt 20 -EPDFFontEmbedderTest.WidgetDrawsWhatNoFontHasWithTheLastResort 20 -EPDFFontEmbedderTest.WidgetWritesWithADocumentProgram 52 -EPDFFormEmbedderTest.ANegativeWidgetRotationIsDrawnAsItsTurn 2 -EPDFFormEmbedderTest.AttachToLegacyMergedFieldKeepsFieldId 6 +EPDFFontEmbedderTest.SimpleFieldFontWritesThroughItsProgram 14 +EPDFFontEmbedderTest.UnauthorizedRegisteredFontDoesNotTakeOverABox 27 +EPDFFontEmbedderTest.WidgetDrawsEachClusterInAFontThatHasIt 22 +EPDFFontEmbedderTest.WidgetDrawsWhatNoFontHasWithTheLastResort 22 +EPDFFontEmbedderTest.WidgetWritesWithADocumentProgram 58 +EPDFFormEmbedderTest.ANegativeWidgetRotationIsDrawnAsItsTurn 3 +EPDFFormEmbedderTest.AttachToLegacyMergedFieldKeepsFieldId 7 EPDFFormEmbedderTest.AttachToSignatureFieldDrawsItsBox 7 EPDFFormEmbedderTest.AttachWidgetsFormsARadioGroup 11 EPDFFormEmbedderTest.CalculationOrderSetReplaceAndRemove 1 @@ -244,14 +244,16 @@ EPDFFormEmbedderTest.EventActionsSetReplaceAndRemove 6 EPDFFormEmbedderTest.FieldEmbedMetadataIsSnapshotted 1 EPDFFormEmbedderTest.FieldEmbedMetadataReadsAndWrites 2 EPDFFormEmbedderTest.FieldEmbedMetadataWritesTheFieldNotItsParent 1 -EPDFFormEmbedderTest.FieldSettersValidateAndApply 3 +EPDFFormEmbedderTest.FieldSettersValidateAndApply 4 EPDFFormEmbedderTest.GenerateFormFieldAPRefusesAnotherSubtype 2 EPDFFormEmbedderTest.ListBoxTopIndexIsRead 1 EPDFFormEmbedderTest.ListBoxValuesAreAnArray 1 EPDFFormEmbedderTest.MalformedDefaultReadsAsUnsupported 1 -EPDFFormEmbedderTest.NewFieldAppearanceIsAFormXObject 7 +EPDFFormEmbedderTest.NewFieldAppearanceIsAFormXObject 8 EPDFFormEmbedderTest.NoneShadowsAParentFieldsValue 2 EPDFFormEmbedderTest.PushButtonIsAuthorableAndShowsItsCaption 8 +EPDFFormEmbedderTest.RedrawIsANewStreamEveryTime 19 +EPDFFormEmbedderTest.RedrawLeavesASharedAppearanceAlone 13 EPDFFormEmbedderTest.RepairBakeClearsNeedAppearances 24 EPDFFormEmbedderTest.RepairBakesMissingAppearances 4 EPDFFormEmbedderTest.RepairCreatesAcroFormAndLinksKids 4 @@ -422,7 +424,7 @@ EPDFWidgetDrawingEmbedderTest.ADrawingWithAMatrixIsPlacedByItsBox 14 EPDFWidgetDrawingEmbedderTest.AFittedCaptionTakesAThirdOfTheButton 15 EPDFWidgetDrawingEmbedderTest.AForeignButtonKeepsItsIconInEveryLayout 14 EPDFWidgetDrawingEmbedderTest.AForeignIconOnlyButtonSurvivesARedraw 5 -EPDFWidgetDrawingEmbedderTest.AFormWithoutPicturesListsNoDrawing 16 +EPDFWidgetDrawingEmbedderTest.AFormWithoutPicturesListsNoDrawing 19 EPDFWidgetDrawingEmbedderTest.AMalformedEntryThatReadsAsTheValueIsWrittenAnew 25 EPDFWidgetDrawingEmbedderTest.AMarkIsPlacedAsAPageIsFitted 196 EPDFWidgetDrawingEmbedderTest.AMarkSavedBeforeThisChangeIsADrawing 13 From 89d1bc3165faaa698759212c97c6b5ed50e136c2 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Sun, 29 Nov 2026 22:56:05 +0200 Subject: [PATCH 2/2] Keep a redrawn field in its layer, and its same appearances the same A review of pull request 135 found two things a new stream lost, which a redraw into the old stream had kept for a text field, a combo box and a list box. The kinds that got new streams before had lost them already. A stream may say which layer it shows in (/OC). The new stream said nothing, so a field whose appearance is in a layer that is off showed its value after a fill, in a reader that goes by the entry. A widget's rollover and pressed appearances (/R, /D) may be its normal one. They went on naming the old stream, with the old value. NameNormalAppearance now names the new appearance for every drawer. A new stream takes the /OC of the stream it replaces, the one of its state for a check box or a radio button. An /R or a /D that named the replaced stream, for the widget or for a state, names the new one, and one made apart stays as it is. A dictionary of states that is an indirect object is copied onto the widget first, as /AP is: another widget may name it. A capture taken before the redraw still brings everything back, since it puts the widget's /AP back whole. Tests: EPDFWidgetDrawingEmbedderTest.ARedrawKeepsTheLayerAndTheSameAppearances, over a text field, a combo box, a list box, a push button with a caption and one without, a signature box, a check box and a radio button, and EPDFCaptureEmbedderTest.RedrawnFieldComesBackWithItsSameAppearances. Both fail without the change, the first for every kind. The first is listed as a layer-mode writer. --- .../cpdf_appearancegenerator_forms.cpp | 135 ++++++++++-- docs/embedpdf/fork-ledger.md | 11 +- fpdfsdk/epdf_capture_embeddertest.cpp | 47 ++++ fpdfsdk/epdf_widget_drawing_embeddertest.cpp | 202 ++++++++++++++++++ public/epdf_annot.h | 8 +- testing/embedpdf_layer_mode_writers.txt | 1 + 6 files changed, 385 insertions(+), 19 deletions(-) diff --git a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp index d46b4e24f..d63232762 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include "constants/annotation_common.h" #include "constants/appearance.h" @@ -540,6 +541,119 @@ RetainPtr OwnAppearanceDict(CPDF_Document* doc, return annot_dict->GetOrCreateDictFor(pdfium::annotation::kAP); } +// A widget's new normal appearance: the stream |objnum|, for the state +// |state| (/Off, /Yes) or for a widget without states when |state| is empty. +struct NormalAppearance { + ByteString state; + uint32_t objnum; +}; + +// The stream a normal appearance (an /AP's /N) holds for |state|: the stream +// it is for a widget without states, else the one under the state's name. +RetainPtr NormalStreamFor(const CPDF_Object* normal, + const ByteString& state) { + if (!normal) { + return nullptr; + } + if (state.IsEmpty()) { + return pdfium::WrapRetain(normal->AsStream()); + } + const CPDF_Dictionary* states = + normal->IsStream() ? nullptr : normal->AsDictionary(); + return states ? states->GetStreamFor(state.AsStringView()) : nullptr; +} + +// Makes |key| (/R or /D) of a widget's own /AP name |appearance|'s stream +// where it named the stream |replaced|: the entry itself for a widget +// without states, else the entry's state. Its states may be an indirect +// object, which another widget may name too, so the widget gets a copy of +// them first. +void FollowReplacedStream(CPDF_Document* doc, + CPDF_Dictionary* ap, + const ByteString& key, + const NormalAppearance& appearance, + uint32_t replaced) { + RetainPtr entry = ap->GetObjectFor(key.AsStringView()); + if (!entry) { + return; + } + if (appearance.state.IsEmpty()) { + const CPDF_Reference* named = entry->AsReference(); + if (named && named->GetRefObjNum() == replaced) { + ap->SetNewFor(key, doc, appearance.objnum); + } + return; + } + RetainPtr held = + ap->GetDirectObjectFor(key.AsStringView()); + const CPDF_Dictionary* states = + held && !held->IsStream() ? held->AsDictionary() : nullptr; + if (!states) { + return; + } + RetainPtr member = + states->GetObjectFor(appearance.state.AsStringView()); + const CPDF_Reference* named = member ? member->AsReference() : nullptr; + if (!named || named->GetRefObjNum() != replaced) { + return; + } + if (entry->IsReference()) { + ap->SetFor(key, states->CloneForHolder(doc)); + } + ap->GetMutableDictFor(key.AsStringView()) + ->SetNewFor(appearance.state, doc, appearance.objnum); +} + +// Names a widget's new normal appearance, in an /AP of its own +// (OwnAppearanceDict()). The streams are new and the ones they replace are +// read only, so what the old appearance said beyond its drawing is said +// again here: +// - the layer it shows in: a new stream takes the /OC of the stream it +// replaces, the one of its state; +// - which other appearances are the same one: an /R or a /D that named the +// replaced stream, for the widget or for the state, names the new one. A +// rollover or pressed appearance made apart stays as it is. +void NameNormalAppearance(CPDF_Document* doc, + CPDF_Dictionary* annot_dict, + const std::vector& appearances) { + RetainPtr old_ap = + annot_dict->GetDictFor(pdfium::annotation::kAP); + RetainPtr old_normal = + old_ap ? old_ap->GetDirectObjectFor("N") : nullptr; + + RetainPtr ap = OwnAppearanceDict(doc, annot_dict); + for (const NormalAppearance& appearance : appearances) { + RetainPtr replaced = + NormalStreamFor(old_normal.Get(), appearance.state); + if (!replaced) { + continue; + } + RetainPtr layer = + replaced->GetDict()->GetObjectFor("OC"); + RetainPtr stream = + layer ? ToStream(doc->GetMutableIndirectObject(appearance.objnum)) + : nullptr; + if (stream) { + stream->GetMutableDict()->SetFor("OC", layer->CloneForHolder(doc)); + } + if (replaced->GetObjNum() != 0) { + for (const char* key : {"R", "D"}) { + FollowReplacedStream(doc, ap.Get(), key, appearance, + replaced->GetObjNum()); + } + } + } + + if (appearances.size() == 1 && appearances.front().state.IsEmpty()) { + ap->SetNewFor("N", doc, appearances.front().objnum); + return; + } + RetainPtr states = ap->SetNewFor("N"); + for (const NormalAppearance& appearance : appearances) { + states->SetNewFor(appearance.state, doc, appearance.objnum); + } +} + // True for a push button that draws no caption beside its icon: one that // shows its icon alone (/MK /TP 1), and one that shows both (2 to 6) when it // has an icon and no caption. GenerateIconButtonAP() draws these. @@ -1057,8 +1171,8 @@ void GenerateIconButtonAP(APGenerationTarget* target, } const uint32_t normal_obj_num = CreateFormXObjectStream( doc, content, dims.bbox, dims.matrix, std::move(resources)); - OwnAppearanceDict(doc, target->persistent_annot_dict) - ->SetNewFor("N", doc, normal_obj_num); + NameNormalAppearance(doc, target->persistent_annot_dict, + {{ByteString(), normal_obj_num}}); } bool GenerateFormAPToTarget(APGenerationTarget* target, @@ -1220,8 +1334,6 @@ bool GenerateFormAPToTarget(APGenerationTarget* target, // nothing of it is copied into a layer. RetainPtr normal_stream = doc->NewIndirect(pdfium::MakeRetain()); - OwnAppearanceDict(doc, annot_dict) - ->SetNewFor("N", doc, normal_stream->GetObjNum()); normal_stream->SetDataFromStringstreamAndRemoveFilter(&app_stream); RetainPtr stream_dict = normal_stream->GetMutableDict(); // A form XObject, said so: a stream made here has no type yet, and @@ -1236,6 +1348,8 @@ bool GenerateFormAPToTarget(APGenerationTarget* target, if (drawn_icon != 0) { NameButtonIcon(resources.Get(), doc, drawn_icon); } + NameNormalAppearance(doc, annot_dict, + {{ByteString(), normal_stream->GetObjNum()}}); return true; } @@ -1408,8 +1522,7 @@ void CPDF_AppearanceGenerator::GenerateBoxFormAP(CPDF_Document* doc, // too, or a drawing someone placed in this one. const uint32_t normal_obj_num = CreateFormXObjectStream(doc, content, dims.bbox, dims.matrix); - OwnAppearanceDict(doc, annot_dict) - ->SetNewFor("N", doc, normal_obj_num); + NameNormalAppearance(doc, annot_dict, {{ByteString(), normal_obj_num}}); } // static @@ -1460,9 +1573,8 @@ void CPDF_AppearanceGenerator::GenerateCheckboxFormAP( on_state = "Yes"; } - RetainPtr n_dict = ap_dict->SetNewFor("N"); - n_dict->SetNewFor("Off", doc, off_obj_num); - n_dict->SetNewFor(on_state, doc, yes_obj_num); + NameNormalAppearance(doc, annot_dict, + {{"Off", off_obj_num}, {on_state, yes_obj_num}}); if (!annot_dict->KeyExist("AS")) { annot_dict->SetNewFor("AS", "Off"); @@ -1574,9 +1686,8 @@ void CPDF_AppearanceGenerator::GenerateRadioButtonFormAP( } } - RetainPtr n_dict = ap_dict->SetNewFor("N"); - n_dict->SetNewFor("Off", doc, off_obj_num); - n_dict->SetNewFor(on_state, doc, yes_obj_num); + NameNormalAppearance(doc, annot_dict, + {{"Off", off_obj_num}, {on_state, yes_obj_num}}); if (!annot_dict->KeyExist("AS")) { annot_dict->SetNewFor("AS", "Off"); diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index 66e4f8271..777f42c4d 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -364,10 +364,13 @@ stream on every redraw, whatever kind the field is: the stream it had may be ano a picture a push button showed, so it is never written into, and the icon its resources named goes with it. It also stays as it reads, so a capture taken before the redraw (`public/epdf_capture.h`) brings the widget back with the appearance it named: an import never -replaces a stream the layer holds. 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` and `/BS` before a setter writes one (`OwnMKForWriting` and -`BorderStyleDictForWrite`, both through `OwnDictEntry`): another annotation may name the same +replaces a stream the layer holds. What the old appearance said beyond its drawing is said of +the new one (`NameNormalAppearance`): a new stream takes the `/OC` of the stream it replaces, and +an `/R` or a `/D` that named that stream, for the widget or for a state, names the new one. A +rollover or pressed appearance made apart stays. 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` 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 diff --git a/fpdfsdk/epdf_capture_embeddertest.cpp b/fpdfsdk/epdf_capture_embeddertest.cpp index e84c7cac3..c986c9c06 100644 --- a/fpdfsdk/epdf_capture_embeddertest.cpp +++ b/fpdfsdk/epdf_capture_embeddertest.cpp @@ -844,6 +844,53 @@ TEST_F(EPDFCaptureEmbedderTest, RedrawnFieldLeavesTheFilesAppearanceAlone) { EXPECT_EQ(file_bytes, RawBytesOf(layer.get(), kFileSquareAp)); } +// A rollover appearance that is the normal one follows a redraw to the new +// stream, and comes back with it: the capture taken before the write puts +// /AP back whole, naming under both keys the stream it named. +TEST_F(EPDFCaptureEmbedderTest, RedrawnFieldComesBackWithItsSameAppearances) { + ScopedFPDFDocument layer = OpenLayer(); + ASSERT_TRUE(layer); + // The stream the field's /AP names under |key|, or 0. + auto named = [&layer](const char* key) -> uint32_t { + RetainPtr dict = DictOf(layer.get(), kMergedField); + RetainPtr ap = + dict ? dict->GetDictFor("AP") : nullptr; + RetainPtr entry = ap ? ap->GetObjectFor(key) : nullptr; + const CPDF_Reference* ref = ToReference(entry.Get()); + return ref ? ref->GetRefObjNum() : 0; + }; + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + ASSERT_TRUE(Fill(layer.get(), kMergedField, L"Bea")); + const uint32_t before_ap = named("N"); + ASSERT_NE(0u, before_ap); + WritableDict(layer.get(), kMergedField) + ->GetMutableDictFor("AP") + ->SetNewFor( + "R", CPDFDocumentFromFPDFDocument(layer.get()), before_ap); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + const std::string before_bytes = RawBytesOf(layer.get(), before_ap); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + const std::vector capture = + ExportDict(layer.get(), kMergedField, "AP MK"); + ASSERT_FALSE(capture.empty()); + ASSERT_TRUE(Fill(layer.get(), kMergedField, L"Cyrus")); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + const uint32_t after_ap = named("N"); + ASSERT_NE(0u, after_ap); + EXPECT_NE(before_ap, after_ap); + EXPECT_EQ(after_ap, named("R")); + EXPECT_EQ(before_bytes, RawBytesOf(layer.get(), before_ap)); + + ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get())); + ASSERT_TRUE(ImportDict(layer.get(), capture)); + ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get())); + EXPECT_EQ(before_ap, named("N")); + EXPECT_EQ(before_ap, named("R")); + EXPECT_EQ(before_bytes, RawBytesOf(layer.get(), before_ap)); +} + // A dictionary captured without deep keys holds no objects: what it refers // to is kept as it is. TEST_F(EPDFCaptureEmbedderTest, ShallowDictionaryHoldsNoObjects) { diff --git a/fpdfsdk/epdf_widget_drawing_embeddertest.cpp b/fpdfsdk/epdf_widget_drawing_embeddertest.cpp index 70c02e46a..de7fde51e 100644 --- a/fpdfsdk/epdf_widget_drawing_embeddertest.cpp +++ b/fpdfsdk/epdf_widget_drawing_embeddertest.cpp @@ -3943,3 +3943,205 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconEntryThatNamesNoFormIsNoIcon) { ASSERT_TRUE(EPDFAnnot_ClearMKIcon(button.get(), EPDF_MK_ICON_I)); EXPECT_FALSE(DictOf(button.get())->GetDictFor("MK")->KeyExist("I")); } + +namespace { + +// The object number `dict` names under `key`, or 0 when the entry is no +// reference. +uint32_t NamedUnder(const CPDF_Dictionary* dict, ByteStringView key) { + RetainPtr entry = dict ? dict->GetObjectFor(key) : nullptr; + const CPDF_Reference* named = ToReference(entry.Get()); + return named ? named->GetRefObjNum() : 0; +} + +// A widget of the document below: its number, and the streams of its normal +// appearance as the file holds them, by state for a check box or a radio +// button. +struct FileWidget { + const char* kind; + uint32_t number = 0; + // Without states. + uint32_t normal = 0; + // With states: the two streams, and the dictionary of them /R names, an + // object of its own. + uint32_t yes = 0; + uint32_t off = 0; + uint32_t rollover_states = 0; +}; + +constexpr uint32_t kLayer = 6; + +// One page with a widget of every kind, each merged with its field. Every +// normal appearance is a stream in the layer `kLayer`, which is off. A widget +// without states names that one stream as /N, /R and /D. A check box and a +// radio button name their two under /N and under /D, and under /R a +// dictionary of the two that is an object of its own. The last widget, a +// text field, has a rollover appearance made apart. +std::string MakeEveryKind(std::vector* widgets, uint32_t* apart) { + std::vector objects = { + "", // 1: the catalog, written once the widgets have their numbers. + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "", // 3: the page, likewise. + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /ZapfDingbats >>", + "<< /Type /OCG /Name (Secret) >>", + }; + auto add = [&objects](std::string body) { + objects.push_back(std::move(body)); + return static_cast(objects.size()); + }; + auto ref = [](uint32_t number) { return std::to_string(number) + " 0 R"; }; + const std::string in_layer = + "/Type /XObject /Subtype /Form /BBox [0 0 160 24] /OC " + ref(kLayer); + auto widget = [&](const std::string& name, const std::string& entries, + int row, const std::string& ap) { + const int bottom = 20 + 30 * row; + return add("<< /Type /Annot /Subtype /Widget /T (" + name + ") " + entries + + " /DA (/Helv 12 Tf 0 g) /F 4 /Rect [20 " + + std::to_string(bottom) + " 180 " + std::to_string(bottom + 24) + + "] /P 3 0 R /AP << " + ap + " >> >>"); + }; + + struct Kind { + const char* name; + const char* entries; + bool states; + }; + static constexpr Kind kKinds[] = { + {"text", "/FT /Tx /V (Old)", false}, + {"combo", "/FT /Ch /Ff 131072 /Opt [(One) (Two)] /V (One)", false}, + {"list", "/FT /Ch /Opt [(One) (Two)] /V (One)", false}, + {"button", "/FT /Btn /Ff 65536 /MK << /CA (Go) >>", false}, + {"icon", "/FT /Btn /Ff 65536 /MK << /TP 1 >>", false}, + {"box", "/FT /Sig", false}, + {"check", "/FT /Btn /V /Off /AS /Off /MK << /CA (4) >>", true}, + {"radio", "/FT /Btn /Ff 32768 /V /Off /AS /Off", true}, + }; + int row = 0; + for (const Kind& kind : kKinds) { + FileWidget file{kind.name}; + if (kind.states) { + file.yes = add(Stream(in_layer, "0 0 1 rg 2 2 16 16 re f")); + file.off = add(Stream(in_layer, "0 0 1 RG 2 2 16 16 re S")); + const std::string both = + "<< /Yes " + ref(file.yes) + " /Off " + ref(file.off) + " >>"; + file.rollover_states = add(both); + file.number = widget( + kind.name, kind.entries, row++, + "/N " + both + " /D " + both + " /R " + ref(file.rollover_states)); + } else { + file.normal = add(Stream(in_layer, "0 0 1 rg 0 0 9 9 re f")); + const std::string one = ref(file.normal); + file.number = widget(kind.name, kind.entries, row++, + "/N " + one + " /R " + one + " /D " + one); + } + widgets->push_back(file); + } + FileWidget own{"apart"}; + own.normal = add(Stream(in_layer, "0 0 1 rg 0 0 9 9 re f")); + *apart = add(Stream("/Type /XObject /Subtype /Form /BBox [0 0 160 24]", + "1 0 0 rg 0 0 9 9 re f")); + own.number = widget("apart", "/FT /Tx /V (Old)", row++, + "/N " + ref(own.normal) + " /R " + ref(*apart)); + widgets->push_back(own); + + std::string all; + for (const FileWidget& file : *widgets) { + all += ref(file.number) + " "; + } + objects[0] = + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [" + all + + "] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 4 0 R /ZaDb 5 0 R >> >> " + ">> /OCProperties << /OCGs [" + + ref(kLayer) + "] /D << /OFF [" + ref(kLayer) + "] >> >> >>"; + objects[2] = + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 320] /Resources << >> " + "/Annots [" + + all + "] >>"; + return MakePdf(objects); +} + +} // namespace + +// A redraw of any kind of field gives the widget new streams, and what its +// appearance said beyond its drawing is said of them: each new stream is in +// the layer the stream it replaces was in, and a rollover or pressed +// appearance that was the normal one is the new normal one. A rollover +// appearance made apart stays, and so does a dictionary of states that is an +// object of its own, which another widget may name. +TEST_F(EPDFWidgetDrawingEmbedderTest, + ARedrawKeepsTheLayerAndTheSameAppearances) { + std::vector widgets; + uint32_t apart = 0; + const std::string bytes = MakeEveryKind(&widgets, &apart); + embedpdf_test::ScopedTestDocument doc(embedpdf_test::LoadMemDocumentForTest( + bytes.data(), bytes.size(), nullptr)); + ASSERT_TRUE(doc); + ScopedFPDFPage page(FPDF_LoadPage(doc.get(), 0)); + ASSERT_TRUE(page); + ASSERT_EQ(static_cast(widgets.size()), + FPDFPage_GetAnnotCount(page.get())); + for (int index = 0; index < FPDFPage_GetAnnotCount(page.get()); ++index) { + ScopedFPDFAnnotation annot(FPDFPage_GetAnnot(page.get(), index)); + ASSERT_TRUE(annot); + ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(annot.get())) + << widgets[index].kind; + } + + CPDF_Document* pdf = CPDFDocumentFromFPDFDocument(doc.get()); + auto dict_of = [pdf](uint32_t number) { + return ToDictionary(pdf->GetOrParseIndirectObject(number)); + }; + // The new stream `stream` stands for `replaced`: another object, in the + // same layer. + auto stands_for = [](const CPDF_Stream* stream, uint32_t replaced) { + return stream && stream->GetObjNum() != 0 && + stream->GetObjNum() != replaced && + NamedUnder(stream->GetDict().Get(), "OC") == kLayer; + }; + for (const FileWidget& file : widgets) { + SCOPED_TRACE(file.kind); + RetainPtr widget = dict_of(file.number); + ASSERT_TRUE(widget); + RetainPtr ap = widget->GetDictFor("AP"); + ASSERT_TRUE(ap); + if (file.yes == 0) { + RetainPtr normal = ap->GetStreamFor("N"); + EXPECT_TRUE(stands_for(normal.Get(), file.normal)); + if (std::string(file.kind) == "apart") { + EXPECT_EQ(apart, NamedUnder(ap.Get(), "R")); + continue; + } + const uint32_t drawn = normal ? normal->GetObjNum() : 0; + EXPECT_EQ(drawn, NamedUnder(ap.Get(), "R")); + EXPECT_EQ(drawn, NamedUnder(ap.Get(), "D")); + continue; + } + RetainPtr normal = + ToDictionary(ap->GetDirectObjectFor("N")); + RetainPtr pressed = + ToDictionary(ap->GetDirectObjectFor("D")); + RetainPtr rollover = + ToDictionary(ap->GetDirectObjectFor("R")); + ASSERT_TRUE(normal); + ASSERT_TRUE(pressed); + ASSERT_TRUE(rollover); + const std::pair states[] = {{"Yes", file.yes}, + {"Off", file.off}}; + for (const auto& [state, replaced] : states) { + SCOPED_TRACE(state); + RetainPtr stream = normal->GetStreamFor(state); + EXPECT_TRUE(stands_for(stream.Get(), replaced)); + const uint32_t drawn = stream ? stream->GetObjNum() : 0; + EXPECT_EQ(drawn, NamedUnder(pressed.Get(), state)); + EXPECT_EQ(drawn, NamedUnder(rollover.Get(), state)); + } + // The widget's /R is a copy of its own now. The object it named is as + // the file holds it. + EXPECT_EQ(0u, NamedUnder(ap.Get(), "R")); + RetainPtr shared = dict_of(file.rollover_states); + ASSERT_TRUE(shared); + EXPECT_EQ(file.yes, NamedUnder(shared.Get(), "Yes")); + EXPECT_EQ(file.off, NamedUnder(shared.Get(), "Off")); + } +} diff --git a/public/epdf_annot.h b/public/epdf_annot.h index 684bffde5..894bf964f 100644 --- a/public/epdf_annot.h +++ b/public/epdf_annot.h @@ -1786,9 +1786,11 @@ FPDF_EXPORT int FPDF_CALLCONV EPDFAnnot_GetMKRotation(FPDF_ANNOTATION annot); // still reaches. So a picture a button no longer names or draws is in no // file saved in full afterwards, and a widget put back from a capture taken // before the redraw (public/epdf_capture.h) names an appearance that reads -// as it did. A widget whose /AP is an indirect object, which another widget -// may name too, gets a copy of its own before an appearance in it is -// replaced. +// as it did. A new stream is in the layer (/OC) the stream it replaces was +// in, and a rollover or pressed appearance (/R, /D) that named that stream, +// for the widget or for a state, names the new one; one made apart stays as +// it is. A widget whose /AP is an indirect object, which another widget may +// name too, gets a copy of its own before an appearance in it is replaced. // // annot - handle to a widget annotation. // diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 334891394..1b4db657d 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -429,6 +429,7 @@ EPDFWidgetDrawingEmbedderTest.AMalformedEntryThatReadsAsTheValueIsWrittenAnew 25 EPDFWidgetDrawingEmbedderTest.AMarkIsPlacedAsAPageIsFitted 196 EPDFWidgetDrawingEmbedderTest.AMarkSavedBeforeThisChangeIsADrawing 13 EPDFWidgetDrawingEmbedderTest.APushButtonWithoutAnAppearanceIsNotDrawn 3 +EPDFWidgetDrawingEmbedderTest.ARedrawKeepsTheLayerAndTheSameAppearances 20 EPDFWidgetDrawingEmbedderTest.ARedrawnButtonCopiesNoOldAppearanceIntoALayer 3 EPDFWidgetDrawingEmbedderTest.ARefitKeepsTheDrawingShared 16 EPDFWidgetDrawingEmbedderTest.AReopenedFilePlacesItsDrawingAgain 14