Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 133 additions & 28 deletions core/fpdfdoc/cpdf_appearancegenerator_forms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <optional>
#include <sstream>
#include <utility>
#include <vector>

#include "constants/annotation_common.h"
#include "constants/appearance.h"
Expand Down Expand Up @@ -540,6 +541,119 @@ RetainPtr<CPDF_Dictionary> 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<const CPDF_Stream> 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<const CPDF_Object> 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<CPDF_Reference>(key, doc, appearance.objnum);
}
return;
}
RetainPtr<const CPDF_Object> held =
ap->GetDirectObjectFor(key.AsStringView());
const CPDF_Dictionary* states =
held && !held->IsStream() ? held->AsDictionary() : nullptr;
if (!states) {
return;
}
RetainPtr<const CPDF_Object> 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<CPDF_Reference>(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<NormalAppearance>& appearances) {
RetainPtr<const CPDF_Dictionary> old_ap =
annot_dict->GetDictFor(pdfium::annotation::kAP);
RetainPtr<const CPDF_Object> old_normal =
old_ap ? old_ap->GetDirectObjectFor("N") : nullptr;

RetainPtr<CPDF_Dictionary> ap = OwnAppearanceDict(doc, annot_dict);
for (const NormalAppearance& appearance : appearances) {
RetainPtr<const CPDF_Stream> replaced =
NormalStreamFor(old_normal.Get(), appearance.state);
if (!replaced) {
continue;
}
RetainPtr<const CPDF_Object> layer =
replaced->GetDict()->GetObjectFor("OC");
RetainPtr<CPDF_Stream> 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<CPDF_Reference>("N", doc, appearances.front().objnum);
return;
}
RetainPtr<CPDF_Dictionary> states = ap->SetNewFor<CPDF_Dictionary>("N");
for (const NormalAppearance& appearance : appearances) {
states->SetNewFor<CPDF_Reference>(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.
Expand Down Expand Up @@ -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<CPDF_Reference>("N", doc, normal_obj_num);
NameNormalAppearance(doc, target->persistent_annot_dict,
{{ByteString(), normal_obj_num}});
}

bool GenerateFormAPToTarget(APGenerationTarget* target,
Expand Down Expand Up @@ -1209,25 +1323,17 @@ 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<CPDF_Stream> normal_stream;
if (type != CPDF_AppearanceGenerator::kPushButton) {
RetainPtr<CPDF_Dictionary> ap_dict =
annot_dict->GetMutableDictFor(pdfium::annotation::kAP);
normal_stream = ap_dict ? ap_dict->GetMutableStreamFor("N") : nullptr;
}
if (!normal_stream) {
normal_stream =
doc->NewIndirect<CPDF_Stream>(pdfium::MakeRetain<CPDF_Dictionary>());
OwnAppearanceDict(doc, annot_dict)
->SetNewFor<CPDF_Reference>("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<CPDF_Stream> normal_stream =
doc->NewIndirect<CPDF_Stream>(pdfium::MakeRetain<CPDF_Dictionary>());
normal_stream->SetDataFromStringstreamAndRemoveFilter(&app_stream);
RetainPtr<CPDF_Dictionary> stream_dict = normal_stream->GetMutableDict();
// A form XObject, said so: a stream made here has no type yet, and
Expand All @@ -1242,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;
}

Expand Down Expand Up @@ -1414,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<CPDF_Reference>("N", doc, normal_obj_num);
NameNormalAppearance(doc, annot_dict, {{ByteString(), normal_obj_num}});
}

// static
Expand Down Expand Up @@ -1466,9 +1573,8 @@ void CPDF_AppearanceGenerator::GenerateCheckboxFormAP(
on_state = "Yes";
}

RetainPtr<CPDF_Dictionary> n_dict = ap_dict->SetNewFor<CPDF_Dictionary>("N");
n_dict->SetNewFor<CPDF_Reference>("Off", doc, off_obj_num);
n_dict->SetNewFor<CPDF_Reference>(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<CPDF_Name>("AS", "Off");
Expand Down Expand Up @@ -1580,9 +1686,8 @@ void CPDF_AppearanceGenerator::GenerateRadioButtonFormAP(
}
}

RetainPtr<CPDF_Dictionary> n_dict = ap_dict->SetNewFor<CPDF_Dictionary>("N");
n_dict->SetNewFor<CPDF_Reference>("Off", doc, off_obj_num);
n_dict->SetNewFor<CPDF_Reference>(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<CPDF_Name>("AS", "Off");
Expand Down
20 changes: 13 additions & 7 deletions docs/embedpdf/fork-ledger.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,13 +359,19 @@ 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. 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
when the entry is well formed and reads as the value (three numbers from 0 to 1, a string, an
Expand Down
138 changes: 138 additions & 0 deletions fpdfsdk/epdf_capture_embeddertest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -753,6 +763,134 @@ 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<uint8_t> 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<CPDF_Dictionary>("AP")
->SetNewFor<CPDF_Reference>(
"N", CPDFDocumentFromFPDFDocument(layer.get()), kFileSquareAp);
ASSERT_TRUE(EPDFLayer_CommitTransaction(layer.get()));

ASSERT_TRUE(EPDFLayer_BeginTransaction(layer.get()));
const std::vector<uint8_t> 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 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<const CPDF_Dictionary> dict = DictOf(layer.get(), kMergedField);
RetainPtr<const CPDF_Dictionary> ap =
dict ? dict->GetDictFor("AP") : nullptr;
RetainPtr<const CPDF_Object> 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<CPDF_Reference>(
"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<uint8_t> 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) {
Expand Down
Loading