Coverage Report

Created: 2026-01-09 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFAcroFormDocumentHelper.cc
Line
Count
Source
1
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
2
3
#include <qpdf/AcroForm.hh>
4
5
#include <qpdf/Pl_Buffer.hh>
6
#include <qpdf/QPDFObjectHandle_private.hh>
7
#include <qpdf/QPDFPageDocumentHelper.hh>
8
#include <qpdf/QPDF_private.hh>
9
#include <qpdf/QTC.hh>
10
#include <qpdf/QUtil.hh>
11
#include <qpdf/ResourceFinder.hh>
12
#include <qpdf/Util.hh>
13
14
#include <deque>
15
#include <utility>
16
17
using namespace qpdf;
18
using namespace qpdf::impl;
19
using namespace std::literals;
20
21
using AcroForm = impl::AcroForm;
22
23
QPDFAcroFormDocumentHelper::QPDFAcroFormDocumentHelper(QPDF& qpdf) :
24
0
    QPDFDocumentHelper(qpdf),
25
0
    m(std::make_shared<Members>(qpdf))
26
0
{
27
0
}
28
29
QPDFAcroFormDocumentHelper&
30
QPDFAcroFormDocumentHelper::get(QPDF& qpdf)
31
0
{
32
0
    return qpdf.doc().acroform_dh();
33
0
}
34
35
void
36
QPDFAcroFormDocumentHelper::validate(bool repair)
37
0
{
38
0
    m->validate(repair);
39
0
}
40
41
void
42
AcroForm::validate(bool repair)
43
0
{
44
0
    invalidateCache();
45
0
    analyze();
46
0
}
47
48
void
49
QPDFAcroFormDocumentHelper::invalidateCache()
50
0
{
51
0
    m->invalidateCache();
52
0
}
53
54
void
55
AcroForm::invalidateCache()
56
0
{
57
0
    cache_valid_ = false;
58
0
    fields_.clear();
59
0
    annotation_to_field_.clear();
60
0
    bad_fields_.clear();
61
0
    name_to_fields_.clear();
62
0
}
63
64
bool
65
QPDFAcroFormDocumentHelper::hasAcroForm()
66
0
{
67
0
    return m->hasAcroForm();
68
0
}
69
70
bool
71
AcroForm::hasAcroForm()
72
0
{
73
0
    return qpdf.getRoot().hasKey("/AcroForm");
74
0
}
75
76
QPDFObjectHandle
77
AcroForm::getOrCreateAcroForm()
78
0
{
79
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
80
0
    if (!acroform.isDictionary()) {
81
0
        acroform = qpdf.getRoot().replaceKeyAndGetNew(
82
0
            "/AcroForm", qpdf.makeIndirectObject(QPDFObjectHandle::newDictionary()));
83
0
    }
84
0
    return acroform;
85
0
}
86
87
void
88
QPDFAcroFormDocumentHelper::addFormField(QPDFFormFieldObjectHelper ff)
89
0
{
90
0
    m->addFormField(ff);
91
0
}
92
93
void
94
AcroForm::addFormField(QPDFFormFieldObjectHelper ff)
95
0
{
96
0
    auto acroform = getOrCreateAcroForm();
97
0
    auto fields = acroform.getKey("/Fields");
98
0
    if (!fields.isArray()) {
99
0
        fields = acroform.replaceKeyAndGetNew("/Fields", QPDFObjectHandle::newArray());
100
0
    }
101
0
    fields.appendItem(ff.getObjectHandle());
102
0
    traverseField(ff.getObjectHandle(), {}, 0);
103
0
}
104
105
void
106
QPDFAcroFormDocumentHelper::addAndRenameFormFields(std::vector<QPDFObjectHandle> fields)
107
0
{
108
0
    m->addAndRenameFormFields(fields);
109
0
}
110
111
void
112
AcroForm::addAndRenameFormFields(std::vector<QPDFObjectHandle> fields)
113
0
{
114
0
    analyze();
115
0
    std::map<std::string, std::string> renames;
116
0
    QPDFObjGen::set seen;
117
0
    for (std::list<QPDFObjectHandle> queue{fields.begin(), fields.end()}; !queue.empty();
118
0
         queue.pop_front()) {
119
0
        auto& obj = queue.front();
120
0
        if (seen.add(obj)) {
121
0
            auto kids = obj.getKey("/Kids");
122
0
            if (kids.isArray()) {
123
0
                for (auto const& kid: kids.aitems()) {
124
0
                    queue.push_back(kid);
125
0
                }
126
0
            }
127
128
0
            if (obj.hasKey("/T")) {
129
                // Find something we can append to the partial name that makes the fully qualified
130
                // name unique. When we find something, reuse the same suffix for all fields in this
131
                // group with the same name. We can only change the name of fields that have /T, and
132
                // this field's /T is always at the end of the fully qualified name, appending to /T
133
                // has the effect of appending the same thing to the fully qualified name.
134
0
                std::string old_name = QPDFFormFieldObjectHelper(obj).getFullyQualifiedName();
135
0
                if (!renames.contains(old_name)) {
136
0
                    std::string new_name = old_name;
137
0
                    int suffix = 0;
138
0
                    std::string append;
139
0
                    while (!getFieldsWithQualifiedName(new_name).empty()) {
140
0
                        ++suffix;
141
0
                        append = "+" + std::to_string(suffix);
142
0
                        new_name = old_name + append;
143
0
                    }
144
0
                    renames[old_name] = append;
145
0
                }
146
0
                std::string append = renames[old_name];
147
0
                if (!append.empty()) {
148
0
                    obj.replaceKey(
149
0
                        "/T",
150
0
                        QPDFObjectHandle::newUnicodeString(
151
0
                            obj.getKey("/T").getUTF8Value() + append));
152
0
                }
153
0
            }
154
0
        }
155
0
    }
156
157
0
    for (auto const& i: fields) {
158
0
        addFormField(i);
159
0
    }
160
0
}
161
162
void
163
QPDFAcroFormDocumentHelper::removeFormFields(std::set<QPDFObjGen> const& to_remove)
164
0
{
165
0
    m->removeFormFields(to_remove);
166
0
}
167
168
void
169
AcroForm::removeFormFields(std::set<QPDFObjGen> const& to_remove)
170
0
{
171
0
    auto acroform = qpdf.getRoot().getKey("/AcroForm");
172
0
    if (!acroform.isDictionary()) {
173
0
        return;
174
0
    }
175
0
    auto fields = acroform.getKey("/Fields");
176
0
    if (!fields.isArray()) {
177
0
        return;
178
0
    }
179
180
0
    for (auto const& og: to_remove) {
181
0
        auto it = fields_.find(og);
182
0
        if (it != fields_.end()) {
183
0
            for (auto aoh: it->second.annotations) {
184
0
                annotation_to_field_.erase(aoh.getObjectHandle().getObjGen());
185
0
            }
186
0
            auto const& name = it->second.name;
187
0
            if (!name.empty()) {
188
0
                name_to_fields_[name].erase(og);
189
0
                if (name_to_fields_[name].empty()) {
190
0
                    name_to_fields_.erase(name);
191
0
                }
192
0
            }
193
0
            fields_.erase(og);
194
0
        }
195
0
    }
196
197
0
    int i = 0;
198
0
    while (std::cmp_less(i, fields.size())) {
199
0
        auto field = fields.getArrayItem(i);
200
0
        if (to_remove.contains(field.getObjGen())) {
201
0
            fields.eraseItem(i);
202
0
        } else {
203
0
            ++i;
204
0
        }
205
0
    }
206
0
}
207
208
void
209
QPDFAcroFormDocumentHelper::setFormFieldName(QPDFFormFieldObjectHelper ff, std::string const& name)
210
0
{
211
0
    m->setFormFieldName(ff, name);
212
0
}
213
214
void
215
AcroForm::setFormFieldName(QPDFFormFieldObjectHelper ff, std::string const& name)
216
0
{
217
0
    ff.setFieldAttribute("/T", name);
218
0
    traverseField(ff, ff["/Parent"], 0);
219
0
}
220
221
std::vector<QPDFFormFieldObjectHelper>
222
QPDFAcroFormDocumentHelper::getFormFields()
223
0
{
224
0
    return m->getFormFields();
225
0
}
226
227
std::vector<QPDFFormFieldObjectHelper>
228
AcroForm::getFormFields()
229
0
{
230
0
    analyze();
231
0
    std::vector<QPDFFormFieldObjectHelper> result;
232
0
    for (auto const& [og, data]: fields_) {
233
0
        if (!data.annotations.empty()) {
234
0
            result.emplace_back(qpdf.getObject(og));
235
0
        }
236
0
    }
237
0
    return result;
238
0
}
239
240
std::set<QPDFObjGen>
241
QPDFAcroFormDocumentHelper::getFieldsWithQualifiedName(std::string const& name)
242
0
{
243
0
    return m->getFieldsWithQualifiedName(name);
244
0
}
245
246
std::set<QPDFObjGen>
247
AcroForm::getFieldsWithQualifiedName(std::string const& name)
248
0
{
249
0
    analyze();
250
    // Keep from creating an empty entry
251
0
    auto iter = name_to_fields_.find(name);
252
0
    if (iter != name_to_fields_.end()) {
253
0
        return iter->second;
254
0
    }
255
0
    return {};
256
0
}
257
258
std::vector<QPDFAnnotationObjectHelper>
259
QPDFAcroFormDocumentHelper::getAnnotationsForField(QPDFFormFieldObjectHelper h)
260
0
{
261
0
    return m->getAnnotationsForField(h);
262
0
}
263
264
std::vector<QPDFAnnotationObjectHelper>
265
AcroForm::getAnnotationsForField(QPDFFormFieldObjectHelper h)
266
0
{
267
0
    analyze();
268
0
    std::vector<QPDFAnnotationObjectHelper> result;
269
0
    QPDFObjGen og(h.getObjectHandle().getObjGen());
270
0
    if (fields_.contains(og)) {
271
0
        result = fields_[og].annotations;
272
0
    }
273
0
    return result;
274
0
}
275
276
std::vector<QPDFAnnotationObjectHelper>
277
QPDFAcroFormDocumentHelper::getWidgetAnnotationsForPage(QPDFPageObjectHelper h)
278
0
{
279
0
    return m->getWidgetAnnotationsForPage(h);
280
0
}
281
282
std::vector<QPDFAnnotationObjectHelper>
283
AcroForm::getWidgetAnnotationsForPage(QPDFPageObjectHelper h)
284
0
{
285
0
    return h.getAnnotations("/Widget");
286
0
}
287
288
std::vector<QPDFFormFieldObjectHelper>
289
QPDFAcroFormDocumentHelper::getFormFieldsForPage(QPDFPageObjectHelper ph)
290
0
{
291
0
    return m->getFormFieldsForPage(ph);
292
0
}
293
294
std::vector<QPDFFormFieldObjectHelper>
295
AcroForm::getFormFieldsForPage(QPDFPageObjectHelper ph)
296
0
{
297
0
    analyze();
298
0
    QPDFObjGen::set todo;
299
0
    std::vector<QPDFFormFieldObjectHelper> result;
300
0
    for (auto& annot: getWidgetAnnotationsForPage(ph)) {
301
0
        auto field = getFieldForAnnotation(annot).getTopLevelField();
302
0
        if (todo.add(field) && field.getObjectHandle().isDictionary()) {
303
0
            result.push_back(field);
304
0
        }
305
0
    }
306
0
    return result;
307
0
}
308
309
QPDFFormFieldObjectHelper
310
QPDFAcroFormDocumentHelper::getFieldForAnnotation(QPDFAnnotationObjectHelper h)
311
0
{
312
0
    return m->getFieldForAnnotation(h);
313
0
}
314
315
QPDFFormFieldObjectHelper
316
AcroForm::getFieldForAnnotation(QPDFAnnotationObjectHelper h)
317
0
{
318
0
    QPDFObjectHandle oh = h.getObjectHandle();
319
0
    if (!oh.isDictionaryOfType("", "/Widget")) {
320
0
        return Null::temp();
321
0
    }
322
0
    analyze();
323
0
    QPDFObjGen og(oh.getObjGen());
324
0
    if (annotation_to_field_.contains(og)) {
325
0
        return annotation_to_field_[og];
326
0
    }
327
0
    return Null::temp();
328
0
}
329
330
void
331
AcroForm::analyze()
332
0
{
333
0
    if (cache_valid_) {
334
0
        return;
335
0
    }
336
0
    cache_valid_ = true;
337
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
338
0
    if (!(acroform.isDictionary() && acroform.hasKey("/Fields"))) {
339
0
        return;
340
0
    }
341
0
    QPDFObjectHandle fields = acroform.getKey("/Fields");
342
0
    if (Array fa = fields) {
343
        // Traverse /AcroForm to find annotations and map them bidirectionally to fields.
344
0
        for (auto const& field: fa) {
345
0
            traverseField(field, {}, 0);
346
0
        }
347
0
    } else {
348
0
        acroform.warn("/Fields key of /AcroForm dictionary is not an array; ignoring");
349
0
        fields = Array::empty();
350
0
    }
351
352
    // All Widget annotations should have been encountered by traversing /AcroForm, but in case any
353
    // weren't, find them by walking through pages, and treat any widget annotation that is not
354
    // associated with a field as its own field. This just ensures that requesting the field for any
355
    // annotation we find through a page's /Annots list will have some associated field. Note that
356
    // a file that contains this kind of error will probably not
357
    // actually work with most viewers.
358
359
0
    for (QPDFPageObjectHelper ph: pages) {
360
0
        for (auto const& iter: getWidgetAnnotationsForPage(ph)) {
361
0
            QPDFObjectHandle annot(iter.getObjectHandle());
362
0
            QPDFObjGen og(annot.getObjGen());
363
0
            if (!annotation_to_field_.contains(og)) {
364
                // This is not supposed to happen, but it's easy enough for us to handle this case.
365
                // Treat the annotation as its own field. This could allow qpdf to sensibly handle a
366
                // case such as a PDF creator adding a self-contained annotation (merged with the
367
                // field dictionary) to the page's /Annots array and forgetting to also put it in
368
                // /AcroForm.
369
0
                annot.warn(
370
0
                    "this widget annotation is not reachable from /AcroForm in the document "
371
0
                    "catalog");
372
0
                annotation_to_field_[og] = QPDFFormFieldObjectHelper(annot);
373
0
                fields_[og].annotations.emplace_back(annot);
374
0
            }
375
0
        }
376
0
    }
377
0
}
378
379
bool
380
AcroForm::traverseField(QPDFObjectHandle field, QPDFObjectHandle const& parent, int depth)
381
0
{
382
0
    if (depth > 100) {
383
        // Arbitrarily cut off recursion at a fixed depth to avoid specially crafted files that
384
        // could cause stack overflow.
385
0
        return false;
386
0
    }
387
0
    if (!field.indirect()) {
388
0
        field.warn(
389
0
            "encountered a direct object as a field or annotation while traversing /AcroForm; "
390
0
            "ignoring field or annotation");
391
0
        return false;
392
0
    }
393
0
    if (field == parent) {
394
0
        field.warn("loop detected while traversing /AcroForm");
395
0
        return false;
396
0
    }
397
0
    if (!field.isDictionary()) {
398
0
        field.warn(
399
0
            "encountered a non-dictionary as a field or annotation while traversing /AcroForm; "
400
0
            "ignoring field or annotation");
401
0
        return false;
402
0
    }
403
0
    QPDFObjGen og(field.getObjGen());
404
0
    if (fields_.contains(og) || annotation_to_field_.contains(og) || bad_fields_.contains(og)) {
405
0
        field.warn("loop detected while traversing /AcroForm");
406
0
        return false;
407
0
    }
408
409
    // A dictionary encountered while traversing the /AcroForm field may be a form field, an
410
    // annotation, or the merger of the two. A field that has no fields below it is a terminal. If a
411
    // terminal field looks like an annotation, it is an annotation because annotation dictionary
412
    // fields can be merged with terminal field dictionaries. Otherwise, the annotation fields might
413
    // be there to be inherited by annotations below it.
414
415
0
    FormNode node = field;
416
0
    const bool is_field = node.field();
417
0
    const bool is_annotation = node.widget();
418
419
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper field found", (depth == 0) ? 0 : 1);
420
0
    QTC::TC("qpdf", "QPDFAcroFormDocumentHelper annotation found", (is_field ? 0 : 1));
421
422
0
    if (!is_field && !is_annotation) {
423
0
        field.warn(
424
0
            "encountered an object that is neither field nor annotation while traversing "
425
0
            "/AcroForm");
426
0
        return false;
427
0
    }
428
429
0
    if (is_annotation) {
430
0
        auto our_field = (is_field ? field : parent);
431
0
        fields_[our_field].annotations.emplace_back(field);
432
0
        annotation_to_field_[og] = QPDFFormFieldObjectHelper(our_field);
433
0
    }
434
435
0
    if (!is_field) {
436
0
        return true;
437
0
    }
438
439
0
    if (depth != 0 && field["/Parent"] != parent) {
440
0
        for (auto const& kid: Array(field["/Parent"]["/Kids"])) {
441
0
            if (kid == field) {
442
0
                field.warn("while traversing /AcroForm found field with two parents");
443
0
                return true;
444
0
            }
445
0
        }
446
0
        for (auto const& kid: Array(field["/Parent"]["/Kids"])) {
447
0
            if (kid == parent) {
448
0
                field.warn("loop detected while traversing /AcroForm");
449
0
                return false;
450
0
            }
451
0
        }
452
0
        field.warn("encountered invalid /Parent entry while traversing /AcroForm; correcting");
453
0
        field.replaceKey("/Parent", parent);
454
0
    }
455
456
0
    if (node.T()) {
457
0
        auto old = fields_.find(og);
458
0
        if (old != fields_.end() && !old->second.name.empty()) {
459
            // We might be updating after a name change, so remove any old information
460
0
            name_to_fields_[old->second.name].erase(og);
461
0
        }
462
0
        std::string name = node.fully_qualified_name();
463
0
        fields_[og].name = name;
464
0
        name_to_fields_[name].insert(og);
465
0
    }
466
467
0
    for (auto const& kid: node.Kids()) {
468
0
        if (bad_fields_.contains(kid)) {
469
0
            continue;
470
0
        }
471
472
0
        if (!traverseField(kid, field, 1 + depth)) {
473
0
            bad_fields_.insert(kid);
474
0
        }
475
0
    }
476
0
    return true;
477
0
}
478
479
bool
480
QPDFAcroFormDocumentHelper::getNeedAppearances()
481
0
{
482
0
    return m->getNeedAppearances();
483
0
}
484
485
bool
486
AcroForm::getNeedAppearances()
487
0
{
488
0
    bool result = false;
489
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
490
0
    if (acroform.isDictionary() && acroform.getKey("/NeedAppearances").isBool()) {
491
0
        result = acroform.getKey("/NeedAppearances").getBoolValue();
492
0
    }
493
0
    return result;
494
0
}
495
496
void
497
QPDFAcroFormDocumentHelper::setNeedAppearances(bool val)
498
0
{
499
0
    m->setNeedAppearances(val);
500
0
}
501
502
void
503
AcroForm::setNeedAppearances(bool val)
504
0
{
505
0
    QPDFObjectHandle acroform = qpdf.getRoot().getKey("/AcroForm");
506
0
    if (!acroform.isDictionary()) {
507
0
        qpdf.getRoot().warn(
508
0
            "ignoring call to QPDFAcroFormDocumentHelper::setNeedAppearances"
509
0
            " on a file that lacks an /AcroForm dictionary");
510
0
        return;
511
0
    }
512
0
    if (val) {
513
0
        acroform.replaceKey("/NeedAppearances", QPDFObjectHandle::newBool(true));
514
0
    } else {
515
0
        acroform.removeKey("/NeedAppearances");
516
0
    }
517
0
}
518
519
void
520
QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded()
521
0
{
522
0
    m->generateAppearancesIfNeeded();
523
0
}
524
525
void
526
AcroForm::generateAppearancesIfNeeded()
527
0
{
528
0
    if (!getNeedAppearances()) {
529
0
        return;
530
0
    }
531
532
0
    for (auto const& page: QPDFPageDocumentHelper(qpdf).getAllPages()) {
533
0
        for (auto& aoh: getWidgetAnnotationsForPage(page)) {
534
0
            QPDFFormFieldObjectHelper ffh = getFieldForAnnotation(aoh);
535
0
            if (ffh.getFieldType() == "/Btn") {
536
                // Rather than generating appearances for button fields, rely on what's already
537
                // there. Just make sure /AS is consistent with /V, which we can do by resetting the
538
                // value of the field back to itself. This code is referenced in a comment in
539
                // QPDFFormFieldObjectHelper::generateAppearance.
540
0
                if (ffh.isRadioButton() || ffh.isCheckbox()) {
541
0
                    ffh.setV(ffh.getValue());
542
0
                }
543
0
            } else {
544
0
                ffh.generateAppearance(aoh);
545
0
            }
546
0
        }
547
0
    }
548
0
    setNeedAppearances(false);
549
0
}
550
551
void
552
QPDFAcroFormDocumentHelper::disableDigitalSignatures()
553
0
{
554
0
    m->disableDigitalSignatures();
555
0
}
556
557
void
558
AcroForm::disableDigitalSignatures()
559
0
{
560
0
    qpdf.removeSecurityRestrictions();
561
0
    std::set<QPDFObjGen> to_remove;
562
0
    auto fields = getFormFields();
563
0
    for (auto& f: fields) {
564
0
        auto ft = f.getFieldType();
565
0
        if (ft == "/Sig") {
566
0
            auto oh = f.getObjectHandle();
567
0
            to_remove.insert(oh.getObjGen());
568
            // Make this no longer a form field. If it's also an annotation, the annotation will
569
            // survive. If it's only a field and is no longer referenced, it will disappear.
570
0
            oh.removeKey("/FT");
571
            // Remove fields that are specific to signature fields.
572
0
            oh.removeKey("/V");
573
0
            oh.removeKey("/SV");
574
0
            oh.removeKey("/Lock");
575
0
        }
576
0
    }
577
0
    removeFormFields(to_remove);
578
0
}
579
580
void
581
AcroForm::adjustInheritedFields(
582
    QPDFObjectHandle obj,
583
    bool override_da,
584
    std::string const& from_default_da,
585
    bool override_q,
586
    int from_default_q)
