write_snag_list.rs

Le fichier Rust de l'exemple « Une liste de réserves, chaque défaut marqué sur le plan ». La feuille que produit la réception de locaux : le plan du plateau au 1:300 avec neuf défauts marqués là où ils sont, la liste de ces défauts une par ligne, et ce qu'ils représentent. Les marques sont posées au-dessus de la page : le logiciel de lecture les liste, les trie, et les imprime ou les laisse hors du papier.

Rust 1879 lignes

À quoi sert cet exemple

Quand des locaux changent de mains, les deux parties parcourent le plateau ensemble et notent ce qui n'est pas fini. Cette feuille est ce que donne cette visite. Le plan du plateau vient d'abord, chaque défaut marqué là où il est ; puis les mêmes défauts, un par ligne, avec le local, ce qui a été relevé, à quel point il gêne, le corps d'état qui en répond et la date avant laquelle il doit être repris ; puis trois tableaux qui disent ce que les neuf représentent, par degré, par local et par corps d'état. Aucun chiffre n'y est saisi à la main. La surface d'un local est celle du rectangle que le plan en trace, lue à l'échelle où le plan est réglé ; une part est un compte rapporté aux neuf ; une date est celle de la réception augmentée du délai que le degré accorde. Relevez un dixième défaut, et le plan, la liste et les trois tableaux bougent ensemble.

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
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
//! Creates the snag list drawn up when premises are handed over: a plan of the
//! floor with every defect marked on it, the list of those defects one to a
//! line, and a summary of what they come to.
//!
//! The marks on the plan are annotations, which is what sets this sheet apart
//! from every other example here. An annotation sits above the page rather than
//! inside what the page draws: reading software lists it, filters it, shows it,
//! hides it or leaves it off the paper, and the plan underneath is untouched
//! either way. The plan is drawn once; the reserves come and go over it.
//!
//! Five kinds of mark are used, one per shape the standard offers for this: a
//! cloud round a patch that is wholly under reserve, a ring on a defect that
//! sits at one point, an arrow whose closed head rests on what the note is
//! about, the outline of a defect that spreads over an area, and a run along a
//! defect that follows a line. Every one of them carries the words of its line
//! in the list, so what a screen reader speaks and what the list prints are the
//! same sentence.
//!
//! Every figure on the sheet is worked out rather than written down. A room's
//! area comes from the rectangle the plan draws it as, at the scale the plan is
//! set to. A degree's count is the number of snags carrying it, its share is
//! that count against the total, and the date each snag is to be made good by
//! is the handover plus the days its degree allows. The last of those dates is
//! the greatest of them.
//!
//! Every word the sheet prints is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one it is printed in. What is not language stays
//! out of it: the firm, the site, the handover, the reference, the room
//! rectangles, the counts, the areas, the shares and the dates read the same
//! whichever set of words is drawn.
//!
//! Usage: `cargo run --example write_snag_list -- tmp/snags.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_snag_list --
//! tmp/reserves.pdf`

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

use chrono::{Datelike, Days, NaiveDate};

