Coverage Report

Created: 2025-11-24 06:47

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/FormField.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 FormField = qpdf::impl::FormField;
20
21
const QPDFObjectHandle FormField::null_oh;
22
23
class QPDFFormFieldObjectHelper::Members: public FormField
24
{
25
  public:
26
    Members(QPDFObjectHandle const& oh) :
27
0
        FormField(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
FormField
63
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::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
FormField::setFieldAttribute(std::string const& key, QPDFObjectHandle value)
417
0
{
418
0
    oh().replaceKey(key, value);
419
0
}
420
421
void
422
QPDFFormFieldObjectHelper::setFieldAttribute(std::string const& key, std::string const& utf8_value)
423
0
{
424
0
    m->setFieldAttribute(key, utf8_value);
425
0
}
426
427
void
428
FormField::setFieldAttribute(std::string const& key, std::string const& utf8_value)
429
0
{
430
0
    oh().replaceKey(key, QPDFObjectHandle::newUnicodeString(utf8_value));
431
0
}
432
433
void
434
QPDFFormFieldObjectHelper::setV(QPDFObjectHandle value, bool need_appearances)
435
0
{
436
0
    m->setV(value, need_appearances);
437
0
}
438
439
void
440
FormField::setV(QPDFObjectHandle value, bool need_appearances)
441
0
{
442
0
    Name name = value;
443
0
    if (FT() == "/Btn") {
444
0
        if (isCheckbox()) {
445
0
            if (!name) {
446
0
                warn("ignoring attempt to set a checkbox field to a value whose type is not name");
447
0
                return;
448
0
            }
449
            // Accept any value other than /Off to mean checked. Files have been seen that use
450
            // /1 or other values.
451
0
            setCheckBoxValue(name != "/Off");
452
0
            return;
453
0
        }
454
0
        if (isRadioButton()) {
455
0
            if (!name) {
456
0
                warn(
457
0
                    "ignoring attempt to set a radio button field to an object that is not a name");
458
0
                return;
459
0
            }
460
0
            setRadioButtonValue(name);
461
0
            return;
462
0
        }
463
0
        if (isPushbutton()) {
464
0
            warn("ignoring attempt set the value of a pushbutton field");
465
0
        }
466
0
        return;
467
0
    }
468
0
    if (value.isString()) {
469
0
        setFieldAttribute("/V", QPDFObjectHandle::newUnicodeString(value.getUTF8Value()));
470
0
    } else {
471
0
        setFieldAttribute("/V", value);
472
0
    }
473
0
    if (need_appearances) {
474
0
        QPDF& qpdf = oh().getQPDF(
475
0
            "QPDFFormFieldObjectHelper::setV called with need_appearances = "
476
0
            "true on an object that is not associated with an owning QPDF");
477
0
        qpdf.doc().acroform().setNeedAppearances(true);
478
0
    }
479
0
}
480
481
void
482
QPDFFormFieldObjectHelper::setV(std::string const& utf8_value, bool need_appearances)
483
0
{
484
0
    m->setV(utf8_value, need_appearances);
485
0
}
486
487
void
488
FormField::setV(std::string const& utf8_value, bool need_appearances)
489
0
{
490
0
    setV(QPDFObjectHandle::newUnicodeString(utf8_value), need_appearances);
491
0
}
492
493
void
494
FormField::setRadioButtonValue(QPDFObjectHandle name)
495
0
{
496
    // Set the value of a radio button field. This has the following specific behavior:
497
    // * If this is a radio button field that has a parent that is also a radio button field and has
498
    //   no explicit /V, call itself on the parent
499
    // * If this is a radio button field with children, set /V to the given value. Then, for each
500
    //   child, if the child has the specified value as one of its keys in the /N subdictionary of
501
    //   its /AP (i.e. its normal appearance stream dictionary), set /AS to name; otherwise, if /Off
502
    //   is a member, set /AS to /Off.
503
    // Note that we never turn on /NeedAppearances when setting a radio button field.
504
0
    QPDFObjectHandle parent = oh().getKey("/Parent");
505
0
    if (parent.isDictionary() && parent.getKey("/Parent").null()) {
506
0
        FormField ph(parent);
507
0
        if (ph.isRadioButton()) {
508
            // This is most likely one of the individual buttons. Try calling on the parent.
509
0
            ph.setRadioButtonValue(name);
510
0
            return;
511
0
        }
512
0
    }
513
514
0
    QPDFObjectHandle kids = oh().getKey("/Kids");
515
0
    if (!(isRadioButton() && parent.null() && kids.isArray())) {
516
0
        warn("don't know how to set the value of this field as a radio button");
517
0
        return;
518
0
    }
519
0
    setFieldAttribute("/V", name);
520
0
    for (auto const& kid: kids.as_array()) {
521
0
        QPDFObjectHandle AP = kid.getKey("/AP");
522
0
        QPDFObjectHandle annot;
523
0
        if (AP.null()) {
524
            // The widget may be below. If there is more than one, just find the first one.
525
0
            for (auto const& grandkid: kid.getKey("/Kids").as_array()) {
526
0
                AP = grandkid.getKey("/AP");
527
0
                if (!AP.null()) {
528
0
                    annot = grandkid;
529
0
                    break;
530
0
                }
531
0
            }
532
0
        } else {
533
0
            annot = kid;
534
0
        }
535
0
        if (!annot) {
536
0
            warn("unable to set the value of this radio button");
537
0
            continue;
538
0
        }
539
0
        if (AP.isDictionary() && AP.getKey("/N").isDictionary() &&
540
0
            AP.getKey("/N").hasKey(name.getName())) {
541
0
            annot.replaceKey("/AS", name);
542
0
        } else {
543
0
            annot.replaceKey("/AS", QPDFObjectHandle::newName("/Off"));
544
0
        }
545
0
    }
546
0
}
547
548
void
549
FormField::setCheckBoxValue(bool value)
550
0
{
551
0
    QPDFObjectHandle AP = oh().getKey("/AP");
552
0
    QPDFObjectHandle annot;
553
0
    if (AP.null()) {
554
        // The widget may be below. If there is more than one, just
555
        // find the first one.
556
0
        QPDFObjectHandle kids = oh().getKey("/Kids");
557
0
        for (auto const& kid: oh().getKey("/Kids").as_array(qpdf::strict)) {
558
0
            AP = kid.getKey("/AP");
559
0
            if (!AP.null()) {
560
0
                QTC::TC("qpdf", "QPDFFormFieldObjectHelper checkbox kid widget");
561
0
                annot = kid;
562
0
                break;
563
0
            }
564
0
        }
565
0
    } else {
566
0
        annot = oh();
567
0
    }
568
0
    std::string on_value;
569
0
    if (value) {
570
        // Set the "on" value to the first value in the appearance stream's normal state dictionary
571
        // that isn't /Off. If not found, fall back to /Yes.
572
0
        if (AP.isDictionary()) {
573
0
            for (auto const& item: AP.getKey("/N").as_dictionary()) {
574
0
                if (item.first != "/Off") {
575
0
                    on_value = item.first;
576
0
                    break;
577
0
                }
578
0
            }
579
0
        }
580
0
        if (on_value.empty()) {
581
0
            on_value = "/Yes";
582
0
        }
583
0
    }
584
585
    // Set /AS to the on value or /Off in addition to setting /V.
586
0
    QPDFObjectHandle name = QPDFObjectHandle::newName(value ? on_value : "/Off");
587
0
    setFieldAttribute("/V", name);
588
0
    if (!annot) {
589
0
        QTC::TC("qpdf", "QPDFObjectHandle broken checkbox");
590
0
        warn("unable to set the value of this checkbox");
591
0
        return;
592
0
    }
593
0
    QTC::TC("qpdf", "QPDFFormFieldObjectHelper set checkbox AS");
594
0
    annot.replaceKey("/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
FormField::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
    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
FormField::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
FormField::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
        Dictionary AP = aoh.getAppearanceDictionary();
905
0
        if (!AP) {
906
0
            aoh.getObjectHandle().replaceKey("/AP", Dictionary::empty());
907
0
            AP = aoh.getAppearanceDictionary();
908
0
        }
909
0
        AP.replace("/N", AS);
910
0
    }
911
0
    if (!AS.isStream()) {
912
0
        aoh.warn("unable to get normal appearance stream for update");
913
0
        return;
914
0
    }
915
916
0
    if (AS.obj_sp().use_count() > 3) {
917
0
        aoh.warn("unable to generate text appearance from shared appearance stream for update");
918
0
        return;
919
0
    }
920
0
    QPDFObjectHandle bbox_obj = AS.getDict().getKey("/BBox");
921
0
    if (!bbox_obj.isRectangle()) {
922
0
        aoh.warn("unable to get appearance stream bounding box");
923
0
        return;
924
0
    }
925
0
    QPDFObjectHandle::Rectangle bbox = bbox_obj.getArrayAsRectangle();
926
0
    std::string DA = default_appearance();
927
0
    std::string V = value();
928
0
    std::vector<std::string> opt;
929
0
    if (isChoice() && (getFlags() & ff_ch_combo) == 0) {
930
0
        opt = getChoices();
931
0
    }
932
933
0
    TfFinder tff;
934
0
    Pl_QPDFTokenizer tok("tf", &tff);
935
0
    tok.writeString(DA);
936
0
    tok.finish();
937
0
    double tf = tff.getTf();
938
0
    DA = tff.getDA();
939
940
0
    std::string (*encoder)(std::string const&, char) = &QUtil::utf8_to_ascii;
941
0
    std::string font_name = tff.getFontName();
942
0
    if (!font_name.empty()) {
943
        // See if the font is encoded with something we know about.
944
0
        Dictionary resources = AS.getDict()["/Resources"];
945
0
        Dictionary font = getFontFromResource(resources, font_name);
946
0
        if (!font) {
947
0
            font = getFontFromResource(getDefaultResources(), font_name);
948
0
            if (resources) {
949
0
                if (resources.indirect()) {
950
0
                    resources = resources.qpdf()->makeIndirectObject(resources.copy());
951
0
                    AS.getDict().replaceKey("/Resources", resources);
952
0
                }
953
                // Use mergeResources to force /Font to be local
954
0
                QPDFObjectHandle res = resources;
955
0
                res.mergeResources(Dictionary({{"/Font", Dictionary::empty()}}));
956
0
                res.getKey("/Font").replaceKey(font_name, font);
957
0
            }
958
0
        }
959
960
0
        if (Name Encoding = font["/Encoding"]) {
961
0
            if (Encoding == "/WinAnsiEncoding") {
962
0
                encoder = &QUtil::utf8_to_win_ansi;
963
0
            } else if (Encoding == "/MacRomanEncoding") {
964
0
                encoder = &QUtil::utf8_to_mac_roman;
965
0
            }
966
0
        }
967
0
    }
968
969
0
    V = (*encoder)(V, '?');
970
0
    for (size_t i = 0; i < opt.size(); ++i) {
971
0
        opt.at(i) = (*encoder)(opt.at(i), '?');
972
0
    }
973
0
    AS.addTokenFilter(
974
0
        std::shared_ptr<QPDFObjectHandle::TokenFilter>(new ValueSetter(DA, V, opt, tf, bbox)));
975
0
}