587
0
{
588
0
    if (!(override_da || override_q)) {
589
0
        return;
590
0
    }
591
    // Override /Q or /DA if needed. If this object has a field type, directly or inherited, it is a
592
    // field and not just an annotation. In that case, we need to override if we are getting a value
593
    // from the document that is different from the value we would have gotten from the old
594
    // document. We must take care not to override an explicit value. It's possible that /FT may be
595
    // inherited by lower fields that may explicitly set /DA or /Q or that this is a field whose
596
    // type does not require /DA or /Q and we may be put a value on the field that is unused. This
597
    // is harmless, so it's not worth trying to work around.
598
599
0
    auto has_explicit = [](QPDFFormFieldObjectHelper& field, std::string const& key) {
600
0
        if (field.getObjectHandle().hasKey(key)) {
601
0
            return true;
602
0
        }
603
0
        return !field.getInheritableFieldValue(key).null();
604
0
    };
605
606
0
    if (override_da || override_q) {
607
0
        QPDFFormFieldObjectHelper cur_field(obj);
608
0
        if (override_da && (!has_explicit(cur_field, "/DA"))) {
609
0
            std::string da = cur_field.getDefaultAppearance();
610
0
            if (da != from_default_da) {
611
0
                obj.replaceKey("/DA", QPDFObjectHandle::newUnicodeString(from_default_da));
612
0
            }
613
0
        }
614
0
        if (override_q && (!has_explicit(cur_field, "/Q"))) {
615
0
            int q = cur_field.getQuadding();
616
0
            if (q != from_default_q) {
617
0
                obj.replaceKey("/Q", QPDFObjectHandle::newInteger(from_default_q));
618
0
            }
619
0
        }
620
0
    }
621
0
}
622
623
namespace
624
{
625
    class ResourceReplacer: public QPDFObjectHandle::TokenFilter
626
    {
627
      public:
628
        ResourceReplacer(
629
            std::map<std::string, std::map<std::string, std::string>> const& dr_map,
630
            std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames);
631
0
        ~ResourceReplacer() override = default;
632
        void handleToken(QPDFTokenizer::Token const&) override;
633
634
      private:
635
        size_t offset{0};
636
        std::map<std::string, std::map<size_t, std::string>> to_replace;
637
    };
638
} // namespace
639
640
ResourceReplacer::ResourceReplacer(
641
    std::map<std::string, std::map<std::string, std::string>> const& dr_map,
642
    std::map<std::string, std::map<std::string, std::vector<size_t>>> const& rnames)
