write_shapes.rs

Die Rust-Datei des Beispiels „Ein Monatsbericht, seine Diagramme in Kurven gezeichnet“. Ein Kreisdiagramm, wohin die Stunden gingen, eine Ringanzeige, wie weit die Arbeit im Jahr fortgeschritten ist, eine Karte mit abgerundeten Ecken und Bögen, denen gesagt wird, wohin sie führen, statt wie weit sie sich drehen.

Rust 1245 Zeilen

Wofür dieses Beispiel da ist

Der Monatsbericht einer Druckerei sagt, wohin die Stunden gingen, wie weit die Arbeit im Jahr fortgeschritten ist und wie sich die Aufträge Woche für Woche entwickelt haben. Diese Zahlen kommen meist als auf die Seite geklebte Bilder: am Bildschirm in Ordnung, unscharf, sobald jemand sie druckt oder genauer hinsieht.

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
//! Writes a month's activity report out of the shapes a page has no operator
//! for: a pie with notched swatches, a ring gauge, a card with rounded corners,
//! a line whose corners are eased off, and an arc whose radii are enlarged
//! until they reach.
//!
//! PDF states a path with straight segments and cubic curves and nothing else,
//! so a circle is four curves and a slice of a pie is an arc with two straight
//! sides. Everything on this page is asked for by name — a centre and a radius,
//! two angles, three points — and the curves are worked out for it.
//!
//! The second page tells the pen where to go in other ways: a step from where
//! it stands, a turn and a length, an ellipse by its two radii, a heart given
//! as SVG path data, a slice closed on its centre. It paints the same star four
//! ways, sets joins and dashes, moves, leans and restores the axes, and names
//! colours by their numbers.
//!
//! Both sets of words are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The dash's pattern is not: it is
//! written as the file writes it.
//!
//! Usage: `cargo run --example write_shapes -- tmp/shapes.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_shapes`

use std::env;
use std::f64::consts::{FRAC_PI_2, TAU};
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::{
    Cmyk, Color, Dash, Document, EllipticalArc, FitBox, FitMode, Font, FontHandle, LineCap,
    LineJoin, LineStyle, Page, Rect, Rgb, SvgPath, TextFlow,
};

