write_redaction.rs

Le fichier Rust de l’exemple « Une déposition dont une partie est masquée avant d’être communiquée ». Trois marques mesurées sur les mots mêmes qu’elles couvrent : l’une montre le motif au milieu de son emplacement, l’autre le répète sur toute la longueur d’un emplacement plus large, la troisième couvre sans un mot. Une marque dit ce qui doit partir ; elle ne l’enlève pas.

Rust 1309 lignes

À quoi sert cet exemple

Une déposition est transmise entière à la partie adverse, et ce qui identifie le témoin ne l’accompagne pas : le nom, l’adresse, le compte. Les trois boîtes de cette page sont mesurées sur les lignes mêmes qu’elles couvrent — la largeur des mots, la hauteur qu’ils atteignent au-dessus et au-dessous de la ligne — au lieu d’être posées sur une zone que quelqu’un a jugée à peu près bonne. Chacune dit aussi ce qui doit tenir lieu du texte qu’elle masque : la première affiche le motif en son centre, la deuxième le répète tout le long d’un espace trop large pour qu’un seul mot le couvre, et la troisième masque sans rien dire.

Ce que montre cet exemple

   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
//! Marks what has to come out of a statement before it is released.
//!
//! A redaction is a mark, and only a mark. It states which part of the page
//! must go, what is to be shown in its place, and what colour fills the gap —
//! and all three describe the page as it will be once a reading software has
//! applied the mark and written the document out again. Until then the words
//! are still in the file under the box, and a search finds them. That is the
//! mistake this page is laid out to make visible.
//!
//! The upper half is the statement as it is released: the entries readable,
//! each under a mark that covers exactly the words it hides, because every box
//! is measured off the line it stands on rather than guessed.
//!
//! Under the statement, one line carries the five marks a reviewer lays on a
//! passage without asking for anything to go: each word is highlighted,
//! underlined, struck through or squiggled under, as it says, and a caret in
//! the last gap marks where the last word is to be inserted. The patches are
//! read off the laid-out line, never measured by hand. The reviewer has also
//! circled the line's label freehand, with an arrow to the line, and left a
//! sticky note at its end.
//!
//! The lower half is drawn by this example, in its own ink, to show what those
//! three redactions ask for. The first shows a word in the middle of the gap.
//! The second repeats it along the whole width, which is what a long entry
//! needs so that the reason stays legible across it. The third shows nothing at
//! all.
//!
//! The second page lays every other kind of mark, each carrying a name, flags
//! that keep it on the paper, a layer of its own, a border, an action when it
//! is clicked and another when the pointer comes onto it and leaves it: a box
//! with a dashed border, a ring the mark draws itself, lines ending eight other
//! ways, an area, a run, a note under each of six icons, a file pinned under
//! three, a stroke by hand, a caret, an underline and a redaction over two
//! areas, the last two read back for what they hold.
//!
//! Usage: `cargo run --example write_redaction -- tmp/redaction.pdf`
//!        `HQF_PDF_LANG=fr cargo run --example write_redaction -- tmp/caviarde.pdf`

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

use hqf_pdf::action::{Action, MenuItem, WidgetTriggers};
use hqf_pdf::annotation::{
    Annotation, AnnotationBorder, AttachmentIcon, BorderEffect, Caret, Circle, FileAttachment,
    FreeText, Ink, Line, LineEnding, MarkStyle, NoteIcon, PolyLine, Polygon, Redaction, Square,
    StickyNote, TextMark,
};
use hqf_pdf::content::{Content, Dash};
use hqf_pdf::form::FieldAlign;
use hqf_pdf::layout::{Quad, Rect, RichText, Style, TextFlow};
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::{AnnotationFlags, Document, Font, FontHandle, Layer, Page, PageFit, Rgb};

#[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.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The margin the page is laid out inside.
const MARGIN: f64 = 56.0;

/// How far the page runs across, between the margins.
const WIDTH: f64 = 483.0;

/// How far the value of an entry stands from the margin.
const VALUE: f64 = 160.0;

/// The size the entries are set in.
const SIZE: f64 = 11.0;

/// The size the word in a gap is set in.
const SHOWN_SIZE: f64 = 9.0;

/// How far a mark reaches above and below the baseline of the line it covers.
const OVER: f64 = 3.0;
const UNDER: f64 = 3.0;

/// How many entries of the statement are struck out.
const STRUCK: usize = 3;

/// Where each entry's baseline sits, as released.
const ROWS: [f64; STRUCK] = [700.0, 676.0, 652.0];

/// Where each gap's baseline sits, in the half drawn to show what the marks ask
/// for.
const SHOWN_ROWS: [f64; STRUCK] = [486.0, 462.0, 438.0];

/// Where the box of the line carrying the five review marks starts, from the
/// top.
const REVIEW_TOP: f64 = 562.0;

/// The side of the square a sticky note's icon is drawn in.
const NOTE: f64 = 20.0;

/// The loop drawn freehand around the review line's label, as offsets on an
/// ellipse of unit half-axes centred on the label, in the order the pen went.
const LOOP: [(f64, f64); 13] = [
    (-1.0, 0.1),
    (-0.92, -0.55),
    (-0.6, -0.95),
    (0.0, -1.08),
    (0.62, -0.97),
    (0.97, -0.5),
    (1.04, 0.12),
    (0.9, 0.66),
    (0.5, 1.0),
    (-0.05, 1.06),
    (-0.6, 0.92),
    (-0.95, 0.48),
    (-1.06, -0.08),
];

/// The colour a highlight is painted in.
const HIGHLIGHT: Rgb = Rgb::new(1.0, 0.85, 0.2);

/// The colour the three stroked marks are drawn in.
const REVIEW_INK: Rgb = Rgb::new(0.75, 0.1, 0.1);