643
0
{
644
    // We have:
645
    // * dr_map[resource_type][key] == new_key
646
    // * rnames[resource_type][key] == set of offsets
647
    //
648
    // We want:
649
    // * to_replace[key][offset] = new_key
650
651
0
    for (auto const& [rtype, key_offsets]: rnames) {
652
0
        auto dr_map_rtype = dr_map.find(rtype);
653
0
        if (dr_map_rtype == dr_map.end()) {
654
0
            continue;
655
0
        }
656
0
        for (auto const& [old_key, offsets]: key_offsets) {
657
0
            auto dr_map_rtype_old = dr_map_rtype->second.find(old_key);
658
0
            if (dr_map_rtype_old == dr_map_rtype->second.end()) {
659
0
                continue;
660
0
            }
661
0
            for (auto const& offs: offsets) {
662
0
                to_replace[old_key][offs] = dr_map_rtype_old->second;
663
0
            }
664
0
        }
665
0
    }
666
0
}
667
668
void
669
ResourceReplacer::handleToken(QPDFTokenizer::Token const& token)
670
0
{
671
0
    if (token.getType() == QPDFTokenizer::tt_name) {
672
0
        auto it1 = to_replace.find(token.getValue());
673
0
        if (it1 != to_replace.end()) {
674
0
            auto it2 = it1->second.find(offset);
675
0
            if (it2 != it1->second.end()) {
676
0
                QTC::TC("qpdf", "QPDFAcroFormDocumentHelper replaced DA token");
677
0
                write(it2->second);
678
0
                offset += token.getRawValue().length();
679
0
                return;
680
0
            }
681
0
        }
682
0
    }
683
0
    offset += token.getRawValue().length();
684
0
    writeToken(token);
685
0
}
686
687
void
688
AcroForm::adjustDefaultAppearances(
689
    QPDFObjectHandle obj, std::map<std::string, std::map<std::string, std::string>> const& dr_map)
