write_form.rs

Die Rust-Datei des Beispiels „Ein interaktives Formular“. Ein Formular, das ein Leser ausfüllt: Textfelder, ein Kontrollkästchen, eine Dropdown-Liste, Optionsfelder.

Rust 1622 Zeilen

Wofür dieses Beispiel da ist

Ein Formular, das gedruckt, mit Stift ausgefüllt, eingescannt und zurückgeschickt werden muss, ist ein Formular, das gut die Hälfte Ihrer Kunden nie zurückgibt. Die Alternative ist ein Dokument, das dort ausgefüllt wird, wo es gelesen wird, und getippt zurückkommt — das ist auch die einzige Fassung, die danach jemand lesen kann, und die einzige, aus der eine Maschine die Antworten herausholen kann.

Was dieses Beispiel zeigt

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
//! Writes a document with a small form: labelled boxes a reader fills in, a
//! check box a reader ticks, a drop-down a reader picks from, a set of radio
//! buttons a reader chooses one of, and a field a reader signs.
//!
//! Each text field is a labelled rectangle the reader types into. The label is
//! drawn on the page, as any other text; the box beside it is the field, empty
//! but for any value it starts with. The check box under them is ticked on or
//! off and shows a star when it is, the drop-down under that offers a set of
//! options, the radio buttons under that let one of several be chosen, and the
//! signature field under those is a place the reader signs. Reading software
//! draws what is typed, the star, the chosen option, and the dot itself. The
//! notes box at the foot of the page is shown on the screen and left off the
//! paper. The box along the right edge of the page is filled in sideways, its
//! text reading from the bottom up.
//!
//! The email field reports its answer under `customer_email` rather than under
//! its own name, which is the name the program receiving the form reads.
//!
//! Every field carries a border, so the boxes a reader clicks are plain to see.
//! The standard draws none by default. The country the form starts with is
//! drawn in hollow blue letters, filled in white and outlined in blue, as a
//! suggestion the reader may keep or type over.
//!
//! The second page is a grid of buttons, each doing one thing when pressed:
//! turning the page, going back to the form or to its signature line, sending
//! the form four ways, clearing it, filling it from a file, showing and hiding
//! the notes, opening another document or a file, printing. Under them, seven
//! buttons show an icon, one per layout of icon and caption, each fitting the
//! icon its own way and showing another while pointed at and pressed; the last
//! button answers every event a widget reports.
//!
//! The third page sets every setting a field takes: a comb of six boxes, a
//! password, a read-only reference, a required field with its help, a note
//! never sent, the five symbols a tick can take, a sorted list sending values
//! of its own, a drop-down the reader may type into, radio buttons that cannot
//! all be cleared and two of which stand for the same choice, and three
//! signature fields each freezing part of the form. The foot of the page reads
//! back the borders drawn above it, then holds two boxes that state nothing of
//! their own: the group of fields they sit in states their font, their size,
//! their centring, that they are read-only, and the order number they both
//! show, once for the two. The buttons and the settings sit on a layer of their
//! own.
//!
//! A structure tree names each of the two payment buttons as an element of its
//! own, carrying the label drawn beside it.
//!
//! The labels, the options and the document's title are held in `Words`, once
//! per language, and `HQF_PDF_LANG` picks which set is drawn. A field's name is
//! not among them: it is what a filled form's data comes back under, so it
//! stays the same whichever language the page is drawn in.
//!
//! Usage: `cargo run --example write_form -- tmp/form.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_form -- tmp/formulaire.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::action::{Action, FieldSet, MenuItem, PageTriggers, SubmitFormat, WidgetTriggers};
use hqf_pdf::content::{BorderStyle, Content, Dash};
use hqf_pdf::cos::Name;
use hqf_pdf::read::FieldKind;
use hqf_pdf::{
    AnnotationFlags, ButtonLayout, CheckBox, CheckSymbol, ChoiceField, Document, Drawing, Field,
    FieldAlign, FieldBorder, FieldGroup, FieldRotation, Font, FontHandle, IconFit, IconScale,
    IconStretch, Layer, LayerHandle, License, Page, PageFit, PressHighlight, PushButton,
    RadioGroup, Rect, Rgb, SignatureField, SignatureLock, StructElement, StructureTree, TabOrder,
    TextField,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// How many text fields the form asks for.
const TEXT_FIELDS: usize = 3;

/// The text fields the form asks for: the name a filled form's data comes back
/// under, and the value the field starts with.
const FIELDS: [(&str, &str); TEXT_FIELDS] = [("Name", ""), ("Email", ""), ("Country", "France")];

/// The names the two radio buttons send back, in the order they are drawn.
const PAYMENT_VALUES: [&str; 2] = ["card", "transfer"];

/// The payment group's place among the first page's fields: after the text
/// fields, the check box and the drop-down.
const PAYMENT_FIELD: usize = TEXT_FIELDS + 2;

/// The text field whose answer a submitted form reports under another name, and
/// that name.
const SENT_AS: (&str, &str) = ("Email", "customer_email");

/// The words the page is written in, one set per language.
///
/// A field's name is not here: it is the name a filled form's data comes back
/// under, and reading software that changed language would send back something
/// else. What a reader reads is: the labels, the options the drop-down offers,
/// the line beside each radio button, and the title the document carries.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The label drawn beside each text field, in the order `FIELDS` names
    /// them.
    labels: [&'static str; TEXT_FIELDS],
    /// The line beside the check box.
    subscribe: &'static str,
    /// The label beside the drop-down.
    plan: &'static str,
    /// The options the drop-down offers; the second is the one it starts on.
    plans: [&'static str; 2],
    /// The label beside the radio buttons.
    payment: &'static str,
    /// The line beside each radio button, in the order they are drawn.
    payments: [&'static str; 2],
    /// The label beside the signature field.
    signature: &'static str,
    /// The label above the notes box, which is shown on the screen and left off
    /// the paper.
    notes: &'static str,
    /// What the box along the right edge starts holding, read sideways.
    office: &'static str,
    /// The title the document carries in its information dictionary.
    document_title: &'static str,
    /// The second page's title.
    buttons_title: &'static str,
    /// The caption of each button of the second page, in the order
    /// [`button_actions`] gives what each does.
    button_captions: [&'static str; 17],
    /// The heading over the buttons that show an icon.
    icons_heading: &'static str,
    /// The caption of a button that shows an icon, and the one it shows while
    /// the pointer is over it and while it is pressed.
    icon_caption: &'static str,
    /// See [`Words::icon_caption`].
    rollover: &'static str,
    /// See [`Words::icon_caption`].
    pressed: &'static str,
    /// What a button that shows an icon does, told to the reader.
    icon_tip: &'static str,
    /// The caption of the button that answers every event.
    watched: &'static str,
    /// What the field that event shows says.
    hint: &'static str,
    /// The third page's title.
    settings_title: &'static str,
    /// The label beside each text field of the third page.
    text_labels: [&'static str; 5],
    /// What the code field tells the reader it wants.
    code_tip: &'static str,
    /// What the surname field tells the reader it wants.
    surname_tip: &'static str,
    /// The label beside the five ticks.
    symbols: &'static str,
    /// The label beside the list.
    list: &'static str,
    /// The values the list offers.
    colours: [&'static str; 3],
    /// The label beside the drop-down the reader may type into.
    combo: &'static str,
    /// The values that drop-down offers.
    speeds: [&'static str; 2],
    /// The label beside the radio buttons of the third page.
    delivery: &'static str,
    /// What each of those radio buttons means.
    deliveries: [&'static str; 2],
    /// The label beside each of the three signature fields.
    signatures: [&'static str; 3],
    /// What each style of border is called: solid, dashed, bevelled, inset,
    /// underlined.
    styles: [&'static str; 5],
    /// The label beside each of the two boxes of the group of fields.
    group_labels: [&'static str; 2],
    /// The line saying what the two boxes take from their group.
    group_note: &'static str,
}

impl Words {
    /// The words the page is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "Please fill in",
    labels: ["Name", "Email", "Country"],
    subscribe: "Subscribe to the newsletter",
    plan: "Plan",
    plans: ["Monthly", "Yearly"],
    payment: "Payment",
    payments: ["Card", "Transfer"],
    signature: "Signature",
    notes: "Notes, shown on the screen and left off the paper",
    office: "For office use: file 2026-0917",
    document_title: "A document with a form",
    buttons_title: "Buttons, and what pressing one does",
    button_captions: [
        "First page",
        "Previous page",
        "Next page",
        "Last page",
        "Back to the form",
        "To the signature",
        "Send as FDF",
        "Send as HTML",
        "Send as XFDF",
        "Send the whole file",
        "Clear the form",
        "Fill from a file",
        "Show the notes",
        "Hide the notes",
        "Open the terms",
        "Open the read-me",
        "Print",
    ],
    icons_heading: "Buttons with an icon: seven layouts, each fitting the icon its own way",
    icon_caption: "Stamp",
    rollover: "Over",
    pressed: "Down",
    icon_tip: "Stamps the form",
    watched: "A button that answers every event",
    hint: "The pointer is on the button",
    settings_title: "Every setting a field takes",
    text_labels: [
        "Code, six boxes",
        "PIN, hidden as typed",
        "Reference, read only",
        "Surname, required",
        "Internal note, never sent",
    ],
    code_tip: "Six letters or figures, one to a box",
    surname_tip: "As on your identity card",
    symbols: "Five ticks, each its own symbol",
    list: "Several choices, sorted",
    colours: ["Blue", "Green", "Red"],
    combo: "One choice, or your own",
    speeds: ["Normal", "Urgent"],
    delivery: "Delivery",
    deliveries: ["By post, in three days", "By courier, the next day"],
    signatures: [
        "Signing freezes the code",
        "Signing freezes all but the note",
        "Signing freezes everything",
    ],
    styles: ["solid", "dashed", "bevelled", "inset", "underlined"],
    group_labels: ["Order number", "Order number, copy"],
    group_note: "Both boxes take their font, size, centring and value from the group they sit in.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Merci de remplir ce formulaire",
    labels: ["Nom", "Courriel", "Pays"],
    subscribe: "S’abonner à la lettre d’information",
    plan: "Formule",
    plans: ["Mensuelle", "Annuelle"],
    payment: "Paiement",
    payments: ["Carte", "Virement"],
    signature: "Signature",
    notes: "Notes, visibles à l’écran, non imprimées",
    office: "Réservé à l’administration : dossier 2026-0917",
    document_title: "Un document avec un formulaire",
    buttons_title: "Des boutons, et ce que fait chacun",
    button_captions: [
        "Première page",
        "Page précédente",
        "Page suivante",
        "Dernière page",
        "Retour au formulaire",
        "Aller à la signature",
        "Envoyer en FDF",
        "Envoyer en HTML",
        "Envoyer en XFDF",
        "Envoyer tout le fichier",
        "Effacer le formulaire",
        "Remplir depuis un fichier",
        "Afficher les notes",
        "Masquer les notes",
        "Ouvrir les conditions",
        "Ouvrir le mode d’emploi",
        "Imprimer",
    ],
    icons_heading: "Des boutons à icône : sept dispositions, chacune ajustant l’icône à sa façon",
    icon_caption: "Tampon",
    rollover: "Survol",
    pressed: "Appui",
    icon_tip: "Tamponne le formulaire",
    watched: "Un bouton qui répond à chaque évènement",
    hint: "Le pointeur est sur le bouton",
    settings_title: "Tous les réglages d’un champ",
    text_labels: [
        "Code, six cases",
        "Code secret, masqué à la saisie",
        "Référence, en lecture seule",
        "Nom, obligatoire",
        "Note interne, jamais envoyée",
    ],
    code_tip: "Six lettres ou chiffres, un par case",
    surname_tip: "Comme sur votre pièce d’identité",
    symbols: "Cinq coches, cinq symboles",
    list: "Plusieurs choix, triés",
    colours: ["Bleu", "Vert", "Rouge"],
    combo: "Un choix, ou le vôtre",
    speeds: ["Normale", "Urgente"],
    delivery: "Livraison",
    deliveries: ["Par la poste, en trois jours", "Par coursier, le lendemain"],
    signatures: [
        "La signature fige le code",
        "La signature fige tout sauf la note",
        "La signature fige tout",
    ],
    styles: ["plein", "tireté", "biseauté", "en creux", "souligné"],
    group_labels: ["Numéro de commande", "Numéro de commande, copie"],
    group_note: "Les deux cases prennent police, taille, centrage et valeur du groupe qui les contient.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Graag invullen",
    labels: ["Naam", "E-mail", "Land"],
    subscribe: "Abonneren op de nieuwsbrief",
    plan: "Abonnement",
    plans: ["Maandelijks", "Jaarlijks"],
    payment: "Betaling",
    payments: ["Kaart", "Overschrijving"],
    signature: "Handtekening",
    notes: "Notities, op het scherm getoond en niet afgedrukt",
    office: "Intern gebruik: dossier 2026-0917",
    document_title: "Een document met een formulier",
    buttons_title: "Knoppen, en wat een klik erop doet",
    button_captions: [
        "Eerste pagina",
        "Vorige pagina",
        "Volgende pagina",
        "Laatste pagina",
        "Terug naar het formulier",
        "Naar de handtekening",
        "Verzenden als FDF",
        "Verzenden als HTML",
        "Verzenden als XFDF",
        "Het hele bestand verzenden",
        "Formulier wissen",
        "Invullen uit een bestand",
        "Notities tonen",
        "Notities verbergen",
        "Voorwaarden openen",
        "Leesmij openen",
        "Afdrukken",
    ],
    icons_heading: "Knoppen met pictogram: zeven indelingen, elk plaatst het pictogram anders",
    icon_caption: "Stempel",
    rollover: "Erboven",
    pressed: "Ingedrukt",
    icon_tip: "Stempelt het formulier",
    watched: "Een knop die op elke gebeurtenis reageert",
    hint: "De aanwijzer staat op de knop",
    settings_title: "Elke instelling die een veld aanneemt",
    text_labels: [
        "Code, zes vakjes",
        "Pincode, verborgen bij het typen",
        "Referentie, alleen-lezen",
        "Achternaam, verplicht",
        "Interne notitie, nooit verzonden",
    ],
    code_tip: "Zes letters of cijfers, één per vakje",
    surname_tip: "Zoals op uw identiteitskaart",
    symbols: "Vijf vinkjes, elk met eigen symbool",
    list: "Meerdere keuzes, gesorteerd",
    colours: ["Blauw", "Groen", "Rood"],
    combo: "Eén keuze, of uw eigen",
    speeds: ["Normaal", "Spoed"],
    delivery: "Levering",
    deliveries: ["Per post, in drie dagen", "Per koerier, de volgende dag"],
    signatures: [
        "Ondertekenen vergrendelt de code",
        "Tekenen vergrendelt bijna alles",
        "Ondertekenen vergrendelt alles",
    ],
    styles: [
        "doorgetrokken",
        "gestreept",
        "afgeschuind",
        "verzonken",
        "onderstreept",
    ],
    group_labels: ["Bestelnummer", "Bestelnummer, kopie"],
    group_note: "Beide vakken nemen lettertype, grootte, centrering en waarde over van hun groep.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Preencha, por favor",
    labels: ["Nome", "E-mail", "País"],
    subscribe: "Subscrever a newsletter",
    plan: "Plano",
    plans: ["Mensal", "Anual"],
    payment: "Pagamento",
    payments: ["Cartão", "Transferência"],
    signature: "Assinatura",
    notes: "Notas, visíveis no ecrã e omitidas no papel",
    office: "Uso interno: processo 2026-0917",
    document_title: "Um documento com um formulário",
    buttons_title: "Botões, e o que faz premir cada um",
    button_captions: [
        "Primeira página",
        "Página anterior",
        "Página seguinte",
        "Última página",
        "Voltar ao formulário",
        "Ir para a assinatura",
        "Enviar como FDF",
        "Enviar como HTML",
        "Enviar como XFDF",
        "Enviar o ficheiro inteiro",
        "Limpar o formulário",
        "Importar do ficheiro",
        "Mostrar as notas",
        "Ocultar as notas",
        "Abrir as condições",
        "Abrir o leia-me",
        "Imprimir",
    ],
    icons_heading: "Botões com ícone: sete disposições, cada uma encaixa o ícone a seu modo",
    icon_caption: "Carimbo",
    rollover: "Por cima",
    pressed: "Premido",
    icon_tip: "Carimba o formulário",
    watched: "Um botão que responde a cada evento",
    hint: "O ponteiro está sobre o botão",
    settings_title: "Cada definição que um campo aceita",
    text_labels: [
        "Código, seis caixas",
        "PIN, oculto ao escrever",
        "Referência, só de leitura",
        "Apelido, obrigatório",
        "Nota interna, nunca enviada",
    ],
    code_tip: "Seis letras ou algarismos, um por caixa",
    surname_tip: "Como no seu cartão de cidadão",
    symbols: "Cinco vistos com o seu símbolo",
    list: "Várias escolhas, ordenadas",
    colours: ["Azul", "Verde", "Vermelho"],
    combo: "Uma escolha, ou a sua",
    speeds: ["Normal", "Urgente"],
    delivery: "Entrega",
    deliveries: ["Por correio, em três dias", "Por estafeta, no dia seguinte"],
    signatures: [
        "Assinar congela o código",
        "Assinar congela tudo menos a nota",
        "Assinar congela tudo",
    ],
    styles: [
        "contínuo",
        "tracejado",
        "biselado",
        "embutido",
        "sublinhado",
    ],
    group_labels: ["Número da encomenda", "Número da encomenda, cópia"],
    group_note: "As duas caixas recebem tipo de letra, tamanho, centragem e valor do seu grupo.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Compilare, per favore",
    labels: ["Nome", "E-mail", "Paese"],
    subscribe: "Iscriversi alla newsletter",
    plan: "Piano",
    plans: ["Mensile", "Annuale"],
    payment: "Pagamento",
    payments: ["Carta", "Bonifico"],
    signature: "Firma",
    notes: "Note, visibili a schermo e omesse sulla carta",
    office: "Uso interno: pratica 2026-0917",
    document_title: "Un documento con un modulo",
    buttons_title: "Pulsanti, e cosa fa premerne uno",
    button_captions: [
        "Prima pagina",
        "Pagina precedente",
        "Pagina successiva",
        "Ultima pagina",
        "Torna al modulo",
        "Alla firma",
        "Invia come FDF",
        "Invia come HTML",
        "Invia come XFDF",
        "Invia l’intero file",
        "Svuota il modulo",
        "Compila da un file",
        "Mostra le note",
        "Nascondi le note",
        "Apri le condizioni",
        "Apri il leggimi",
        "Stampa",
    ],
    icons_heading: "Pulsanti con icona: sette disposizioni, ognuna adatta l’icona a modo suo",
    icon_caption: "Timbro",
    rollover: "Sopra",
    pressed: "Premuto",
    icon_tip: "Timbra il modulo",
    watched: "Un pulsante che risponde a ogni evento",
    hint: "Il puntatore è sul pulsante",
    settings_title: "Ogni impostazione che accetta un campo",
    text_labels: [
        "Codice, sei caselle",
        "PIN, nascosto mentre si digita",
        "Riferimento, sola lettura",
        "Cognome, obbligatorio",
        "Nota interna, mai inviata",
    ],
    code_tip: "Sei lettere o cifre, una per casella",
    surname_tip: "Come sulla carta d’identità",
    symbols: "Cinque spunte con il loro simbolo",
    list: "Più scelte, ordinate",
    colours: ["Blu", "Verde", "Rosso"],
    combo: "Una scelta, o la vostra",
    speeds: ["Normale", "Urgente"],
    delivery: "Consegna",
    deliveries: ["Per posta, in tre giorni", "Per corriere, il giorno dopo"],
    signatures: [
        "La firma blocca il codice",
        "La firma blocca tutto tranne la nota",
        "La firma blocca tutto",
    ],
    styles: [
        "continuo",
        "tratteggiato",
        "smussato",
        "incassato",
        "sottolineato",
    ],
    group_labels: ["Numero d’ordine", "Numero d’ordine, copia"],
    group_note: "Entrambe le caselle prendono carattere, corpo, centratura e valore dal loro gruppo.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Rellene, por favor",
    labels: ["Nombre", "Correo electrónico", "País"],
    subscribe: "Suscribirse al boletín",
    plan: "Plan",
    plans: ["Mensual", "Anual"],
    payment: "Pago",
    payments: ["Tarjeta", "Transferencia"],
    signature: "Firma",
    notes: "Notas, visibles en pantalla y omitidas en papel",
    office: "Uso interno: expediente 2026-0917",
    document_title: "Un documento con un formulario",
    buttons_title: "Botones, y lo que hace pulsar cada uno",
    button_captions: [
        "Primera página",
        "Página anterior",
        "Página siguiente",
        "Última página",
        "Volver al formulario",
        "Ir a la firma",
        "Enviar como FDF",
        "Enviar como HTML",
        "Enviar como XFDF",
        "Enviar el archivo entero",
        "Vaciar el formulario",
        "Rellenar desde un archivo",
        "Mostrar las notas",
        "Ocultar las notas",
        "Abrir las condiciones",
        "Abrir el léame",
        "Imprimir",
    ],
    icons_heading: "Botones con icono: siete disposiciones, cada una coloca el icono a su modo",
    icon_caption: "Sello",
    rollover: "Encima",
    pressed: "Pulsado",
    icon_tip: "Sella el formulario",
    watched: "Un botón que responde a cada evento",
    hint: "El puntero está sobre el botón",
    settings_title: "Cada ajuste que admite un campo",
    text_labels: [
        "Código, seis casillas",
        "PIN, oculto al teclear",
        "Referencia, solo lectura",
        "Apellido, obligatorio",
        "Nota interna, nunca enviada",
    ],
    code_tip: "Seis letras o cifras, una por casilla",
    surname_tip: "Como en su documento de identidad",
    symbols: "Cinco marcas con su símbolo",
    list: "Varias opciones, ordenadas",
    colours: ["Azul", "Verde", "Rojo"],
    combo: "Una opción, o la suya",
    speeds: ["Normal", "Urgente"],
    delivery: "Entrega",
    deliveries: [
        "Por correo, en tres días",
        "Por mensajero, al día siguiente",
    ],
    signatures: [
        "Firmar congela el código",
        "Firmar congela todo menos la nota",
        "Firmar congela todo",
    ],
    styles: [
        "continuo",
        "discontinuo",
        "biselado",
        "hundido",
        "subrayado",
    ],
    group_labels: ["Número de pedido", "Número de pedido, copia"],
    group_note: "Ambas casillas toman fuente, tamaño, centrado y valor del grupo que las contiene.",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Bitte ausfüllen",
    labels: ["Name", "E-Mail", "Land"],
    subscribe: "Newsletter abonnieren",
    plan: "Tarif",
    plans: ["Monatlich", "Jährlich"],
    payment: "Zahlung",
    payments: ["Karte", "Überweisung"],
    signature: "Unterschrift",
    notes: "Notizen, auf dem Bildschirm gezeigt und auf dem Papier weggelassen",
    office: "Für den Bürogebrauch: Akte 2026-0917",
    document_title: "Ein Dokument mit einem Formular",
    buttons_title: "Schaltflächen und was ein Klick darauf bewirkt",
    button_captions: [
        "Erste Seite",
        "Vorherige Seite",
        "Nächste Seite",
        "Letzte Seite",
        "Zurück zum Formular",
        "Zur Unterschrift",
        "Als FDF senden",
        "Als HTML senden",
        "Als XFDF senden",
        "Ganze Datei senden",
        "Formular leeren",
        "Aus einer Datei füllen",
        "Notizen zeigen",
        "Notizen verbergen",
        "Bedingungen öffnen",
        "Liesmich-Datei öffnen",
        "Drucken",
    ],
    icons_heading: "Schaltflächen mit Symbol: sieben Anordnungen, jede auf ihre Art",
    icon_caption: "Stempel",
    rollover: "Zeiger darüber",
    pressed: "Gedrückt",
    icon_tip: "Stempelt das Formular",
    watched: "Eine Schaltfläche, die auf jedes Ereignis antwortet",
    hint: "Der Zeiger ist auf der Schaltfläche",
    settings_title: "Jede Einstellung, die ein Feld annimmt",
    text_labels: [
        "Code, sechs Kästchen",
        "PIN, beim Tippen verborgen",
        "Referenz, schreibgeschützt",
        "Nachname, Pflichtfeld",
        "Interne Notiz, wird nie gesendet",
    ],
    code_tip: "Sechs Buchstaben oder Ziffern, eine pro Kästchen",
    surname_tip: "Wie auf Ihrem Personalausweis",
    symbols: "Fünf Häkchen, fünf Symbole",
    list: "Mehrfachauswahl, sortiert",
    colours: ["Blau", "Grün", "Rot"],
    combo: "Auswahl oder eigene Eingabe",
    speeds: ["Normal", "Dringend"],
    delivery: "Lieferung",
    deliveries: ["Per Post, in drei Tagen", "Per Kurier, am nächsten Tag"],
    signatures: [
        "Signieren sperrt den Code",
        "Signieren sperrt fast alles",
        "Signieren sperrt alles",
    ],
    styles: [
        "durchgezogen",
        "gestrichelt",
        "abgeschrägt",
        "vertieft",
        "unterstrichen",
    ],
    group_labels: ["Bestellnummer", "Bestellnummer, Kopie"],
    group_note: "Beide Felder übernehmen Schrift, Größe, Zentrierung und Wert von ihrer Gruppe.",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// The size the labels and the field text are set at.
const SIZE: f64 = 12.0;

/// The colour every field's border is stroked in.
const BORDER: Rgb = Rgb::gray(0.6);
/// The width every field's border is stroked at, in points.
const BORDER_WIDTH: f64 = 0.75;
/// The colour a value the form starts with is outlined in, so it reads as a
/// suggestion rather than as something the reader typed.
const SUGGESTED: Rgb = Rgb::new(0.1, 0.3, 0.7);
/// The colour the letters of a suggested value are filled in, inside their
/// outline.
const SUGGESTED_FILL: Rgb = Rgb::new(1.0, 1.0, 1.0);
/// The width a suggested value's letters are outlined at, in points.
const SUGGESTED_OUTLINE: f64 = 0.5;

/// Draws one line, with its baseline at `(x, y)`.
fn draw(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(text));
    content.end_text();
    Ok(())
}

/// The box along the right edge of the page, turned a quarter so its text runs
/// up the edge.
fn office_field(font: &FontHandle, words: &'static Words) -> TextField {
    TextField::new("Office", 500.0, 440.0, SIZE + 4.0, 280.0, font.name(), SIZE)
        .value(words.office)
        .rotation(FieldRotation::Quarter)
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
}

/// The form page: a title, then a label and a fillable box for each field.
fn form_page(font: &FontHandle, words: &'static Words) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();

    draw(&mut content, font, 20.0, 72.0, 760.0, words.title)?;

    let mut top = 700.0;
    for ((name, value), label) in FIELDS.iter().zip(words.labels) {
        draw(&mut content, font, SIZE, 72.0, top, label)?;
        let field = TextField::new(
            *name,
            180.0,
            top - 3.0,
            240.0,
            SIZE + 4.0,
            font.name(),
            SIZE,
        )
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH));
        let field = if *name == SENT_AS.0 {
            field.mapping_name(SENT_AS.1)
        } else {
            field
        };
        page.fields.push(
            if value.is_empty() {
                field
            } else {
                field
                    .value(*value)
                    .text_color(SUGGESTED_FILL)
                    .text_stroke(SUGGESTED, SUGGESTED_OUTLINE)
            }
            .into(),
        );
        top = SIZE.mul_add(-3.0, top);
    }

    draw(&mut content, font, SIZE, 90.0, top, words.subscribe)?;
    page.fields.push(
        CheckBox::new("Subscribe", 72.0, top - 2.0, SIZE, SIZE)
            .checked()
            .symbol(CheckSymbol::Star)
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
            .into(),
    );
    top = SIZE.mul_add(-3.0, top);

    draw(&mut content, font, SIZE, 72.0, top, words.plan)?;
    page.fields.push(
        ChoiceField::new(
            "Plan",
            180.0,
            top - 3.0,
            240.0,
            SIZE + 4.0,
            font.name(),
            SIZE,
        )
        .option(words.plans[0])
        .option(words.plans[1])
        .selected(words.plans[1])
        .dropdown()
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
        .into(),
    );
    top = SIZE.mul_add(-3.0, top);

    draw(&mut content, font, SIZE, 72.0, top, words.payment)?;
    page.fields.push(
        RadioGroup::new("Payment")
            .option(PAYMENT_VALUES[0], 180.0, top - 3.0, SIZE, SIZE)
            .option(PAYMENT_VALUES[1], 320.0, top - 3.0, SIZE, SIZE)
            .selected(PAYMENT_VALUES[0])
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
            .into(),
    );
    draw(&mut content, font, SIZE, 198.0, top, words.payments[0])?;
    draw(&mut content, font, SIZE, 338.0, top, words.payments[1])?;
    top = SIZE.mul_add(-4.0, top);

    draw(&mut content, font, SIZE, 72.0, top, words.signature)?;
    page.fields.push(
        SignatureField::new("Signature", 180.0, top - 12.0, 240.0, 40.0)
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
            .into(),
    );
    top = SIZE.mul_add(-5.0, top);

    // Neither printed nor hidden: on the screen, and off the paper.
    draw(&mut content, font, SIZE, 72.0, top, words.notes)?;
    page.fields.push(
        TextField::new(
            "Notes",
            72.0,
            top - 42.0,
            348.0,
            SIZE + 20.0,
            font.name(),
            SIZE,
        )
        .multiline()
        .flags(AnnotationFlags::none())
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
        .into(),
    );

    page.fields.push(office_field(font, words).into());

    page.content = content.into_bytes();
    Ok(page)
}

/// The left edge of the fields of the third page.
const FIELD_X: f64 = 300.0;

/// Where a submitted form is sent.
const SUBMIT_TO: &str = "https://hqf-pdf.com/forms/submit";

/// The group of fields at the foot of the third page.
const ORDER_GROUP: &str = "Order";

/// The partial names of the two fields of that group.
const ORDER_FIELDS: [&str; 2] = ["Number", "Copy"];

/// The value the group hands down to both its fields.
const ORDER_NUMBER: &str = "2026-0917";

/// The group the two fields at the foot of the third page sit in: it states,
/// once, the kind, the font and size, the centring, the read-only flag and the
/// value both take.
fn order_group(font: &FontHandle) -> FieldGroup {
    FieldGroup::new([ORDER_GROUP])
        .kind(FieldKind::Text)
        .read_only()
        .default_appearance(font.name(), SIZE)
        .align(FieldAlign::Center)
        .value(ORDER_NUMBER)
}

/// The width and height of a button of the second page.
const BUTTON: (f64, f64) = (150.0, 22.0);

/// The left edge of each of the three columns of buttons.
const BUTTON_COLUMNS: [f64; 3] = [72.0, 232.0, 392.0];

/// The values the list offers, each sent back under a name of its own.
const LIST_EXPORTS: [&str; 3] = ["blue", "green", "red"];

/// What each of the buttons of the second page does, in the order their
/// captions are drawn.
fn button_actions() -> [Action; 17] {
    [
        Action::MenuItem(MenuItem::FirstPage),
        Action::MenuItem(MenuItem::PreviousPage),
        Action::MenuItem(MenuItem::NextPage),
        Action::MenuItem(MenuItem::LastPage),
        Action::Page {
            index: 0,
            view: PageFit::FullWidth { top: 780.0 },
        },
        Action::Named("signature".to_owned()),
        Action::SubmitFields {
            url: SUBMIT_TO.to_owned(),
            fields: FieldSet::All,
            format: SubmitFormat::Fdf {
                with_no_value: true,
            },
        },
        Action::SubmitFields {
            url: SUBMIT_TO.to_owned(),
            fields: FieldSet::Only(vec!["Name".to_owned(), "Email".to_owned()]),
            format: SubmitFormat::Html {
                get: false,
                with_click: true,
            },
        },
        Action::SubmitFields {
            url: SUBMIT_TO.to_owned(),
            fields: FieldSet::AllBut(vec!["Notes".to_owned()]),
            format: SubmitFormat::Xfdf,
        },
        Action::SubmitFields {
            url: SUBMIT_TO.to_owned(),
            fields: FieldSet::All,
            format: SubmitFormat::WholeDocument { get: false },
        },
        Action::ResetFields(FieldSet::All),
        Action::ImportFields {
            file: "answers.fdf".to_owned(),
        },
        Action::Show(vec!["Notes".to_owned()]),
        Action::Hide(vec!["Notes".to_owned()]),
        Action::OtherDocument {
            file: "terms.pdf".to_owned(),
            page: 0,
            view: PageFit::WholePage,
            element: None,
            new_window: Some(true),
        },
        Action::Launch {
            file: "readme.txt".to_owned(),
            new_window: Some(false),
        },
        Action::ViewerCommand("Print".to_owned()),
    ]
}

/// A small stamp drawn once, the icon the buttons of the second page show.
fn stamp() -> Result<Drawing, hqf_pdf::Error> {
    let mut icon = Content::new();
    icon.set_fill(Rgb::new(0.75, 0.15, 0.15))?;
    icon.circle(10.0, 10.0, 9.0)?.fill();
    icon.set_fill(Rgb::gray(1.0))?;
    icon.rect(6.0, 6.0, 8.0, 8.0)?.fill();
    Ok(Drawing::new(icon, Rect::new(0.0, 0.0, 20.0, 20.0)))
}

/// The same stamp in blue, shown while the pointer is over a button or the
/// button is pressed.
fn stamp_pressed() -> Result<Drawing, hqf_pdf::Error> {
    let mut icon = Content::new();
    icon.set_fill(Rgb::new(0.15, 0.3, 0.75))?;
    icon.circle(10.0, 10.0, 9.0)?.fill();
    Ok(Drawing::new(icon, Rect::new(0.0, 0.0, 20.0, 20.0)))
}

/// The second page: a grid of buttons, each doing one thing when pressed, and a
/// row of buttons that show an icon, laid out and fitted each its own way.
#[allow(
    clippy::too_many_lines,
    reason = "the page is one list of buttons, read from top to bottom"
)]
fn buttons_page(
    doc: &mut Document,
    font: &FontHandle,
    words: &'static Words,
    layer: &LayerHandle,
) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();
    page.tab_order = Some(TabOrder::Row);
    draw(&mut content, font, 20.0, 72.0, 760.0, words.buttons_title)?;

    let mut top = 710.0;
    for ((place, (caption, action)), rank) in words
        .button_captions
        .iter()
        .zip(button_actions())
        .enumerate()
        .zip(0_u32..)
    {
        let column = BUTTON_COLUMNS[place % BUTTON_COLUMNS.len()];
        if place > 0 && place % BUTTON_COLUMNS.len() == 0 {
            top -= 34.0;
        }
        page.fields.push(Field::Push(
            PushButton::new(
                format!("Button{place}"),
                column,
                top,
                BUTTON.0,
                BUTTON.1,
                font.name(),
                10.0,
            )
            .caption(*caption)
            .action(action)
            .background(Rgb::gray(0.93))
            .border(FieldBorder::beveled(BORDER, BORDER_WIDTH))
            .tab_rank(rank),
        ));
    }

    // The buttons that show an icon: one per layout, each fitting the icon its
    // own way.
    top -= 60.0;
    draw(&mut content, font, SIZE, 72.0, top, words.icons_heading)?;
    let icon = doc.add_drawing(stamp()?);
    let pressed = doc.add_drawing(stamp_pressed()?);
    let layouts = [
        (
            ButtonLayout::CaptionOnly,
            IconFit::new().scale(IconScale::Always),
        ),
        (
            ButtonLayout::IconOnly,
            IconFit::new().scale(IconScale::WhenBigger),
        ),
        (
            ButtonLayout::CaptionBelowIcon,
            IconFit::new().scale(IconScale::WhenSmaller),
        ),
        (
            ButtonLayout::CaptionAboveIcon,
            IconFit::new().scale(IconScale::Never),
        ),
        (
            ButtonLayout::CaptionRightOfIcon,
            IconFit::new().stretch(IconStretch::Proportional),
        ),
        (
            ButtonLayout::CaptionLeftOfIcon,
            IconFit::new().stretch(IconStretch::Anamorphic),
        ),
        (
            ButtonLayout::CaptionOverIcon,
            IconFit::new().leftover(0.0, 1.0).ignore_border(),
        ),
    ];
    let highlights = [
        PressHighlight::None,
        PressHighlight::Invert,
        PressHighlight::Outline,
        PressHighlight::Push,
    ];
    let rotations = [
        FieldRotation::Upright,
        FieldRotation::Half,
        FieldRotation::ThreeQuarters,
    ];
    top -= 70.0;
    let mut x = 72.0;
    for (place, (layout, fit)) in layouts.into_iter().enumerate() {
        let button = PushButton::new(
            format!("Stamp{place}"),
            x,
            top,
            60.0,
            50.0,
            font.name(),
            8.0,
        )
        .caption(words.icon_caption)
        .rollover_caption(words.rollover)
        .down_caption(words.pressed)
        .icon(&icon)
        .rollover_icon(&pressed)
        .down_icon(&pressed)
        .layout(layout)
        .icon_fit(fit)
        .text_color(Rgb::new(0.1, 0.1, 0.4))
        .border(FieldBorder::inset(BORDER, BORDER_WIDTH))
        .highlight(highlights[place % highlights.len()])
        .rotation(rotations[place % rotations.len()])
        .tooltip(words.icon_tip)
        .description(words.icon_tip)
        .mapping_name(format!("stamp_{place}"))
        .flags(AnnotationFlags::none().printed().no_zoom())
        .layer(layer);
        page.fields.push(Field::Push(match place {
            0 => button.read_only(),
            1 => button.required(),
            2 => button.no_export(),
            _ => button,
        }));
        x += 68.0;
    }

    // One more button, which answers to every event a widget reports.
    top -= 50.0;
    page.fields.push(Field::Push(
        PushButton::new("Watched", 72.0, top, 230.0, BUTTON.1, font.name(), 10.0)
            .caption(words.watched)
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
            .triggers(
                WidgetTriggers::new()
                    .enter(Action::Show(vec!["Hint".to_owned()]))
                    .exit(Action::Hide(vec!["Hint".to_owned()]))
                    .up(Action::MenuItem(MenuItem::NextPage))
                    .focused(Action::Show(vec!["Hint".to_owned()]))
                    .blurred(Action::Hide(vec!["Hint".to_owned()]))
                    .page_opened(Action::Hide(vec!["Hint".to_owned()]))
                    .page_closed(Action::Hide(vec!["Hint".to_owned()]))
                    .page_shown(Action::Hide(vec!["Hint".to_owned()]))
                    .page_hidden(Action::Hide(vec!["Hint".to_owned()])),
            ),
    ));
    page.fields.push(Field::Text(
        TextField::new("Hint", 320.0, top, 200.0, BUTTON.1, font.name(), 9.0)
            .value(words.hint)
            .read_only()
            .flags(AnnotationFlags::none().hidden()),
    ));

    page.content = content.into_bytes();
    Ok(page)
}

/// The words a field's border is described by, from the style it reads back.
#[allow(
    clippy::match_same_arms,
    reason = "a style the page has no word for reads as the plainest one"
)]
const fn style_name(words: &Words, style: &BorderStyle) -> &'static str {
    match style {
        BorderStyle::Solid => words.styles[0],
        BorderStyle::Dashed(_) => words.styles[1],
        BorderStyle::Beveled => words.styles[2],
        BorderStyle::Inset => words.styles[3],
        BorderStyle::Underline => words.styles[4],
        _ => words.styles[0],
    }
}

/// The third page: every setting a field takes, one field after another.
#[allow(
    clippy::too_many_lines,
    reason = "the page is one list of fields, read from top to bottom"
)]
fn settings_page(
    font: &FontHandle,
    words: &'static Words,
    layer: &LayerHandle,
) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();
    page.tab_order = Some(TabOrder::Column);
    page.triggers = PageTriggers::new()
        .opened(Action::Show(vec!["Code".to_owned()]))
        .closed(Action::ResetFields(FieldSet::Only(vec!["Pin".to_owned()])));
    draw(&mut content, font, 20.0, 72.0, 760.0, words.settings_title)?;

    let dashed = FieldBorder::dashed(BORDER, 1.0, Dash::on_off(3.0, 2.0)?);
    let beveled = FieldBorder::beveled(BORDER, BORDER_WIDTH);
    let inset = FieldBorder::inset(BORDER, BORDER_WIDTH);

    let mut top = 710.0;
    let text_fields = [
        TextField::new(
            "Code",
            FIELD_X,
            top - 3.0,
            120.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .max_length(6)
        .comb(6)
        .tooltip(words.code_tip)
        .align(FieldAlign::Center)
        .border(dashed.clone()),
        TextField::new(
            "Pin",
            FIELD_X,
            top - 33.0,
            120.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .password()
        .required()
        .border(beveled.clone()),
        TextField::new(
            "Reference",
            FIELD_X,
            top - 63.0,
            200.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .value("HQF-2026-0917")
        .default_value("HQF-2026-0917")
        .read_only()
        .align(FieldAlign::Right)
        .border(inset.clone()),
        TextField::new(
            "Surname",
            FIELD_X,
            top - 93.0,
            200.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .required()
        .description(words.surname_tip)
        .background(Rgb::new(1.0, 0.98, 0.85))
        .highlight(PressHighlight::Outline)
        .tab_rank(1)
        .triggers(WidgetTriggers::new().blurred(Action::Show(vec!["Surname".to_owned()])))
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH)),
        TextField::new(
            "Internal",
            FIELD_X,
            top - 123.0,
            200.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .no_export()
        .layer(layer)
        .border(FieldBorder::underline(BORDER, BORDER_WIDTH)),
    ];
    for (field, label) in text_fields.into_iter().zip(words.text_labels) {
        draw(&mut content, font, SIZE, 72.0, top, label)?;
        page.fields.push(Field::Text(field));
        top -= 30.0;
    }

    // The five symbols a tick can take, each box sending back "yes".
    draw(&mut content, font, SIZE, 72.0, top, words.symbols)?;
    let symbols = [
        CheckSymbol::Check,
        CheckSymbol::Cross,
        CheckSymbol::Circle,
        CheckSymbol::Diamond,
        CheckSymbol::Square,
    ];
    let mut x = FIELD_X;
    for (place, symbol) in symbols.into_iter().enumerate() {
        let tick = CheckBox::new(format!("Tick{place}"), x, top - 2.0, SIZE, SIZE)
            .symbol(symbol)
            .export_value("yes")
            .background(Rgb::gray(0.97))
            .highlight(PressHighlight::Push)
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH));
        page.fields.push(Field::Check(match place {
            0 => tick.checked().checked_by_default(),
            1 => tick.read_only(),
            2 => tick.required().description(words.symbols),
            3 => tick.no_export().tab_rank(2),
            _ => tick
                .layer(layer)
                .triggers(WidgetTriggers::new().up(Action::Show(vec!["Code".to_owned()]))),
        }));
        x += 30.0;
    }
    top -= 40.0;

    // A list offering several values at once, sorted, each sent back under a
    // name of its own; then a drop-down the reader may also type into.
    draw(&mut content, font, SIZE, 72.0, top, words.list)?;
    let mut list = ChoiceField::new(
        "Colours",
        FIELD_X,
        top - 44.0,
        150.0,
        56.0,
        font.name(),
        SIZE,
    )
    .multi_select()
    .sorted()
    .required()
    .background(Rgb::gray(0.97))
    .highlight(PressHighlight::Invert)
    .tab_rank(3)
    .description(words.list)
    .layer(layer)
    .triggers(WidgetTriggers::new().blurred(Action::Show(vec!["Colours".to_owned()])))
    .border(dashed.clone());
    for (label, export) in words.colours.iter().zip(LIST_EXPORTS) {
        list = list.option_with_export(export, *label);
    }
    page.fields
        .push(Field::Choice(list.default_selected(LIST_EXPORTS[0])));
    top -= 70.0;

    draw(&mut content, font, SIZE, 72.0, top, words.combo)?;
    page.fields.push(Field::Choice(
        ChoiceField::new(
            "Speed",
            FIELD_X,
            top - 3.0,
            150.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .option(words.speeds[0])
        .option(words.speeds[1])
        .dropdown()
        .editable()
        .default_selected(words.speeds[0])
        .align(FieldAlign::Center)
        .border(beveled.clone()),
    ));
    page.fields.push(Field::Choice(
        ChoiceField::new(
            "SpeedCopy",
            FIELD_X + 160.0,
            top - 3.0,
            110.0,
            SIZE + 6.0,
            font.name(),
            SIZE,
        )
        .option(words.speeds[0])
        .dropdown()
        .read_only()
        .no_export()
        .align(FieldAlign::Right)
        .border(inset.clone()),
    ));
    top -= 40.0;

    // Two ways of delivery, each described; the group cannot be emptied again,
    // and a third button stands for the same choice as the first.
    draw(&mut content, font, SIZE, 72.0, top, words.delivery)?;
    page.fields.push(Field::Radio(
        RadioGroup::new("Delivery")
            .option("post", FIELD_X, top - 3.0, SIZE, SIZE)
            .option("courier", FIELD_X + 80.0, top - 3.0, SIZE, SIZE)
            .option("post", FIELD_X + 160.0, top - 3.0, SIZE, SIZE)
            .default_selected("post")
            .description("post", words.deliveries[0])
            .description("courier", words.deliveries[1])
            .no_toggle_to_off()
            .in_unison()
            .required()
            .background(Rgb::gray(0.97))
            .highlight(PressHighlight::Outline)
            .tab_rank(4)
            .layer(layer)
            .triggers(WidgetTriggers::new().up(Action::Show(vec!["Delivery".to_owned()])))
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH)),
    ));
    page.fields.push(Field::Radio(
        RadioGroup::new("Wrapping")
            .option("paper", FIELD_X, top - 23.0, SIZE, SIZE)
            .read_only()
            .no_export()
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH)),
    ));
    top -= 60.0;

    // Three signature fields, each freezing part of the form once signed.
    for (place, (label, lock)) in words
        .signatures
        .iter()
        .zip([
            SignatureLock::only(["Code"]),
            SignatureLock::all_but(["Internal"]),
            SignatureLock::all(),
        ])
        .enumerate()
    {
        draw(&mut content, font, SIZE, 72.0, top, label)?;
        let field = SignatureField::new(format!("Sign{place}"), FIELD_X, top - 20.0, 200.0, 34.0)
            .locks(lock)
            .tooltip(*label)
            .description(*label)
            .background(Rgb::gray(0.97))
            .tab_rank(5)
            .highlight(PressHighlight::Invert)
            .layer(layer)
            .triggers(WidgetTriggers::new().focused(Action::Show(vec!["Code".to_owned()])))
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH));
        page.fields.push(Field::Signature(match place {
            0 => field.required(),
            1 => field.read_only(),
            _ => field.no_export(),
        }));
        top -= 44.0;
    }

    // What each of the borders above is, read back from the border itself.
    for border in [dashed, beveled, inset] {
        let line = format!(
            "{}, {} pt, {}",
            style_name(words, border.style()),
            border.width(),
            border
                .color()
                .to_components()
                .iter()
                .map(|value| format!("{value:.1}"))
                .collect::<Vec<_>>()
                .join(" ")
        );
        draw(&mut content, font, 9.0, 72.0, top, &line)?;
        top -= 14.0;
    }

    // Two boxes stating nothing of their own: the group above them states it.
    top -= 10.0;
    draw(&mut content, font, 9.0, 72.0, top, words.group_note)?;
    top -= 24.0;
    for (child, label) in ORDER_FIELDS.iter().zip(words.group_labels) {
        draw(&mut content, font, SIZE, 72.0, top, label)?;
        page.fields.push(Field::Text(
            TextField::in_group(
                format!("{ORDER_GROUP}.{child}"),
                FIELD_X,
                top - 3.0,
                200.0,
                SIZE + 6.0,
            )
            .border(FieldBorder::solid(BORDER, BORDER_WIDTH)),
        ));
        top -= 30.0;
    }

    page.content = content.into_bytes();
    Ok(page)
}