/// What each entry states. None of it is anybody's: the statement is written
/// for this page.
const ENTRIES: [&str; STRUCK] = [
    "Claire Vasseur",
    "14 rue des Lilas, 59000 Lille",
    "FR76 3000 1007 9412 3456 7890 185",
];

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The heading over the statement as it is released.
    released: &'static str,
    /// The heading over the half drawn to show what the marks ask for.
    applied: &'static str,
    /// What each struck-out entry is called.
    labels: [&'static str; STRUCK],
    /// What the line carrying the review marks is called.
    review: &'static str,
    /// The five words of that line, each naming the mark it carries: the
    /// highlight, the underline, the strike-out, the squiggle and the caret
    /// before the last word.
    marked: [&'static str; 5],
    /// What the loop drawn freehand around the review line's label says.
    circled: &'static str,
    /// What the sticky note at the end of the review line says.
    note: &'static str,
    /// The word shown in the first gap, and repeated along the second.
    shown: &'static str,
    /// The paragraph the statement is released with.
    body: &'static str,
    /// The line under it all.
    caption: &'static str,
    /// The second page's title, and the paragraph under it.
    marks_title: &'static str,
    /// See [`Words::marks_title`].
    marks_lead: &'static str,
    /// The name of the layer the marks of the second page belong to.
    layer: &'static str,
    /// What the attached file is, told to the reader.
    attachment: &'static str,
    /// What each row of the second page shows. `{dash}`, `{style}`, `{areas}`
    /// and `{shows}` stand for what is read back from the mark.
    rows: [&'static str; 12],
    /// The word the underline of the second page is laid under.
    sample: &'static str,
    /// What each style of text mark is called: highlight, underline,
    /// strike-out, squiggle.
    styles: [&'static str; 4],
    /// What a redaction that shows no words shows.
    nothing: &'static str,
    /// The words the remark of the last row lays in its box.
    remark: &'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: "Witness statement, released in part",
    released: "As it is released",
    applied: "As a reading software shows it once it has applied the marks",
    labels: ["Name", "Address", "Account"],
    review: "Review",
    marked: [
        "highlighted",
        "underlined",
        "struck",
        "squiggled",
        "inserted",
    ],
    circled: "circled by hand",
    note: "None of these five marks asks for anything to go.",
    shown: "REDACTED",
    body: "The statement itself is released whole. What identifies the witness \
           is struck out above: the name shows the reason in the middle of its \
           gap, the address repeats it along the length of a longer one, and \
           the account is covered without a word.",
    caption: "A mark says what must go. It does not take it out. Until a reading \
              software applies these marks and writes the document out again, \
              the words are still under the boxes and a search finds them — \
              which is why the lower half is drawn here in this example's own \
              ink, and is not what the file states.",
    marks_title: "What else a mark can carry",
    marks_lead: "Each mark below carries a name, flags that decide where it shows, a layer of \
its own, a border, and something to do when it is clicked or pointed at.",
    layer: "Review",
    attachment: "The statement, as a file",
    rows: [
        "A box with a dashed border, dash {dash}",
        "A ring the mark draws itself",
        "Lines ending eight other ways",
        "An area that goes to the first page",
        "A run that answers the pointer",
        "Six note icons, the first left open",
        "A file pinned under three icons",
        "A stroke by hand",
        "A caret where a paragraph begins",
        "A mark read back: {style}, {areas} area",
        "A redaction over {areas} areas, showing {shows}",
        "Words laid in a box of their own",
    ],
    sample: "sample",
    styles: ["highlight", "underline", "strike-out", "squiggle"],
    nothing: "nothing",
    remark: "Totals to check against the delivery note",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Déposition de témoin, communiquée en partie",
    released: "Telle qu’elle est communiquée",
    applied: "Telle qu’un logiciel de lecture l’affiche une fois les marques appliquées",
    labels: ["Nom", "Adresse", "Compte"],
    review: "Relecture",
    marked: ["surligné", "souligné", "barré", "ondulé", "inséré"],
    circled: "entouré à main levée",
    note: "Aucune de ces cinq marques ne demande de retirer quoi que ce soit.",
    shown: "CAVIARDÉ",
    body: "La déposition elle-même est communiquée en entier. Ce qui identifie le témoin \
est caviardé ci-dessus\u{a0}: sur le nom, le motif figure au milieu de la zone \
masquée\u{a0}; sur l’adresse, plus longue, il se répète d’un bout à l’autre\u{a0}; le \
compte est masqué sans un mot.",
    caption: "Une marque dit ce qui doit disparaître. Elle ne l’enlève pas. Tant qu’un \
logiciel de lecture n’a pas appliqué ces marques et réécrit le document, les \
mots restent sous les marques et une recherche les trouve\u{a0}— c’est pourquoi la \
moitié inférieure est tracée ici avec l’encre propre de cet exemple\u{a0}: elle ne \
reflète pas le contenu du fichier.",
    marks_title: "Ce qu’une marque peut contenir d’autre",
    marks_lead: "Chaque marque ci-dessous contient un nom, des indicateurs qui déterminent où \
elle s’affiche, son propre calque, une bordure et une action au clic ou au \
survol.",
    layer: "Relecture",
    attachment: "La déposition sous forme de fichier",
    rows: [
        "Un cadre à bordure en tirets, motif {dash}",
        "Un anneau que la marque trace elle-même",
        "Des lignes terminées de huit autres façons",
        "Une zone qui mène à la première page",
        "Un tracé qui réagit au pointeur",
        "Six icônes de note, la première ouverte",
        "Un fichier joint sous trois icônes",
        "Un trait à main levée",
        "Un signe d’insertion en début de paragraphe",
        "Une marque lue\u{a0}: {style}, {areas}\u{a0}zone",
        "Un caviardage sur {areas}\u{a0}zones, texte affiché\u{a0}: {shows}",
        "Un texte posé dans son propre cadre",
    ],
    sample: "exemple",
    styles: [
        "surlignage",
        "soulignement",
        "biffure",
        "soulignement ondulé",
    ],
    nothing: "rien",
    remark: "Totaux à rapprocher du bon de livraison",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Getuigenverklaring, gedeeltelijk vrijgegeven",
    released: "Zoals ze vrijgegeven wordt",
    applied: "Zoals leessoftware haar toont nadat de markeringen zijn toegepast",
    labels: ["Naam", "Adres", "Rekening"],
    review: "Beoordeling",
    marked: [
        "gemarkeerd",
        "onderstreept",
        "doorgestreept",
        "gekronkeld",
        "ingevoegd",
    ],
    circled: "met de hand omcirkeld",
    note: "Geen van deze vijf markeringen vraagt dat er iets verdwijnt.",
    shown: "WEGGELAKT",
    body: "De verklaring zelf wordt volledig vrijgegeven. Wat de getuige identificeert, is hierboven weggelakt: de naam toont de reden midden in zijn gat, het adres herhaalt haar over de lengte van een langer gat, en de rekening wordt zonder een woord afgedekt.",
    caption: "Een markering zegt wat weg moet. Ze haalt het niet weg. Tot leessoftware deze markeringen toepast en het document opnieuw schrijft, staan de woorden nog onder de kaders en vindt een zoekopdracht ze; daarom is de onderste helft hier getekend in de eigen inkt van dit voorbeeld, en is ze niet wat het bestand vermeldt.",
    marks_title: "Wat een markering nog meer kan bevatten",
    marks_lead: "Elke markering hieronder heeft een naam, vlaggen die bepalen waar ze te zien is, een eigen laag, een rand en iets om te doen als erop geklikt of gewezen wordt.",
    layer: "Beoordeling",
    attachment: "De verklaring, als bestand",
    rows: [
        "Een kader met een streepjesrand, patroon {dash}",
        "Een ring die de markering zelf tekent",
        "Lijnen die op acht andere manieren eindigen",
        "Een gebied dat naar de eerste pagina leidt",
        "Een gebroken lijn die op de aanwijzer reageert",
        "Zes notitiepictogrammen, het eerste open",
        "Een bijgevoegd bestand onder drie pictogrammen",
        "Een lijn uit de vrije hand",
        "Een invoegteken waar een alinea begint",
        "Een uitgelezen markering: {style}, {areas} gebied",
        "Een weglating over {areas} gebieden, met {shows}",
        "Tekst in een eigen kader",
    ],
    sample: "voorbeeld",
    styles: ["markering", "onderstreping", "doorhaling", "kronkellijn"],
    nothing: "niets",
    remark: "Totalen vergelijken met de pakbon",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Declaração de testemunha, divulgada em parte",
    released: "Tal como é divulgada",
    applied: "Como um programa de leitura a mostra depois de aplicar as marcas",
    labels: ["Nome", "Morada", "Conta"],
    review: "Revisão",
    marked: ["realçado", "sublinhado", "riscado", "ondulado", "inserido"],
    circled: "rodeado à mão",
    note: "Nenhuma destas cinco marcas pede que se retire alguma coisa.",
    shown: "RASURADO",
    body: "A declaração é divulgada inteira. O que identifica a testemunha está riscado acima: o nome mostra o motivo no meio do seu espaço, a morada repete-o ao longo de um mais comprido, e a conta é tapada sem uma palavra.",
    caption: "Uma marca diz o que tem de sair. Não o retira. Até um programa de leitura aplicar estas marcas e voltar a escrever o documento, as palavras continuam por baixo das caixas e uma pesquisa encontra-as; é por isso que a metade de baixo é desenhada aqui com a tinta própria deste exemplo, e não é o que o ficheiro indica.",
    marks_title: "O que mais uma marca pode conter",
    marks_lead: "Cada marca abaixo leva um nome, indicadores que decidem onde se vê, uma camada própria, um contorno e algo a fazer quando é clicada ou apontada.",
    layer: "Revisão",
    attachment: "A declaração, como ficheiro",
    rows: [
        "Uma caixa de contorno tracejado, padrão {dash}",
        "Um círculo desenhado pela própria marca",
        "Linhas que acabam de outras oito formas",
        "Uma zona que leva à primeira página",
        "Uma linha quebrada que reage ao ponteiro",
        "Seis ícones de nota, o primeiro aberto",
        "Um ficheiro anexado a três ícones",
        "Um traço à mão livre",
        "Um sinal de inserção onde começa um parágrafo",
        "Uma marca relida: {style}, {areas} zona",
        "Uma rasura sobre {areas} zonas, à vista: {shows}",
        "Um texto numa caixa própria",
    ],
    sample: "amostra",
    styles: ["realce", "sublinhado", "rasurado", "ondulado"],
    nothing: "nada",
    remark: "Totais a conferir com a guia de remessa",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Dichiarazione del testimone, pubblicata in parte",
    released: "Come viene pubblicata",
    applied: "Come la mostra un programma di lettura dopo aver applicato i segni",
    labels: ["Nome", "Indirizzo", "Conto"],
    review: "Revisione",
    marked: [
        "evidenziato",
        "sottolineato",
        "barrato",
        "ondulato",
        "inserito",
    ],
    circled: "cerchiato a mano",
    note: "Nessuno di questi cinque segni chiede di togliere qualcosa.",
    shown: "OSCURATO",
    body: "La dichiarazione è pubblicata per intero. Ciò che identifica il testimone è cancellato qui sopra: il nome mostra il motivo al centro del suo spazio, l’indirizzo lo ripete lungo uno più lungo, e il conto è coperto senza una parola.",
    caption: "Un segno dice cosa deve sparire. Non lo toglie. Finché un programma di lettura non applica questi segni e riscrive il documento, le parole sono ancora sotto i riquadri e una ricerca le trova; per questo la metà inferiore è disegnata qui con l’inchiostro proprio di questo esempio, e non è ciò che indica il file.",
    marks_title: "Cos’altro può contenere un segno",
    marks_lead: "Ogni segno qui sotto porta un nome, indicatori che decidono dove si vede, un livello proprio, un bordo e qualcosa da fare quando lo si clicca o lo si punta.",
    layer: "Revisione",
    attachment: "La dichiarazione, come file",
    rows: [
        "Un riquadro dal bordo tratteggiato, trattino {dash}",
        "Un anello che il segno disegna da sé",
        "Linee che finiscono in otto altri modi",
        "Una zona che porta alla prima pagina",
        "Una linea spezzata che reagisce al puntatore",
        "Sei icone di nota, la prima aperta",
        "Un file allegato sotto tre icone",
        "Un tratto a mano libera",
        "Un segno di inserimento dove inizia un paragrafo",
        "Un segno letto: {style}, {areas} zona",
        "Un oscuramento su {areas} zone, testo mostrato: {shows}",
        "Un testo in un riquadro tutto suo",
    ],
    sample: "campione",
    styles: [
        "evidenziazione",
        "sottolineatura",
        "barratura",
        "ondulazione",
    ],
    nothing: "nulla",
    remark: "Totali da confrontare con il DDT",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Declaración de testigo, publicada en parte",
    released: "Tal como se publica",
    applied: "Como la muestra un programa de lectura tras aplicar las marcas",
    labels: ["Nombre", "Dirección", "Cuenta"],
    review: "Revisión",
    marked: ["resaltado", "subrayado", "tachado", "ondulado", "insertado"],
    circled: "rodeado a mano",
    note: "Ninguna de estas cinco marcas pide que se quite nada.",
    shown: "CENSURADO",
    body: "La declaración se publica entera. Lo que identifica al testigo está tapado arriba: el nombre muestra el motivo en medio de su hueco, la dirección lo repite a lo largo de uno más largo y la cuenta se tapa sin una palabra.",
    caption: "Una marca dice lo que debe quitarse. No lo quita. Hasta que un programa de lectura aplica estas marcas y vuelve a escribir el documento, las palabras siguen bajo las cajas y una búsqueda las encuentra; por eso la mitad inferior se dibuja aquí con la tinta propia de este ejemplo, y no es lo que indica el archivo.",
    marks_title: "Qué más puede llevar una marca",
    marks_lead: "Cada marca de abajo lleva un nombre, indicadores que deciden dónde se ve, una capa propia, un borde y algo que hacer cuando se hace clic en ella o se pasa el puntero sobre ella.",
    layer: "Revisión",
    attachment: "La declaración, como archivo",
    rows: [
        "Un recuadro de borde discontinuo, patrón {dash}",
        "Un círculo trazado por la propia marca",
        "Líneas que terminan de otras ocho formas",
        "Una zona que lleva a la primera página",
        "Una línea quebrada que responde al puntero",
        "Seis iconos de nota, el primero abierto",
        "Un mismo archivo adjunto a tres iconos",
        "Un trazo a mano alzada",
        "Un signo de intercalación donde empieza un párrafo",
        "Una marca leída: {style}, zonas: {areas}",
        "Zonas por censurar: {areas}; visible: {shows}",
        "Un texto en su propio recuadro",
    ],
    sample: "muestra",
    styles: ["resaltado", "subrayado", "tachado", "ondulado"],
    nothing: "nada",
    remark: "Totales que cotejar con el albarán",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Zeugenaussage, teilweise freigegeben",
    released: "So, wie sie freigegeben wird",
    applied: "So, wie eine Lesesoftware sie zeigt, nachdem sie die Markierungen angewandt hat",
    labels: ["Name", "Adresse", "Konto"],
    review: "Prüfung",
    marked: [
        "hervorgehoben",
        "unterstrichen",
        "durchgestrichen",
        "geschlängelt",
        "eingefügt",
    ],
    circled: "von Hand umkreist",
    note: "Keine dieser fünf Markierungen verlangt, dass etwas wegkommt.",
    shown: "GESCHWÄRZT",
    body: "Die Aussage selbst wird vollständig freigegeben. Was den Zeugen erkennbar macht, ist oben getilgt: Der Name zeigt den Grund in der Mitte seiner Lücke, die Adresse wiederholt ihn über eine längere Lücke, und das Konto wird wortlos abgedeckt.",
    caption: "Eine Markierung sagt, was wegmuss. Sie nimmt es nicht heraus. Bis eine Lesesoftware diese Markierungen anwendet und das Dokument neu schreibt, stehen die Wörter noch unter den Kästen, und eine Suche findet sie — darum ist die untere Hälfte hier mit der eigenen Farbe dieses Beispiels gezeichnet und nicht das, was die Datei angibt.",
    marks_title: "Was eine Markierung noch alles kann",
    marks_lead: "Jede Markierung unten trägt einen Namen, Kennzeichen, die bestimmen, wo sie erscheint, eine eigene Ebene, einen Rahmen und etwas, das beim Klicken oder Zeigen geschieht.",
    layer: "Prüfung",
    attachment: "Die Aussage, als Datei",
    rows: [
        "Gestrichelter Rahmen, Strichmuster {dash}",
        "Ring, den die Markierung selbst zeichnet",
        "Linien mit acht weiteren Endformen",
        "Bereich, der zur ersten Seite führt",
        "Linienzug, der auf den Mauszeiger reagiert",
        "Sechs Notizsymbole, das erste offen",
        "Datei, an drei Symbole angeheftet",
        "Freihandstrich",
        "Einfügezeichen am Absatzbeginn",
        "Ausgelesen: {style}, Bereiche: {areas}",
        "Schwärzung, Bereiche: {areas}, zeigt {shows}",
        "Text in eigenem Rahmen",
    ],
    sample: "Muster",
    styles: [
        "Hervorhebung",
        "Unterstreichung",
        "Durchstreichung",
        "Schlängellinie",
    ],
    nothing: "nichts",
    remark: "Summen mit dem Lieferschein abgleichen",
};

/// 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),
];

/// Writes a line of ordinary text at `(x, y)`.
fn write(
    content: &mut Content,
    font: &FontHandle,
    x: f64,
    y: f64,
    size: 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(())
}

/// Writes a paragraph in a column the width of the page.
fn paragraph(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    top: f64,
    color: Rgb,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(font, size).leading(size * 1.4).color(color);
    let lines = flow.break_lines(text, WIDTH);
    content.begin_text();
    flow.draw(content, &lines, MARGIN, top, WIDTH)?;
    content.end_text();
    Ok(())
}

/// The most copies of a word one gap is filled with.
const MOST_COPIES: usize = 64;

/// Converts a count of copies to a float. A gap holds at most [`MOST_COPIES`]
/// of them, which is nowhere near where a `usize` loses precision as an `f64`.
#[expect(
    clippy::cast_precision_loss,
    reason = "a count of copies is far below f64's exact-integer range"
)]
const fn count_f64(n: usize) -> f64 {
    n as f64
}