690
0
{
691
    // This method is called on a field that has been copied from another file but whose /DA still
692
    // refers to resources in the original file's /DR.
693
694
    // When appearance streams are generated for variable text fields (see ISO 32000 PDF spec
695
    // section 12.7.3.3), the field's /DA is used to generate content of the appearance stream. /DA
696
    // contains references to resources that may be resolved in the document's /DR dictionary, which
697
    // appears in the document's /AcroForm dictionary. For fields that we copied from other
698
    // documents, we need to ensure that resources are mapped correctly in the case of conflicting
699
    // names. For example, if a.pdf's /DR has /F1 pointing to one font and b.pdf's /DR also has /F1
700
    // but it points elsewhere, we need to make sure appearance streams of fields copied from b.pdf
701
    // into a.pdf use whatever font /F1 meant in b.pdf, not whatever it means in a.pdf. This method
702
    // takes care of that. It is only called on fields copied from foreign files.
703
704
    // A few notes:
705
    //
706
    // * If the from document's /DR and the current document's /DR have conflicting keys, we have
707
    //   already resolved the conflicts before calling this method. The dr_map parameter contains
708
    //   the mapping from old keys to new keys.
709
    //
710
    // * /DA may be inherited from the document's /AcroForm dictionary. By the time this method has
711
    //   been called, we have already copied any document-level values into the fields to avoid
712
    //   having them inherit from the new document. This was done in adjustInheritedFields.
713
714
0
    auto DA = obj.getKey("/DA");
715
0
    if (!DA.isString()) {
716
0
        return;
717
0
    }
718
719
    // Find names in /DA. /DA is a string that contains content stream-like code, so we create a
720
    // stream out of the string and then filter it. We don't attach the stream to anything, so it
721
    // will get discarded.
722
0
    ResourceFinder rf;
723
0
    auto da_stream = QPDFObjectHandle::newStream(&qpdf, DA.getUTF8Value());
724
0
    try {
725
0
        auto nwarnings = qpdf.numWarnings();
726
0
        da_stream.parseAsContents(&rf);
727
0
        if (qpdf.numWarnings() > nwarnings) {
728
0
            QTC::TC("qpdf", "QPDFAcroFormDocumentHelper /DA parse error");
729
0
        }
730
0
    } catch (std::exception& e) {
731
        // No way to reproduce in test suite right now since error conditions are converted to
732
        // warnings.
733
0
        obj.warn("Unable to parse /DA: "s + e.what() + "; this form field may not update properly");
734
0
        return;
735
0
    }
736
737
    // Regenerate /DA by filtering its tokens.
738
0
    ResourceReplacer rr(dr_map, rf.getNamesByResourceType());
739
0
    Pl_Buffer buf_pl("filtered DA");
740
0
    da_stream.filterAsContents(&rr, &buf_pl);
741
0
    std::string new_da = buf_pl.getString();
742
0
    obj.replaceKey("/DA", QPDFObjectHandle::newString(new_da));
743
0
}
744
745
void
746
AcroForm::adjustAppearanceStream(
747
    QPDFObjectHandle stream, std::map<std::string, std::map<std::string, std::string>> dr_map)