#[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 page is set in when the caller names none: the one committed
/// for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The page's title.
    title: &'static str,
    /// What the page is about.
    lead: &'static str,
    /// The heading over the pie.
    pie: &'static str,
    /// What the four slices of the pie are called.
    slices: [&'static str; 4],
    /// The heading over the ring gauge.
    gauge: &'static str,
    /// What the ring gauge counts.
    gauge_label: &'static str,
    /// The heading over the card.
    card: &'static str,
    /// What the line inside the card shows.
    card_label: &'static str,
    /// The heading over the arcs.
    arcs: &'static str,
    /// What the arc through three points is called.
    through: &'static str,
    /// What the arc whose radii are enlarged until they reach is called.
    enlarged: &'static str,
    /// What the four arcs of one ellipse are called.
    four: &'static str,
    /// What a curve costs, and what it does not.
    caveat: &'static str,
    /// The second page's title.
    pen_title: &'static str,
    /// What the second page is about.
    pen_lead: &'static str,
    /// The heading over the steps and the stars.
    steps: &'static str,
    /// What each of the four stars is painted with.
    stars: [&'static str; 4],
    /// The heading over the ellipse, the slice and the turned arcs.
    ellipses: &'static str,
    /// What the heart given as SVG path data is called.
    heart: &'static str,
    /// The heading over the joins and the dash.
    corners: &'static str,
    /// What the two zigzags' miter limits do.
    miters: [&'static str; 2],
    /// The heading over the three squares whose axes move.
    axes: &'static str,
    /// What each of the three squares shows.
    squares: [&'static str; 3],
    /// The heading over the colours given by number.
    numbers: &'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: "The month, drawn in curves",
    lead: "A page states a path with straight segments and cubic curves, and \
           with nothing else: there is no circle operator and no arc operator. \
           Every shape below was asked for by name — a centre and a radius, \
           two angles, three points to pass through — and the curves were \
           worked out for it. No piece bends further than a quarter turn, so a \
           circle is four curves and the outline is out by a fortieth of a \
           point on a circle an inch across.",
    pie: "Where the hours went",
    slices: ["Drawing office", "Plates and proofs", "Delivery", "Storage"],
    gauge: "How far into the year the work is",
    gauge_label: "of the year's work is behind us",
    card: "A card whose corners are eased off",
    card_label: "Orders taken, week by week",
    arcs: "Arcs told where to go, not how far to turn",
    through: "One arc, through three points",
    enlarged: "Radii enlarged",
    four: "Four arcs, between the same two points",
    caveat: "A curve costs six numbers and a straight segment costs two, so a \
             circle is five lines of a page rather than one. What it does not \
             cost is a picture: the shapes here are drawn by reading software \
             at whatever size the page is shown, and they stay sharp at any of \
             them.",
    pen_title: "Where the pen goes next",
    pen_lead: "A point can be given from where the pen stands rather than from \
               the corner of the page: a step across and up, or a turn and a \
               length. A path is closed, filled and stroked in one operator, by \
               either of the two rules that decide what is inside. The axes \
               themselves can be moved, leaned, and put back as the page had \
               them.",
    steps: "Steps from where the pen stands, and a star told by turns",
    stars: [
        "Even-odd, closed",
        "Non-zero, closed",
        "Even-odd, left open",
        "Outline, closed",
    ],
    ellipses: "An ellipse, a slice closed on its centre, and an arc turned",
    heart: "A heart given as SVG path data",
    corners: "Pointed joins cut off past a limit, and a dash begun partway",
    miters: ["Limit 1.5: cut", "Limit 10: pointed"],
    axes: "Axes moved, leaned, and put back",
    squares: ["Moved", "Leaned", "Put back inside a turn"],
    numbers: "Colours given by their numbers: grey, then the four inks",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Le mois, en courbes",
    lead: "Une page décrit un tracé avec des segments droits et des courbes cubiques, et \
rien d’autre : il n’y a ni opérateur de cercle ni opérateur d’arc. Chaque \
forme ci-dessous a été demandée par son nom — un centre et un rayon, deux \
angles, trois points par où passer — et les courbes ont été calculées pour \
elle. Aucun morceau ne tourne de plus d’un quart de tour : un cercle fait donc \
quatre courbes, et le contour s’écarte d’un quarantième de point sur un cercle \
de deux centimètres et demi.",
    pie: "Où sont passées les heures",
    slices: [
        "Bureau d’études",
        "Plaques et épreuves",
        "Livraison",
        "Entreposage",
    ],
    gauge: "Où en est le travail de l’année",
    gauge_label: "du travail de l’année est déjà fait",
    card: "Une carte aux coins arrondis",
    card_label: "Commandes reçues, semaine par semaine",
    arcs: "Des arcs à qui l’on dit où aller, pas de combien tourner",
    through: "Un arc, par trois points",
    enlarged: "Rayons agrandis",
    four: "Quatre arcs, entre les deux mêmes points",
    caveat: "Une courbe coûte six nombres et un segment droit en coûte deux : un cercle \
fait donc cinq lignes de page au lieu d’une. Ce qu’il ne coûte pas, c’est une \
image : les formes ci-dessus sont tracées par le logiciel de lecture à la \
taille où la page est affichée, et restent nettes à toutes les tailles.",
    pen_title: "Où va la plume ensuite",
    pen_lead: "Un point peut se donner depuis la position de la plume plutôt que depuis \
le coin de la page : un pas en largeur et en hauteur, ou un angle et une longueur. Un \
seul opérateur ferme un tracé, le remplit et en trace le contour, selon l’une ou l’autre \
des deux règles qui décident de ce qui est dedans. Les axes eux-mêmes se déplacent, \
s’inclinent, et reviennent tels que la page les avait.",
    steps: "Des pas depuis la position de la plume, et une étoile décrite par ses angles",
    stars: [
        "Pair-impair, fermée",
        "Non nul, fermée",
        "Pair-impair, ouverte",
        "Contour, fermée",
    ],
    ellipses: "Une ellipse, une part refermée sur son centre, et un arc tourné",
    heart: "Un cœur décrit par un chemin SVG",
    corners: "Des angles vifs coupés au-delà d’une limite, et un tireté entamé en cours de motif",
    miters: ["Limite 1,5 : coupé", "Limite 10 : pointu"],
    axes: "Des axes déplacés, inclinés, puis remis en place",
    squares: ["Déplacé", "Incliné", "Remis droit dans une rotation"],
    numbers: "Des couleurs données par leurs valeurs : un gris, puis les quatre encres",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "De maand, getekend in curven",
    lead: "Een pagina beschrijft een pad met rechte stukken en kubische curven, en met niets anders: er is geen cirkeloperator en geen boogoperator. Elke vorm hieronder is bij naam gevraagd (een middelpunt en een straal, twee hoeken, drie punten om door te gaan) en de curven zijn ervoor berekend. Geen stuk buigt verder dan een kwartslag, dus een cirkel is vier curven en de omtrek wijkt een veertigste punt af op een cirkel van een inch.",
    pie: "Waar de uren heen gingen",
    slices: ["Tekenkamer", "Platen en proeven", "Levering", "Opslag"],
    gauge: "Hoe ver in het jaar het werk is",
    gauge_label: "van het werk van het jaar ligt achter ons",
    card: "Een kaart met afgeronde hoeken",
    card_label: "Orders binnen, week na week",
    arcs: "Bogen die te horen krijgen waar ze heen gaan, niet hoever ze draaien",
    through: "Eén boog, door drie punten",
    enlarged: "Stralen vergroot",
    four: "Vier bogen, tussen dezelfde twee punten",
    caveat: "Een curve kost zes getallen en een recht stuk twee, dus een cirkel is vijf regels van een pagina in plaats van één. Wat ze niet kost is een afbeelding: de vormen hier worden door leessoftware getekend op het formaat waarop de pagina getoond wordt, en blijven op elk formaat scherp.",
    pen_title: "Waar de pen daarna heen gaat",
    pen_lead: "Een punt kan gegeven worden vanaf waar de pen staat in plaats van vanaf de hoek van de pagina: een stap opzij en omhoog, of een draai en een lengte. Een pad wordt gesloten, gevuld en getrokken met één operator, volgens een van de twee regels die bepalen wat binnen ligt. De assen zelf kunnen verschoven, schuin gezet en teruggezet worden zoals de pagina ze had.",
    steps: "Stappen vanaf waar de pen staat, en een ster gegeven in draaien",
    stars: [
        "Even-oneven, dicht",
        "Niet-nul, gesloten",
        "Even-oneven, open",
        "Omtrek, gesloten",
    ],
    ellipses: "Een ellips, een punt gesloten op zijn middelpunt, en een gedraaide boog",
    heart: "Een hart beschreven met SVG-padgegevens",
    corners: "Puntige hoeken afgeknot voorbij een grens, en een streep halverwege begonnen",
    miters: ["Grens 1,5: afgeknot", "Grens 10: puntig"],
    axes: "Assen verschoven, schuin gezet en teruggezet",
    squares: ["Verschoven", "Schuin gezet", "Teruggezet binnen een draai"],
    numbers: "Kleuren gegeven met hun getallen: grijs, dan de vier inkten",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "O mês, desenhado em curvas",
    lead: "Uma página só conhece traçados feitos de segmentos retos e curvas cúbicas, e nada mais: não há operador de círculo nem de arco. Cada forma abaixo foi pedida pelo nome (um centro e um raio, dois ângulos, três pontos por onde passar) e as curvas foram calculadas para ela. Nenhuma peça dobra mais de um quarto de volta, por isso um círculo são quatro curvas e o contorno desvia-se um quadragésimo de ponto num círculo de uma polegada.",
    pie: "Para onde foram as horas",
    slices: [
        "Gabinete técnico",
        "Chapas e provas",
        "Entrega",
        "Armazenagem",
    ],
    gauge: "Em que ponto do ano está o trabalho",
    gauge_label: "do trabalho do ano já ficou para trás",
    card: "Um cartão de cantos suavizados",
    card_label: "Encomendas recebidas, semana a semana",
    arcs: "Arcos a que se diz para onde ir, não quanto rodar",
    through: "Um arco, por três pontos",
    enlarged: "Raios maiores",
    four: "Quatro arcos, entre os mesmos dois pontos",
    caveat: "Uma curva custa seis números e um segmento reto dois, por isso um círculo são cinco linhas de página e não uma. O que não custa é uma imagem: as formas aqui são desenhadas pelo programa de leitura ao tamanho a que a página for mostrada, e ficam nítidas em qualquer um.",
    pen_title: "Para onde vai a caneta a seguir",
    pen_lead: "Um ponto pode ser dado a partir de onde está a caneta em vez do canto da página: um passo na largura e para cima, ou uma rotação e um comprimento. Um traçado fecha-se, preenche-se e traça-se com um só operador, por qualquer das duas regras que decidem o que está dentro. Os próprios eixos podem ser deslocados, inclinados e repostos como a página os tinha.",
    steps: "Passos a partir de onde está a caneta, e uma estrela dada por rotações",
    stars: [
        "Par-ímpar, fechado",
        "Não nulo, fechado",
        "Par-ímpar, aberto",
        "Contorno, fechado",
    ],
    ellipses: "Uma elipse, uma fatia fechada no centro e um arco rodado",
    heart: "Um coração definido por um caminho SVG",
    corners: "Junções em bico cortadas para lá de um limite, e um tracejado começado a meio",
    miters: ["Limite 1,5: cortada", "Limite 10: em bico"],
    axes: "Eixos deslocados, inclinados e repostos",
    squares: ["Deslocados", "Inclinados", "Repostos dentro de uma rotação"],
    numbers: "Cores dadas pelos seus números: cinzento, depois as quatro tintas",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Il mese, disegnato in curve",
    lead: "Una pagina dà un tracciato con segmenti retti e curve cubiche, e nient’altro: non esiste un operatore di cerchio né di arco. Ogni forma qui sotto è stata chiesta per nome (un centro e un raggio, due angoli, tre punti per cui passare) e le curve sono state calcolate apposta. Nessun pezzo gira più di un quarto di giro, così un cerchio è fatto di quattro curve e il contorno sbaglia di un quarantesimo di punto su un cerchio di un pollice.",
    pie: "Dove sono andate le ore",
    slices: ["Ufficio tecnico", "Lastre e prove", "Consegna", "Deposito"],
    gauge: "A che punto dell’anno è il lavoro",
    gauge_label: "del lavoro dell’anno è alle spalle",
    card: "Un biglietto dagli angoli smussati",
    card_label: "Ordini ricevuti, settimana per settimana",
    arcs: "Archi a cui si dice dove andare, non quanto girare",
    through: "Un arco, per tre punti",
    enlarged: "Raggi ingranditi",
    four: "Quattro archi, tra gli stessi due punti",
    caveat: "Una curva costa sei numeri e un segmento retto due, così un cerchio occupa cinque righe di pagina anziché una. Ciò che non costa è un’immagine: le forme qui sono disegnate dal programma di lettura alla dimensione a cui è mostrata la pagina, e restano nitide a ognuna.",
    pen_title: "Dove va poi la penna",
    pen_lead: "Un punto può essere dato da dove sta la penna anziché dall’angolo della pagina: un passo in larghezza e in alto, o una rotazione e una lunghezza. Un tracciato si chiude, si riempie e si traccia con un solo operatore, secondo l’una o l’altra delle due regole che decidono cosa sta dentro. Gli assi stessi si possono spostare, inclinare e rimettere come li aveva la pagina.",
    steps: "Passi da dove sta la penna, e una stella data per rotazioni",
    stars: [
        "Pari-dispari, chiuso",
        "Non zero, chiuso",
        "Pari-dispari, aperto",
        "Contorno, chiuso",
    ],
    ellipses: "Un’ellisse, una fetta chiusa sul centro e un arco ruotato",
    heart: "Un cuore definito da un tracciato SVG",
    corners: "Giunzioni a punta tagliate oltre un limite, e un tratteggio iniziato a metà",
    miters: ["Limite 1,5: tagliata", "Limite 10: a punta"],
    axes: "Assi spostati, inclinati e rimessi",
    squares: ["Spostati", "Inclinati", "Rimessi dentro una rotazione"],
    numbers: "Colori dati per numeri: grigio, poi i quattro inchiostri",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "El mes, dibujado en curvas",
    lead: "Una página da un trazado con segmentos rectos y curvas cúbicas, y con nada más: no hay operador de círculo ni de arco. Cada forma de abajo se pidió por su nombre —un centro y un radio, dos ángulos, tres puntos por los que pasar— y las curvas se calcularon para ella. Ninguna pieza gira más de un cuarto de vuelta, así que un círculo son cuatro curvas y el contorno se desvía la cuadragésima parte de un punto en un círculo de una pulgada.",
    pie: "Adónde se fueron las horas",
    slices: [
        "Oficina técnica",
        "Planchas y pruebas",
        "Entrega",
        "Almacenaje",
    ],
    gauge: "Cuánto del año lleva hecho el trabajo",
    gauge_label: "del trabajo del año ya está hecho",
    card: "Una tarjeta de esquinas suavizadas",
    card_label: "Pedidos recibidos, semana a semana",
    arcs: "Arcos a los que se dice adónde ir, no cuánto girar",
    through: "Un arco, por tres puntos",
    enlarged: "Radios ampliados",
    four: "Cuatro arcos, entre los mismos dos puntos",
    caveat: "Una curva cuesta seis números y un segmento recto dos, así que un círculo son cinco líneas de página y no una. Lo que no cuesta es una imagen: las formas de aquí las dibuja el programa de lectura al tamaño en que se muestre la página, y se ven nítidas a cualquier tamaño.",
    pen_title: "Adónde va la pluma después",
    pen_lead: "Un punto puede darse desde donde está la pluma en vez de desde la esquina de la página: un paso a lo ancho y hacia arriba, o un giro y una longitud. Un trazado se cierra, se rellena y se traza con un solo operador, por cualquiera de las dos reglas que deciden qué está dentro. Los propios ejes pueden moverse, inclinarse y volver a como los tenía la página.",
    steps: "Pasos desde donde está la pluma, y una estrella dada por giros",
    stars: [
        "Par-impar, cerrado",
        "No nulo, cerrado",
        "Par-impar, abierto",
        "Contorno, cerrado",
    ],
    ellipses: "Una elipse, una porción cerrada en su centro y un arco girado",
    heart: "Un corazón definido con datos de trazado SVG",
    corners: "Uniones en punta cortadas pasado un límite, y un guion empezado a medias",
    miters: ["Límite 1,5: cortada", "Límite 10: en punta"],
    axes: "Ejes movidos, inclinados y restablecidos",
    squares: ["Movidos", "Inclinados", "Restablecidos dentro de un giro"],
    numbers: "Colores dados por sus números: gris, luego las cuatro tintas",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Der Monat, in Kurven gezeichnet",
    lead: "Eine Seite gibt einen Pfad mit geraden Abschnitten und kubischen Kurven an, und mit nichts anderem: Es gibt keinen Operator für Kreise und keinen für Bögen. Jede Form unten wurde beim Namen verlangt — ein Mittelpunkt und ein Radius, zwei Winkel, drei Punkte, durch die sie läuft —, und die Kurven wurden für sie berechnet. Kein Stück biegt sich weiter als eine Vierteldrehung, also ist ein Kreis vier Kurven, und die Kontur weicht bei einem Kreis von einem Zoll Durchmesser um ein Vierzigstel Punkt ab.",
    pie: "Wohin die Stunden gingen",
    slices: [
        "Zeichenbüro",
        "Platten und Andrucke",
        "Lieferung",
        "Lagerung",
    ],
    gauge: "Wie weit die Jahresarbeit fortgeschritten ist",
    gauge_label: "der Jahresarbeit liegen hinter uns",
    card: "Eine Karte mit abgerundeten Ecken",
    card_label: "Aufträge, Woche für Woche",
    arcs: "Bögen, denen gesagt wird, wohin, nicht wie weit sie drehen",
    through: "Ein Bogen, durch drei Punkte",
    enlarged: "Größere Radien",
    four: "Vier Bögen zwischen denselben zwei Punkten",
    caveat: "Eine Kurve kostet sechs Zahlen und ein gerader Abschnitt zwei, also ist ein Kreis fünf Zeilen einer Seite statt einer. Was er nicht kostet, ist ein Bild: Die Formen hier zeichnet die Lesesoftware in jeder Größe, in der die Seite gezeigt wird, und sie bleiben in jeder scharf.",
    pen_title: "Wohin der Stift als Nächstes geht",
    pen_lead: "Ein Punkt kann von dort aus angegeben werden, wo der Stift steht, statt von der Ecke der Seite: ein Schritt nach rechts und nach oben oder eine Drehung und eine Länge. Ein Pfad wird mit einem Operator geschlossen, gefüllt und gezogen, nach einer der beiden Regeln, die bestimmen, was innen liegt. Die Achsen selbst lassen sich verschieben, neigen und so zurücksetzen, wie die Seite sie hatte.",
    steps: "Schritte von der Stelle des Stifts, und ein Stern aus Drehungen",
    stars: [
        "Gerade/ungerade, zu",
        "Nicht null, zu",
        "Gerade/ungerade",
        "Kontur, geschlossen",
    ],
    ellipses: "Eine Ellipse, ein zur Mitte geschlossenes Stück und ein gedrehter Bogen",
    heart: "Ein Herz aus SVG-Pfaddaten",
    corners: "Spitze Verbindungen jenseits einer Grenze abgeschnitten, und ein mittendrin begonnener Strich",
    miters: ["Grenze 1,5: abgeschnitten", "Grenze 10: spitz"],
    axes: "Achsen verschoben, geneigt und zurückgesetzt",
    squares: ["Verschoben", "Geneigt", "In einer Drehung zurückgesetzt"],
    numbers: "Farben nach ihren Zahlen: Grau, dann die vier Farben",
};

/// 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 left edge of everything on the page.
const LEFT: f64 = 72.0;

/// How wide a block of text, and the card, are.
const WIDTH: f64 = 451.0;

/// The hours the four slices of the pie stand for.
const HOURS: [i32; 4] = [64, 41, 27, 18];

/// The orders taken in each of seven weeks, which the line in the card draws.
const ORDERS: [i32; 7] = [26, 38, 31, 52, 44, 61, 57];

/// The most orders the line in the card leaves room for.
const CEILING: f64 = 70.0;

/// How far round the year the gauge has come.
const DONE: f64 = 0.62;

/// How far in from the left edge the arc whose radii are enlarged begins.
const ENLARGED_AT: f64 = 212.0;

/// How much room the name of the arc whose radii are enlarged has.
const ENLARGED_ROOM: f64 = 76.0;

/// The radii the arc whose radii are enlarged is asked for, too short to reach
/// across the sixty points between its two ends.
const SHORT_RADII: (f64, f64) = (6.0, 3.0);

/// How far in from the left edge the name of the heart begins, under the
/// ellipse's right end, below everything else in that row.
const HEART_NAME_AT: f64 = 110.0;

/// How much room the name of the heart has: up to where the turned arcs begin.
const HEART_ROOM: f64 = 185.0;

/// The heart beside the ellipse, as SVG path data on a square a hundred units
/// across: two lobes of cubic curves, each carried on by a smooth one, and a
/// round window of two relative arcs.
const HEART: &str = "M50 30C50 10 10 10 10 35S40 70 50 90C60 70 90 60 90 35S50 10 50 30ZM22 34a6 6 0 1 1 12 0a6 6 0 1 1-12 0z";

/// The four colours the slices and the line are drawn in.
const fn palette() -> [Rgb; 4] {
    [
        Rgb::new(0.16, 0.33, 0.62),
        Rgb::new(0.30, 0.57, 0.75),
        Rgb::new(0.55, 0.73, 0.82),
        Rgb::new(0.79, 0.86, 0.90),
    ]
}

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    handle: &FontHandle,
    size: f64,
    top: f64,
    text: &str,
) -> Result<f64, hqf_pdf::Error> {
    let flow = TextFlow::new(handle, size);
    let lines = flow.break_lines(text, WIDTH);
    c.begin_text();
    flow.draw(c, &lines, LEFT, top, WIDTH)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// Sets one line of words at `(x, y)`.
fn label(
    c: &mut Content,
    handle: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    text: &str,
    room: f64,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(handle, size);
    c.begin_text();
    flow.draw(c, &flow.break_lines(text, room), x, y, room)?;
    c.end_text();
    Ok(())
}

/// What share of the hours each slice of the pie stands for.
fn shares() -> [f64; 4] {
    let mut total = 0;
    for hours in HOURS {
        total += hours;
    }
    let mut out = [0.0; 4];
    for (share, hours) in out.iter_mut().zip(HOURS) {
        *share = f64::from(hours) / f64::from(total);
    }
    out
}

/// Draws the pie about `(cx, cy)`, and names each slice beside it.
///
/// A slice is one arc with two straight sides: the arc writes where it begins,
/// a segment runs back to the centre, and closing the subpath draws the other
/// side. Each swatch beside a name is a closed run of four corners grooved by a
/// radius below nothing, which cuts every corner in rather than off.
fn pie(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    cx: f64,
    cy: f64,
) -> Result<(), hqf_pdf::Error> {
    let radius = 68.0;
    let mut start = FRAC_PI_2;
    for (share, colour) in shares().into_iter().zip(palette()) {
        let sweep = TAU * share;
        c.save_state();
        c.set_fill(colour)?;
        c.arc(cx, cy, radius, start, -sweep)?;
        c.line_to(cx, cy)?;
        c.close_path();
        c.fill();
        c.restore_state();
        start -= sweep;
    }

    // The names sit to the right of the pie, one under the other, each behind a
    // swatch of its own colour.
    let mut y = cy + 46.0;
    for (colour, name) in palette().into_iter().zip(words.slices) {
        c.save_state();
        c.set_fill(colour)?;
        let (left, bottom) = (cx + 96.0, y);
        let corners = [
            (left, bottom),
            (left + 12.0, bottom),
            (left + 12.0, bottom + 12.0),
            (left, bottom + 12.0),
        ];
        c.rounded_polyline(&corners, -3.0, true)?;
        c.fill();
        c.restore_state();
        label(c, handle, 9.5, cx + 116.0, y + 3.0, name, 180.0)?;
        y -= 26.0;
    }
    Ok(())
}

/// Draws the ring gauge about `(cx, cy)`, the part that is done in the darkest
/// colour of the palette.
///
/// The pale track is one circle laid inside another and filled by the even-odd
/// rule, which leaves the ring between them. The part that is done is an arc
/// drawn with a thick pen over that ring.
fn gauge(c: &mut Content, cx: f64, cy: f64) -> Result<(), hqf_pdf::Error> {
    c.save_state();
    c.set_fill(Rgb::new(0.90, 0.92, 0.95))?;
    c.circle(cx, cy, 46.0)?;
    c.circle(cx, cy, 30.0)?;
    c.fill_even_odd();
    c.restore_state();

    c.save_state();
    c.set_line_width(16.0)?;
    c.set_stroke(palette()[0])?;
    c.arc(cx, cy, 38.0, FRAC_PI_2, -(TAU * DONE))?;
    c.stroke();
    c.restore_state();
    Ok(())
}

/// Draws the card and the line of orders inside it, and hands back the ordinate
/// the card ends at.
fn card(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<f64, hqf_pdf::Error> {
    let height = 96.0;
    let bottom = top - height;

    c.save_state();
    c.set_fill(Rgb::new(0.96, 0.97, 0.98))?;
    c.set_stroke(Rgb::gray(0.72))?;
    c.set_line_width(0.8)?;
    c.rounded_rect(LEFT, bottom, WIDTH, height, 14.0)?;
    c.fill_and_stroke();
    c.restore_state();

    label(
        c,
        handle,
        9.0,
        LEFT + 18.0,
        top - 20.0,
        words.card_label,
        300.0,
    )?;

    // The seven weeks are spaced evenly across the card, and each order count
    // is measured up from the floor of the plot.
    let floor = bottom + 18.0;
    let plot = 52.0;
    let step = (WIDTH - 36.0) / 6.0;
    let mut points = Vec::with_capacity(ORDERS.len());
    let mut x = LEFT + 18.0;
    for orders in ORDERS {
        let share = f64::from(orders) / CEILING;
        points.push((x, floor + plot * share));
        x += step;
    }

    c.save_state();
    c.set_line_width(2.2)?;
    c.set_stroke(palette()[1])?;
    c.rounded_polyline(&points, 14.0, false)?;
    c.stroke();
    c.restore_state();
    Ok(bottom)
}

/// Draws the arc through three points, the arc whose radii are enlarged, and
/// the four arcs of one ellipse, and names all three.
fn curves(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    // The two figures bulge above and below the line they are drawn on, so both
    // are named over their own drawing rather than under it.
    let base = top - 74.0;

    label(c, handle, 8.5, LEFT, top - 12.0, words.through, 200.0)?;
    c.save_state();
    c.set_line_width(1.6)?;
    c.set_stroke(palette()[0])?;
    c.move_to(LEFT, base)?;
    c.arc_through(LEFT, base, LEFT + 100.0, base + 26.0, LEFT + 200.0, base)?;
    c.stroke();
    c.restore_state();

    // Radii too short to reach from one end to the other are refused unless the
    // shape asks for them to be enlarged: both are scaled by the same amount,
    // and the arc is half of the ellipse that comes of it.
    let start = LEFT + ENLARGED_AT;
    label(
        c,
        handle,
        8.5,
        start,
        top - 12.0,
        words.enlarged,
        ENLARGED_ROOM,
    )?;
    c.save_state();
    c.set_line_width(1.6)?;
    c.set_stroke(palette()[0])?;
    c.move_to(start, base)?;
    c.elliptical_arc(
        start,
        base,
        start + 60.0,
        base,
        SHORT_RADII.0,
        SHORT_RADII.1,
        EllipticalArc::new().clockwise().enlarge_radii(),
    )?;
    c.stroke();
    c.restore_state();

    // The same two ends, the same two radii, and the four arcs that answer
    // them: the long way round and the short, each walked either way.
    let from_x = LEFT + 300.0;
    let to_x = LEFT + 400.0;
    let shapes = [
        EllipticalArc::new(),
        EllipticalArc::new().clockwise(),
        EllipticalArc::new().large(),
        EllipticalArc::new().large().clockwise(),
    ];
    label(c, handle, 8.5, from_x, top - 12.0, words.four, 220.0)?;
    for (shape, colour) in shapes.into_iter().zip(palette()) {
        c.save_state();
        c.set_line_width(1.6)?;
        c.set_stroke(colour)?;
        c.move_to(from_x, base)?;
        c.elliptical_arc(from_x, base, to_x, base, 62.0, 18.0, shape)?;
        c.stroke();
        c.restore_state();
    }
    Ok(())
}

/// Draws the steps and the four stars from `top` down.
///
/// The steps are given from where the pen stands, and the second flight begins
/// a step away from where the first one ends. Each star is five equal sides,
/// each turned two fifths of a turn from the one before.
fn steps_and_stars(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    c.save_state();
    c.set_stroke_gray(0.2)?;
    c.set_line_width(1.4)?;
    c.move_to(LEFT, top - 70.0)?;
    for _ in 0..4 {
        c.line_by(14.0, 0.0)?.line_by(0.0, 14.0)?;
    }
    c.move_by(10.0, -56.0)?;
    for _ in 0..4 {
        c.line_by(10.0, 0.0)?.line_by(0.0, 10.0)?;
    }
    c.stroke();
    c.restore_state();

    let side = 50.0;
    let turn = 0.4 * TAU;
    let mut left = LEFT + 130.0;
    for (index, name) in words.stars.into_iter().enumerate() {
        c.save_state();
        c.set_fill(palette()[1])?;
        c.set_stroke(palette()[0])?;
        c.set_line_width(1.2)?;
        c.move_to(left, top - 22.0)?;
        c.move_polar(0.0, 0.0)?;
        let mut angle = 0.0;
        for _ in 0..4 {
            c.line_polar(angle, side)?;
            angle -= turn;
        }
        match index {
            0 => c.close_fill_and_stroke_even_odd(),
            1 => c.close_fill_and_stroke(),
            2 => c.fill_and_stroke_even_odd(),
            _ => c.close_and_stroke(),
        };
        c.restore_state();
        label(c, handle, 7.5, left, top - 88.0, name, 80.0)?;
        left += 84.0;
    }
    Ok(())
}

/// Draws an ellipse, a heart given as SVG path data, a slice closed on its
/// centre and an arc on a turned ellipse, from `top` down.
fn ellipses(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    let middle = top - 40.0;
    c.save_state();
    c.set_fill(palette()[2])?;
    c.ellipse(LEFT + 60.0, middle, 60.0, 30.0)?;
    c.fill();

    // The heart's square of a hundred units fitted into a box of fifty points,
    // and its window left open by the even-odd rule.
    let heart = SvgPath::parse(HEART)?;
    c.set_fill(palette()[1])?;
    c.svg_path_in(
        &heart,
        Some([0.0, 0.0, 100.0, 100.0]),
        Rect::new(LEFT + 130.0, middle - 25.0, 50.0, 50.0),
        &FitBox::new(FitMode::Contain),
    )?;
    c.fill_even_odd();

    // The slice: out from the centre to the rim, round, and closed back.
    let (cx, cy, radius) = (LEFT + 200.0, middle - 20.0, 50.0);
    c.set_fill(palette()[0])?;
    c.move_to(cx, cy)?;
    c.line_to(cx + radius, cy)?;
    c.arc_to(cx, cy, radius, 0.0, FRAC_PI_2 * 0.8)?;
    c.close_path();
    c.fill();

    // The same two ends and radii, the ellipse turned a twelfth of a turn and
    // then a third.
    for (turned, colour) in [(TAU / 12.0, palette()[1]), (TAU / 3.0, palette()[0])] {
        c.set_stroke(colour)?;
        c.set_line_width(1.6)?;
        c.move_to(LEFT + 300.0, middle)?;
        c.elliptical_arc(
            LEFT + 300.0,
            middle,
            LEFT + 400.0,
            middle,
            60.0,
            50.0,
            EllipticalArc::new().x_rotation(turned),
        )?;
        c.stroke();
    }
    c.restore_state();
    label(
        c,
        handle,
        7.5,
        LEFT + HEART_NAME_AT,
        top - 82.0,
        words.heart,
        HEART_ROOM,
    )
}

/// Draws two zigzags whose miter limits differ, and a dashed line whose pattern
/// begins partway, from `top` down.
fn corners(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    let mut left = LEFT;
    for (limit, name) in [1.5, 10.0].into_iter().zip(words.miters) {
        c.save_state();
        c.set_stroke(palette()[0])?;
        c.set_line_width(7.0)?;
        c.set_line_style(&LineStyle::new().join(LineJoin::Miter))?;
        c.set_miter_limit(limit)?;
        c.move_to(left, top - 60.0)?;
        c.line_to(left + 20.0, top - 20.0)?;
        c.line_to(left + 40.0, top - 60.0)?;
        c.line_to(left + 60.0, top - 20.0)?;
        c.stroke();
        c.restore_state();
        label(c, handle, 7.5, left, top - 78.0, name, 120.0)?;
        left += 130.0;
    }

    let dash = Dash::new([9.0, 3.0, 2.0, 3.0])?.starting_at(5.0)?;
    let pattern = format!(
        "[{}] {:.0}",
        dash.lengths()
            .iter()
            .map(|length| format!("{length:.0}"))
            .collect::<Vec<_>>()
            .join(" "),
        dash.phase()
    );
    c.save_state();
    c.set_stroke(palette()[1])?;
    c.set_line_width(3.0)?;
    c.set_line_style(
        &LineStyle::new()
            .dash(dash)
            .cap(LineCap::Round)
            .join(LineJoin::Miter)
            .miter_limit(4.0),
    )?;
    c.move_to(LEFT + 270.0, top - 30.0)?;
    c.line_to(LEFT + 440.0, top - 30.0)?;
    c.line_to(LEFT + 400.0, top - 60.0)?;
    c.stroke();
    c.restore_state();
    label(c, handle, 7.5, LEFT + 270.0, top - 78.0, &pattern, 160.0)
}

/// Draws the same square three times, from `top` down: its axes moved, leaned,
/// and put back as the page had them inside a turn.
fn axes(
    c: &mut Content,
    handle: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<(), hqf_pdf::Error> {
    let bottom = top - 70.0;
    c.save_state();
    c.set_fill(palette()[2])?;
    c.translate(LEFT, bottom)?;
    c.rect(0.0, 0.0, 50.0, 50.0)?.fill();
    c.restore_state();

    c.save_state();
    c.set_fill(palette()[1])?;
    c.translate(LEFT + 150.0, bottom)?;
    c.skew(TAU / 12.0, 0.0)?;
    c.rect(0.0, 0.0, 50.0, 50.0)?.fill();
    c.restore_state();

    // Inside a turn of an eighth, the axes are put back as the page had them,
    // so the square stands upright where the turn would have tipped it.
    c.save_state();
    c.rotate(TAU / 8.0, LEFT + 325.0, bottom + 25.0)?;
    c.replace_transform([1.0, 0.0, 0.0, 1.0, LEFT + 300.0, bottom])?;
    c.set_fill(palette()[0])?;
    c.rect(0.0, 0.0, 50.0, 50.0)?.fill();
    c.restore_state();

    let mut left = LEFT;
    for name in words.squares {
        label(c, handle, 7.5, left, bottom - 14.0, name, 140.0)?;
        left += 150.0;
    }
    Ok(())
}

/// Paints a row of swatches whose colours are given by their numbers, from
/// `top` down: three greys, then a colour in the four inks, filled and
/// outlined, and the same colour named as a device colour.
fn numbers(c: &mut Content, handle: &FontHandle, top: f64) -> Result<(), hqf_pdf::Error> {
    let bottom = top - 40.0;
    let mut left = LEFT;
    for grey in [0.25, 0.5, 0.75] {
        c.set_fill_gray(grey)?;
        c.rect(left, bottom, 40.0, 30.0)?.fill();
        left += 50.0;
    }

    c.save_state();
    c.set_fill_cmyk(0.0, 0.6, 0.9, 0.0)?;
    c.set_stroke_cmyk(0.9, 0.5, 0.0, 0.2)?;
    c.set_line_width(4.0)?;
    c.rect(left + 10.0, bottom, 40.0, 30.0)?.fill_and_stroke();
    c.restore_state();
    left += 70.0;

    let inks = Color::Cmyk(Cmyk::new(0.0, 0.6, 0.9, 0.0));
    let light = Color::Rgb(Rgb::new(0.30, 0.57, 0.75));
    for colour in [inks, light] {
        c.save_state();
        c.set_fill(colour)?;
        c.rect(left, bottom, 40.0, 30.0)?.fill();
        c.restore_state();
        let numbers = colour
            .to_components()
            .iter()
            .map(|value| format!("{value:.2}"))
            .collect::<Vec<_>>()
            .join(" ");
        label(c, handle, 7.5, left, bottom - 14.0, &numbers, 110.0)?;
        left += 120.0;
    }
    Ok(())
}

/// Draws the second page.
fn pen_page(c: &mut Content, text: &FontHandle, words: &Words) -> Result<(), hqf_pdf::Error> {
    let mut top = 790.0;
    top = block(c, text, 17.0, top, words.pen_title)? - 12.0;
    top = block(c, text, 9.5, top, words.pen_lead)? - 22.0;

    top = block(c, text, 11.0, top, words.steps)? - 12.0;
    steps_and_stars(c, text, words, top)?;
    top -= 110.0;

    top = block(c, text, 11.0, top, words.ellipses)? - 12.0;
    ellipses(c, text, words, top)?;
    top -= 100.0;

    top = block(c, text, 11.0, top, words.corners)? - 12.0;
    corners(c, text, words, top)?;
    top -= 100.0;

    top = block(c, text, 11.0, top, words.axes)? - 12.0;
    axes(c, text, words, top)?;
    top -= 110.0;

    top = block(c, text, 11.0, top, words.numbers)? - 12.0;
    numbers(c, text, top)
}

/// Draws the whole page.
fn build(words: &Words, font: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let text = doc.add_font(Font::parse(fs::read(font)?)?);

    let mut c = Content::new();
    let mut top = 790.0;
    top = block(&mut c, &text, 17.0, top, words.title)? - 12.0;
    top = block(&mut c, &text, 9.5, top, words.lead)? - 22.0;

    top = block(&mut c, &text, 11.0, top, words.pie)? - 12.0;
    pie(&mut c, &text, words, LEFT + 74.0, top - 74.0)?;
    top -= 152.0;

    top = block(&mut c, &text, 11.0, top, words.gauge)? - 12.0;
    gauge(&mut c, LEFT + 52.0, top - 50.0)?;
    label(
        &mut c,
        &text,
        9.5,
        LEFT + 118.0,
        top - 46.0,
        words.gauge_label,
        280.0,
    )?;
    top -= 100.0;

    top = block(&mut c, &text, 11.0, top, words.card)? - 12.0;
    top = card(&mut c, &text, words, top)? - 24.0;

    top = block(&mut c, &text, 11.0, top, words.arcs)? - 12.0;
    curves(&mut c, &text, words, top)?;
    top -= 118.0;

    c.set_fill(Rgb::gray(0.35))?;
    block(&mut c, &text, 8.5, top, words.caveat)?;

    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;

    let mut c = Content::new();
    pen_page(&mut c, &text, words)?;
    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;
    Ok(doc.to_bytes()?)
}

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 = env::args().skip(1);
    // 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 = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("shapes")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let bytes = build(words, &font_path)?;

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

#[cfg(test)]
mod tests {
    use hqf_pdf::{Content, EllipticalArc, Font, FontHandle, SvgPath};

    use super::{
        CEILING, ENLARGED_AT, ENLARGED_ROOM, HEART, HEART_NAME_AT, HEART_ROOM, LEFT, ORDERS,
        SHORT_RADII, WIDTH, WORDS, default_font, language, shares,
    };

    /// The font the page is set in, to measure what it draws.
    fn handle() -> FontHandle {
        let mut doc = hqf_pdf::Document::new();
        doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the test font")).expect("a font"),
        )
    }

    /// The lines two languages are allowed to write the same way.
    const SPARED: [&str; 2] = [
        // Written the same way in Portuguese.
        r#""Entrega""#,
        r#""Inclinados""#,
    ];

    #[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:?}"
        );
    }

    #[test]
    fn the_four_slices_of_the_pie_make_one_whole_turn() {
        let mut total = 0.0;
        for share in shares() {
            total += share;
        }

        assert!(
            (total - 1.0).abs() < 1e-12,
            "the slices come to {total} of a turn"
        );
    }

    #[test]
    fn no_week_of_orders_runs_over_the_ceiling_the_plot_leaves() {
        for orders in ORDERS {
            assert!(
                f64::from(orders) <= CEILING,
                "a week of {orders} orders is over the {CEILING} the plot draws"
            );
        }
    }

    #[test]
    fn every_name_beside_the_pie_fits_the_room_left_beside_it() {
        let font = handle();
        // A slice is named to the right of the pie, past its swatch.
        let room = 180.0;
        for (_, words) in &WORDS {
            for name in words.slices {
                assert!(
                    font.measure(name, 9.5) <= room,
                    "{name:?} needs {} of {room}",
                    font.measure(name, 9.5)
                );
            }
        }
    }

    /// A name under a figure of the second page that ran past its room would
    /// run into the name of the next figure.
    #[test]
    fn every_name_on_the_second_page_fits_under_its_figure() {
        let font = handle();
        for (_, words) in &WORDS {
            let named = words
                .stars
                .iter()
                .map(|name| (*name, 80.0))
                .chain(words.miters.iter().map(|name| (*name, 120.0)))
                .chain(words.squares.iter().map(|name| (*name, 140.0)))
                .chain(std::iter::once((words.heart, HEART_ROOM)));
            for (name, room) in named {
                assert!(
                    font.measure(name, 7.5) <= room,
                    "{name:?} needs {} of {room}",
                    font.measure(name, 7.5)
                );
            }
        }
    }

    #[test]
    fn the_name_of_the_heart_stops_short_of_the_turned_arcs() {
        // The turned arcs begin three hundred points in from the left edge, and
        // the ellipse's lowest point is above the line the name is set on.
        const { assert!(HEART_NAME_AT + HEART_ROOM <= 300.0 - 5.0) };
    }

    #[test]
    fn the_heart_reads_as_svg_path_data() {
        let heart = SvgPath::parse(HEART).expect("the heart is SVG path data");

        assert_eq!(heart.len(), 10);
    }

    #[test]
    fn the_name_of_the_enlarged_arc_fits_between_its_two_neighbours() {
        let font = handle();
        // The name of the arc through three points is given two hundred points
        // from the left edge, and the name of the four arcs begins three
        // hundred in.
        const { assert!(ENLARGED_AT >= 200.0 + 12.0) };
        const { assert!(ENLARGED_AT + ENLARGED_ROOM <= 300.0 - 12.0) };
        for (_, words) in &WORDS {
            assert!(
                font.measure(words.enlarged, 8.5) <= ENLARGED_ROOM,
                "{:?} needs {} of {ENLARGED_ROOM}",
                words.enlarged,
                font.measure(words.enlarged, 8.5)
            );
        }
    }

    #[test]
    fn the_enlarged_arc_is_asked_for_with_radii_that_cannot_reach() {
        let mut refused = Content::new();
        let plain = refused.elliptical_arc(
            0.0,
            0.0,
            60.0,
            0.0,
            SHORT_RADII.0,
            SHORT_RADII.1,
            EllipticalArc::new().clockwise(),
        );

        assert!(plain.is_err(), "the radii reach without being enlarged");
    }

    #[test]
    fn the_page_stays_inside_its_own_right_margin() {
        // The four arcs of one ellipse are the rightmost thing drawn. They are
        // cut from an ellipse standing midway between their two ends, so they
        // run out one radius past that middle and no further.
        let middle = LEFT + 350.0;
        let widest = middle + 62.0;

        assert!(widest <= LEFT + WIDTH, "the arcs run to {widest}");
    }

    #[test]
    fn a_slice_of_the_pie_is_one_arc_shut_by_two_straight_sides() {
        let mut slice = Content::new();
        slice.arc(100.0, 100.0, 76.0, 0.0, -1.0).expect("finite");
        slice.line_to(100.0, 100.0).expect("finite");
        slice.close_path();
        let written = String::from_utf8(slice.as_bytes().to_vec()).expect("operators are text");

        assert!(written.starts_with("176 100 m\n"), "the slice is {written}");
        assert!(
            written.ends_with("100 100 l\nh\n"),
            "the slice is {written}"
        );
    }

    #[test]
    fn the_four_arcs_of_one_ellipse_are_four_different_shapes() {
        let shapes = [
            EllipticalArc::new(),
            EllipticalArc::new().clockwise(),
            EllipticalArc::new().large(),
            EllipticalArc::new().large().clockwise(),
        ];
        let mut drawn = Vec::new();
        for shape in shapes {
            let mut content = Content::new();
            content
                .elliptical_arc(0.0, 0.0, 100.0, 0.0, 62.0, 30.0, shape)
                .expect("the radii reach");
            drawn.push(content.as_bytes().to_vec());
        }

        for (index, one) in drawn.iter().enumerate() {
            for other in drawn.iter().skip(index + 1) {
                assert_ne!(one, other, "two of the four arcs are the same shape");
            }
        }
    }
}