/// How many copies of a word `one` wide, set `step` apart, stand in `room`.
fn fitting(room: f64, one: f64, step: f64) -> usize {
    (0..MOST_COPIES)
        .take_while(|copy| count_f64(*copy).mul_add(step, one) <= room)
        .count()
}

/// Draws the gap a mark asks for: the colour it states, and the words it shows
/// in it, set where its alignment puts them and repeated if it asks for that.
fn gap(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    width: f64,
    shown: &str,
    align: FieldAlign,
    repeating: bool,
) -> Result<(), hqf_pdf::Error> {
    content.save_state();
    content.set_fill(Rgb::BLACK)?;
    content.rect(MARGIN + VALUE, y - UNDER, width, SIZE + OVER + UNDER)?;
    content.fill();

    if !shown.is_empty() {
        content.set_fill(Rgb::gray(1.0))?;
        let one = font.measure(shown, SHOWN_SIZE);
        let step = one + font.measure("   ", SHOWN_SIZE);
        let left = MARGIN + VALUE;
        let start = match align {
            FieldAlign::Center => (width - one).mul_add(0.5, left),
            FieldAlign::Right => left + width - one,
            _ => left,
        };
        let room = left + width - start;
        let times = if repeating {
            fitting(room, one, step)
        } else {
            usize::from(one <= room)
        };
        for copy in 0..times {
            let at = count_f64(copy).mul_add(step, start);
            write(content, font, at, y, SHOWN_SIZE, shown)?;
        }
    }
    content.restore_state();
    Ok(())
}

