Coverage Report

Created: 2025-12-14 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFFormFieldObjectHelper.cc
Line
Count
Source
1
#include <qpdf/QPDFFormFieldObjectHelper.hh>
2
3
#include <qpdf/AcroForm.hh>
4
5
#include <qpdf/Pl_QPDFTokenizer.hh>
6
#include <qpdf/QIntC.hh>
7
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
8
#include <qpdf/QPDFAnnotationObjectHelper.hh>
9
#include <qpdf/QPDFObjectHandle_private.hh>
10
#include <qpdf/QPDF_private.hh>
11
#include <qpdf/QTC.hh>
12
#include <qpdf/QUtil.hh>
13
#include <cstdlib>
14
15
#include <memory>
16
17
using namespace qpdf;
18
19
using FormNode = qpdf::impl::FormNode;
20
21
const QPDFObjectHandle FormNode::null_oh;
22
23
class QPDFFormFieldObjectHelper::Members: public FormNode
24
{
25
  public:
26
    Members(QPDFObjectHandle const& oh) :
27
0
        FormNode(oh)
28
0
    {
29
0
    }
30
};
31
32
QPDFFormFieldObjectHelper::QPDFFormFieldObjectHelper(QPDFObjectHandle o) :
33
0
    QPDFObjectHelper(o),
34
0
    m(std::make_shared<Members>(oh()))
35
0
{
36
0
}
37
38
QPDFFormFieldObjectHelper::QPDFFormFieldObjectHelper() :
39
0
    QPDFObjectHelper(Null::temp()),
40
0
    m(std::make_shared<Members>(QPDFObjectHandle()))