use hqf_pdf::annotation::{
    Annotation, AnnotationBorder, BorderEffect, Circle, Line, LineEnding, PolyLine, Polygon, Square,
};
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{Document, Font, FontHandle, Page, 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 when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The sheet, in points: A4 upright.
const PAGE_WIDTH: f64 = 595.276;
const PAGE_HEIGHT: f64 = 841.890;

/// The margins every page keeps clear.
const LEFT: f64 = 56.0;
const RIGHT: f64 = PAGE_WIDTH - LEFT;

/// Where the first baseline of a page sits, and where its foot is written.
const HEAD_TOP: f64 = 786.0;
const FOOT: f64 = 54.0;

/// The steps a page comes down by: between two lines of a block, between two
/// blocks, between two blocks that stand apart, and between two rows of a
/// table.
const LINE: f64 = 12.0;
const BLOCK: f64 = 22.0;
const GAP: f64 = BLOCK * 2.0;
const ROW: f64 = 21.0;

/// The sizes the sheet is set at.
const FIRM_SIZE: f64 = 15.0;
const TITLE_SIZE: f64 = 19.0;
const HEADING_SIZE: f64 = 11.0;
const BODY: f64 = 9.0;
const SMALL: f64 = 8.0;
const TINY: f64 = 6.5;

/// The near-black the sheet is set in, the grey its labels take, and the rule
/// that parts two blocks.
const INK: Rgb = Rgb {
    r: 0.11,
    g: 0.12,
    b: 0.14,
};
const MUTED: Rgb = Rgb {
    r: 0.42,
    g: 0.44,
    b: 0.48,
};
const RULE: Rgb = Rgb {
    r: 0.78,
    g: 0.79,
    b: 0.82,
};

/// The grey a table's head band and its every other row are filled with.
const HEAD_BAND: Rgb = Rgb {
    r: 0.90,
    g: 0.91,
    b: 0.93,
};
const ROW_BAND: Rgb = Rgb {
    r: 0.965,
    g: 0.968,
    b: 0.972,
};

/// The floor of a room, the wall round the premises, and the partition between
/// two rooms.
const FLOOR: Rgb = Rgb {
    r: 0.965,
    g: 0.960,
    b: 0.945,
};
const SHELL_INK: Rgb = Rgb {
    r: 0.20,
    g: 0.22,
    b: 0.26,
};
const PARTITION_INK: Rgb = Rgb {
    r: 0.52,
    g: 0.54,
    b: 0.58,
};

/// The tint the outline of a spreading defect is filled with.
const FOOTPRINT_TINT: Rgb = Rgb {
    r: 0.98,
    g: 0.93,
    b: 0.86,
};

/// The colour every mark of a degree is drawn in.
const MINOR_INK: Rgb = Rgb {
    r: 0.83,
    g: 0.60,
    b: 0.05,
};
const MAJOR_INK: Rgb = Rgb {
    r: 0.87,
    g: 0.35,
    b: 0.05,
};
const BLOCKING_INK: Rgb = Rgb {
    r: 0.76,
    g: 0.09,
    b: 0.14,
};

/// The width a wall, a partition and a mark are stroked with, in points.
const SHELL_WIDTH_PT: f64 = 1.6;
const PARTITION_WIDTH: f64 = 0.9;
const MARK_WIDTH: f64 = 1.2;

/// How far the arcs of a cloud bulge, from 0 to 2.
const CLOUD_BULGE: f64 = 1.0;

/// The firm that inspected the premises, the premises themselves, and the
/// reference the sheet is filed under. The same whichever language the sheet is
/// printed in.
const FIRM: &str = "Vaugelade & Ferrand";
const SITE: &str = "Îlot Cassiopée, 42 quai de la Fonderie, 44200 Nantes";
const INSPECTOR: &str = "M. Ravel, Y. Sombath";
const REFERENCE: &str = "RS-2026-0914-03";

/// The day the premises were handed over, as a year, a month and a day.
const HANDOVER: (i32, u32, u32) = (2026, 9, 14);

/// The scale the plan is set to, and what turns a length on the premises into a
/// length on the paper: a millimetre is 72/25.4 points, so a centimetre of the
/// premises is a tenth of that, divided again by the scale.
const SCALE_DENOMINATOR: f64 = 300.0;
const POINTS_PER_INCH: f64 = 72.0;
const MILLIMETRES_PER_INCH: f64 = 25.4;
const PLAN_SCALE: f64 = 10.0 * POINTS_PER_INCH / (SCALE_DENOMINATOR * MILLIMETRES_PER_INCH);

/// The premises, in centimetres: how far the shell runs across and up.
const SHELL_WIDTH: f64 = 4800.0;
const SHELL_HEIGHT: f64 = 2600.0;

/// Where the plan's own origin — the inner corner of the shell nearest the
/// bottom left — sits on the page, in points. It is set across the middle of
/// the text.
const PLAN_LEFT: f64 = LEFT + ((RIGHT - LEFT) - SHELL_WIDTH * PLAN_SCALE) / 2.0;
const PLAN_BOTTOM: f64 = 370.0;

/// How far a room's name sits in from its own corner, in points.
const PLAN_PAD: f64 = 5.0;

/// How far the code of a snag sits from the mark it names, in points.
const CODE_OFFSET: f64 = 3.0;

/// One room of the premises: the corner nearest the plan's origin and how far
/// it runs, in centimetres. What the room is called is a word, and is held in
/// `Words` at the place the room has here.
#[derive(Debug)]
struct Room {
    /// The corner nearest the plan's origin.
    x: f64,
    /// See [`Self::x`].
    y: f64,
    /// How far the room runs across.
    width: f64,
    /// How far it runs up.
    height: f64,
}

/// The rooms, in the order the plan lays them out.
const ROOMS: [Room; 4] = [
    Room {
        x: 0.0,
        y: 0.0,
        width: 1800.0,
        height: 1100.0,
    },
    Room {
        x: 0.0,
        y: 1100.0,
        width: 1800.0,
        height: 1500.0,
    },
    Room {
        x: 1800.0,
        y: 0.0,
        width: 3000.0,
        height: 1700.0,
    },
    Room {
        x: 1800.0,
        y: 1700.0,
        width: 3000.0,
        height: 900.0,
    },
];

/// One run of wall the plan draws, in centimetres, and whether it holds the
/// premises in or only parts two rooms.
#[derive(Debug)]
struct Wall {
    /// Where the run begins.
    from: (f64, f64),
    /// Where it ends.
    to: (f64, f64),
    /// Whether it is the shell rather than a partition.
    shell: bool,
}

/// Every run of wall, cut short at each doorway so the openings show.
const WALLS: [Wall; 12] = [
    Wall {
        from: (0.0, 0.0),
        to: (200.0, 0.0),
        shell: true,
    },
    Wall {
        from: (320.0, 0.0),
        to: (4800.0, 0.0),
        shell: true,
    },
    Wall {
        from: (4800.0, 0.0),
        to: (4800.0, 2600.0),
        shell: true,
    },
    Wall {
        from: (4800.0, 2600.0),
        to: (0.0, 2600.0),
        shell: true,
    },
    Wall {
        from: (0.0, 2600.0),
        to: (0.0, 0.0),
        shell: true,
    },
    Wall {
        from: (1800.0, 0.0),
        to: (1800.0, 300.0),
        shell: false,
    },
    Wall {
        from: (1800.0, 390.0),
        to: (1800.0, 1750.0),
        shell: false,
    },
    Wall {
        from: (1800.0, 1840.0),
        to: (1800.0, 2600.0),
        shell: false,
    },
    Wall {
        from: (0.0, 1100.0),
        to: (700.0, 1100.0),
        shell: false,
    },
    Wall {
        from: (790.0, 1100.0),
        to: (1800.0, 1100.0),
        shell: false,
    },
    Wall {
        from: (1800.0, 1700.0),
        to: (2600.0, 1700.0),
        shell: false,
    },
    Wall {
        from: (2690.0, 1700.0),
        to: (4800.0, 1700.0),
        shell: false,
    },
];

/// How badly a snag stands in the way of the premises being used.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Degree {
    /// It is to be made good, and nothing waits on it.
    Minor,
    /// It keeps part of the premises from being used as they are meant to be.
    Major,
    /// Nothing else proceeds until it is made good.
    Blocking,
}

impl Degree {
    /// The days the trade is given to make it good, counted from the handover.
    const fn days(self) -> u32 {
        match self {
            Self::Minor => 30,
            Self::Major => 21,
            Self::Blocking => 7,
        }
    }

    /// The colour every mark of this degree is drawn in.
    const fn ink(self) -> Rgb {
        match self {
            Self::Minor => MINOR_INK,
            Self::Major => MAJOR_INK,
            Self::Blocking => BLOCKING_INK,
        }
    }

    /// Its place in the table of words.
    const fn place(self) -> usize {
        match self {
            Self::Minor => 0,
            Self::Major => 1,
            Self::Blocking => 2,
        }
    }
}

/// Every degree, in the order the summary sets them out: the one that holds
/// everything up first.
const DEGREES: [Degree; 3] = [Degree::Blocking, Degree::Major, Degree::Minor];

/// How a snag is marked on the plan, in centimetres of the premises.
#[derive(Debug)]
enum Mark {
    /// A cloud round a patch the whole of which is under reserve.
    Cloud {
        /// The corner of the patch nearest the plan's origin.
        x: f64,
        /// See [`Self::Cloud::x`].
        y: f64,
        /// How far the patch runs across.
        width: f64,
        /// How far it runs up.
        height: f64,
    },
    /// A ring round a defect that sits at one point.
    Ring {
        /// Where the defect sits.
        x: f64,
        /// See [`Self::Ring::x`].
        y: f64,
        /// How far the ring stands off it.
        radius: f64,
    },
    /// An arrow whose head rests on what the note is about.
    Arrow {
        /// The tail, where the code of the snag is written.
        from: (f64, f64),
        /// The head.
        to: (f64, f64),
    },
    /// The outline of a defect that spreads over an area.
    Footprint {
        /// Its corners, in the order they are joined.
        corners: &'static [(f64, f64)],
    },
    /// A run along a defect that follows a line.
    Run {
        /// The points it passes through, in order.
        along: &'static [(f64, f64)],
    },
}

impl Mark {
    /// Where the code of the snag is written, in centimetres.
    const fn anchor(&self) -> (f64, f64) {
        match *self {
            Self::Cloud { x, y, height, .. } => (x, y + height),
            Self::Ring { x, y, radius } => (x + radius, y + radius),
            Self::Arrow { from, .. } => from,
            Self::Footprint { corners } => corners[0],
            Self::Run { along } => along[0],
        }
    }
}

/// One snag: where it was found, how badly it stands in the way, who answers
/// for it, and how it is marked on the plan. What the defect is is a word, and
/// is held in `Words` at the place the snag has here.
#[derive(Debug)]
struct Snag {
    /// The room it was found in, as its place in the table of rooms.
    room: usize,
    /// How badly it stands in the way.
    degree: Degree,
    /// The trade that answers for it, as its place in the table of trades.
    trade: usize,
    /// How it is marked on the plan.
    mark: Mark,
}