/// Draws the review line, its label beside it, and hands back the patch each of
/// its five words covers and the baseline the label sits on.
///
/// Each word is a span of its own, so each comes back as a box of its own once
/// the line is laid out.
fn review_line(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
) -> Result<(Vec<Quad>, f64), hqf_pdf::Error> {
    let plain = Style::new(font, SIZE);
    let [first, second, third, fourth, fifth] = words.marked;
    let review = RichText::new()
        .span(first, &plain)
        .span("   ", &plain)
        .span(second, &plain)
        .span("   ", &plain)
        .span(third, &plain)
        .span("   ", &plain)
        .span(fourth, &plain)
        .span("   ", &plain)
        .span(fifth, &plain);
    let reviewed = review.break_lines(WIDTH - VALUE);
    review.draw(
        content,
        &reviewed,
        MARGIN + VALUE,
        REVIEW_TOP,
        WIDTH - VALUE,
    )?;
    // The label sits on the line's baseline, one line's height below its top.
    let baseline = reviewed
        .first()
        .map_or(REVIEW_TOP - SIZE, |line| REVIEW_TOP - line.height());
    write(content, font, MARGIN, baseline, SIZE, words.review)?;
    let boxes = review.fragment_boxes(&reviewed, MARGIN + VALUE, REVIEW_TOP, WIDTH - VALUE);
    Ok((
        boxes.iter().flatten().map(Quad::of_rect).collect(),
        baseline,
    ))
}