41
0
{
42
0
}
43
44
bool
45
QPDFFormFieldObjectHelper::isNull()
46
0
{
47
0
    return m->null();
48
0
}
49
50
QPDFFormFieldObjectHelper
51
QPDFFormFieldObjectHelper::getParent()
52
0
{
53
0
    return {Null::if_null(m->Parent().oh())};
54
0
}
55
56
QPDFFormFieldObjectHelper
57
QPDFFormFieldObjectHelper::getTopLevelField(bool* is_different)
58
0
{
59
0
    return Null::if_null(m->root_field(is_different).oh());
60
0
}
61
62
FormNode
63
FormNode::root_field(bool* is_different)
64
0
{
65
0
    if (is_different) {
66
0
        *is_different = false;
67
0
    }
68
0
    if (!obj) {
69
0
        return {};
70
0
    }
71
0
    auto rf = *this;
72
0
    size_t depth = 0; // Don't bother with loop detection until depth becomes suspicious
73
0
    QPDFObjGen::set seen;
74
0
    while (rf.Parent() && (++depth < 10 || seen.add(rf))) {
75
0
        rf = rf.Parent();
76
0
        if (is_different) {
77
0
            *is_different = true;
78
0
        }
79
0
    }
80
0
    return rf;
81
0
}
82
83
QPDFObjectHandle
84
QPDFFormFieldObjectHelper::getInheritableFieldValue(std::string const& name)
85
0
{
86
0
    return Null::if_null(m->inheritable_value<QPDFObjectHandle>(name));
87
0
}
88
89
QPDFObjectHandle const&
90
FormNode::inherited(std::string const& name, bool acroform) const
91
0
{
92
0
    if (!obj) {
93
0
        return null_oh;
94
0
    }
95
0
    auto node = *this;
96
0
    QPDFObjGen::set seen;
97
0
    size_t depth = 0; // Don't bother with loop detection until depth becomes suspicious
98
0
    while (node.Parent() && (++depth < 10 || seen.add(node))) {
99
0
        node = node.Parent();
100
0
        if (auto const& result = node[name]) {
101
0
            return {result};
102
0
        }
103
0
    }
104
0
    return acroform ? from_AcroForm(name) : null_oh;
105
0
}
106
107
std::string
108
QPDFFormFieldObjectHelper::getInheritableFieldValueAsString(std::string const& name)
109
0
{
110
0
    return m->inheritable_string(name);
111
0
}
112
113
std::string
114
FormNode::inheritable_string(std::string const& name) const
115
0
{
116
0
    if (auto fv = inheritable_value<String>(name)) {
117
0
        return fv.utf8_value();
118
0
    }
119
0
    return {};
120
0
}
121
122
std::string
123
QPDFFormFieldObjectHelper::getInheritableFieldValueAsName(std::string const& name)
124
0
{
125
0
    if (auto fv = m->inheritable_value<Name>(name)) {
126
0
        return fv;
127
0
    }
128
0
    return {};
129
0
}
130
131
std::string
132
QPDFFormFieldObjectHelper::getFieldType()
133
0
{
134
0
    if (auto ft = m->FT()) {
135
0
        return ft;
136
0
    }
137
0
    return {};
138
0
}
139
140
std::string
141
QPDFFormFieldObjectHelper::getFullyQualifiedName()
142
0
{
143
0
    return m->fully_qualified_name();
144
0
}
145
146
std::string
147
FormNode::fully_qualified_name() const
148
0
{
149
0
    std::string result;
150
0
    auto node = *this;
151
0
    QPDFObjGen::set seen;
152
0
    size_t depth = 0; // Don't bother with loop detection until depth becomes suspicious
153
0
    while (node && (++depth < 10 || seen.add(node))) {
154
0
        if (auto T = node.T()) {
155
0
            if (!result.empty()) {
156
0
                result.insert(0, 1, '.');
157
0
            }
158
0
            result.insert(0, T.utf8_value());
159
0
        }
160
0
        node = node.Parent();
161
0
    }
162
0
    return result;
163
0
}
164
165
std::string
166
QPDFFormFieldObjectHelper::getPartialName()
167
0
{
168
0
    return m->partial_name();
169
0
}
170
171
std::string
172
FormNode::partial_name() const
173
0
{
174
0
    if (auto pn = T()) {
175
0
        return pn.utf8_value();
176
0
    }
177
0
    return {};
178
0
}
179
180
std::string
181
QPDFFormFieldObjectHelper::getAlternativeName()
182
0
{
183
0
    return m->alternative_name();
184
0
}
185
186
std::string
187
FormNode::alternative_name() const
188
0
{
189
0
    if (auto an = TU()) {
190
0
        return an.utf8_value();
191
0
    }
192
0
    return fully_qualified_name();
193
0
}
194
195
std::string
196
QPDFFormFieldObjectHelper::getMappingName()
197
0
{
198
0
    return m->mapping_name();
199
0
}
200
201
std::string
202
FormNode::mapping_name() const
203
0
{
204
0
    if (auto mn = TM()) {
205
0
        return mn.utf8_value();
206
0
    }
207
0
    return alternative_name();
208
0
}
209
210
QPDFObjectHandle
211
QPDFFormFieldObjectHelper::getValue()
212
0
{
213
0
    return Null::if_null(m->V<QPDFObjectHandle>());
214
0
}
215
216
std::string
217
QPDFFormFieldObjectHelper::getValueAsString()
218
0
{
219
0
    return m->value();
220
0
}
221
222
std::string
223
FormNode::value() const
224
0
{
225
0
    return inheritable_string("/V");
226
0
}
227
228
QPDFObjectHandle
229
QPDFFormFieldObjectHelper::getDefaultValue()
230
0
{
231
0
    return Null::if_null(m->DV());
232
0
}
233
234
std::string
235
QPDFFormFieldObjectHelper::getDefaultValueAsString()
236
0
{
237
0
    return m->default_value();
238
0
}
239
240
std::string
241
FormNode::default_value() const
242
0
{
243
0
    return inheritable_string("/DV");
244
0
}
245
246
QPDFObjectHandle
247
QPDFFormFieldObjectHelper::getDefaultResources()
248
0
{
249
0
    return Null::if_null(m->getDefaultResources());
250
0
}
251
252
QPDFObjectHandle
253
FormNode::getDefaultResources()
254
0
{
255
0
    return from_AcroForm("/DR");
256
0
}
257
258
std::string
259
QPDFFormFieldObjectHelper::getDefaultAppearance()
260
0
{
261
0
    return m->default_appearance();
262
0
}
263
264
std::string
265
FormNode::default_appearance() const
266
0
{
267
0
    if (auto DA = inheritable_value<String>("/DA")) {
268
0
        return DA.utf8_value();
269
0
    }
270
0
    if (String DA = from_AcroForm("/DA")) {
271
0
        return DA.utf8_value();
272
0
    }
273
0
    return {};
274
0
}
275
276
int
277
QPDFFormFieldObjectHelper::getQuadding()
278
0
{
279
0
    return m->getQuadding();
280
0
}
281
282
int
283
FormNode::getQuadding()
284
0
{
285
0
    auto fv = inheritable_value<QPDFObjectHandle>("/Q");
286
0
    bool looked_in_acroform = false;
287
0
    if (!fv.isInteger()) {
288
0
        fv = from_AcroForm("/Q");
289
0
        looked_in_acroform = true;
290
0
    }
291
0
    if (fv.isInteger()) {
292
0
        QTC::TC("qpdf", "QPDFFormFieldObjectHelper Q present", looked_in_acroform ? 0 : 1);
293
0
        return QIntC::to_int(fv.getIntValue());
294
0
    }
295
0
    return 0;
296
0
}
297
298
int
299
QPDFFormFieldObjectHelper::getFlags()
300
0
{
301
0
    return m->getFlags();
302
0
}
303
304
int
305
FormNode::getFlags()
306
0
{
307
0
    auto f = inheritable_value<QPDFObjectHandle>("/Ff");
308
0
    return f.isInteger() ? f.getIntValueAsInt() : 0;
309
0
}
310
311
bool
312
QPDFFormFieldObjectHelper::isText()
313
0
{
314
0
    return m->isText();
315
0
}
316
317
bool
318
FormNode::isText()
319
0
{
320
0
    return FT() == "/Tx";
321
0
}
322
323
bool
324
QPDFFormFieldObjectHelper::isCheckbox()
325
0
{
326
0
    return m->isCheckbox();
327
0
}
328
329
bool
330
FormNode::isCheckbox()
331
0
{
332
0
    return FT() == "/Btn" && (getFlags() & (ff_btn_radio | ff_btn_pushbutton)) == 0;
333
0
}
334
335
bool
336
QPDFFormFieldObjectHelper::isChecked()
337
0
{
338
0
    return m->isChecked();
339
0
}
340
341
bool
342
FormNode::isChecked()
343
0
{
344
0
    return isCheckbox() && V<Name>() != "/Off";
345
0
}
346
347
bool
348
QPDFFormFieldObjectHelper::isRadioButton()
349
0
{
350
0
    return m->isRadioButton();
351
0
}
352
353
bool
354
FormNode::isRadioButton()
355
0
{
356
0
    return FT() == "/Btn" && (getFlags() & ff_btn_radio) == ff_btn_radio;
357
0
}
358
359
bool
360
QPDFFormFieldObjectHelper::isPushbutton()
361
0
{
362
0
    return m->isPushbutton();
363
0
}
364
365
bool
366
FormNode::isPushbutton()
367
0
{
368
0
    return FT() == "/Btn" && (getFlags() & ff_btn_pushbutton) == ff_btn_pushbutton;
369
0
}
370
371
bool
372
QPDFFormFieldObjectHelper::isChoice()
373
0
{
374
0
    return m->isChoice();
375
0
}
376
377
bool
378
FormNode::isChoice()
379
0
{
380
0
    return FT() == "/Ch";
381
0
}
382
383
std::vector<std::string>
384
QPDFFormFieldObjectHelper::getChoices()
385
0
{
386
0
    return m->getChoices();
387
0
}
388
389
std::vector<std::string>
390
FormNode::getChoices()
391
0
{
392
0
    if (!isChoice()) {
393
0
        return {};
394
0
    }
395
0
    std::vector<std::string> result;
396
0
    for (auto const& item: inheritable_value<Array>("/Opt")) {
397
0
        if (item.isString()) {
398
0
            result.emplace_back(item.getUTF8Value());
399
0
        } else if (item.size() == 2) {
400
0
            auto display = item.getArrayItem(1);
401
0
            if (display.isString()) {
402
0
                result.emplace_back(display.getUTF8Value());
403
0
            }
404
0
        }
405
0
    }
406
0
    return result;
407
0
}
408
409
void
410
QPDFFormFieldObjectHelper::setFieldAttribute(std::string const& key, QPDFObjectHandle value)
411
0
{
412
0
    m->setFieldAttribute(key, value);
413
0
}
414
415
void
416
FormNode::setFieldAttribute(std::string const& key, QPDFObjectHandle value)
417
0
{
418
0
    replace(key, value);
419
0
}
420
421
void
422
FormNode::setFieldAttribute(std::string const& key, Name const& value)
423
0
{
424
0
    replace(key, value);
425
0
}
426
427
void
428
QPDFFormFieldObjectHelper::setFieldAttribute(std::string const& key, std::string const& utf8_value)
429
0
{
430
0
    m->setFieldAttribute(key, utf8_value);
431
0
}
432
433
void
434
FormNode::setFieldAttribute(std::string const& key, std::string const& utf8_value)
435
0
{
436
0
    replace(key, String::utf16(utf8_value));
437
0
}
438
439
void
440
QPDFFormFieldObjectHelper::setV(QPDFObjectHandle value, bool need_appearances)
441
0
{
442
0
    m->setV(value, need_appearances);
443
0
}
444
445
void
446
FormNode::setV(QPDFObjectHandle value, bool need_appearances)
447
0
{
448
0
    Name name = value;
449
0
    if (FT() == "/Btn") {
450
0
        if (isCheckbox()) {
451
0
            if (!name) {
452
0
                warn("ignoring attempt to set a checkbox field to a value whose type is not name");
453
0
                return;
454
0
            }
455
            // Accept any value other than /Off to mean checked. Files have been seen that use
456
            // /1 or other values.
457
0
            setCheckBoxValue(name != "/Off");
458
0
            return;
459
0
        }
460
0
        if (isRadioButton()) {
461
0
            if (!name) {
462
0
                warn(
463
0
                    "ignoring attempt to set a radio button field to an object that is not a name");
464
0
                return;
465
0
            }
466
0
            setRadioButtonValue(name);
467
0
            return;
468
0
        }
469
0
        if (isPushbutton()) {
470
0
            warn("ignoring attempt set the value of a pushbutton field");
471
0
        }
472
0
        return;
473
0
    }
474
0
    if (value.isString()) {
475
0
        setFieldAttribute("/V", QPDFObjectHandle::newUnicodeString(value.getUTF8Value()));
476
0
    } else {
477
0
        setFieldAttribute("/V", value);
478
0
    }
479
0
    if (need_appearances) {
480
0
        QPDF& qpdf = oh().getQPDF(
481
0
            "QPDFFormFieldObjectHelper::setV called with need_appearances = "
482
0
            "true on an object that is not associated with an owning QPDF");
483
0
        qpdf.doc().acroform().setNeedAppearances(true);
484
0
    }
485
0
}
486
487
void
488
QPDFFormFieldObjectHelper::setV(std::string const& utf8_value, bool need_appearances)
489
0
{
490
0
    m->setV(utf8_value, need_appearances);
491
0
}
492
493
void
494
FormNode::setV(std::string const& utf8_value, bool need_appearances)
495
0
{
496
0
    setV(QPDFObjectHandle::newUnicodeString(utf8_value), need_appearances);
497
0
}
498
499
void
500
FormNode::setRadioButtonValue(QPDFObjectHandle name)
501
0
{
502
    // Set the value of a radio button field. This has the following specific behavior:
503
    // * If this is a radio button field that has a parent that is also a radio button field and has
504
    //   no explicit /V, call itself on the parent
505
    // * If this is a radio button field with children, set /V to the given value. Then, for each
506
    //   child, if the child has the specified value as one of its keys in the /N subdictionary of
507
    //   its /AP (i.e. its normal appearance stream dictionary), set /AS to name; otherwise, if /Off
508
    //   is a member, set /AS to /Off.
509
    // Note that we never turn on /NeedAppearances when setting a radio button field.
510
0
    QPDFObjectHandle parent = oh().getKey("/Parent");
511
0
    if (parent.isDictionary() && parent.getKey("/Parent").null()) {
512
0
        FormNode ph(parent);
513
0
        if (ph.isRadioButton()) {
514
            // This is most likely one of the individual buttons. Try calling on the parent.
515
0
            ph.setRadioButtonValue(name);
516
0
            return;
517
0
        }
518
0
    }
519
0
    auto kids = Kids();
520
0
    if (!(isRadioButton() && parent.null() && kids)) {
521
0
        warn("don't know how to set the value of this field as a radio button");
522
0
        return;
523
0
    }
524
0
    setFieldAttribute("/V", name);
525
0
    for (FormNode kid: kids) {
526
0
        auto ap = kid.AP();
527
0
        QPDFObjectHandle annot;
528
0
        if (!ap) {
529
            // The widget may be below. If there is more than one, just find the first one.
530
0
            for (FormNode grandkid: kid.Kids()) {
531
0
                ap = grandkid.AP();
532
0
                if (ap) {
533
0
                    annot = grandkid;
534
0
                    break;
535
0
                }
536
0
            }
537
0
        } else {
538
0
            annot = kid;
539
0
        }
540
0
        if (!annot) {
541
0
            warn("unable to set the value of this radio button");
542
0
            continue;
543
0
        }
544
0
        if (ap["/N"].contains(name.getName())) {
545
0
            annot.replace("/AS", name);
546
0
        } else {
547
0
            annot.replace("/AS", Name("/Off"));
548
0
        }
549
0
    }
550
0
}
551
552
void
553
FormNode::setCheckBoxValue(bool value)
554
0
{
555
0
    auto ap = AP();
556
0
    QPDFObjectHandle annot;
557
0
    if (ap) {
558
0
        annot = oh();
559
0
    } else {
560
        // The widget may be below. If there is more than one, just find the first one.
561
0
        for (FormNode kid: Kids()) {
562
0
            ap = kid.AP();
563
0
            if (ap) {
564
0
                annot = kid;
565
0
                break;
566
0
            }
567
0
        }
568
0
    }
569
0
    std::string on_value;
570
0
    if (value) {
571
        // Set the "on" value to the first value in the appearance stream's normal state dictionary
572
        // that isn't /Off. If not found, fall back to /Yes.
573
0
        if (ap) {
574
0
            for (auto const& item: Dictionary(ap["/N"])) {
575
0
                if (item.first != "/Off") {
576
0
                    on_value = item.first;
577
0
                    break;
578
0
                }
579
0
            }
580
0
        }
581
0
        if (on_value.empty()) {
582
0
            on_value = "/Yes";
583
0
        }
584
0
    }
585
586
    // Set /AS to the on value or /Off in addition to setting /V.
587
0
    auto name = Name(value ? on_value : "/Off");
588
0
    setFieldAttribute("/V", name);
589
0
    if (!annot) {
590
0
        warn("unable to set the value of this checkbox");
591
0
        return;
592
0
    }
593
0
    annot.replace("/AS", name);
594
0
}
595
596
void
597
QPDFFormFieldObjectHelper::generateAppearance(QPDFAnnotationObjectHelper& aoh)
598
0
{
599
0
    m->generateAppearance(aoh);
600
0
}
601
602
void
603
FormNode::generateAppearance(QPDFAnnotationObjectHelper& aoh)
604
0
{
605
    // Ignore field types we don't know how to generate appearances for. Button fields don't really
606
    // need them -- see code in QPDFAcroFormDocumentHelper::generateAppearancesIfNeeded.
607
0
    auto ft = FT();
608
0
    if (ft == "/Tx" || ft == "/Ch") {
609
0
        generateTextAppearance(aoh);
610
0
    }
611
0
}
612
613
namespace
614
{
615
    class ValueSetter: public QPDFObjectHandle::TokenFilter
616
    {
617
      public:
618
        ValueSetter(
619
            std::string const& DA,
620
            std::string const& V,
621
            std::vector<std::string> const& opt,
622
            double tf,
623
            QPDFObjectHandle::Rectangle const& bbox);
624
0
        ~ValueSetter() override = default;
625
        void handleToken(QPDFTokenizer::Token const&) override;
626
        void handleEOF() override;
627
        void writeAppearance();
628
629
      private:
630
        std::string DA;
631
        std::string V;
632
        std::vector<std::string> opt;
633
        double tf;
634
        QPDFObjectHandle::Rectangle bbox;
635
        enum { st_top, st_bmc, st_emc, st_end } state{st_top};
636
        bool replaced{false};
637
    };
638
} // namespace
639
640
ValueSetter::ValueSetter(
641
    std::string const& DA,
642
    std::string const& V,
643
    std::vector<std::string> const& opt,
644
    double tf,
645
    QPDFObjectHandle::Rectangle const& bbox) :