/// The corners of the one defect that spreads over an area, and the points the
/// one that follows a line passes through.
const SPREAD: [(f64, f64); 5] = [
    (2200.0, 300.0),
    (3400.0, 300.0),
    (3400.0, 900.0),
    (2900.0, 1120.0),
    (2200.0, 900.0),
];
const ALONG: [(f64, f64); 3] = [(1810.0, 1880.0), (1810.0, 2220.0), (1810.0, 2560.0)];

/// The snags, in the order they were found.
const SNAGS: [Snag; 9] = [
    Snag {
        room: 0,
        degree: Degree::Major,
        trade: 0,
        mark: Mark::Ring {
            x: 260.0,
            y: 150.0,
            radius: 130.0,
        },
    },
    Snag {
        room: 0,
        degree: Degree::Minor,
        trade: 1,
        mark: Mark::Cloud {
            x: 900.0,
            y: 780.0,
            width: 780.0,
            height: 240.0,
        },
    },
    Snag {
        room: 1,
        degree: Degree::Minor,
        trade: 2,
        mark: Mark::Ring {
            x: 900.0,
            y: 1850.0,
            radius: 170.0,
        },
    },
    Snag {
        room: 1,
        degree: Degree::Major,
        trade: 3,
        mark: Mark::Run { along: &ALONG },
    },
    Snag {
        room: 2,
        degree: Degree::Major,
        trade: 4,
        mark: Mark::Footprint { corners: &SPREAD },
    },
    Snag {
        room: 2,
        degree: Degree::Blocking,
        trade: 5,
        mark: Mark::Arrow {
            from: (4260.0, 980.0),
            to: (3620.0, 130.0),
        },
    },
    Snag {
        room: 2,
        degree: Degree::Minor,
        trade: 5,
        mark: Mark::Ring {
            x: 4380.0,
            y: 1360.0,
            radius: 160.0,
        },
    },
    Snag {
        room: 3,
        degree: Degree::Blocking,
        trade: 6,
        mark: Mark::Cloud {
            x: 2250.0,
            y: 1780.0,
            width: 520.0,
            height: 520.0,
        },
    },
    Snag {
        room: 3,
        degree: Degree::Major,
        trade: 7,
        mark: Mark::Arrow {
            from: (3540.0, 1840.0),
            to: (4280.0, 2400.0),
        },
    },
];

/// The right edge of each of the six columns of the list, measured from the
/// left margin, in points.
const LIST_COLUMNS: [f64; 6] = [28.0, 124.0, 282.0, 340.0, 408.0, 483.276];

/// The right edge of each of the three columns the summary counts a degree or a
/// trade in, and of the four it counts a room in.
const COUNT_COLUMNS: [f64; 3] = [190.0, 260.0, 330.0];
const ROOM_COLUMNS: [f64; 4] = [190.0, 275.0, 345.0, 415.0];