/// What the reviewer adds by hand: a loop around the review line's label, whose
/// baseline is `baseline`, with an arrow from it to the line, all in one
/// scribble of three strokes; and a sticky note at the line's end.
fn by_hand(
    font: &FontHandle,
    baseline: f64,
    words: &Words,
) -> Result<[Annotation; 2], hqf_pdf::Error> {
    let label = font.measure(words.review, SIZE);
    let (cx, cy) = (MARGIN + label / 2.0, baseline + 3.5);
    let (rx, ry) = (label / 2.0 + 7.0, 10.0);
    let circle: Vec<(f64, f64)> = LOOP
        .iter()
        .map(|(dx, dy)| (cx + dx * rx, cy + dy * ry))
        .collect();
    let tip = MARGIN + VALUE - 8.0;
    let tail = cx + rx + 3.0;
    let arrow = vec![(tail, cy), (f64::midpoint(tail, tip), cy + 2.0), (tip, cy)];
    let head = vec![(tip - 5.0, cy + 4.0), (tip, cy), (tip - 5.0, cy - 4.0)];
    Ok([
        Ink::new(vec![circle, arrow, head])?
            .color(REVIEW_INK)
            .contents(words.circled)
            .into(),
        StickyNote::new(MARGIN + WIDTH - NOTE, baseline - 6.0, words.note)
            .icon(NoteIcon::Comment)
            .color(HIGHLIGHT)
            .into(),
    ])
}

/// The five review marks: four on the patch of the word naming each, and a
/// caret centred on the gap before the last word, its point on the line.
fn review_marks(
    patches: &[Quad],
    words: &Words,
) -> Result<[Annotation; 5], Box<dyn std::error::Error>> {
    let [highlighted, underlined, struck, squiggled, inserted] = patches else {
        return Err("the review line is laid out as five words".into());
    };
    // The gap runs from the right edge of the upright box around the patch
    // before it to the lower left corner of the patch after it.
    let before = squiggled.bounds();
    let gap_start = before.x() + before.width();
    let (gap_end, foot) = inserted.corners()[0];
    Ok([
        TextMark::highlight(vec![*highlighted], HIGHLIGHT)?
            .contents(words.marked[0])
            .into(),
        TextMark::underline(vec![*underlined])?
            .color(REVIEW_INK)
            .contents(words.marked[1])
            .into(),
        TextMark::strike_out(vec![*struck])?
            .color(REVIEW_INK)
            .contents(words.marked[2])
            .into(),
        TextMark::squiggly(vec![*squiggled])?
            .color(REVIEW_INK)
            .contents(words.marked[3])
            .into(),
        Caret::new(
            f64::midpoint(gap_start, gap_end) - 4.0,
            foot - 3.0,
            8.0,
            8.0,
        )
        .color(REVIEW_INK)
        .inset(1.0, 0.0, 1.0, 0.0)
        .contents(words.marked[4])
        .into(),
    ])
}