/// The structure tree: the payment group's two buttons, each a `Form` element
/// named by its label, gathered in a `Div`.
fn payment_tree(words: &Words) -> StructureTree {
    let mut group = StructElement::new("Div");
    for (button, label) in words.payments.iter().enumerate() {
        group = group.child(
            StructElement::new("Form")
                .button(0, PAYMENT_FIELD, button)
                .alt(*label),
        );
    }
    StructureTree::new().child(StructElement::new("Document").child(group))
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args: Vec<String> = env::args().skip(1).collect();

    let evaluation = args.iter().any(|arg| arg == "--evaluation");
    args.retain(|arg| !arg.starts_with("--"));

    let mut args = args.into_iter();
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("form")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(if evaluation {
        License::evaluation()
    } else {
        licence::licensed()
    });
    doc.set_info(Name::new("Title"), words.document_title);

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    doc.add_page(form_page(&font, words)?)?;

    // The buttons and the settings sit on a layer of their own, which reading
    // software can hide; the signature line of the first page is a named place
    // a button goes to.
    let layer = doc.add_layer(Layer::new("Controls"))?;
    doc.add_destination(
        "signature",
        0,
        PageFit::Fixed {
            left: Some(72.0),
            top: Some(400.0),
            zoom: None,
        },
    )?;
    let buttons = buttons_page(&mut doc, &font, words, &layer)?;
    doc.add_page(buttons)?;
    doc.add_page(settings_page(&font, words, &layer)?)?;
    doc.add_field_group(order_group(&font))?;
    doc.set_structure(payment_tree(words));

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;
    println!("wrote {} ({} bytes)", path, bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font};

    use super::{BUTTON, FIELD_X, SIZE, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. A form asks
    /// for a signature under the same word in English and in French.
    const SPARED: [&str; 26] = [
        "signature: \"Signature\"",
        // Written the same way in German.
        r#""Name""#,
        r#""Normal""#,
        // Written the same way in Spanish.
        r#""Urgente""#,
        r#"plan: "Plan""#,
        // Written the same way in Italian.
        r#""Normale""#,
        r#""Verde""#,
        r#""continuo""#,
        r#"signature: "Firma""#,
        // Written the same way in Portuguese.
        r#""Anual""#,
        r#""Azul""#,
        r#""E-mail""#,
        r#""Enviar como FDF""#,
        r#""Enviar como HTML""#,
        r#""Enviar como XFDF""#,
        r#""Imprimir""#,
        r#""Nome""#,
        r#""Nota interna, nunca enviada""#,
        r#""País""#,
        r#""Página anterior""#,
        r#""biselado""#,
        r#""Última página""#,
        r#"delivery: "Entrega""#,
        r#"payment: "Pagamento""#,
        // Written the same way in Dutch.
        r#""Land""#,
        r#"icon_caption: "Stempel""#,
    ];

    #[test]
    fn every_language_draws_the_page_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the form says these in more than one language: {untranslated:?}"
        );
    }

    /// A caption wider than its button, or a label running into the field
    /// beside it, would be cut or overlap.
    #[test]
    fn every_caption_and_label_fits_its_room() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        for (_, words) in WORDS {
            for caption in words.button_captions {
                let width = font.measure(caption, 10.0);
                assert!(width <= BUTTON.0 - 8.0, "{caption:?} needs {width}");
            }
            let labels = words
                .text_labels
                .iter()
                .chain(&words.signatures)
                .chain(&words.group_labels)
                .chain([&words.symbols, &words.list, &words.combo, &words.delivery]);
            for label in labels {
                let width = font.measure(label, SIZE);
                assert!(width <= FIELD_X - 80.0, "{label:?} needs {width}");
            }
            let heading = font.measure(words.icons_heading, SIZE);
            assert!(
                heading <= 460.0,
                "{:?} needs {heading}",
                words.icons_heading
            );
            let note = font.measure(words.group_note, 9.0);
            assert!(note <= 460.0, "{:?} needs {note}", words.group_note);
        }
    }
}