/// Every word the sheet prints, in one language.
///
/// What is not language stays out of it: the firm, the site, the inspectors,
/// the reference, the handover, the room rectangles, the counts, the areas, the
/// shares and the dates are drawn from data of their own and read the same in
/// every language.
#[derive(Debug)]
struct Words {
    /// What the file says it is, and the line under the firm's name.
    title: &'static str,
    tagline: &'static str,
    /// The four marks at the head of the first page.
    site: &'static str,
    handover: &'static str,
    reference: &'static str,
    inspected: &'static str,
    /// What the plan is headed, and what its scale stands under.
    plan: &'static str,
    scale: &'static str,
    /// The legend under the plan, and one line for each kind of mark.
    legend: &'static str,
    cloud: &'static str,
    ring: &'static str,
    arrow: &'static str,
    footprint: &'static str,
    run: &'static str,
    /// The key to the colours, and how long a degree is given, worded round the
    /// number of days.
    key: &'static str,
    within: &'static str,
    /// What the reader is told about the marks, over two lines.
    note: [&'static str; 2],
    /// The three degrees, in the order [`Degree::place`] gives them.
    degrees: [&'static str; 3],
    /// The rooms, in the order the plan lays them out.
    rooms: [&'static str; 4],
    /// The trades that answer for the snags.
    trades: [&'static str; 8],
    /// The nine snags, in the order the list holds them.
    natures: [&'static str; 9],
    /// The heads of the six columns of the list.
    number: &'static str,
    room: &'static str,
    nature: &'static str,
    degree: &'static str,
    due: &'static str,
    trade: &'static str,
    /// What the date a snag is to be made good by stands under, in a sentence
    /// rather than at the head of a column.
    repair: &'static str,
    /// What the list and the summary are headed.
    list: &'static str,
    summary: &'static str,
    /// The heads of the two tables of the summary and of their own columns.
    by_degree: &'static str,
    by_room: &'static str,
    by_trade: &'static str,
    counted: &'static str,
    share: &'static str,
    area: &'static str,
    total: &'static str,
    /// The last line of the summary.
    latest: &'static str,
    /// The two words the foot of every page numbers it with.
    page: &'static str,
    of: &'static str,
}

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

/// The sheet in English.
const ENGLISH: Words = Words {
    title: "Snag list",
    tagline: "Building surveyors",
    site: "SITE",
    handover: "HANDOVER",
    reference: "REFERENCE",
    inspected: "INSPECTED BY",
    plan: "The floor, and where each snag sits",
    scale: "Scale",
    legend: "What each mark means",
    cloud: "Cloud — the whole of the patch it runs round is under reserve.",
    ring: "Ring — a defect that sits at one point.",
    arrow: "Arrow — the head rests on what the note is about.",
    footprint: "Outline — a defect that spreads over an area of its own.",
    run: "Run — a defect that follows a line, a crack, a joint or a skirting.",
    key: "What each colour means",
    within: "made good within {days} days of the handover",
    note: [
        "Every mark on the plan says the same words as its line in the list.",
        "Reading software shows them, hides them or leaves them off the paper.",
    ],
    degrees: ["Minor", "Major", "Blocking"],
    rooms: ["Reception", "Meeting room", "Open office", "Service core"],
    trades: [
        "Joinery",
        "Painting",
        "Plastering",
        "Glazing",
        "Floor covering",
        "Electrics",
        "Plumbing",
        "Air handling",
    ],
    natures: [
        "Entrance door rubs on the floor",
        "Paint runs on the end partition",
        "Ceiling tile cracked over table",
        "Glazed partition scratched",
        "Floor covering lifting at joints",
        "Three sockets dead on south run",
        "Luminaire missing over copier",
        "Water at the foot of the riser",
        "Extract grille not connected",
    ],
    number: "NO.",
    room: "ROOM",
    nature: "WHAT WAS FOUND",
    degree: "DEGREE",
    due: "MAKE GOOD BY",
    trade: "TRADE",
    repair: "to be made good by",
    list: "The snags, one to a line",
    summary: "What the snags come to",
    by_degree: "Gathered by degree",
    by_room: "Gathered by room",
    by_trade: "Gathered by trade",
    counted: "SNAGS",
    share: "SHARE",
    area: "AREA",
    total: "TOTAL",
    latest: "The last of the dates the work is to be made good by",
    page: "Page",
    of: "of",
};

/// The sheet in French.
const FRENCH: Words = Words {
    title: "Liste de réserves",
    tagline: "Cabinet d'expertise du bâtiment",
    site: "CHANTIER",
    handover: "RÉCEPTION",
    reference: "RÉFÉRENCE",
    inspected: "VISITE FAITE PAR",
    plan: "Le plateau, et où sont les réserves",
    scale: "Échelle",
    legend: "Ce que dit chaque marque",
    cloud: "Nuage — toute la surface qu'il entoure est sous réserve.",
    ring: "Cercle — un défaut qui tient en un point.",
    arrow: "Flèche — la pointe se pose sur ce qui est en cause.",
    footprint: "Contour — un défaut qui s'étend sur une surface.",
    run: "Filet — un défaut qui suit une ligne, fissure, joint ou plinthe.",
    key: "Ce que dit chaque couleur",
    within: "reprise dans les {days} jours qui suivent la réception",
    note: [
        "Chaque marque du plan dit les mêmes mots que sa ligne dans la liste.",
        "Le logiciel de lecture les affiche, les masque ou les laisse hors du papier.",
    ],
    degrees: ["Mineure", "Majeure", "Bloquante"],
    rooms: [
        "Accueil",
        "Salle de réunion",
        "Plateau ouvert",
        "Locaux techniques",
    ],
    trades: [
        "Menuiserie",
        "Peinture",
        "Plâtrerie",
        "Vitrerie",
        "Sols souples",
        "Électricité",
        "Plomberie",
        "Ventilation",
    ],
    natures: [
        "Porte d'entrée qui frotte au sol",
        "Coulures de peinture sur cloison",
        "Dalle de plafond fendue au centre",
        "Cloison vitrée rayée",
        "Revêtement de sol qui se décolle",
        "Trois prises mortes au sud",
        "Luminaire manquant au-dessus",
        "Eau au pied de la colonne",
        "Grille d'extraction non raccordée",
    ],
    number: "N°",
    room: "LOCAL",
    nature: "CE QUI A ÉTÉ RELEVÉ",
    degree: "DEGRÉ",
    due: "LEVÉE AVANT LE",
    trade: "CORPS D'ÉTAT",
    repair: "à reprendre avant le",
    list: "Les réserves, une par ligne",
    summary: "Ce que les réserves représentent",
    by_degree: "Par degré",
    by_room: "Par local",
    by_trade: "Par corps d'état",
    counted: "RÉSERVES",
    share: "PART",
    area: "SURFACE",
    total: "TOTAL",
    latest: "La dernière des dates de reprise",
    page: "Page",
    of: "sur",
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// `digits`, its thousands parted by a no-break space, which is how every
/// language this example is written in parts them.
fn grouped(digits: &str) -> String {
    let mut out = String::with_capacity(digits.len() + 4);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    out
}

/// A count, written as the sheet writes one.
fn counted(value: usize) -> String {
    grouped(&value.to_string())
}

/// A measurement, written with one decimal, its thousands parted by a no-break
/// space and its decimal by a point.
fn measured(value: f64) -> String {
    let written = format!("{value:.1}");
    let (whole, fraction) = written.split_once('.').unwrap_or((written.as_str(), "0"));
    format!("{}.{fraction}", grouped(whole))
}

/// What `count` out of `total` comes to, as a share of a hundred rounded to the
/// nearest tenth.
fn share(count: usize, total: usize) -> String {
    let tenths = (count * 1000 + total / 2) / total;
    format!(
        "{}.{}\u{00A0}%",
        grouped(&(tenths / 10).to_string()),
        tenths % 10
    )
}

/// The code the sheet knows the snag at `place` by.
fn code(place: usize) -> String {
    format!("S-{:02}", place + 1)
}

/// The floor area of `room`, in square metres.
fn area(room: &Room) -> f64 {
    room.width * room.height / 10_000.0
}

/// The floor area of the whole premises, in square metres.
fn total_area() -> f64 {
    ROOMS.iter().map(area).sum()
}

/// How many snags were found in the room at `place`.
fn found_in(place: usize) -> usize {
    SNAGS.iter().filter(|snag| snag.room == place).count()
}

/// How many snags the trade at `place` answers for.
fn answered_for(place: usize) -> usize {
    SNAGS.iter().filter(|snag| snag.trade == place).count()
}

/// How many snags carry `degree`.
fn found_at(degree: Degree) -> usize {
    SNAGS.iter().filter(|snag| snag.degree == degree).count()
}

/// The day the premises were handed over.
#[allow(
    clippy::expect_used,
    reason = "the handover falls on a day of the calendar"
)]
const fn handover() -> NaiveDate {
    NaiveDate::from_ymd_opt(HANDOVER.0, HANDOVER.1, HANDOVER.2)
        .expect("the handover falls on a day of the calendar")
}

/// The day a snag of `degree` is to be made good by: the handover plus the days
/// that degree allows.
#[allow(
    clippy::expect_used,
    reason = "a month after the handover falls on a day of the calendar"
)]
fn due(degree: Degree) -> NaiveDate {
    handover()
        .checked_add_days(Days::new(u64::from(degree.days())))
        .expect("a month after the handover falls on a day of the calendar")
}

/// The last of the days the snags are to be made good by.
fn latest() -> NaiveDate {
    SNAGS
        .iter()
        .fold(handover(), |last, snag| last.max(due(snag.degree)))
}

/// A day, written from its largest unit to its smallest, which is how every
/// language this example is written in writes one on a sheet like this.
fn written(day: NaiveDate) -> String {
    format!("{:04}-{:02}-{:02}", day.year(), day.month(), day.day())
}

/// How long a degree is given, in that language's words.
fn allowed(degree: Degree, words: &Words) -> String {
    words
        .within
        .replace("{days}", &grouped(&degree.days().to_string()))
}

/// How far a length on the premises runs on the page.
fn across(centimetres: f64) -> f64 {
    centimetres * PLAN_SCALE
}

/// Where a length on the premises falls on the page, across and up.
fn at_x(centimetres: f64) -> f64 {
    PLAN_LEFT + across(centimetres)
}

fn at_y(centimetres: f64) -> f64 {
    PLAN_BOTTOM + across(centimetres)
}

/// The corners of a mark, as they fall on the page.
fn plotted(corners: &[(f64, f64)]) -> Vec<(f64, f64)> {
    corners.iter().map(|&(x, y)| (at_x(x), at_y(y))).collect()
}

/// Draws a line of text, left-aligned, in a colour of its own.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, color: Rgb, s: &str) {
    let _ = content.set_fill(color);
    content.begin_text();
    let _ = content.set_font(font, size);
    let _ = content.text_origin(x, y);
    content.show_glyphs(&font.glyphs(s));
    content.end_text();
}

/// Draws a line of text whose right edge sits at `right`.
fn text_right(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    right: f64,
    y: f64,
    color: Rgb,
    s: &str,
) {
    text(
        content,
        font,
        size,
        right - font.measure(s, size),
        y,
        color,
        s,
    );
}

/// Draws a rule across the width of the text.
fn rule(content: &mut Content, y: f64) -> Result<(), hqf_pdf::Error> {
    content.set_stroke(RULE)?;
    content.set_line_width(0.6)?;
    content.move_to(LEFT, y)?;
    content.line_to(RIGHT, y)?;
    content.stroke();
    Ok(())
}

/// Fills a band the width of the text, from `y` up by `height`.
fn band(content: &mut Content, y: f64, height: f64, color: Rgb) -> Result<(), hqf_pdf::Error> {
    content.set_fill(color)?;
    content.rect(LEFT, y, RIGHT - LEFT, height)?;
    content.fill();
    Ok(())
}

/// Draws the firm and what the sheet is, and hands back the baseline it ends
/// on.
fn head(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    text(content, font, FIRM_SIZE, LEFT, y, INK, FIRM);
    text_right(content, font, SMALL, RIGHT, y, MUTED, REFERENCE);
    y -= LINE;
    text(content, font, SMALL, LEFT, y, MUTED, words.tagline);
    y -= BLOCK + LINE;
    text(content, font, TITLE_SIZE, LEFT, y, INK, words.title);
    y
}

/// Draws the four marks that say which premises the sheet is about, and hands
/// back the baseline it ends on.
fn marks(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    for (label, value) in [
        (words.site, SITE.to_owned()),
        (words.handover, written(handover())),
        (words.inspected, INSPECTOR.to_owned()),
        (words.reference, REFERENCE.to_owned()),
    ] {
        text(content, font, TINY, LEFT, y, MUTED, label);
        text(content, font, BODY, LEFT + 96.0, y, INK, &value);
        y -= LINE + 2.0;
    }
    y
}

/// Draws the floor: the room it is cut into, the wall round it, and what each
/// room is called and comes to.
fn floor(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), hqf_pdf::Error> {
    for room in &ROOMS {
        content.set_fill(FLOOR)?;
        content.rect(
            at_x(room.x),
            at_y(room.y),
            across(room.width),
            across(room.height),
        )?;
        content.fill();
    }

    for wall in &WALLS {
        let (color, width) = if wall.shell {
            (SHELL_INK, SHELL_WIDTH_PT)
        } else {
            (PARTITION_INK, PARTITION_WIDTH)
        };
        content.set_stroke(color)?;
        content.set_line_width(width)?;
        content.move_to(at_x(wall.from.0), at_y(wall.from.1))?;
        content.line_to(at_x(wall.to.0), at_y(wall.to.1))?;
        content.stroke();
    }

    for (room, name) in ROOMS.iter().zip(words.rooms) {
        let top = at_y(room.y + room.height) - PLAN_PAD - SMALL;
        text(
            content,
            font,
            SMALL,
            at_x(room.x) + PLAN_PAD,
            top,
            INK,
            name,
        );
        let measure = format!("{} m²", measured(area(room)));
        text(
            content,
            font,
            TINY,
            at_x(room.x) + PLAN_PAD,
            top - LINE,
            MUTED,
            &measure,
        );
    }
    Ok(())
}

/// Draws the code of every snag beside the mark that stands for it.
fn codes(content: &mut Content, font: &FontHandle) {
    for (place, snag) in SNAGS.iter().enumerate() {
        let (x, y) = snag.mark.anchor();
        text(
            content,
            font,
            TINY,
            at_x(x) + CODE_OFFSET,
            at_y(y) + CODE_OFFSET,
            snag.degree.ink(),
            &code(place),
        );
    }
}

/// The words reading software speaks in place of a mark: the same line the list
/// prints, run together.
fn spoken(place: usize, snag: &Snag, words: &Words) -> String {
    format!(
        "{} — {} — {} — {} — {} {}",
        code(place),
        words.rooms[snag.room],
        words.natures[place],
        words.degrees[snag.degree.place()],
        words.repair,
        written(due(snag.degree))
    )
}

/// The mark one snag wears on the plan.
///
/// # Errors
///
/// If a footprint or a run names too few points to enclose or to join anything.
fn marked(place: usize, snag: &Snag, words: &Words) -> Result<Annotation, hqf_pdf::Error> {
    let ink = snag.degree.ink();
    let border = AnnotationBorder::solid(MARK_WIDTH);
    let says = spoken(place, snag, words);
    let named = code(place);

    Ok(match snag.mark {
        Mark::Cloud {
            x,
            y,
            width,
            height,
        } => Square::new(at_x(x), at_y(y), across(width), across(height))
            .effect(BorderEffect::Cloudy {
                intensity: CLOUD_BULGE,
            })
            .color(ink)
            .border(border)
            .name(named)
            .contents(says)
            .into(),
        Mark::Ring { x, y, radius } => Circle::new(
            at_x(x - radius),
            at_y(y - radius),
            across(radius * 2.0),
            across(radius * 2.0),
        )
        .color(ink)
        .border(border)
        .name(named)
        .contents(says)
        .into(),
        Mark::Arrow { from, to } => Line::new(at_x(from.0), at_y(from.1), at_x(to.0), at_y(to.1))
            .endings(LineEnding::None, LineEnding::ClosedArrow)
            .interior(ink)
            .color(ink)
            .border(border)
            .name(named)
            .contents(says)
            .into(),
        Mark::Footprint { corners } => Polygon::new(plotted(corners))?
            .interior(FOOTPRINT_TINT)
            .color(ink)
            .border(border)
            .name(named)
            .contents(says)
            .into(),
        Mark::Run { along } => PolyLine::new(plotted(along))?
            .endings(LineEnding::Butt, LineEnding::Butt)
            .color(ink)
            .border(border)
            .name(named)
            .contents(says)
            .into(),
    })
}

/// Draws what each kind of mark means and what each colour means, and hands
/// back the baseline it ends on.
fn legend(content: &mut Content, font: &FontHandle, words: &Words, top: f64) -> f64 {
    let mut y = top;
    text(content, font, HEADING_SIZE, LEFT, y, INK, words.legend);
    y -= BLOCK;
    for line in [
        words.cloud,
        words.ring,
        words.arrow,
        words.footprint,
        words.run,
    ] {
        text(content, font, SMALL, LEFT, y, INK, line);
        y -= LINE + 2.0;
    }

    y -= BLOCK - LINE;
    text(content, font, HEADING_SIZE, LEFT, y, INK, words.key);
    y -= BLOCK;
    for degree in DEGREES {
        let _ = content.set_fill(degree.ink());
        let _ = content.rect(LEFT, y - 0.5, SMALL, SMALL);
        content.fill();
        let named = format!(
            "{} — {}",
            words.degrees[degree.place()],
            allowed(degree, words)
        );
        text(content, font, SMALL, LEFT + SMALL + 6.0, y, INK, &named);
        y -= LINE + 2.0;
    }

    y -= BLOCK - LINE;
    for line in words.note {
        text(content, font, SMALL, LEFT, y, MUTED, line);
        y -= LINE;
    }
    y
}

/// Draws the rule and the numbering every page ends on.
fn foot(content: &mut Content, font: &FontHandle, words: &Words, sheet: usize) {
    let _ = rule(content, FOOT + LINE);
    let named = format!("{} · {REFERENCE}", words.title);
    text(content, font, TINY, LEFT, FOOT, MUTED, &named);
    let numbered = format!(
        "{} {} {} {}",
        words.page,
        counted(sheet + 1),
        words.of,
        counted(SHEETS.len())
    );
    text_right(content, font, TINY, RIGHT, FOOT, MUTED, &numbered);
}

/// Draws the short head the pages after the first carry, and hands back the
/// baseline it ends on.
fn banner(content: &mut Content, font: &FontHandle, heading: &str) -> f64 {
    text(content, font, SMALL, LEFT, HEAD_TOP, MUTED, FIRM);
    text_right(content, font, SMALL, RIGHT, HEAD_TOP, MUTED, REFERENCE);
    let _ = rule(content, HEAD_TOP - 8.0);
    let y = HEAD_TOP - BLOCK - LINE;
    text(content, font, TITLE_SIZE, LEFT, y, INK, heading);
    y - GAP
}

/// Draws one row of a table, each cell against the right edge of its column,
/// save the first two, which are set from the left.
fn list_row(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    size: f64,
    color: Rgb,
    cells: &[String; 6],
) {
    let mut left = LEFT;
    for (place, cell) in cells.iter().enumerate() {
        let right = LEFT + LIST_COLUMNS[place];
        if place == 3 || place == 4 {
            text_right(content, font, size, right - 6.0, y, color, cell);
        } else {
            text(content, font, size, left, y, color, cell);
        }
        left = right + 6.0;
    }
}

/// What the plan is headed: what it shows, the scale it is set to, and how far
/// the premises run.
fn plan_heading(words: &Words) -> String {
    format!(
        "{} — {} 1:{SCALE_DENOMINATOR:.0} — {} m × {} m",
        words.plan,
        words.scale,
        measured(SHELL_WIDTH / 100.0),
        measured(SHELL_HEIGHT / 100.0)
    )
}

/// Draws the plan, the marks over it and what they mean.
///
/// # Errors
///
/// If a mark names too few points, or a shape cannot be drawn.
fn plan_sheet(font: &FontHandle, words: &Words, sheet: usize) -> Result<Page, Box<dyn Error>> {
    let mut content = Content::new();
    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);