/// Where the marks of the second page stand, and how far each row stands under
/// the one before.
const MARK_X: f64 = 330.0;
/// See [`MARK_X`].
const MARK_STEP: f64 = 52.0;

/// The name a mark of the second page carries, from its row.
fn mark_name(row: usize) -> String {
    format!("review-{row}")
}

/// What a mark of the second page does when it is clicked: going back to the
/// statement.
const fn to_statement() -> Action {
    Action::Page {
        index: 0,
        view: PageFit::WholePage,
    }
}

/// What a mark of the second page does when the pointer comes onto it and
/// leaves it.
fn pointed_at() -> WidgetTriggers {
    WidgetTriggers::new()
        .enter(Action::MenuItem(MenuItem::FirstPage))
        .exit(Action::MenuItem(MenuItem::LastPage))
}

/// A ring about `(x, y)` the mark draws itself, rather than one reading
/// software draws from its border. An appearance is drawn in the page's own
/// coordinates.
fn ring(x: f64, y: f64) -> Result<Content, hqf_pdf::Error> {
    let mut ring = Content::new();
    ring.set_stroke(REVIEW_INK)?;
    ring.set_line_width(3.0)?;
    ring.circle(x, y, 12.0)?.stroke();
    Ok(ring)
}

/// The second page: every other mark, each carrying a name, flags, a layer, a
/// border, and something to do when clicked or pointed at.
#[allow(
    clippy::too_many_lines,
    reason = "the page is one list of marks, read from top to bottom"
)]
fn marks_page(
    doc: &mut Document,
    font: &FontHandle,
    words: &Words,
) -> Result<Page, Box<dyn std::error::Error>> {
    let layer = doc.add_layer(Layer::new(words.layer))?;
    let file = doc.attach(Attachment::new(
        "statement.txt",
        words.attachment,
        "text/plain",
        Relationship::Unspecified,
        "2026-09-17T09:00:00Z",
        ENTRIES[0],
    ));
    let shown = AnnotationFlags::none().printed();
    let dashed = AnnotationBorder::dashed(1.5, Dash::on_off(4.0, 2.0)?);
    let pattern = dashed.dash().map_or_else(String::new, |dash| {
        dash.lengths()
            .iter()
            .map(|length| format!("{length:.0}"))
            .collect::<Vec<_>>()
            .join(" ")
    });
    let thin = AnnotationBorder::solid(1.0);

    let mut content = Content::new();
    write(&mut content, font, MARGIN, 780.0, 16.0, words.marks_title)?;
    paragraph(
        &mut content,
        font,
        9.0,
        760.0,
        Rgb::gray(0.35),
        words.marks_lead,
    )?;
    let boxed = words.rows[0].replace("{dash}", &pattern);

    let rows: Vec<f64> = (0..12)
        .map(|row| f64::from(row).mul_add(-MARK_STEP, 690.0))
        .collect();
    let mut page = Page::a4();

    // A box with a dashed border, drawn plain rather than as a cloud.
    page.annotations.push(Annotation::Square(
        Square::new(MARK_X, rows[0] - 8.0, 120.0, 26.0)
            .effect(BorderEffect::Plain)
            .border(dashed.clone())
            .color(REVIEW_INK)
            .contents(boxed.as_str())
            .name(mark_name(0))
            .flags(shown)
            .layer(&layer)
            .action(to_statement())
            .triggers(pointed_at()),
    ));

    // A ring the mark draws itself.
    page.annotations.push(Annotation::Circle(
        Circle::new(MARK_X, rows[1] - 10.0, 30.0, 30.0)
            .appearance(ring(MARK_X + 15.0, rows[1] + 5.0)?)
            .border(thin.clone())
            .color(REVIEW_INK)
            .contents(words.rows[1])
            .name(mark_name(1))
            .flags(shown.no_rotate())
            .layer(&layer)
            .action(to_statement())
            .triggers(pointed_at()),
    ));

    // Four lines, each ending two other ways.
    let endings = [
        (LineEnding::Square, LineEnding::Circle),
        (LineEnding::Diamond, LineEnding::OpenArrow),
        (LineEnding::ROpenArrow, LineEnding::RClosedArrow),
        (LineEnding::Slash, LineEnding::Slash),
    ];
    let mut x = MARK_X;
    for (from, to) in endings {
        page.annotations.push(Annotation::Line(
            Line::new(x, rows[2] + 4.0, x + 40.0, rows[2] + 4.0)
                .endings(from, to)
                .interior(REVIEW_INK)
                .border(thin.clone())
                .color(REVIEW_INK)
                .contents(words.rows[2])
                .name(mark_name(2))
                .flags(shown)
                .layer(&layer)
                .action(to_statement())
                .triggers(pointed_at()),
        ));
        x += 55.0;
    }

    // An area that goes back to the statement when clicked.
    page.annotations.push(Annotation::Polygon(
        Polygon::new(vec![
            (MARK_X, rows[3] - 8.0),
            (MARK_X + 60.0, rows[3] - 8.0),
            (MARK_X + 80.0, rows[3] + 14.0),
            (MARK_X + 20.0, rows[3] + 18.0),
        ])?
        .interior(Rgb::new(1.0, 0.9, 0.9))
        .border(thin.clone())
        .color(REVIEW_INK)
        .contents(words.rows[3])
        .name(mark_name(3))
        .flags(shown)
        .layer(&layer)
        .action(Action::MenuItem(MenuItem::FirstPage))
        .triggers(pointed_at()),
    ));

    // A run that answers the pointer coming onto it and leaving it.
    page.annotations.push(Annotation::PolyLine(
        PolyLine::new(vec![
            (MARK_X, rows[4]),
            (MARK_X + 30.0, rows[4] + 12.0),
            (MARK_X + 60.0, rows[4]),
            (MARK_X + 90.0, rows[4] + 12.0),
        ])?
        .border(dashed)
        .color(REVIEW_INK)
        .contents(words.rows[4])
        .name(mark_name(4))
        .flags(shown)
        .layer(&layer)
        .action(to_statement())
        .triggers(pointed_at()),
    ));

    // Six notes, one per icon, the first left open.
    let icons = [
        NoteIcon::Note,
        NoteIcon::Key,
        NoteIcon::Help,
        NoteIcon::NewParagraph,
        NoteIcon::Paragraph,
        NoteIcon::Insert,
    ];
    let mut x = MARK_X;
    for (place, icon) in icons.into_iter().enumerate() {
        let note = StickyNote::new(x, rows[5] - 6.0, words.note)
            .icon(icon)
            .border(thin.clone())
            .color(HIGHLIGHT)
            .name(mark_name(5))
            .flags(shown)
            .layer(&layer)
            .action(to_statement())
            .triggers(pointed_at());
        page.annotations.push(Annotation::StickyNote(if place == 0 {
            note.open()
        } else {
            note
        }));
        x += 30.0;
    }

    // The same file pinned under three icons.
    let mut x = MARK_X;
    for icon in [
        AttachmentIcon::Graph,
        AttachmentIcon::PushPin,
        AttachmentIcon::Tag,
    ] {
        page.annotations.push(Annotation::FileAttachment(
            FileAttachment::new(x, rows[6] - 6.0, file)
                .icon(icon)
                .border(thin.clone())
                .color(REVIEW_INK)
                .contents(words.attachment)
                .name(mark_name(6))
                .flags(shown)
                .layer(&layer)
                .action(to_statement())
                .triggers(pointed_at()),
        ));
        x += 40.0;
    }

    // A stroke by hand.
    page.annotations.push(Annotation::Ink(
        Ink::new(vec![vec![
            (MARK_X, rows[7]),
            (MARK_X + 20.0, rows[7] + 10.0),
            (MARK_X + 40.0, rows[7] - 4.0),
            (MARK_X + 60.0, rows[7] + 8.0),
        ]])?
        .border(AnnotationBorder::solid(2.0))
        .color(REVIEW_INK)
        .contents(words.rows[7])
        .name(mark_name(7))
        .flags(shown)
        .layer(&layer)
        .action(to_statement())
        .triggers(pointed_at()),
    ));

    // A caret marking where a paragraph is to begin.
    page.annotations.push(Annotation::Caret(
        Caret::new(MARK_X, rows[8] - 4.0, 12.0, 12.0)
            .paragraph()
            .border(thin.clone())
            .color(REVIEW_INK)
            .contents(words.rows[8])
            .name(mark_name(8))
            .flags(shown)
            .layer(&layer)
            .action(to_statement())
            .triggers(pointed_at()),
    ));

    // A word underlined, the mark read back for its style and its areas.
    let sample_width = font.measure(words.sample, SIZE);
    write(&mut content, font, MARK_X, rows[9], SIZE, words.sample)?;
    let patch = Rect::new(MARK_X, rows[9] - UNDER, sample_width, SIZE + OVER + UNDER).quad();
    let underline = TextMark::underline(vec![patch])?
        .border(thin.clone())
        .color(REVIEW_INK)
        .contents(words.sample)
        .name(mark_name(9))
        .flags(shown)
        .layer(&layer)
        .action(to_statement())
        .triggers(pointed_at());
    let kind = match underline.style() {
        MarkStyle::Highlight => words.styles[0],
        MarkStyle::Underline => words.styles[1],
        MarkStyle::StrikeOut => words.styles[2],
        MarkStyle::Squiggly => words.styles[3],
    };
    let read_back = words.rows[9]
        .replace("{style}", kind)
        .replace("{areas}", &underline.areas().len().to_string());
    page.annotations.push(Annotation::TextMark(underline));

    // A redaction over two areas, drawing its own overlay, read back for its
    // areas and for the words it shows.
    let patches = [
        Rect::new(MARK_X, rows[10] - 4.0, 60.0, 14.0).quad(),
        Rect::new(MARK_X + 70.0, rows[10] - 4.0, 60.0, 14.0).quad(),
    ];
    let mut overlay = Content::new();
    overlay.set_stroke(Rgb::gray(1.0))?;
    overlay.move_to(2.0, 2.0)?.line_to(56.0, 12.0)?.stroke();
    let redaction = Redaction::new(MARK_X, rows[10] - 4.0, 130.0, 14.0)
        .over(patches)
        .fill(Rgb::BLACK)
        .overlay(overlay)
        .border(thin.clone())
        .color(REVIEW_INK)
        .name(mark_name(10))
        .flags(shown)
        .layer(&layer)
        .action(to_statement())
        .triggers(pointed_at());
    let overlaid = redaction.text().unwrap_or(words.nothing);
    let redacted = words.rows[10]
        .replace("{areas}", &redaction.areas().len().to_string())
        .replace("{shows}", overlaid);
    let redaction = redaction.contents(redacted.as_str());
    page.annotations.push(Annotation::Redaction(redaction));

    // A remark laid in a box of its own, its text set by the library.
    let remark = TextFlow::new(font, 9.0)
        .color(REVIEW_INK)
        .left_indent(4.0)
        .right_indent(4.0);
    page.annotations.push(Annotation::FreeText(
        FreeText::new(MARK_X, rows[11] - 6.0, 200.0, 20.0, &remark, words.remark)?
            .border(thin)
            .color(REVIEW_INK)
            .name(mark_name(11))
            .flags(shown)
            .layer(&layer)
            .action(to_statement())
            .triggers(pointed_at()),
    ));

    // The label of each row, some of them read back from the mark they name.
    for (row, (at, label)) in rows.iter().zip(words.rows).enumerate() {
        let line = match row {
            0 => boxed.clone(),
            9 => read_back.clone(),
            10 => redacted.clone(),
            _ => label.to_owned(),
        };
        write(&mut content, font, MARGIN, *at, 9.5, &line)?;
    }

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

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

#[allow(
    clippy::too_many_lines,
    reason = "the statement is one page, laid out from top to bottom"
)]
fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    // 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 out = env::args()
        .nth(1)
        .unwrap_or_else(|| language.file_name(&out::default_path("redaction")));

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(default_font())?)?);

    let widths: [f64; STRUCK] = std::array::from_fn(|struck| font.measure(ENTRIES[struck], SIZE));

    let mut content = Content::new();
    write(&mut content, &font, MARGIN, 780.0, 16.0, words.title)?;

    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    write(&mut content, &font, MARGIN, 736.0, 9.0, words.released)?;
    write(&mut content, &font, MARGIN, 522.0, 9.0, words.applied)?;
    content.restore_state();

    for ((row, label), entry) in ROWS.iter().zip(words.labels).zip(ENTRIES) {
        write(&mut content, &font, MARGIN, *row, SIZE, label)?;
        write(&mut content, &font, MARGIN + VALUE, *row, SIZE, entry)?;
    }
    paragraph(&mut content, &font, 10.0, 618.0, Rgb::BLACK, words.body)?;

    let (patches, baseline) = review_line(&mut content, &font, words)?;

    for (row, label) in SHOWN_ROWS.iter().zip(words.labels) {
        write(&mut content, &font, MARGIN, *row, SIZE, label)?;
    }
    gap(
        &mut content,
        &font,
        SHOWN_ROWS[0],
        widths[0],
        words.shown,
        FieldAlign::Center,
        false,
    )?;
    gap(
        &mut content,
        &font,
        SHOWN_ROWS[1],
        widths[1],
        words.shown,
        FieldAlign::Left,
        true,
    )?;
    gap(
        &mut content,
        &font,
        SHOWN_ROWS[2],
        widths[2],
        "",
        FieldAlign::Left,
        false,
    )?;

    paragraph(
        &mut content,
        &font,
        8.5,
        402.0,
        Rgb::gray(0.35),
        words.caption,
    )?;

    let mut page = Page::a4();
    page.content = content.into_bytes();

    // Each mark covers the words it hides and nothing else, so it is measured
    // off the line it stands on.
    let marks: [Redaction; STRUCK] = std::array::from_fn(|struck| {
        Redaction::new(
            MARGIN + VALUE,
            ROWS[struck] - UNDER,
            widths[struck],
            SIZE + OVER + UNDER,
        )
        .fill(Rgb::BLACK)
    });
    let [named, lived, banked] = marks;
    page.annotations.push(
        named
            .overlay_text(words.shown)
            .aligned(FieldAlign::Center)
            .into(),
    );
    page.annotations.push(
        lived
            .overlay_text(words.shown)
            .repeating(true)
            .aligned(FieldAlign::Left)
            .into(),
    );
    page.annotations.push(banked.into());
    page.annotations.extend(review_marks(&patches, words)?);
    page.annotations.extend(by_hand(&font, baseline, words)?);

    doc.add_page(page)?;
    let marks = marks_page(&mut doc, &font, words)?;
    doc.add_page(marks)?;

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

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

    use super::{
        ENTRIES, MARGIN, MARK_X, ROWS, SHOWN_ROWS, STRUCK, WORDS, default_font, language, licence,
        marks_page,
    };

    /// The lines two languages write the same way, where two languages spell a
    /// word alike. Every word on the page is a word of the language it is in.
    const SPARED: [&str; 5] = [
        // Written the same way in German.
        r#""Adresse""#,
        r#""Name""#,
        // Written the same way in Portuguese.
        r#""Nome""#,
        r#""ondulado""#,
        r#"nothing: "nada""#,
    ];

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

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

    /// The entries stand far enough apart that no mark reaches the line above
    /// it: a mark that overlapped its neighbour would cover a word nobody asked
    /// to strike out. The same has to hold of the gaps drawn under them. A
    /// label of the second page must stop short of the mark it names.
    #[test]
    fn every_label_of_the_second_page_stops_short_of_its_mark() {
        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 row in words.rows {
                let label = row
                    .replace("{dash}", "4 2")
                    .replace("{style}", words.styles[2])
                    .replace("{areas}", "2")
                    .replace("{shows}", words.nothing);
                let width = font.measure(&label, 9.5);
                assert!(width <= MARK_X - MARGIN - 10.0, "{label:?} needs {width}");
            }
        }
    }

    /// What a mark of the second page says is the sentence its label reads,
    /// every figure and word read back from the mark put in its place.
    #[test]
    fn every_mark_of_the_second_page_says_its_words_with_nothing_left_to_fill() {
        for (_, words) in WORDS {
            let mut doc = Document::new();
            doc.set_license(licence::licensed());
            let font = doc.add_font(
                Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                    .expect("the committed font parses"),
            );
            let page = marks_page(&mut doc, &font, words).expect("the page is set");
            doc.add_page(page).expect("the page is added");
            let reader = Reader::new(doc.to_bytes().expect("the document is written"))
                .expect("the document reads");

            let said: Vec<String> = reader
                .annotations(0)
                .expect("the page's marks read")
                .into_iter()
                .filter_map(|mark| mark.contents)
                .collect();

            assert!(!said.is_empty(), "the marks say nothing");
            for contents in said {
                assert!(
                    !contents.contains('{'),
                    "a mark says {contents:?}, a placeholder left in it"
                );
            }
        }
    }

    #[test]
    fn no_two_marks_reach_each_other() {
        assert_eq!(ROWS.len(), ENTRIES.len());
        assert_eq!(STRUCK, ENTRIES.len());
        let apart = super::SIZE + super::OVER + super::UNDER;
        for rows in [ROWS, SHOWN_ROWS] {
            for pair in rows.windows(2) {
                assert!(pair[0] - pair[1] > apart);
            }
        }
    }
}