748
0
{
749
    // We don't have to modify appearance streams or their resource dictionaries for them to display
750
    // properly, but we need to do so to make them save to regenerate. Suppose an appearance stream
751
    // as a font /F1 that is different from /F1 in /DR, and that when we copy the field, /F1 is
752
    // remapped to /F1_1. When the field is regenerated, /F1_1 won't appear in the stream's resource
753
    // dictionary, so the regenerated appearance stream will revert to the /F1_1 in /DR. If we
754
    // adjust existing appearance streams, we are protected from this problem.
755
756
0
    auto dict = stream.getDict();
757
0
    auto resources = dict.getKey("/Resources");
758
759
    // Make sure this stream has its own private resource dictionary.
760
0
    bool was_indirect = resources.isIndirect();
761
0
    resources = resources.shallowCopy();
762
0
    if (was_indirect) {
763
0
        resources = qpdf.makeIndirectObject(resources);
764
0
    }
765
0
    dict.replaceKey("/Resources", resources);
766
    // Create a dictionary with top-level keys so we can use mergeResources to force them to be
767
    // unshared. We will also use this to resolve conflicts that may already be in the resource
768
    // dictionary.
769
0
    auto merge_with = QPDFObjectHandle::newDictionary();
770
0
    for (auto const& top_key: dr_map) {
771
0
        merge_with.replaceKey(top_key.first, QPDFObjectHandle::newDictionary());
772
0
    }
773
0
    resources.mergeResources(merge_with);
774
    // Rename any keys in the resource dictionary that we remapped.
775
0
    for (auto const& i1: dr_map) {
776
0
        std::string const& top_key = i1.first;
777
0
        auto subdict = resources.getKey(top_key);
778
0
        if (!subdict.isDictionary()) {
779
0
            continue;
780
0
        }
781
0
        for (auto const& i2: i1.second) {
782
0
            std::string const& old_key = i2.first;
783
0
            std::string const& new_key = i2.second;
784
0
            auto existing_new = subdict.getKey(new_key);
785
0
            if (!existing_new.null()) {
786
                // The resource dictionary already has a key in it matching what we remapped an old
787
                // key to, so we'll have to move it out of the way. Stick it in merge_with, which we
788
                // will re-merge with the dictionary when we're done. We know merge_with already has
789
                // dictionaries for all the top keys.
790
0
                merge_with.getKey(top_key).replaceKey(new_key, existing_new);
791
0
            }
792
0
            auto existing_old = subdict.getKey(old_key);
793
0
            if (!existing_old.null()) {
794
0
                subdict.replaceKey(new_key, existing_old);
795
0
                subdict.removeKey(old_key);
796
0
            }
797
0
        }
798
0
    }
799
    // Deal with any any conflicts by re-merging with merge_with and updating our local copy of
800
    // dr_map, which we will use to modify the stream contents.
801
0
    resources.mergeResources(merge_with, &dr_map);
802
    // Remove empty subdictionaries
803
0
    for (auto iter: resources.ditems()) {
804
0
        if (iter.second.isDictionary() && iter.second.getKeys().empty()) {
805
0
            resources.removeKey(iter.first);
806
0
        }
807
0
    }
808
809
    // Now attach a token filter to replace the actual resources.
810
0
    ResourceFinder rf;
811
0
    try {
812
0
        auto nwarnings = qpdf.numWarnings();
813
0
        stream.parseAsContents(&rf);
814
0
        QTC::TC(
815
0
            "qpdf",
816
0
            "QPDFAcroFormDocumentHelper AP parse error",
817
0
            qpdf.numWarnings() > nwarnings ? 0 : 1);
818
0
        auto rr = new ResourceReplacer(dr_map, rf.getNamesByResourceType());
819
0
        auto tf = std::shared_ptr<QPDFObjectHandle::TokenFilter>(rr);
820
0
        stream.addTokenFilter(tf);
821
0
    } catch (std::exception& e) {
822
        // No way to reproduce in test suite right now since error conditions are converted to
823
        // warnings.
824
0
        stream.warn("Unable to parse appearance stream: "s + e.what());
825
0
    }
826
0
}
827
828
void
829
QPDFAcroFormDocumentHelper::transformAnnotations(
830
    QPDFObjectHandle a_old_annots,
831
    std::vector<QPDFObjectHandle>& new_annots,
832
    std::vector<QPDFObjectHandle>& new_fields,
833
    std::set<QPDFObjGen>& old_fields,
834
    QPDFMatrix const& cm,
835
    QPDF* from_qpdf,
836
    QPDFAcroFormDocumentHelper* from_afdh)