    let y = head(&mut content, font, words, HEAD_TOP);
    let y = marks(&mut content, font, words, y - BLOCK - LINE);

    rule(&mut content, y - 6.0)?;
    let heading = plan_heading(words);
    text(
        &mut content,
        font,
        HEADING_SIZE,
        LEFT,
        y - BLOCK,
        INK,
        &heading,
    );

    floor(&mut content, font, words)?;
    codes(&mut content, font);

    rule(&mut content, PLAN_BOTTOM - BLOCK)?;
    legend(&mut content, font, words, PLAN_BOTTOM - GAP);
    foot(&mut content, font, words, sheet);

    for (place, snag) in SNAGS.iter().enumerate() {
        page.annotations.push(marked(place, snag, words)?);
    }

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

/// Draws the snags, one to a line.
///
/// # Errors
///
/// If a band or a rule cannot be drawn.
fn list_sheet(font: &FontHandle, words: &Words, sheet: usize) -> Result<Page, Box<dyn Error>> {
    let mut content = Content::new();
    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);

    let top = banner(&mut content, font, words.list);

    band(&mut content, top - 6.0, ROW, HEAD_BAND)?;
    let heads = [
        words.number.to_owned(),
        words.room.to_owned(),
        words.nature.to_owned(),
        words.degree.to_owned(),
        words.due.to_owned(),
        words.trade.to_owned(),
    ];
    list_row(&mut content, font, top, TINY, MUTED, &heads);