646
0
    DA(DA),
647
0
    V(V),
648
0
    opt(opt),
649
0
    tf(tf),
650
0
    bbox(bbox)
651
0
{
652
0
}
653
654
void
655
ValueSetter::handleToken(QPDFTokenizer::Token const& token)
656
0
{
657
0
    QPDFTokenizer::token_type_e ttype = token.getType();
658
0
    std::string value = token.getValue();
659
0
    bool do_replace = false;
660
0
    switch (state) {
661
0
    case st_top:
662
0
        writeToken(token);
663
0
        if (token.isWord("BMC")) {
664
0
            state = st_bmc;
665
0
        }
666
0
        break;
667
668
0
    case st_bmc:
669
0
        if ((ttype == QPDFTokenizer::tt_space) || (ttype == QPDFTokenizer::tt_comment)) {
670
0
            writeToken(token);
671
0
        } else {
672
0
            state = st_emc;
673
0
        }
674
        // fall through to emc
675
676
0
    case st_emc:
677
0
        if (token.isWord("EMC")) {
678
0
            do_replace = true;
679
0
            state = st_end;
680
0
        }
681
0
        break;
682
683
0
    case st_end:
684
0
        writeToken(token);
685
0
        break;
686
0
    }
687
0
    if (do_replace) {
688
0
        writeAppearance();
689
0
    }
690
0
}
691
692
void
693
ValueSetter::handleEOF()
694
0
{
695
0
    if (!replaced) {
696
0
        QTC::TC("qpdf", "QPDFFormFieldObjectHelper replaced BMC at EOF");
697
0
        write("/Tx BMC\n");
698
0
        writeAppearance();
699
0
    }
700
0
}
701
702
void
703
ValueSetter::writeAppearance()
704
0
{
705
0
    replaced = true;
706
707
    // This code does not take quadding into consideration because doing so requires font metric
708
    // information, which we don't have in many cases.
709
710
0
    double tfh = 1.2 * tf;
711
0
    int dx = 1;
712
713
    // Write one or more lines, centered vertically, possibly with one row highlighted.
714
715
0
    auto max_rows = static_cast<size_t>((bbox.ury - bbox.lly) / tfh);
716
0
    bool highlight = false;
717
0
    size_t highlight_idx = 0;
718
719
0
    std::vector<std::string> lines;
720
0
    if (opt.empty() || (max_rows < 2)) {
721
0
        lines.push_back(V);
722
0
    } else {
723
        // Figure out what rows to write
724
0
        size_t nopt = opt.size();
725
0
        size_t found_idx = 0;
726
0
        bool found = false;
727
0
        for (found_idx = 0; found_idx < nopt; ++found_idx) {
728
0
            if (opt.at(found_idx) == V) {
729
0
                found = true;
730
0
                break;
731
0
            }
732
0
        }
733
0
        if (found) {
734
            // Try to make the found item the second one, but adjust for under/overflow.
735
0
            int wanted_first = QIntC::to_int(found_idx) - 1;
736
0
            int wanted_last = QIntC::to_int(found_idx + max_rows) - 2;
737
0
            QTC::TC("qpdf", "QPDFFormFieldObjectHelper list found");
738
0
            if (wanted_first < 0) {
739
0
                QTC::TC("qpdf", "QPDFFormFieldObjectHelper list first too low");
740
0
                wanted_last -= wanted_first;
741
0
                wanted_first = 0;
742
0
            }
743
0
            if (wanted_last >= QIntC::to_int(nopt)) {
744
0
                QTC::TC("qpdf", "QPDFFormFieldObjectHelper list last too high");
745
0
                auto diff = wanted_last - QIntC::to_int(nopt) + 1;
746
0
                wanted_first = std::max(0, wanted_first - diff);
747
0
                wanted_last -= diff;
748
0
            }
749
0
            highlight = true;
750
0
            highlight_idx = found_idx - QIntC::to_size(wanted_first);
751
0
            for (size_t i = QIntC::to_size(wanted_first); i <= QIntC::to_size(wanted_last); ++i) {
752
0
                lines.push_back(opt.at(i));
753
0
            }
754
0
        } else {
755
0
            QTC::TC("qpdf", "QPDFFormFieldObjectHelper list not found");
756
            // include our value and the first n-1 rows
757
0
            highlight_idx = 0;
758
0
            highlight = true;
759
0
            lines.push_back(V);
760
0
            for (size_t i = 0; ((i < nopt) && (i < (max_rows - 1))); ++i) {
761
0
                lines.push_back(opt.at(i));
762
0
            }
763
0
        }
764
0
    }
765
766
    // Write the lines centered vertically, highlighting if needed
767
0
    size_t nlines = lines.size();
768
0
    double dy = bbox.ury - ((bbox.ury - bbox.lly - (static_cast<double>(nlines) * tfh)) / 2.0);
769
0
    if (highlight) {
770
0
        write(
771
0
            "q\n0.85 0.85 0.85 rg\n" + QUtil::double_to_string(bbox.llx) + " " +
772
0
            QUtil::double_to_string(
773
0
                bbox.lly + dy - (tfh * (static_cast<double>(highlight_idx + 1)))) +
774
0
            " " + QUtil::double_to_string(bbox.urx - bbox.llx) + " " +
775
0
            QUtil::double_to_string(tfh) + " re f\nQ\n");
776
0
    }
777
0
    dy -= tf;
778
0
    write("q\nBT\n" + DA + "\n");
779
0
    for (size_t i = 0; i < nlines; ++i) {
780
        // We could adjust Tm to translate to the beginning the first line, set TL to tfh, and use
781
        // T* for each subsequent line, but doing this would require extracting any Tm from DA,
782
        // which doesn't seem really worth the effort.
783
0
        if (i == 0) {
784
0
            write(
785
0
                QUtil::double_to_string(bbox.llx + static_cast<double>(dx)) + " " +
786
0
                QUtil::double_to_string(bbox.lly + static_cast<double>(dy)) + " Td\n");
787
0
        } else {
788
0
            write("0 " + QUtil::double_to_string(-tfh) + " Td\n");
789
0
        }
790
0
        write(QPDFObjectHandle::newString(lines.at(i)).unparse() + " Tj\n");
791
0
    }
792
0
    write("ET\nQ\nEMC");
793
0
}
794
795
namespace
796
{
797
    class TfFinder final: public QPDFObjectHandle::TokenFilter
798
    {
799
      public:
800
0
        TfFinder() = default;
801
0
        ~TfFinder() final = default;
802
803
        void
804
        handleToken(QPDFTokenizer::Token const& token) final
805
0
        {
806
0
            auto ttype = token.getType();
807
0
            auto const& value = token.getValue();
808
0
            DA.emplace_back(token.getRawValue());
809
0
            switch (ttype) {
810
0
            case QPDFTokenizer::tt_integer:
811
0
            case QPDFTokenizer::tt_real:
812
0
                last_num = strtod(value.c_str(), nullptr);
813
0
                last_num_idx = QIntC::to_int(DA.size() - 1);
814
0
                break;
815
816
0
            case QPDFTokenizer::tt_name:
817
0
                last_name = value;
818
0
                break;
819
820
0
            case QPDFTokenizer::tt_word:
821
0
                if (token.isWord("Tf")) {
822
0
                    if ((last_num > 1.0) && (last_num < 1000.0)) {
823
                        // These ranges are arbitrary but keep us from doing insane things or
824
                        // suffering from over/underflow
825
0
                        tf = last_num;
826
0
                    }
827
0
                    tf_idx = last_num_idx;
828
0
                    font_name = last_name;
829
0
                }
830
0
                break;
831
832
0
            default:
833
0
                break;
834
0
            }
835
0
        }
836
837
        double
838
        getTf() const
839
0
        {
840
0
            return tf;
841
0
        }
842
        std::string
843
        getFontName() const
844
0
        {
845
0
            return font_name;
846
0
        }
847
848
        std::string
849
        getDA()
850
0
        {
851
0
            std::string result;
852
0
            int i = -1;
853
0
            for (auto const& cur: DA) {
854
0
                if (++i == tf_idx) {
855
0
                    double delta = strtod(cur.c_str(), nullptr) - tf;
856
0
                    if (delta > 0.001 || delta < -0.001) {
857
                        // tf doesn't match the font size passed to Tf, so substitute.
858
0
                        QTC::TC("qpdf", "QPDFFormFieldObjectHelper fallback Tf");
859
0
                        result += QUtil::double_to_string(tf);
860
0
                        continue;
861
0
                    }
862
0
                }
863
0
                result += cur;
864
0
            }
865
0
            return result;
866
0
        }
867
868
      private:
869
        double tf{11.0};
870
        int tf_idx{-1};
871
        std::string font_name;
872
        double last_num{0.0};
873
        int last_num_idx{-1};
874
        std::string last_name;
875
        std::vector<std::string> DA;
876
    };
877
} // namespace
878
879
QPDFObjectHandle
880
FormNode::getFontFromResource(QPDFObjectHandle resources, std::string const& name)
881
0
{
882
0
    QPDFObjectHandle result;
883
0
    if (resources.isDictionary() && resources.getKey("/Font").isDictionary() &&
884
0
        resources.getKey("/Font").hasKey(name)) {
885
0
        result = resources.getKey("/Font").getKey(name);
886
0
    }
887
0
    return result;
888
0
}
889
890
void
891
FormNode::generateTextAppearance(QPDFAnnotationObjectHelper& aoh)
892
0
{
893
0
    QPDFObjectHandle AS = aoh.getAppearanceStream("/N");
894
0
    if (AS.null()) {
895
0
        QPDFObjectHandle::Rectangle rect = aoh.getRect();
896
0
        QPDFObjectHandle::Rectangle bbox(0, 0, rect.urx - rect.llx, rect.ury - rect.lly);
897
0
        auto dict = Dictionary(
898
0
            {{"/BBox", QPDFObjectHandle::newFromRectangle(bbox)},
899
0
             {"/Resources", Dictionary({{"/ProcSet", Array({Name("/PDF"), Name("/Text")})}})},
900
0
             {"/Type", Name("/XObject")},
901
0
             {"/Subtype", Name("/Form")}});
902
0
        AS = QPDFObjectHandle::newStream(oh().getOwningQPDF(), "/Tx BMC\nEMC\n");
903
0
        AS.replaceDict(dict);
904
0
        if (auto ap = AP()) {
905
0
            ap.replace("/N", AS);
906
0
        } else {
907
0
            aoh.replace("/AP", Dictionary({{"/N", AS}}));
908
0
        }
909
0
    }
910
0
    if (!AS.isStream()) {
911
0
        aoh.warn("unable to get normal appearance stream for update");
912
0
        return;
913
0
    }
914
915
0
    if (AS.obj_sp().use_count() > 3) {
916
        // The following check ensures that we only update the appearance stream if it is not
917
        // shared. The threshold of 3 is based on the current implementation details:
918
        // - One reference from the local variable AS
919
        // - One reference from the appearance dictionary (/AP)
920
        // - One reference from the object table
921
        // If use_count() is greater than 3, it means the appearance stream is shared elsewhere,
922
        // and updating it could have unintended side effects. This threshold may need to be updated
923
        // if the internal reference counting changes in the future.
924
        // The long-term solution will we to replace appearance streams at the point of flattening
925
        // annotations rather than attaching token filters that modify the streams at time of
926
        // writing.
927
0
        aoh.warn("unable to generate text appearance from shared appearance stream for update");
928
0
        return;
929
0
    }
930
0
    QPDFObjectHandle bbox_obj = AS.getDict().getKey("/BBox");
931
0
    if (!bbox_obj.isRectangle()) {
932
0
        aoh.warn("unable to get appearance stream bounding box");
933
0
        return;
934
0
    }
935
0
    QPDFObjectHandle::Rectangle bbox = bbox_obj.getArrayAsRectangle();
936
0
    std::string DA = default_appearance();
937
0
    std::string V = value();
938
0
    std::vector<std::string> opt;
939
0
    if (isChoice() && (getFlags() & ff_ch_combo) == 0) {
940
0
        opt = getChoices();
941
0
    }
942
943
0
    TfFinder tff;
944
0
    Pl_QPDFTokenizer tok("tf", &tff);
945
0
    tok.writeString(DA);
946
0
    tok.finish();
947
0
    double tf = tff.getTf();
948
0
    DA = tff.getDA();
949
950
0
    std::string (*encoder)(std::string const&, char) = &QUtil::utf8_to_ascii;
951
0
    std::string font_name = tff.getFontName();
952
0
    if (!font_name.empty()) {
953
        // See if the font is encoded with something we know about.
954
0
        Dictionary resources = AS.getDict()["/Resources"];
955
0
        Dictionary font = getFontFromResource(resources, font_name);
956
0
        if (!font) {
957
0
            font = getFontFromResource(getDefaultResources(), font_name);
958
0
            if (resources) {
959
0
                if (resources.indirect()) {
960
0
                    resources = resources.qpdf()->makeIndirectObject(resources.copy());
961
0
                    AS.getDict().replaceKey("/Resources", resources);
962
0
                }
963
                // Use mergeResources to force /Font to be local
964
0
                QPDFObjectHandle res = resources;
965
0
                res.mergeResources(Dictionary({{"/Font", Dictionary::empty()}}));
966
0
                res.getKey("/Font").replaceKey(font_name, font);
967
0
            }
968
0
        }
969
970
0
        if (Name Encoding = font["/Encoding"]) {
971
0
            if (Encoding == "/WinAnsiEncoding") {
972
0
                encoder = &QUtil::utf8_to_win_ansi;
973
0
            } else if (Encoding == "/MacRomanEncoding") {
974
0
                encoder = &QUtil::utf8_to_mac_roman;
975
0
            }
976
0
        }
977
0
    }
978
979
0
    V = (*encoder)(V, '?');
980
0
    for (size_t i = 0; i < opt.size(); ++i) {
981
0
        opt.at(i) = (*encoder)(opt.at(i), '?');
982
0
    }
983
0
    AS.addTokenFilter(
984
0
        std::shared_ptr<QPDFObjectHandle::TokenFilter>(new ValueSetter(DA, V, opt, tf, bbox)));
985
0
}