837
0
{
838
0
    if (!from_qpdf) {
839
        // Assume these are from the same QPDF.
840
0
        from_qpdf = &qpdf;
841
0
        from_afdh = this;
842
0
    } else if (from_qpdf != &qpdf && !from_afdh) {
843
0
        from_afdh = &QPDFAcroFormDocumentHelper::get(*from_qpdf);
844
0
    }
845
0
    m->transformAnnotations(
846
0
        a_old_annots,
847
0
        new_annots,
848
0
        new_fields,
849
0
        old_fields,
850
0
        cm,
851
0
        from_qpdf,
852
0
        from_afdh->m.get(),
853
0
        nullptr);
854
0
}
855
856
void
857
AcroForm::transformAnnotations(
858
    QPDFObjectHandle a_old_annots,
859
    std::vector<QPDFObjectHandle>& new_annots,
860
    std::vector<QPDFObjectHandle>& new_fields,
861
    std::set<QPDFObjGen>& old_fields,
862
    QPDFMatrix const& cm,
863
    QPDF* from_qpdf,
864
    AcroForm* from_afdh,
865
    QPDFObjectHandle* new_page)
866
0
{
867
0
    qpdf_expect(from_qpdf);
868
0
    qpdf_expect(from_afdh);
869
0
    Array old_annots = std::move(a_old_annots);
870
0
    const bool foreign = from_qpdf != &qpdf;
871
872
    // It's possible that we will transform annotations that don't include any form fields. This
873
    // code takes care not to muck around with /AcroForm unless we have to.
874
875
0
    Dictionary acroform = qpdf.getRoot()["/AcroForm"];
876
0
    Dictionary from_acroform = from_qpdf->getRoot()["/AcroForm"];
877
878
    // /DA and /Q may be inherited from the document-level /AcroForm dictionary. If we are copying a
879
    // foreign stream and the stream is getting one of these values from its document's /AcroForm,
880
    // we will need to copy the value explicitly so that it doesn't start getting its default from
881
    // the destination document.
882
0
    std::string from_default_da;
883
0
    int from_default_q = 0;
884
    // If we copy any form fields, we will need to merge the source document's /DR into this
885
    // document's /DR.
886
0
    Dictionary from_dr;
887
0
    std::string default_da;
888
0
    int default_q = 0;
889
0
    if (foreign) {
890
0
        if (acroform) {
891
0
            if (acroform["/DA"].isString()) {
892
0
                default_da = acroform["/DA"].getUTF8Value();
893
0
            }
894
0
            if (Integer Q = acroform["/Q"]) {
895
0
                default_q = Q;
896
0
            }
897
0
        }
898
0
        if (from_acroform) {
899
0
            from_dr = from_acroform["/DR"];
900
0
            if (from_dr) {
901
0
                if (!from_dr.indirect()) {
902
0
                    from_dr = from_qpdf->makeIndirectObject(from_dr);
903
0
                }
904
0
                from_dr = qpdf.copyForeignObject(from_dr);
905
0
            }
906
0
            if (from_acroform["/DA"].isString()) {
907
0
                from_default_da = from_acroform["/DA"].getUTF8Value();
908
0
            }
909
0
            if (Integer Q = from_acroform["/Q"]) {
910
0
                from_default_q = Q;
911
0
            }
912
0
        }
913
0
    }
914
0
    const bool override_da = from_acroform ? from_default_da != default_da : false;
915
0
    const bool override_q = from_acroform ? from_default_q != default_q : false;
916
917
    // If we have to merge /DR, we will need a mapping of conflicting keys for rewriting /DA. Set
918
    // this up for lazy initialization in case we encounter any form fields.
919
0
    std::map<std::string, std::map<std::string, std::string>> dr_map;
920
0
    Dictionary dr;
921
922
0
    auto init_dr_map = [&]() {
923
0
        if (!dr) {
924
            // Ensure that we have a /DR that is an indirect
925
            // dictionary object.
926
0
            if (!acroform) {
927
0
                acroform = getOrCreateAcroForm();
928
0
            }
929
0
            dr = acroform["/DR"];
930
0
            if (!dr) {
931
0
                dr = Dictionary::empty();
932
0
            }
933
0
            QPDFObjectHandle(dr).makeResourcesIndirect(qpdf);
934
0
            if (!dr.indirect()) {
935
0
                acroform.replace("/DR", qpdf.makeIndirectObject(dr));
936
0
                dr = acroform["/DR"];
937
0
            }
938
            // Merge the other document's /DR, creating a conflict map. mergeResources checks to
939
            // make sure both objects are dictionaries. By this point, if this is foreign, from_dr
940
            // has been copied, so we use the target qpdf as the owning qpdf.
941
0
            QPDFObjectHandle(from_dr).makeResourcesIndirect(qpdf);
942
0
            QPDFObjectHandle(dr).mergeResources(from_dr, &dr_map);
943
944
0
            if (from_afdh->getNeedAppearances()) {
945
0
                setNeedAppearances(true);
946
0
            }
947
0
        }
948
0
    };
949
950
    // This helper prevents us from copying the same object multiple times.
951
0
    std::map<QPDFObjGen, QPDFObjectHandle> orig_to_copy;
952
0
    auto maybe_copy_object = [&](QPDFObjectHandle& to_copy) {
953
0
        auto og = to_copy.getObjGen();
954
0
        if (orig_to_copy.contains(og)) {
955
0
            to_copy = orig_to_copy[og];
956
0
            return false;
957
0
        } else {
958
0
            to_copy = qpdf.makeIndirectObject(to_copy.shallowCopy());
959
0
            orig_to_copy[og] = to_copy;
960
0
            return true;
961
0
        }
962
0
    };
963
964
    // Traverse the field, copying kids, and preserving integrity.
965
0
    auto traverse_field = [&](QPDFObjectHandle& top_field) -> void {
966
0
        std::deque<Dictionary> queue({top_field});
967
0
        QPDFObjGen::set seen;
968
0
        for (; !queue.empty(); queue.pop_front()) {
969
0
            auto& obj = queue.front();
970
0
            if (seen.add(obj)) {
971
0
                Dictionary parent = obj["/Parent"];
972
0
                if (parent.indirect()) {
973
0
                    auto parent_og = parent.id_gen();
974
0
                    if (orig_to_copy.contains(parent_og)) {
975
0
                        obj.replace("/Parent", orig_to_copy[parent_og]);
976
0
                    } else {
977
0
                        parent.warn(
978
0
                            "while traversing field " + obj.id_gen().unparse(',') +
979
0
                            ", found parent (" + parent_og.unparse(',') +
980
0
                            ") that had not been seen, indicating likely invalid field structure");
981
0
                    }
982
0
                }
983
0
                size_t i = 0;
984
0
                Array Kids = obj["/Kids"];
985
0
                for (auto& kid: Kids) {
986
0
                    if (maybe_copy_object(kid)) {
987
0
                        Kids.set(i, kid);
988
0
                        queue.emplace_back(kid);
989
0
                    }
990
0
                    ++i;
991
0
                }
992
0
                adjustInheritedFields(
993
0
                    obj, override_da, from_default_da, override_q, from_default_q);
994
0
                if (foreign) {
995
                    // Lazily initialize our /DR and the conflict map.
996
0
                    init_dr_map();
997
                    // The spec doesn't say anything about /DR on the field, but lots of writers
998
                    // put one there, and it is frequently the same as the document-level /DR.
999
                    // To avoid having the field's /DR point to information that we are not
1000
                    // maintaining, just reset it to that if it exists. Empirical evidence
1001
                    // suggests that many readers, including Acrobat, Adobe Acrobat Reader,
1002
                    // chrome, firefox, the mac Preview application, and several of the free
1003
                    // readers on Linux all ignore /DR at the field level.
1004
0
                    if (obj.contains("/DR")) {
1005
0
                        obj.replace("/DR", dr);
1006
0
                    }
1007
0
                    if (obj["/DA"].isString() && !dr_map.empty()) {
1008
0
                        adjustDefaultAppearances(obj, dr_map);
1009
0
                    }
1010
0
                }
1011
0
            }
1012
0
        }
1013
0
    };
1014
1015
0
    auto transform_annotation =
1016
0
        [&](QPDFObjectHandle& annot) -> std::tuple<QPDFObjectHandle, bool, bool> {
1017
        // Make copies of annotations and fields down to the appearance streams, preserving all
1018
        // internal referential integrity. When the incoming annotations are from a different file,
1019
        // we first copy them locally. Then, whether local or foreign, we copy them again so that if
1020
        // we bring the same annotation in multiple times (e.g. overlaying a foreign page onto
1021
        // multiple local pages or a local page onto multiple other local pages), we don't create
1022
        // annotations that are referenced in more than one place. If we did that, the effect of
1023
        // applying transformations would be cumulative, which is definitely not what we want.
1024
        // Besides, annotations and fields are not intended to be referenced in multiple places.
1025
1026
        // Determine if this annotation is attached to a form field. If so, the annotation may be
1027
        // the same object as the form field, or the form field may have the annotation as a kid. In
1028
        // either case, we have to walk up the field structure to find the top-level field. Within
1029
        // one iteration through a set of annotations, we don't want to copy the same item more than
1030
        // once. For example, suppose we have field A with kids B, C, and D, each of which has
1031
        // annotations BA, CA, and DA. When we get to BA, we will find that BA is a kid of B which
1032
        // is under A. When we do a copyForeignObject of A, it will also copy everything else
1033
        // because of the indirect references. When we clone BA, we will want to clone A and then
1034
        // update A's clone's kid to point B's clone and B's clone's parent to point to A's clone.
1035
        // The same thing holds for annotations. Next, when we get to CA, we will again discover
1036
        // that A is the top, but we don't want to re-copy A. We want CA's clone to be linked to the
1037
        // same clone as BA's. Failure to do this will break up things like radio button groups,
1038
        // which all have to kids of the same parent.
1039
1040
0
        auto ffield = from_afdh->getFieldForAnnotation(annot);
1041
0
        auto ffield_oh = ffield.getObjectHandle();
1042
0
        if (ffield.null()) {
1043
0
            return {{}, false, false};
1044
0
        }
1045
0
        if (ffield_oh.isStream()) {
1046
0
            ffield.warn("ignoring form field that's a stream");
1047
0
            return {{}, false, false};
1048
0
        }
1049
0
        if (!ffield_oh.isIndirect()) {
1050
0
            ffield.warn("ignoring form field not indirect");
1051
0
            return {{}, false, false};
1052
0
        }
1053
        // A field and its associated annotation can be the same object. This matters because we
1054
        // don't want to clone the annotation and field separately in this case.
1055
        // Find the top-level field. It may be the field itself.
1056
0
        bool have_parent = false;
1057
0
        QPDFObjectHandle top_field = ffield.getTopLevelField(&have_parent).getObjectHandle();
1058
0
        if (foreign) {
1059
            // copyForeignObject returns the same value if called multiple times with the same
1060
            // field. Create/retrieve the local copy of the original field. This pulls over
1061
            // everything the field references including annotations and appearance streams, but
1062
            // it's harmless to call copyForeignObject on them too. They will already be copied,
1063
            // so we'll get the right object back.
1064
1065
            // top_field and ffield_oh are known to be indirect.
1066
0
            top_field = qpdf.copyForeignObject(top_field);
1067
0
            ffield_oh = qpdf.copyForeignObject(ffield_oh);
1068
0
        } else {
1069
            // We don't need to add top_field to old_fields if it's foreign because the new copy
1070
            // of the foreign field won't be referenced anywhere. It's just the starting point
1071
            // for us to make an additional local copy of.
1072
0
            old_fields.insert(top_field.getObjGen());
1073
0
        }
1074
1075
0
        if (maybe_copy_object(top_field)) {
1076
0
            traverse_field(top_field);
1077
0
        }
1078
1079
        // Now switch to copies. We already switched for top_field
1080
0
        maybe_copy_object(ffield_oh);
1081
0
        return {top_field, true, have_parent};
1082
0
    };
1083
1084
    // Now do the actual copies.
1085
1086
0
    QPDFObjGen::set added_new_fields;
1087
0
    for (auto annot: old_annots) {
1088
0
        if (annot.isStream()) {
1089
0
            annot.warn("ignoring annotation that's a stream");
1090
0
            continue;
1091
0
        }
1092
0
        auto [top_field, have_field, have_parent] = transform_annotation(annot);
1093
1094
0
        QTC::TC(
1095
0
            "qpdf",
1096
0
            "QPDFAcroFormDocumentHelper copy annotation",
1097
0
            (have_field ? 1 : 0) | (foreign ? 2 : 0));
1098
0
        if (have_field) {
1099
0
            QTC::TC(
1100
0
                "qpdf",
1101
0
                "QPDFAcroFormDocumentHelper field with parent",
1102
0
                (have_parent ? 1 : 0) | (foreign ? 2 : 0));
1103
0
        }
1104
0
        if (foreign) {
1105
0
            if (!annot.isIndirect()) {
1106
0
                annot = from_qpdf->makeIndirectObject(annot);
1107
0
            }
1108
0
            annot = qpdf.copyForeignObject(annot);
1109
0
        }
1110
0
        maybe_copy_object(annot);
1111
1112
        // Now we have copies, so we can safely mutate.
1113
0
        if (have_field && added_new_fields.add(top_field)) {
1114
0
            new_fields.emplace_back(top_field);
1115
0
        }
1116
0
        new_annots.emplace_back(annot);
1117
1118
        // Identify and copy any appearance streams
1119
1120
0
        auto ah = QPDFAnnotationObjectHelper(annot);
1121
0
        Dictionary apdict = ah.getAppearanceDictionary();
1122
0
        std::vector<QPDFObjectHandle> streams;
1123
0
        auto replace_stream = [](auto& dict, auto& key, auto& old) {
1124
0
            dict.replace(key, old.copyStream());
1125
0
            return dict[key];
1126
0
        };
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto qpdf::impl::AcroForm::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, qpdf::impl::AcroForm*, QPDFObjectHandle*)::$_0::operator()<qpdf::Dictionary, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(qpdf::Dictionary&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
Unexecuted instantiation: QPDFAcroFormDocumentHelper.cc:auto qpdf::impl::AcroForm::transformAnnotations(QPDFObjectHandle, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::vector<QPDFObjectHandle, std::__1::allocator<QPDFObjectHandle> >&, std::__1::set<QPDFObjGen, std::__1::less<QPDFObjGen>, std::__1::allocator<QPDFObjGen> >&, QPDFMatrix const&, QPDF*, qpdf::impl::AcroForm*, QPDFObjectHandle*)::$_0::operator()<QPDFObjectHandle, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, QPDFObjectHandle>(QPDFObjectHandle&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, QPDFObjectHandle&) const
1127
1128
0
        for (auto& [key1, value1]: apdict) {
1129
0
            if (value1.isStream()) {
1130
0
                streams.emplace_back(replace_stream(apdict, key1, value1));
1131
0
            } else {
1132
0
                for (auto& [key2, value2]: Dictionary(value1)) {
1133
0
                    if (value2.isStream()) {
1134
0
                        streams.emplace_back(replace_stream(value1, key2, value2));
1135
0
                    }
1136
0
                }
1137
0
            }
1138
0
        }
1139
1140
        // Now we can safely mutate the annotation and its appearance streams.
1141
0
        for (auto& stream: streams) {
1142
0
            Dictionary dict = stream.getDict();
1143
1144
0
            QPDFMatrix apcm;
1145
0
            Array omatrix = dict["/Matrix"];
1146
0
            if (omatrix) {
1147
0
                apcm = QPDFMatrix(QPDFObjectHandle(omatrix).getArrayAsMatrix());
1148
0
            }
1149
0
            apcm.concat(cm);
1150
0
            if (omatrix || apcm != QPDFMatrix()) {
1151
0
                dict.replace("/Matrix", QPDFObjectHandle::newFromMatrix(apcm));
1152
0
            }
1153
0
            Dictionary resources = dict["/Resources"];
1154
0
            if (!dr_map.empty() && resources) {
1155
0
                adjustAppearanceStream(stream, dr_map);
1156
0
            }
1157
0
        }
1158
0
        auto rect = cm.transformRectangle(annot["/Rect"].getArrayAsRectangle());
1159
0
        annot.replaceKey("/Rect", QPDFObjectHandle::newFromRectangle(rect));
1160
0
        if (new_page && annot.contains("/P")) {
1161
0
            annot.replace("/P", *new_page);
1162
0
        }
1163
0
    }
1164
0
}
1165
1166
void
1167
QPDFAcroFormDocumentHelper::fixCopiedAnnotations(
1168
    QPDFObjectHandle to_page,
1169
    QPDFObjectHandle from_page,
1170
    QPDFAcroFormDocumentHelper& from_afdh,
1171
    std::set<QPDFObjGen>* added_fields)