    let mut y = top - ROW;
    for (place, snag) in SNAGS.iter().enumerate() {
        if place % 2 == 1 {
            band(&mut content, y - 6.0, ROW, ROW_BAND)?;
        }
        let cells = [
            code(place),
            words.rooms[snag.room].to_owned(),
            words.natures[place].to_owned(),
            words.degrees[snag.degree.place()].to_owned(),
            written(due(snag.degree)),
            words.trades[snag.trade].to_owned(),
        ];
        list_row(&mut content, font, y, SMALL, INK, &cells);
        y -= ROW;
    }

    rule(&mut content, y + ROW - 8.0)?;
    let counted_all = format!("{} — {}", words.total, counted(SNAGS.len()));
    text(&mut content, font, BODY, LEFT, y - 6.0, INK, &counted_all);

    y -= GAP;
    for line in words.note {
        text(&mut content, font, SMALL, LEFT, y, MUTED, line);
        y -= LINE;
    }

    foot(&mut content, font, words, sheet);
    page.content = content.into_bytes();
    Ok(page)
}

/// Draws a table that gathers the snags under a name, one row to a name, and
/// hands back the baseline it ends on. A row that carries a colour is set
/// behind a swatch of it.
///
/// # Errors
///
/// If a band or a rule cannot be drawn.
fn gathered(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    top: f64,
    heading: &str,
    column: &str,
    rows: &[(&str, usize, Option<Rgb>)],
) -> Result<f64, hqf_pdf::Error> {
    let all = SNAGS.len();
    let mut y = top;
    text(content, font, HEADING_SIZE, LEFT, y, INK, heading);

    y -= BLOCK;
    band(content, y - 6.0, ROW, HEAD_BAND)?;
    text(content, font, TINY, LEFT + 6.0, y, MUTED, column);
    let counts = LEFT + COUNT_COLUMNS[1];
    let shares = LEFT + COUNT_COLUMNS[2];
    text_right(content, font, TINY, counts, y, MUTED, words.counted);
    text_right(content, font, TINY, shares, y, MUTED, words.share);

    y -= ROW;
    for &(name, found, swatch) in rows {
        let mut left = LEFT + 6.0;
        if let Some(color) = swatch {
            content.set_fill(color)?;
            content.rect(left, y - 0.5, SMALL, SMALL)?;
            content.fill();
            left += SMALL + 6.0;
        }
        text(content, font, BODY, left, y, INK, name);
        text_right(content, font, BODY, counts, y, INK, &counted(found));
        text_right(content, font, BODY, shares, y, INK, &share(found, all));
        y -= ROW;
    }

    rule(content, y + ROW - 8.0)?;
    text(content, font, BODY, LEFT + 6.0, y, INK, words.total);
    text_right(content, font, BODY, counts, y, INK, &counted(all));
    Ok(y)
}

