Coverage Report

Created: 2026-03-07 06:28

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