1172
0
{
1173
0
    m->fixCopiedAnnotations(to_page, from_page, *from_afdh.m, added_fields);
1174
0
}
1175
1176
void
1177
AcroForm::fixCopiedAnnotations(
1178
    QPDFObjectHandle to_page,
1179
    QPDFObjectHandle from_page,
1180
    AcroForm& from_afdh,
1181
    std::set<QPDFObjGen>* added_fields)
1182
0
{
1183
0
    auto const& old_annots = from_page.getKey("/Annots");
1184
0
    if (old_annots.empty() || !old_annots.isArray()) {
1185
0
        return;
1186
0
    }
1187
1188
0
    std::vector<QPDFObjectHandle> new_annots;
1189
0
    std::vector<QPDFObjectHandle> new_fields;
1190
0
    std::set<QPDFObjGen> old_fields;
1191
0
    transformAnnotations(
1192
0
        old_annots,
1193
0
        new_annots,
1194
0
        new_fields,
1195
0
        old_fields,
1196
0
        QPDFMatrix(),
1197
0
        &(from_afdh.qpdf),
1198
0
        &from_afdh,
1199
0
        &to_page);
1200
1201
0
    to_page.replaceKey("/Annots", QPDFObjectHandle::newArray(new_annots));
1202
0
    addAndRenameFormFields(new_fields);
1203
0
    if (added_fields) {
1204
0
        for (auto const& f: new_fields) {
1205
0
            added_fields->insert(f.getObjGen());
1206
0
        }
1207
0
    }
1208
0
}