/// Draws the table that gathers the snags room by room, with what each room
/// covers, and hands back the baseline it ends on.
///
/// # Errors
///
/// If a band or a rule cannot be drawn.
fn by_room(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    top: f64,
) -> Result<f64, hqf_pdf::Error> {
    let all = SNAGS.len();
    let mut y = top;
    text(content, font, HEADING_SIZE, LEFT, y, INK, words.by_room);

    y -= BLOCK;
    band(content, y - 6.0, ROW, HEAD_BAND)?;
    text(content, font, TINY, LEFT + 6.0, y, MUTED, words.room);
    for (place, column) in [words.area, words.counted, words.share].iter().enumerate() {
        let right = LEFT + ROOM_COLUMNS[place + 1];
        text_right(content, font, TINY, right, y, MUTED, column);
    }

    y -= ROW;
    for (place, name) in words.rooms.iter().enumerate() {
        let found = found_in(place);
        let covered = format!("{} m²", measured(area(&ROOMS[place])));
        text(content, font, BODY, LEFT + 6.0, y, INK, name);
        text_right(
            content,
            font,
            BODY,
            LEFT + ROOM_COLUMNS[1],
            y,
            INK,
            &covered,
        );
        let counted_here = counted(found);
        text_right(
            content,
            font,
            BODY,
            LEFT + ROOM_COLUMNS[2],
            y,
            INK,
            &counted_here,
        );
        let shared = share(found, all);
        text_right(content, font, BODY, LEFT + ROOM_COLUMNS[3], y, INK, &shared);
        y -= ROW;
    }

    rule(content, y + ROW - 8.0)?;
    let covered = format!("{} m²", measured(total_area()));
    text(content, font, BODY, LEFT + 6.0, y, INK, words.total);
    text_right(
        content,
        font,
        BODY,
        LEFT + ROOM_COLUMNS[1],
        y,
        INK,
        &covered,
    );
    text_right(
        content,
        font,
        BODY,
        LEFT + ROOM_COLUMNS[2],
        y,
        INK,
        &counted(all),
    );
    Ok(y)
}

/// Draws what the snags come to: the count and the share of each degree, then
/// of each room, then of each trade, then the last of the dates.
///
/// # Errors
///
/// If a band or a rule cannot be drawn.
fn summary_sheet(font: &FontHandle, words: &Words, sheet: usize) -> Result<Page, Box<dyn Error>> {
    let mut content = Content::new();
    let mut page = Page::new(PAGE_WIDTH, PAGE_HEIGHT);

    let mut y = banner(&mut content, font, words.summary);

    let degrees: Vec<(&str, usize, Option<Rgb>)> = DEGREES
        .iter()
        .map(|&degree| {
            (
                words.degrees[degree.place()],
                found_at(degree),
                Some(degree.ink()),
            )
        })
        .collect();
    y = gathered(
        &mut content,
        font,
        words,
        y,
        words.by_degree,
        words.degree,
        &degrees,
    )?;

    y -= GAP;
    y = by_room(&mut content, font, words, y)?;

    let trades: Vec<(&str, usize, Option<Rgb>)> = words
        .trades
        .iter()
        .enumerate()
        .map(|(place, &name)| (name, answered_for(place), None))
        .collect();
    y -= GAP;
    y = gathered(
        &mut content,
        font,
        words,
        y,
        words.by_trade,
        words.trade,
        &trades,
    )?;

    y -= GAP;
    band(&mut content, y - 8.0, ROW + 6.0, HEAD_BAND)?;
    text(&mut content, font, BODY, LEFT + 6.0, y, INK, words.latest);
    let last = written(latest());
    text_right(
        &mut content,
        font,
        HEADING_SIZE,
        RIGHT - 6.0,
        y - 1.0,
        INK,
        &last,
    );

    foot(&mut content, font, words, sheet);
    page.content = content.into_bytes();
    Ok(page)
}

/// What draws one page of the sheet, given the place that page has in it.
type Sheet = fn(&FontHandle, &Words, usize) -> Result<Page, Box<dyn Error>>;

/// The pages the sheet runs to, in order. The foot of each reads its own place
/// and this table's length, so a page added here numbers itself.
const SHEETS: [Sheet; 3] = [plan_sheet, list_sheet, summary_sheet];

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

