Coverage Report

Created: 2026-12-01 06:44

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