fn run() -> Result<(), Box<dyn 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 path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("snag_list")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(Name::new("Title"), &format!("{} {REFERENCE}", words.title));

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

    for (sheet, draw) in SHEETS.iter().enumerate() {
        doc.add_page(draw(&font, words, sheet)?)?;
    }

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

    println!(
        "wrote {path}: {} bytes, {} snags marked on {} m², last date {}",
        bytes.len(),
        counted(SNAGS.len()),
        measured(total_area()),
        written(latest())
    );
    Ok(())
}

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

    use super::language::Language;
    use super::{
        BODY, DEGREES, Degree, ENGLISH, HEADING_SIZE, LEFT, LIST_COLUMNS, Mark, RIGHT, ROOMS,
        SHEETS, SHELL_HEIGHT, SHELL_WIDTH, SMALL, SNAGS, TINY, WORDS, answered_for, area, code,
        counted, default_font, due, found_at, found_in, grouped, handover, language, latest,
        measured, plan_heading, share, total_area, written,
    };

    /// The lines two languages are allowed to write the same way, each with
    /// what makes the two the same word.
    const SPARED: [&str; 2] = [
        // The line a table ends on is headed by the same word in French as in
        // English.
        r#"total: "TOTAL""#,
        // So is a page of a document.
        r#"page: "Page""#,
    ];

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

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

    /// A number over a thousand holds its thousands apart, a measurement puts a
    /// point before its tenth, and a share is rounded to the nearer tenth.
    #[test]
    fn a_number_is_written_with_a_space_between_its_thousands() {
        assert_eq!(grouped("1234567"), "1\u{00A0}234\u{00A0}567");
        assert_eq!(counted(9), "9");
        assert_eq!(measured(1248.0), "1\u{00A0}248.0");
        assert_eq!(measured(198.0), "198.0");
        assert_eq!(share(1, 3), "33.3\u{00A0}%");
        assert_eq!(share(2, 9), "22.2\u{00A0}%");
    }

    /// Every snag is gathered once under a degree and once under a room, and
    /// the shares of a whole come to a hundred but for what rounding takes.
    #[test]
    fn the_summary_counts_every_snag_once() {
        let all = SNAGS.len();
        let by_degree: usize = DEGREES.iter().map(|&degree| found_at(degree)).sum();
        let by_room: usize = (0..ROOMS.len()).map(found_in).sum();

        assert_eq!(by_degree, all, "the degrees gather {by_degree} of {all}");
        assert_eq!(by_room, all, "the rooms gather {by_room} of {all}");

        for degree in DEGREES {
            assert!(
                found_at(degree) > 0,
                "no snag is {degree:?}, and the summary would print a share of nothing"
            );
        }

        // Every share is rounded to the nearer tenth, so the three of them come
        // to a hundred give or take half a tenth apiece.
        let tenths: usize = DEGREES
            .iter()
            .map(|&degree| (found_at(degree) * 1000 + all / 2) / all)
            .sum();
        let apart = tenths.abs_diff(1000);
        assert!(
            apart <= DEGREES.len(),
            "the shares come to {tenths} tenths of a hundred rather than 1000"
        );
    }

    /// Every trade the sheet names answers for at least one snag, so the table
    /// that gathers them prints no empty row, and the three tables gather the
    /// same nine snags.
    #[test]
    fn every_trade_answers_for_at_least_one_snag() {
        let all = SNAGS.len();
        let by_trade: usize = (0..ENGLISH.trades.len()).map(answered_for).sum();

        assert_eq!(by_trade, all, "the trades answer for {by_trade} of {all}");
        for place in 0..ENGLISH.trades.len() {
            assert!(
                answered_for(place) > 0,
                "no snag is answered for by trade {place}"
            );
        }
    }

    /// The area of the premises is what the rooms of the plan come to, and each
    /// room's is what its own rectangle covers at a hundred square centimetres
    /// to the square metre.
    #[test]
    fn the_area_is_what_the_plan_draws() {
        let summed: f64 = ROOMS.iter().map(area).sum();

        assert!(
            (total_area() - summed).abs() < f64::EPSILON,
            "the premises come to {} and the rooms to {summed}",
            total_area()
        );
        assert_eq!(measured(area(&ROOMS[0])), "198.0");
        assert_eq!(measured(total_area()), "1\u{00A0}248.0");

        let shell = SHELL_WIDTH * SHELL_HEIGHT / 10_000.0;
        assert!(
            summed <= shell,
            "the rooms come to {summed} m² inside a shell of {shell} m²"
        );
    }

    /// A snag is to be made good by the handover plus the days its degree
    /// allows, and the last of those dates is the greatest of them.
    #[test]
    fn a_date_is_the_handover_plus_the_days_the_degree_allows() {
        assert_eq!(written(handover()), "2026-09-14");
        assert_eq!(written(due(Degree::Blocking)), "2026-09-21");
        assert_eq!(written(due(Degree::Major)), "2026-10-05");
        assert_eq!(written(due(Degree::Minor)), "2026-10-14");

        let last = SNAGS
            .iter()
            .map(|snag| due(snag.degree))
            .max()
            .expect("the list holds at least one snag");
        assert_eq!(latest(), last);
    }

    /// Every snag names a room, a trade and a defect the words of every
    /// language hold.
    #[test]
    fn every_snag_names_words_every_language_holds() {
        for (named, words) in WORDS {
            for (place, snag) in SNAGS.iter().enumerate() {
                assert!(
                    snag.room < words.rooms.len(),
                    "{} names room {} of {}",
                    named.code(),
                    snag.room,
                    words.rooms.len()
                );
                assert!(
                    snag.trade < words.trades.len(),
                    "{} names trade {} of {}",
                    named.code(),
                    snag.trade,
                    words.trades.len()
                );
                assert!(
                    !words.natures[place].is_empty(),
                    "{} says nothing of {}",
                    named.code(),
                    code(place)
                );
            }
        }
    }

    /// A mark that falls outside the premises marks nothing: every point of
    /// every mark lies within the shell the plan draws.
    #[test]
    fn every_mark_falls_inside_the_premises() {
        let inside = |x: f64, y: f64, what: &str| {
            assert!(
                (0.0..=SHELL_WIDTH).contains(&x) && (0.0..=SHELL_HEIGHT).contains(&y),
                "{what} stands at ({x}, {y}), outside a shell of {SHELL_WIDTH} by {SHELL_HEIGHT}"
            );
        };

        for (place, snag) in SNAGS.iter().enumerate() {
            let named = code(place);
            match snag.mark {
                Mark::Cloud {
                    x,
                    y,
                    width,
                    height,
                } => {
                    inside(x, y, &named);
                    inside(x + width, y + height, &named);
                }
                Mark::Ring { x, y, radius } => {
                    inside(x - radius, y - radius, &named);
                    inside(x + radius, y + radius, &named);
                }
                Mark::Arrow { from, to } => {
                    inside(from.0, from.1, &named);
                    inside(to.0, to.1, &named);
                }
                Mark::Footprint { corners } => {
                    for &(x, y) in corners {
                        inside(x, y, &named);
                    }
                }
                Mark::Run { along } => {
                    for &(x, y) in along {
                        inside(x, y, &named);
                    }
                }
            }
        }
    }

    /// The plan carries one mark per snag, each kind of mark is used, and every
    /// one of them is an annotation the page holds above what it draws.
    #[test]
    fn every_snag_is_marked_above_the_page() {
        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 (named, words) in WORDS {
            let page = SHEETS[0](&font, words, 0).expect("the plan draws");
            assert_eq!(
                page.annotations.len(),
                SNAGS.len(),
                "the {} plan carries {} marks for {} snags",
                named.code(),
                page.annotations.len(),
                SNAGS.len()
            );
        }

        for kind in ["Cloud", "Ring", "Arrow", "Footprint", "Run"] {
            let drawn = SNAGS
                .iter()
                .filter(|snag| format!("{:?}", snag.mark).starts_with(kind))
                .count();
            assert!(drawn > 0, "no snag is marked by a {kind}");
        }
    }

    /// Weighs one row of the list against the columns it is set in.
    fn fits(font: &FontHandle, named: Language, size: f64, cells: &[String; 6]) {
        let mut left = 0.0;
        for (column, cell) in cells.iter().enumerate() {
            let room = LIST_COLUMNS[column] - left - 6.0;
            let measure = font.measure(cell, size);
            assert!(
                measure <= room,
                "the {} list sets {cell:?} over {measure:.1} points, and its column \
                 has {room:.1}",
                named.code()
            );
            left = LIST_COLUMNS[column] + 6.0;
        }
    }

    /// A cell wider than its column runs into the next one: every cell of the
    /// list, in every language, is set inside the column it belongs to.
    #[test]
    fn every_language_fits_its_cells_in_the_columns() {
        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 (named, words) in WORDS {
            let heads = [
                words.number.to_owned(),
                words.room.to_owned(),
                words.nature.to_owned(),
                words.degree.to_owned(),
                words.due.to_owned(),
                words.trade.to_owned(),
            ];
            fits(&font, named, TINY, &heads);

            for (place, snag) in SNAGS.iter().enumerate() {
                let cells = [
                    code(place),
                    words.rooms[snag.room].to_owned(),
                    words.natures[place].to_owned(),
                    words.degrees[snag.degree.place()].to_owned(),
                    written(due(snag.degree)),
                    words.trades[snag.trade].to_owned(),
                ];
                fits(&font, named, SMALL, &cells);
            }

            for line in [
                words.cloud,
                words.ring,
                words.arrow,
                words.footprint,
                words.run,
            ]
            .into_iter()
            .chain(words.note)
            {
                let measure = font.measure(line, BODY);
                let room = RIGHT - LEFT;
                assert!(
                    measure <= room,
                    "the {} legend sets {line:?} over {measure:.1} points, and the \
                     page has {room:.1}",
                    named.code()
                );
            }

            let heading = plan_heading(words);
            let measure = font.measure(&heading, HEADING_SIZE);
            let room = RIGHT - LEFT;
            assert!(
                measure <= room,
                "the {} plan is headed {heading:?} over {measure:.1} points, and the \
                 page has {room:.1}",
                named.code()
            );
        }
    }
}