write_table_report.rs

Die Rust-Datei des Beispiels „Ein Fahrplan, der über sein eigenes Layout berichtet“. Ein Busfahrplan, bei dem jede Zelle umrandet ist und eine Notiz an jeder sagt, warum sie so groß ist, wie sie ist, mit erklärten Spaltenbreiten und Zeilenhöhen; dann eine trotz ihrer Fehler gesetzte Tabelle, eine über zwei Kästen geteilte Zeile, freier Raum unter Zeilen verteilt, eine für ihren Kasten zu breite Tabelle, die als Ganzes hineingeschrumpft wird, und ein Hinweis, der von Zelle zu Zelle eine Spalte hinunterläuft und dann durch die zwei Zellen einer Zeile.

Rust 1858 Zeilen

Wofür dieses Beispiel da ist

Wenn eine Tabelle falsch herauskommt, lautet die erste Frage, warum eine Spalte so schmal oder eine Zeile so hoch ist. Hier beantwortet die Bibliothek sie. Ein morgendlicher Busfahrplan ist so gesetzt, dass jede Zelle mit einer dünnen Linie umrandet ist, und eine Notiz an jeder Zelle gibt die eigene Darstellung der Bibliothek dazu. Unter der Tabelle zählen einige Zeilen ihre Spalten und deren Breiten, ihre Kopf-, Rumpf- und Fußzeilen, was ihre Zellen enthalten und, für jeden Grund, aus dem eine Zeile ihre Höhe beziehen kann, auf wie viele Zellen er zutrifft.

Was dieses Beispiel zeigt

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

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

use hqf_pdf::annotation::Annotation;
use hqf_pdf::color::Rgb;
use hqf_pdf::content::{Artifact, Content, Dash, LineStyle};
use hqf_pdf::cos::Name;
use hqf_pdf::drawing::Drawing;
use hqf_pdf::layout::{
    Area, Caption, CaptionSide, Cell, CellReport, ColumnWidth, Columns, Damage, FitProgress,
    FittedTable, Guides, HeaderLinks, Holds, Padding, Rect, Row, RowRole, Rule, Settled, Stroke,
    Table, TableFrame, TaggedTable, TextFlow, Thread,
};
use hqf_pdf::structure::Scope;
use hqf_pdf::{
    Axial, Document, FieldBorder, Font, FontHandle, Image, Marks, Page, Paint, Shading,
    StructElement, StructureTree, TextField,
};

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

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

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

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

use language::Language;

/// The font the example writes 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 picture one cell of the timetable holds.
fn picture() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images")
        .join("logo.png")
}

/// How far in from the left edge of the sheet everything starts, in points.
const MARGIN: f64 = 56.0;

/// How wide the text and the timetable run, in points.
const WIDTH: f64 = 483.0;

/// Where the baseline of a page's heading sits, in points up from the foot of
/// the sheet.
const HEAD_TOP: f64 = 790.0;

/// The size a page's heading is set at, in points.
const HEADING: f64 = 16.0;

/// The size the lines under a heading and under a table are set at, in points.
const BODY: f64 = 9.5;

/// How far below one line the next one sits, in points.
const LINE_STEP: f64 = 13.0;

/// The size the cells are set at, in points.
const CELL: f64 = 9.0;

/// Where the timetable's top edge sits, in points up from the foot of the
/// sheet.
const TABLE_TOP: f64 = 735.0;

/// How far down the page the timetable may reach, in points.
const TABLE_ROOM: f64 = 330.0;

/// The colour every cell's outline is drawn in.
const MAGENTA: Rgb = Rgb::new(0.85, 0.0, 0.6);

/// The departure times of the timetable's five rows, which read the same in
/// every language.
const TIMES: [&str; 5] = ["07:40", "07:52", "08:05", "08:07", "08:20"];

/// The line numbers of the timetable's five rows.
const LINES: [&str; 5] = ["12", "12", "12", "31", "31"];

/// The platforms of the shrunk table's five rows.
const PLATFORMS: [&str; 5] = ["1", "2", "1", "3", "2"];

/// The box the shrunk table is shrunk into.
const SHRUNK_AREA: Rect = Rect::new(MARGIN, 60.0, 230.0, 68.0);

/// The smallest factor the shrunk table may be scaled down to.
const SHRUNK_FLOOR: f64 = 0.4;

/// How tall each row of the notice's table is but the last, in points.
const NOTICE_ROW: f64 = 40.0;

/// How far a cell's text is kept from its edges, in points.
const PADDING: f64 = 2.5;

/// How far down the page the notice's table may run, in points.
const NOTICE_ROOM: f64 = 600.0;

/// Every word the pages say, in one language.
#[derive(Debug)]
struct Words {
    /// The language tag the structure tree states.
    lang: &'static str,
    /// The first page's heading, and what the file says of itself.
    title: &'static str,
    /// What the first page says under its heading.
    intro: [&'static str; 2],
    /// The timetable's four column headings.
    headings: [&'static str; 4],
    /// The stops, the third of them reaching down over two rows.
    stops: [&'static str; 4],
    /// The remarks of the first, third and fifth rows.
    remarks: [&'static str; 3],
    /// The timetable's foot, across every column.
    foot: &'static str,
    /// The caption under the timetable.
    caption: &'static str,
    /// What the drawing in the timetable shows, read in its place.
    sign_alt: &'static str,
    /// What the picture in the timetable shows, read in its place.
    logo_alt: &'static str,
    /// How many columns the table has and how wide they came out; `{count}`,
    /// `{width}` and `{widths}` stand for them.
    shape: &'static str,
    /// What two columns come to together, and where the picture landed;
    /// `{span}` and `{place}` stand for them.
    span: &'static str,
    /// What the columns come to on their own; `{widths}` stands for them.
    resolved: &'static str,
    /// What the tallest cell asks for; `{needed}` and `{across}` stand for its
    /// height and the columns it covers.
    tallest: &'static str,
    /// How many rows of each kind were placed; `{heads}`, `{bodies}` and
    /// `{feet}` stand for them.
    roles: &'static str,
    /// What the cells hold; `{texts}`, `{pictures}` and `{drawings}` stand for
    /// how many of each.
    holds: &'static str,
    /// A count of cells whose height one thing settled; `{what}` stands for
    /// that thing and `{cells}` for the count.
    settled: &'static str,
    /// What settled a cell's height, one name per kind, in the order
    /// [`settled_name`] lists them.
    settled_names: [&'static str; 7],
    /// Where the caption was set; `{side}` stands for the side.
    caption_side: &'static str,
    /// The two sides a caption is set on: above, then below.
    sides: [&'static str; 2],
    /// Where the notes come from.
    notes: &'static str,
    /// The second page's heading.
    more_title: &'static str,
    /// What the damaged table's section is.
    damaged_title: &'static str,
    /// The cells of the damaged table: the two of its short row, then the three
    /// of its tall one.
    damaged: [&'static str; 5],
    /// A row covering fewer columns than the table; `{row}`, `{covered}` and
    /// `{columns}` stand for the numbers.
    other_width: &'static str,
    /// A row taller than its box; `{row}` stands for its number.
    past_the_box: &'static str,
    /// The caption over the table whose row is cut, on its first box only.
    split_caption: &'static str,
    /// The two cells of the row that is cut.
    split: [&'static str; 2],
    /// What happened to the row that was cut; `{boxes}` stands for how many
    /// boxes it was laid across.
    split_said: &'static str,
    /// What the table sharing its room is.
    shared_title: &'static str,
    /// The cells of the table sharing its room, two to a row.
    shared: [&'static str; 6],
    /// What the shrunk table is.
    shrunk_title: &'static str,
    /// The headings of the shrunk table's three columns.
    shrunk: [&'static str; 3],
    /// The factor the shrunk table was scaled by; `{percent}` stands for it.
    shrunk_said: &'static str,
    /// The third page's heading.
    notice_title: &'static str,
    /// What the third page says under its heading.
    notice_intro: [&'static str; 2],
    /// What the table running the notice through two columns is.
    columns_said: &'static str,
    /// The heading of the column the notice runs down.
    notice_head: &'static str,
    /// The notice, one text run down the cells of its column.
    notice: &'static str,
}

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

/// The pages in English.
const ENGLISH: Words = Words {
    lang: "en",
    title: "A timetable that reports on itself",
    intro: [
        "Hairlines outline every cell, dashes the table and its caption; crosses mark the",
        "top of each column line, and a grid is ruled over the room left under the table.",
    ],
    headings: ["Stop", "Line", "Remarks", "Departs"],
    stops: [
        "Harbour",
        "Old Market",
        "Cathedral Square, north side",
        "University",
    ],
    remarks: [
        "Step-free boarding at the front door of every bus on this line, and a ramp for \
         wheelchairs on request",
        "Change here for the tram",
        "School days only, narrowed to hold its row",
    ],
    foot: "Every time is the departure from the stop.",
    caption: "Table 1. Morning departures, lines 12 and 31",
    sign_alt: "A bus-stop sign",
    logo_alt: "The operator's logo",
    shape: "{count} columns across {width} pt: {widths} pt",
    span: "The last two columns together: {span} pt; the picture is in column {place}",
    resolved: "Resolved on their own, before any cell is measured: {widths} pt",
    tallest: "The tallest cell asks for {needed} pt, over {across} of the columns",
    roles: "Rows placed: {heads} heading, {bodies} body, {feet} foot",
    holds: "Cells: {texts} of text, {pictures} picture, {drawings} drawing",
    settled: "Height set by {what}: {cells}",
    settled_names: [
        "the cell's own content",
        "a taller cell of its row",
        "the height its row asked for",
        "the fixed height of its row",
        "a cell reaching down over its row",
        "the room shared out under the last row",
        "the rows it covers",
    ],
    caption_side: "The caption is set {side} the table.",
    sides: ["above", "below"],
    notes: "Each note carries the library's own report on its cell, in English.",
    more_title: "Faults, a row cut in two, and room shared out",
    damaged_title: "Laid out despite its faults:",
    damaged: [
        "Monday",
        "Closed for works",
        "Tuesday",
        "12",
        "Diverted by the ring road while the bridge is closed: the stops of the old town \
         are served by line 31, which leaves from the station every ten minutes.",
    ],
    other_width: "Row {row} fills {covered} of {columns} columns; the rest is left empty.",
    past_the_box: "Row {row} runs past the bottom of its box.",
    split_caption: "Table 2. One remark, cut across two boxes",
    split: [
        "Remark",
        "The row holds more than one box has room for, so it is cut where a line ends. \
         Three lines at least stay at the foot of the first box, and three at least go \
         to the head of the next, so that neither box ends or starts on a lone line of \
         the paragraph. The heading cell is set whole in the first box and left empty \
         in the second.",
    ],
    split_said: "The row was laid across {boxes} boxes.",
    shared_title: "The room under the last row, shared out among the rows:",
    shared: ["Monday", "07:40", "Tuesday", "07:45", "Wednesday", "07:40"],
    shrunk_title: "A table 480 points wide, shrunk whole into a box 230 wide:",
    shrunk: ["Departure", "Line", "Platform"],
    shrunk_said: "Scaled to {percent}% on both axes.",
    notice_title: "One notice set through several cells",
    notice_intro: [
        "The notice is one text: each cell of its column takes it up where the cell above stopped,",
        "as many lines as its row holds; the last cell takes what is left, and its row grows to fit.",
    ],
    columns_said: "The same notice through the two cells of one row, the first as tall as half its lines:",
    notice_head: "Notice to travellers",
    notice: "While the bridge on River Street is closed for works, line 12 runs by the ring road and no longer serves the stops of the old town. Line 31 takes them over: it leaves from the station every ten minutes from six in the morning to eleven at night, and stops at each of them on its way to the Harbour. Tickets and passes for line 12 are valid on line 31 without any change. A journey across the river takes about ten minutes more than usual during the works, and the times on the first page already count them. Temporary signs stand beside every stop that is not served, each naming the nearest stop that is. Staff in yellow jackets wait at the Old Market every morning until nine to show the way. The works are planned to end on 20 November, and the usual timetable comes back the following Monday.",
};

/// The pages in French.
const FRENCH: Words = Words {
    lang: "fr",
    title: "Un horaire qui rend compte de lui-même",
    intro: [
        "Un filet cerne chaque cellule, un tireté le tableau et sa légende ; une croix",
        "marque le haut de chaque trait de colonne, une grille couvre la place libre \
sous le tableau.",
    ],
    headings: ["Arrêt", "Ligne", "Remarques", "Départ"],
    stops: [
        "Port",
        "Vieux-Marché",
        "Place de la Cathédrale, côté nord",
        "Université",
    ],
    remarks: [
        "Montée de plain-pied par la porte avant de chaque bus de la ligne, et une rampe \
         pour fauteuil roulant sur demande",
        "Correspondance avec le tramway",
        "Période scolaire uniquement, texte resserré pour tenir sur sa ligne",
    ],
    foot: "Chaque heure est celle du départ de l’arrêt.",
    caption: "Tableau 1. Départs du matin, lignes 12 et 31",
    sign_alt: "Un panneau d’arrêt de bus",
    logo_alt: "Le logo de l’exploitant",
    shape: "{count} colonnes sur {width} pt : {widths} pt",
    span: "Les deux dernières colonnes ensemble : {span} pt ; l’image est en colonne {place}",
    resolved: "Résolues seules, avant toute mesure des cellules : {widths} pt",
    tallest: "La cellule la plus haute demande {needed} pt, sur {across} des colonnes",
    roles: "Lignes placées : {heads} d’en-tête, {bodies} de corps, {feet} de pied",
    holds: "Cellules : {texts} de texte, {pictures} image, {drawings} dessin",
    settled: "Hauteur fixée par {what} : {cells}",
    settled_names: [
        "le contenu de la cellule",
        "une cellule plus haute de sa ligne",
        "la hauteur que sa ligne demande",
        "la hauteur imposée à sa ligne",
        "une cellule qui descend sur sa ligne",
        "la place partagée sous la dernière ligne",
        "les lignes qu’elle couvre",
    ],
    caption_side: "La légende est placée {side} tableau.",
    sides: ["au-dessus du", "au-dessous du"],
    notes: "Chaque note contient le rapport de la bibliothèque sur sa cellule, en anglais.",
    more_title: "Des défauts, une ligne coupée, de la place partagée",
    damaged_title: "Mis en page malgré ses défauts :",
    damaged: [
        "Lundi",
        "Fermé pour travaux",
        "Mardi",
        "12",
        "Dévié par la rocade pendant la fermeture du pont : les arrêts de \
         la vieille ville sont desservis par la ligne 31, qui part de la gare toutes les \
         dix minutes.",
    ],
    other_width: "La ligne {row} remplit {covered} colonnes sur {columns} ; les autres \
restent vides.",
    past_the_box: "La ligne {row} dépasse le bas de son cadre.",
    split_caption: "Tableau 2. Une remarque, coupée sur deux cadres",
    split: [
        "Remarque",
        "La ligne contient plus que ce qu’un cadre peut recevoir : elle est coupée à la \
         fin d’une ligne de texte. Trois lignes au moins restent au pied du premier \
         cadre, et trois au moins passent en tête du suivant, pour qu’aucun cadre ne \
         finisse ni ne commence sur une ligne isolée du paragraphe. La cellule d’en-tête \
         est placée entière dans le premier cadre et laissée vide dans le second.",
    ],
    split_said: "La ligne a été répartie sur {boxes} cadres.",
    shared_title: "La place sous la dernière ligne, partagée entre les lignes :",
    shared: ["Lundi", "07:40", "Mardi", "07:45", "Mercredi", "07:40"],
    shrunk_title: "Un tableau de 480 points de large, ramené tout entier à un cadre de 230 :",
    shrunk: ["Départ", "Ligne", "Quai"],
    shrunk_said: "Ramené à {percent} % sur les deux axes.",
    notice_title: "Un avis qui passe d’une cellule à l’autre",
    notice_intro: [
        "L’avis est un seul texte : chaque cellule de sa colonne le reprend là où la précédente s’est arrêtée,",
        "autant de lignes que sa rangée en tient ; la dernière prend le reste, et sa rangée grandit d’autant.",
    ],
    columns_said: "Le même avis dans les deux cellules d’une rangée, la première tenant la moitié des lignes :",
    notice_head: "Avis aux voyageurs",
    notice: "Pendant la fermeture du pont de la rue du Fleuve pour travaux, la ligne 12 emprunte la rocade et ne dessert plus les arrêts de la vieille ville. La ligne 31 prend le relais : elle part de la gare toutes les dix minutes, de six heures à vingt-trois heures, et les dessert tous en direction du Port. Les billets et abonnements de la ligne 12 sont valables sur la ligne 31, sans aucune démarche. Pendant les travaux, traverser le fleuve demande une dizaine de minutes de plus, et les horaires de la première page en tiennent déjà compte. À côté de chaque arrêt non desservi, un panneau provisoire indique l’arrêt desservi le plus proche. Des agents en gilet jaune vous orientent au Vieux-Marché chaque matin jusqu’à neuf heures. La fin des travaux est prévue le 20 novembre, et les horaires habituels reprennent le lundi suivant.",
};

/// The pages in Dutch.
const DUTCH: Words = Words {
    lang: "nl",
    title: "Een dienstregeling die over zichzelf rapporteert",
    intro: [
        "Haarlijnen omlijnen elke cel, streepjes de tabel en het bijschrift; kruisjes markeren",
        "de bovenkant van elke kolomlijn, en een raster ligt over de ruimte onder de tabel.",
    ],
    headings: ["Halte", "Lijn", "Opmerkingen", "Vertrek"],
    stops: [
        "Haven",
        "Oude Markt",
        "Domplein, noordzijde",
        "Universiteit",
    ],
    remarks: [
        "Drempelloos instappen bij de voordeur van elke bus op deze lijn, en een oprijplaat voor rolstoelen op verzoek",
        "Hier overstappen op de tram",
        "Alleen op schooldagen, versmald om in de rij te passen",
    ],
    foot: "Elke tijd is de vertrektijd van de halte.",
    caption: "Tabel 1. Ochtendvertrekken, lijnen 12 en 31",
    sign_alt: "Een bushaltebord",
    logo_alt: "Het logo van de vervoerder",
    shape: "{count} kolommen over {width} pt: {widths} pt",
    span: "De laatste twee kolommen samen: {span} pt; de afbeelding staat in kolom {place}",
    resolved: "Op zichzelf bepaald, voordat een cel gemeten wordt: {widths} pt",
    tallest: "De hoogste cel vraagt {needed} pt, over {across} van de kolommen",
    roles: "Rijen geplaatst: {heads} kop, {bodies} romp, {feet} voet",
    holds: "Cellen: {texts} met tekst, {pictures} met afbeelding, {drawings} met tekening",
    settled: "Hoogte bepaald door {what}: {cells}",
    settled_names: [
        "de eigen inhoud van de cel",
        "een hogere cel in de rij",
        "de hoogte die de rij vroeg",
        "de vaste hoogte van de rij",
        "een cel die over de rij heen reikt",
        "de ruimte verdeeld onder de laatste rij",
        "de rijen die ze bestrijkt",
    ],
    caption_side: "Het bijschrift staat {side} de tabel.",
    sides: ["boven", "onder"],
    notes: "Elke notitie bevat het eigen rapport van de bibliotheek over haar cel, in het Engels.",
    more_title: "Fouten, een in tweeën gesneden rij, en verdeelde ruimte",
    damaged_title: "Opgemaakt ondanks de fouten:",
    damaged: [
        "Maandag",
        "Gesloten wegens werkzaamheden",
        "Dinsdag",
        "12",
        "Omgeleid via de ringweg zolang de brug dicht is: de haltes in de oude stad worden bediend door lijn 31, die elke tien minuten van het station vertrekt.",
    ],
    other_width: "Rij {row} vult {covered} van de {columns} kolommen; de rest blijft leeg.",
    past_the_box: "Rij {row} loopt voorbij de onderkant van haar kader.",
    split_caption: "Tabel 2. Eén opmerking, over twee kaders gesneden",
    split: [
        "Opmerking",
        "De rij bevat meer dan in één kader past, dus wordt ze gesneden waar een regel eindigt. Minstens drie regels blijven onderaan het eerste kader staan, en minstens drie gaan naar de bovenkant van het volgende, zodat geen kader eindigt of begint met één losse regel van de alinea. De kopcel wordt heel in het eerste kader gezet en in het tweede leeg gelaten.",
    ],
    split_said: "De rij is over {boxes} kaders verdeeld.",
    shared_title: "De ruimte onder de laatste rij, verdeeld over de rijen:",
    shared: ["Maandag", "07:40", "Dinsdag", "07:45", "Woensdag", "07:40"],
    shrunk_title: "Een tabel van 480 punten breed, in zijn geheel verkleind tot een kader van 230 breed:",
    shrunk: ["Vertrek", "Lijn", "Perron"],
    shrunk_said: "Geschaald tot {percent} % op beide assen.",
    notice_title: "Eén bericht dat van cel naar cel doorloopt",
    notice_intro: [
        "Het bericht is één tekst: elke cel van de kolom gaat verder waar de cel erboven ophield,",
        "met zoveel regels als de rij toelaat; de laatste neemt de rest en de rij groeit mee.",
    ],
    columns_said: "Hetzelfde bericht in de twee cellen van één rij, de eerste zo hoog als de helft van zijn regels:",
    notice_head: "Bericht aan reizigers",
    notice: "Zolang de brug in de Rivierstraat wegens werkzaamheden is afgesloten, rijdt lijn 12 via de ringweg en worden de haltes in de oude stad niet meer bediend. Lijn 31 neemt die haltes over: deze lijn vertrekt van zes uur ’s ochtends tot elf uur ’s avonds elke tien minuten vanaf het station en stopt bij al die haltes op weg naar de Haven. Kaartjes en abonnementen voor lijn 12 zijn zonder meer geldig op lijn 31. Tijdens de werkzaamheden duurt een rit over de rivier ongeveer tien minuten langer dan gewoonlijk, en de tijden op de eerste pagina houden daar al rekening mee. Naast elke halte die niet wordt bediend, staat een tijdelijk bord met de dichtstbijzijnde halte die wel wordt bediend. Elke ochtend tot negen uur wijzen medewerkers in gele hesjes bij de Oude Markt de weg. De werkzaamheden zijn naar verwachting op 20 november klaar; vanaf de maandag daarna geldt weer de gewone dienstregeling.",
};

/// The pages in Portuguese.
const PORTUGUESE: Words = Words {
    lang: "pt",
    title: "Um horário que presta contas de si mesmo",
    intro: [
        "Filetes finos contornam cada célula, tracejados a tabela e a legenda; cruzes marcam",
        "o topo de cada linha de coluna, e uma grelha cobre o espaço que sobra por baixo da tabela.",
    ],
    headings: ["Paragem", "Linha", "Observações", "Partida"],
    stops: [
        "Porto",
        "Mercado Velho",
        "Praça da Sé, lado norte",
        "Universidade",
    ],
    remarks: [
        "Entrada sem degrau pela porta da frente de cada autocarro desta linha, e rampa para cadeiras de rodas a pedido",
        "Correspondência aqui com o elétrico",
        "Só em dias de aulas, estreitada para caber na sua linha",
    ],
    foot: "Cada hora é a de partida da paragem.",
    caption: "Tabela 1. Partidas da manhã, linhas 12 e 31",
    sign_alt: "Uma placa de paragem de autocarro",
    logo_alt: "O logótipo do operador",
    shape: "{count} colunas em {width} pt: {widths} pt",
    span: "As duas últimas colunas juntas: {span} pt; a imagem está na coluna {place}",
    resolved: "Resolvidas sozinhas, antes de medir qualquer célula: {widths} pt",
    tallest: "A célula mais alta pede {needed} pt, sobre {across} das colunas",
    roles: "Linhas colocadas: {heads} de cabeçalho, {bodies} de corpo, {feet} de rodapé",
    holds: "Células: {texts} de texto, {pictures} de imagem, {drawings} de desenho",
    settled: "Altura fixada por {what}: {cells}",
    settled_names: [
        "o conteúdo próprio da célula",
        "uma célula mais alta na sua linha",
        "a altura que a sua linha pediu",
        "a altura fixa da sua linha",
        "uma célula que desce sobre a sua linha",
        "o espaço repartido sob a última linha",
        "as linhas que cobre",
    ],
    caption_side: "A legenda fica {side} da tabela.",
    sides: ["acima", "abaixo"],
    notes: "Cada nota leva o relatório da própria biblioteca sobre a sua célula, em inglês.",
    more_title: "Erros, uma linha cortada em duas e espaço repartido",
    damaged_title: "Paginada apesar dos erros:",
    damaged: [
        "Segunda",
        "Fechado para obras",
        "Terça",
        "12",
        "Desviada pela circular enquanto a ponte está fechada: as paragens da zona histórica são servidas pela linha 31, que sai da estação de dez em dez minutos.",
    ],
    other_width: "A linha {row} preenche {covered} de {columns} colunas; o resto fica vazio.",
    past_the_box: "A linha {row} sai pelo fundo da sua caixa.",
    split_caption: "Tabela 2. Uma observação, cortada em duas caixas",
    split: [
        "Observação",
        "A linha tem mais do que cabe numa caixa, por isso é cortada onde acaba uma linha de texto. Pelo menos três linhas ficam no fundo da primeira caixa, e pelo menos três passam para o topo da seguinte, para que nenhuma caixa acabe ou comece com uma linha solta do parágrafo. A célula de título é composta inteira na primeira caixa e deixada vazia na segunda.",
    ],
    split_said: "A linha foi repartida por {boxes} caixas.",
    shared_title: "O espaço sob a última linha, repartido pelas linhas:",
    shared: ["Segunda", "07:40", "Terça", "07:45", "Quarta", "07:40"],
    shrunk_title: "Uma tabela com 480 pontos de largura, reduzida inteira a uma caixa de 230:",
    shrunk: ["Partida", "Linha", "Cais"],
    shrunk_said: "Reduzida a {percent} % nos dois eixos.",
    notice_title: "Um aviso repartido por várias células",
    notice_intro: [
        "O aviso é um só texto: cada célula da sua coluna retoma-o onde a anterior parou,",
        "com as linhas de texto que a sua linha comporta; a última leva o resto e a sua linha cresce.",
    ],
    columns_said: "O mesmo aviso nas duas células de uma linha, a primeira com metade da altura do aviso:",
    notice_head: "Aviso aos passageiros",
    notice: "Enquanto a ponte da Rua do Rio estiver fechada para obras, a linha 12 segue pela circular e deixa de servir as paragens da zona histórica. A linha 31 passa a servi-las: sai da estação de dez em dez minutos, das seis da manhã às onze da noite, e para em cada uma delas a caminho do Porto. Os bilhetes e passes da linha 12 são válidos na linha 31, sem qualquer formalidade. Durante as obras, atravessar o rio demora cerca de mais dez minutos do que o habitual, e os horários da primeira página já contam com isso. Junto a cada paragem sem serviço há uma placa provisória que indica a paragem servida mais próxima. Todas as manhãs, até às nove, funcionários de colete amarelo indicam o caminho no Mercado Velho. As obras devem terminar a 20 de novembro, e o horário habitual regressa na segunda-feira seguinte.",
};

/// The pages in Italian.
const ITALIAN: Words = Words {
    lang: "it",
    title: "Un orario che fa rapporto su sé stesso",
    intro: [
        "Filetti sottili contornano ogni cella, trattini la tabella e la didascalia; croci segnano",
        "la cima di ogni linea di colonna, e una griglia copre lo spazio lasciato sotto la tabella.",
    ],
    headings: ["Fermata", "Linea", "Note", "Partenza"],
    stops: [
        "Porto",
        "Mercato Vecchio",
        "Piazza del Duomo, lato nord",
        "Università",
    ],
    remarks: [
        "Salita senza gradini dalla porta anteriore di ogni autobus di questa linea, e pedana per sedie a rotelle su richiesta",
        "Coincidenza qui con il tram",
        "Solo nei giorni di scuola; ristretta per stare nella sua riga",
    ],
    foot: "Ogni orario è la partenza dalla fermata.",
    caption: "Tabella 1. Partenze del mattino, linee 12 e 31",
    sign_alt: "Un cartello di fermata dell’autobus",
    logo_alt: "Il logo del gestore",
    shape: "{count} colonne su {width} pt: {widths} pt",
    span: "Le ultime due colonne insieme: {span} pt; l’immagine è nella colonna {place}",
    resolved: "Risolte da sole, prima di misurare qualsiasi cella: {widths} pt",
    tallest: "La cella più alta chiede {needed} pt, su {across} delle colonne",
    roles: "Righe collocate: {heads} di intestazione, {bodies} di corpo, {feet} di piede",
    holds: "Celle: {texts} di testo, {pictures} di immagine, {drawings} di disegno",
    settled: "Altezza fissata da {what}: {cells}",
    settled_names: [
        "il contenuto proprio della cella",
        "una cella più alta della sua riga",
        "l’altezza che ha chiesto la sua riga",
        "l’altezza fissa della sua riga",
        "una cella che scende sulla sua riga",
        "lo spazio ripartito sotto l’ultima riga",
        "le righe che copre",
    ],
    caption_side: "La didascalia sta {side} la tabella.",
    sides: ["sopra", "sotto"],
    notes: "Ogni nota porta il rapporto della libreria stessa sulla sua cella, in inglese.",
    more_title: "Errori, una riga tagliata in due e spazio ripartito",
    damaged_title: "Impaginata nonostante gli errori:",
    damaged: [
        "Lunedì",
        "Chiuso per lavori",
        "Martedì",
        "12",
        "Deviata sulla tangenziale mentre il ponte è chiuso: le fermate del centro storico sono servite dalla linea 31, che parte dalla stazione ogni dieci minuti.",
    ],
    other_width: "La riga {row} riempie {covered} di {columns} colonne; il resto resta vuoto.",
    past_the_box: "La riga {row} esce dal fondo del suo riquadro.",
    split_caption: "Tabella 2. Una nota, tagliata su due riquadri",
    split: [
        "Nota",
        "La riga contiene più di quanto stia in un riquadro, così si taglia dove finisce una riga di testo. Almeno tre righe restano al piede del primo riquadro, e almeno tre passano in testa al successivo, perché nessun riquadro finisca o inizi con una riga isolata del paragrafo. La cella di intestazione è composta intera nel primo riquadro e lasciata vuota nel secondo.",
    ],
    split_said: "La riga è stata distribuita su {boxes} riquadri.",
    shared_title: "Lo spazio sotto l’ultima riga, ripartito tra le righe:",
    shared: ["Lunedì", "07:40", "Martedì", "07:45", "Mercoledì", "07:40"],
    shrunk_title: "Una tabella larga 480 punti, ridotta intera in un riquadro largo 230:",
    shrunk: ["Partenza", "Linea", "Binario"],
    shrunk_said: "Scalata al {percent} % sui due assi.",
    notice_title: "Un avviso che passa da una cella all’altra",
    notice_intro: [
        "L’avviso è un solo testo: ogni cella della sua colonna lo riprende dove la precedente si è fermata,",
        "con tante righe di testo quante ne contiene la sua riga; l’ultima prende il resto e la sua riga cresce.",
    ],
    columns_said: "Lo stesso avviso nelle due celle di una riga, la prima alta quanto metà delle sue righe di testo:",
    notice_head: "Avviso ai viaggiatori",
    notice: "Finché il ponte di via del Fiume resta chiuso per lavori, la linea 12 passa per la tangenziale e non serve più le fermate del centro storico. Le serve la linea 31: parte dalla stazione ogni dieci minuti, dalle sei del mattino alle undici di sera, e si ferma a ciascuna di esse in direzione del Porto. Biglietti e abbonamenti della linea 12 valgono sulla linea 31 senza alcuna formalità. Durante i lavori, attraversare il fiume richiede una decina di minuti in più del solito, e gli orari della prima pagina ne tengono già conto. Accanto a ogni fermata non servita, un cartello provvisorio indica la fermata servita più vicina. Al Mercato Vecchio, ogni mattina fino alle nove, personale in gilet giallo indica la strada ai viaggiatori. La fine dei lavori è prevista per il 20 novembre e gli orari consueti tornano in vigore il lunedì successivo.",
};

/// The pages in Spanish.
const SPANISH: Words = Words {
    lang: "es",
    title: "Un horario que informa de sí mismo",
    intro: [
        "Filetes finos rodean cada celda, guiones la tabla y su leyenda; cruces marcan",
        "lo alto de cada línea de columna, y una rejilla cubre el sitio que queda bajo la tabla.",
    ],
    headings: ["Parada", "Línea", "Observaciones", "Salida"],
    stops: [
        "Puerto",
        "Mercado Viejo",
        "Plaza de la Catedral, lado norte",
        "Universidad",
    ],
    remarks: [
        "Acceso sin escalón por la puerta delantera de cada autobús de esta línea, y rampa para sillas de ruedas a petición",
        "Transbordo aquí con el tranvía",
        "Solo días lectivos, estrechada para caber en su fila",
    ],
    foot: "Cada hora es la de salida de la parada.",
    caption: "Tabla 1. Salidas de la mañana, líneas 12 y 31",
    sign_alt: "Un poste de parada de autobús",
    logo_alt: "El logotipo del operador",
    shape: "{count} columnas en {width} pt: {widths} pt",
    span: "Las dos últimas columnas juntas: {span} pt; la imagen está en la columna {place}",
    resolved: "Resueltas por sí solas, antes de medir ninguna celda: {widths} pt",
    tallest: "La celda más alta pide {needed} pt, sobre {across} de las columnas",
    roles: "Filas colocadas: {heads} de cabecera, {bodies} de cuerpo, {feet} de pie",
    holds: "Celdas: {texts} de texto, {pictures} de imagen, {drawings} de dibujo",
    settled: "Altura fijada por {what}: {cells}",
    settled_names: [
        "el contenido propio de la celda",
        "una celda más alta de su fila",
        "la altura que pidió su fila",
        "la altura fija de su fila",
        "una celda que baja sobre su fila",
        "el sitio repartido bajo la última fila",
        "las filas que cubre",
    ],
    caption_side: "La leyenda va {side} de la tabla.",
    sides: ["encima", "debajo"],
    notes: "Cada nota lleva el informe de la propia biblioteca sobre su celda, en inglés.",
    more_title: "Fallos, una fila cortada en dos y sitio repartido",
    damaged_title: "Maquetada pese a sus fallos:",
    damaged: [
        "Lunes",
        "Cerrado por obras",
        "Martes",
        "12",
        "Desviada por la ronda mientras el puente está cerrado: las paradas del casco antiguo las atiende la línea 31, que sale de la estación cada diez minutos.",
    ],
    other_width: "La fila {row} llena {covered} de {columns} columnas; el resto queda vacío.",
    past_the_box: "La fila {row} se sale por abajo de su caja.",
    split_caption: "Tabla 2. Una observación, cortada entre dos cajas",
    split: [
        "Observación",
        "La fila tiene más de lo que cabe en una caja, así que se corta donde acaba una línea. Al menos tres líneas se quedan al pie de la primera caja, y al menos tres pasan a la cabeza de la siguiente, para que ninguna caja acabe ni empiece con una línea suelta del párrafo. La celda de título se compone entera en la primera caja y se deja vacía en la segunda.",
    ],
    split_said: "La fila se repartió en {boxes} cajas.",
    shared_title: "El sitio bajo la última fila, repartido entre las filas:",
    shared: ["Lunes", "07:40", "Martes", "07:45", "Miércoles", "07:40"],
    shrunk_title: "Una tabla de 480 puntos de ancho, reducida entera a una caja de 230:",
    shrunk: ["Salida", "Línea", "Andén"],
    shrunk_said: "Escalada al {percent}\u{a0}% en los dos ejes.",
    notice_title: "Un aviso repartido en varias celdas",
    notice_intro: [
        "El aviso es un solo texto: cada celda de su columna lo retoma donde se detuvo la anterior,",
        "tantas líneas como caben en su fila; la última toma el resto, y su fila crece para darle cabida.",
    ],
    columns_said: "El mismo aviso en las dos celdas de una fila, la primera con la altura de medio aviso:",
    notice_head: "Aviso a los viajeros",
    notice: "Mientras el puente de la calle del Río esté cerrado por obras, la línea 12 circula por la ronda y deja de dar servicio a las paradas del casco antiguo. De ellas se encarga la línea 31: sale de la estación cada diez minutos, de las seis de la mañana a las once de la noche, y para en todas camino del Puerto. Los billetes y abonos de la línea 12 valen en la línea 31 sin ningún trámite. Durante las obras, cruzar el río lleva unos diez minutos más de lo habitual, y los horarios de la primera página ya lo tienen en cuenta. Junto a cada parada sin servicio hay un cartel provisional que indica la parada con servicio más cercana. Cada mañana, hasta las nueve, personal con chaleco amarillo orienta a los viajeros en el Mercado Viejo. Está previsto que las obras terminen el 20 de noviembre y que el horario habitual vuelva el lunes siguiente.",
};

/// The pages in German.
const GERMAN: Words = Words {
    lang: "de",
    title: "Ein Fahrplan, der über sich selbst berichtet",
    intro: [
        "Haarlinien umranden jede Zelle, Striche die Tabelle und ihre Legende; Kreuze markieren",
        "den Kopf jeder Spaltenlinie, und im Raum unter der Tabelle ist ein Raster gezogen.",
    ],
    headings: ["Haltestelle", "Linie", "Hinweise", "Abfahrt"],
    stops: ["Hafen", "Alter Markt", "Domplatz, Nordseite", "Universität"],
    remarks: [
        "Stufenloser Einstieg an der Vordertür jedes Busses dieser Linie, und auf Wunsch eine Rampe für Rollstühle",
        "Hier umsteigen in die Straßenbahn",
        "Nur an Schultagen, verengt, um in seine Zeile zu passen",
    ],
    foot: "Jede Zeit ist die Abfahrt von der Haltestelle.",
    caption: "Tabelle 1. Abfahrten am Morgen, Linien 12 und 31",
    sign_alt: "Ein Haltestellenschild",
    logo_alt: "Das Logo des Verkehrsbetriebs",
    shape: "{count} Spalten über {width} pt: {widths} pt",
    span: "Die letzten zwei Spalten zusammen: {span} pt; das Bild steht in Spalte {place}",
    resolved: "Für sich aufgelöst, bevor eine Zelle gemessen wird: {widths} pt",
    tallest: "Die höchste Zelle verlangt {needed} pt, über {across} der Spalten",
    roles: "Platzierte Zeilen: {heads} Kopf, {bodies} Körper, {feet} Fuß",
    holds: "Zellen: {texts} mit Text, {pictures} mit Bild, {drawings} mit Zeichnung",
    settled: "Höhe bestimmt durch {what}: {cells}",
    settled_names: [
        "den eigenen Inhalt der Zelle",
        "eine höhere Zelle ihrer Zeile",
        "die von ihrer Zeile verlangte Höhe",
        "die feste Höhe ihrer Zeile",
        "eine Zelle, die über ihre Zeile hinabreicht",
        "den unter der letzten Zeile verteilten Raum",
        "die Zeilen, die sie überdeckt",
    ],
    caption_side: "Die Legende steht {side} der Tabelle.",
    sides: ["über", "unter"],
    notes: "Jede Notiz trägt den eigenen Bericht der Bibliothek zu ihrer Zelle, auf Englisch.",
    more_title: "Fehler, eine zweigeteilte Zeile und verteilter Raum",
    damaged_title: "Trotz ihrer Fehler gesetzt:",
    damaged: [
        "Montag",
        "Wegen Bauarbeiten geschlossen",
        "Dienstag",
        "12",
        "Über die Ringstraße umgeleitet, solange die Brücke gesperrt ist: Die Haltestellen der Altstadt bedient die Linie 31, die alle zehn Minuten am Bahnhof abfährt.",
    ],
    other_width: "Zeile {row} füllt {covered} von {columns} Spalten; der Rest bleibt leer.",
    past_the_box: "Zeile {row} läuft über den unteren Rand ihres Rahmens hinaus.",
    split_caption: "Tabelle 2. Ein Hinweis, über zwei Rahmen getrennt",
    split: [
        "Hinweis",
        "Die Zeile fasst mehr, als ein Rahmen Platz hat, also wird sie dort getrennt, wo eine Zeile endet. Mindestens drei Zeilen bleiben am Fuß des ersten Rahmens, und mindestens drei gehen an den Kopf des nächsten, sodass kein Rahmen mit einer einsamen Zeile des Absatzes endet oder beginnt. Die Kopfzelle wird im ersten Rahmen ganz gesetzt und im zweiten leer gelassen.",
    ],
    split_said: "Die Zeile wurde über {boxes} Rahmen gelegt.",
    shared_title: "Der Raum unter der letzten Zeile, unter den Zeilen verteilt:",
    shared: ["Montag", "07:40", "Dienstag", "07:45", "Mittwoch", "07:40"],
    shrunk_title: "Eine Tabelle von 480 Punkt Breite, als Ganzes in einen Rahmen von 230 verkleinert:",
    shrunk: ["Abfahrt", "Linie", "Gleis"],
    shrunk_said: "Auf beiden Achsen auf {percent} % skaliert.",
    notice_title: "Ein Hinweis über mehrere Zellen hinweg",
    notice_intro: [
        "Der Hinweis ist ein einziger Text: Jede Zelle seiner Spalte setzt ihn fort, wo die vorige endete,",
        "mit so vielen Zeilen, wie ihre Tabellenzeile fasst; die letzte nimmt den Rest und wächst mit.",
    ],
    columns_said: "Derselbe Hinweis in beiden Zellen einer Tabellenzeile, die erste mit der Hälfte seiner Zeilen:",
    notice_head: "Hinweis für Fahrgäste",
    notice: "Solange die Brücke in der Flussstraße wegen Bauarbeiten gesperrt ist, fährt die Linie 12 über die Ringstraße und bedient die Haltestellen der Altstadt nicht mehr. Diese übernimmt die Linie 31: Sie fährt von sechs Uhr morgens bis elf Uhr abends alle zehn Minuten am Bahnhof ab und hält an jeder dieser Haltestellen auf dem Weg zum Hafen. Fahrkarten und Zeitkarten der Linie 12 gelten ohne Weiteres auch auf der Linie 31. Während der Bauarbeiten dauert eine Fahrt über den Fluss etwa zehn Minuten länger als sonst; die Zeiten auf der ersten Seite berücksichtigen das bereits. Neben jeder Haltestelle, die nicht bedient wird, steht ein provisorisches Schild mit der nächstgelegenen bedienten Haltestelle. Jeden Morgen bis neun Uhr weisen Mitarbeitende in gelben Westen am Alten Markt den Weg. Die Bauarbeiten sollen am 20. November enden, und ab dem darauffolgenden Montag gilt wieder der gewohnte Fahrplan.",
};

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

/// Where a kind of settling stands in [`Words::settled_names`].
#[allow(
    clippy::match_same_arms,
    reason = "a kind the library adds later reads as the first"
)]
const fn settled_name(settled: Settled) -> usize {
    match settled {
        Settled::ThisCell => 0,
        Settled::AnotherCell => 1,
        Settled::RowFloor => 2,
        Settled::FixedRow => 3,
        Settled::SpanningCell => 4,
        Settled::SharedRoom => 5,
        Settled::SpannedRows => 6,
        _ => 0,
    }
}

/// `line` set at `(x, y)` in `font` at `size` points, as a paragraph of its own
/// with the element standing for it handed back.
fn paragraph(
    content: &mut Content,
    marks: &mut Marks,
    page: usize,
    font: &FontHandle,
    size: f64,
    (x, y): (f64, f64),
    line: &str,
) -> Result<StructElement, hqf_pdf::Error> {
    let id = marks.next_id();
    content.begin_tagged(&Name::new("P"), id);
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    content.end_marked();
    Ok(StructElement::new("P").content(page, id))
}

/// A cell holding `text`, set at the cells' size.
fn cell<'a>(font: &'a FontHandle, text: &str) -> Cell<'a> {
    Cell::new(font, CELL, text).padding(Padding::uniform(PADDING))
}

/// A small drawing of a bus-stop sign: a pole under a disc.
fn sign() -> Result<Drawing, hqf_pdf::Error> {
    let mut content = Content::new();
    content.set_fill_rgb(0.12, 0.35, 0.65)?;
    content.rect(8.5, 0.0, 1.0, 12.0)?.fill();
    content.circle(9.0, 14.0, 5.0)?.fill();
    Ok(Drawing::new(content, Rect::new(0.0, 0.0, 18.0, 19.0)))
}

/// The timetable: four columns sized four ways, a heading row and a foot row, a
/// stop reaching down over two rows, a drawing, a picture, a row of a fixed
/// height, and a caption under it. Hands back the side the caption is set on
/// with the table.
fn timetable<'a>(
    font: &'a FontHandle,
    words: &Words,
    sign: &hqf_pdf::DrawingHandle,
    logo: &hqf_pdf::ImageHandle,
    heading_fill: &Paint,
) -> Result<(Table<'a>, CaptionSide), hqf_pdf::Error> {
    let columns = Columns::new(
        [
            ColumnWidth::LongestWord,
            ColumnWidth::Points(40.0),
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Content,
        ],
        WIDTH,
    )?;
    let mut table = Table::new(columns);
    table.header(1).footer(1).header_links(HeaderLinks::Always);
    let caption = Caption::below(TextFlow::new(font, BODY), words.caption).gap(5.0);
    let side = caption.side();
    table.caption(caption);
    table
        .fill(Area::Whole, Rgb::new(0.99, 0.99, 0.97))
        .fill(Area::OddRows, Rgb::gray(0.95))
        .fill(Area::Column(0), Rgb::new(0.95, 0.97, 1.0))
        .fill(Area::ColumnFromEnd(0), Rgb::new(1.0, 0.97, 0.9))
        .fill(Area::RowFromEnd(1), Rgb::new(0.96, 1.0, 0.95))
        .fill(Area::Header, heading_fill.clone())
        .fill(Area::Footer, Rgb::gray(0.92));
    table
        .rule(Rule::Frame, Stroke::black(0.8))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .rule(Rule::VerticalFromEnd(1), Stroke::black(0.8));

    let mut head = Row::new();
    for heading in words.headings {
        head = head.cell(
            cell(font, heading)
                .character_spacing(0.8)
                .heading(Scope::Column),
        );
    }
    table.push(head);

    let [harbour, market, square, university] = words.stops;
    let [boarding, tram, school] = words.remarks;
    table.push(
        Row::new()
            .cell(cell(font, harbour).heading(Scope::Row))
            .cell(cell(font, LINES[0]))
            .cell(cell(font, boarding))
            .cell(cell(font, TIMES[0])),
    );
    table.push(
        Row::new()
            .cell(cell(font, market).heading(Scope::Row))
            .cell(cell(font, LINES[1]))
            .cell(
                Cell::drawing(sign)
                    .alt(words.sign_alt)
                    .padding(Padding::uniform(PADDING)),
            )
            .cell(cell(font, TIMES[1]))
            .min_height(26.0),
    );
    table.push(
        Row::new()
            .cell(cell(font, square).heading(Scope::Row).span_rows(2))
            .cell(cell(font, LINES[2]))
            .cell(cell(font, tram))
            .cell(cell(font, TIMES[2])),
    );
    table.push(
        Row::new()
            .cell(cell(font, LINES[3]))
            .cell(
                Cell::image(logo)
                    .alt(words.logo_alt)
                    .padding(Padding::uniform(PADDING)),
            )
            .cell(cell(font, TIMES[3])),
    );
    table.push(
        Row::new()
            .cell(cell(font, university).heading(Scope::Row))
            .cell(cell(font, LINES[4]))
            .cell(cell(font, school).horizontal_scaling(80.0))
            .cell(cell(font, TIMES[4]))
            .fixed_height(14.0, 6.0),
    );
    table.push(Row::new().cell(cell(font, words.foot).span(4)));
    Ok((table, side))
}

/// The lines that count the cells of `reports` by what settled their height,
/// one line for each kind that settled at least one.
fn settled_lines(reports: &[CellReport], words: &Words) -> Vec<String> {
    let mut counts = [0_usize; 7];
    for report in reports {
        counts[settled_name(report.settled)] += 1;
    }
    counts
        .iter()
        .zip(words.settled_names)
        .filter(|(count, _)| **count > 0)
        .map(|(count, name)| {
            words
                .settled
                .replace("{what}", name)
                .replace("{cells}", &count.to_string())
        })
        .collect()
}

/// What the placed timetable says of itself, one line each.
fn summary(table: &Table<'_>, placed: &FittedTable<'_>, words: &Words) -> Vec<String> {
    let each: Vec<String> = (0..placed.column_count())
        .filter_map(|column| placed.column_width(column))
        .map(|width| format!("{width:.0}"))
        .collect();
    let shape = words
        .shape
        .replace("{count}", &placed.column_count().to_string())
        .replace("{width}", &format!("{:.0}", placed.width()))
        .replace("{widths}", &each.join(" + "));

    let columns = table.columns();
    let picture = table.cell_column(4, 1).unwrap_or_default();
    let together = words
        .span
        .replace(
            "{span}",
            &format!("{:.0}", columns.span_width(columns.len() - 2, 2)),
        )
        .replace("{place}", &(picture + 1).to_string());

    let mut roles = [0_usize; 3];
    for index in 0..placed.row_count() {
        match placed.row_role(index) {
            Some(RowRole::Header) => roles[0] += 1,
            Some(RowRole::Body) => roles[1] += 1,
            Some(RowRole::Footer) => roles[2] += 1,
            _ => {}
        }
    }
    let roles = words
        .roles
        .replace("{heads}", &roles[0].to_string())
        .replace("{bodies}", &roles[1].to_string())
        .replace("{feet}", &roles[2].to_string());

    let reports = placed.cell_reports();
    let mut held = [0_usize; 3];
    for report in &reports {
        match report.holds {
            Holds::Text { .. } => held[0] += 1,
            Holds::Picture => held[1] += 1,
            Holds::Form => held[2] += 1,
            _ => {}
        }
    }
    let holds = words
        .holds
        .replace("{texts}", &held[0].to_string())
        .replace("{pictures}", &held[1].to_string())
        .replace("{drawings}", &held[2].to_string());

    let alone: Vec<String> = columns
        .resolved()
        .iter()
        .map(|width| format!("{width:.0}"))
        .collect();
    let resolved = words.resolved.replace("{widths}", &alone.join(" + "));

    let mut tallest: Option<&CellReport> = None;
    for report in &reports {
        if tallest.is_none_or(|so_far| report.needed > so_far.needed) {
            tallest = Some(report);
        }
    }

    let mut lines = vec![shape, together, roles, holds, resolved];
    if let Some(report) = tallest {
        lines.push(
            words
                .tallest
                .replace("{needed}", &format!("{:.0}", report.needed))
                .replace("{across}", &report.widths.len().to_string()),
        );
    }
    lines.extend(settled_lines(&reports, words));
    lines
}

/// Outlines what the timetable was placed in: every cell's box in magenta
/// hairlines, the table and its caption in dashed blue, the picture's cell
/// heavier, a green cross on the top of each column line, and a grid over
/// `room`.
fn outline(
    content: &mut Content,
    table: &Table<'_>,
    placed: &FittedTable<'_>,
    room: Rect,
) -> Result<(), hqf_pdf::Error> {
    content.begin_artifact(Artifact::Layout);
    let cells = Guides::hairline(MAGENTA);
    cells.outline_all(content, &placed.cell_boxes())?;

    let dashed = Guides::new(
        Stroke::new(0.6, Rgb::new(0.0, 0.45, 0.85))
            .styled(LineStyle::new().dash(Dash::on_off(3.0, 2.0)?)),
    );
    dashed.outline(content, placed.box_())?;
    if let Some(caption) = placed.caption_box() {
        dashed.outline(content, caption)?;
    }

    let heavy = Guides::new(Stroke::new(cells.stroke().width * 5.0, MAGENTA));
    let column = table.cell_column(4, 1).unwrap_or_default();
    if let Some(box_) = placed.cell_box(4, column) {
        heavy.outline(content, box_)?;
    }

    let crosses = Guides::hairline(Rgb::new(0.0, 0.6, 0.2));
    for line in 0..=placed.column_count() {
        if let Some(x) = placed.column_x(line) {
            crosses.cross(content, x, placed.top(), 4.0)?;
        }
    }

    let step = (room.height() / f64::from(Guides::MOST_LINES)).max(12.0);
    let grid = Guides::hairline(Rgb::gray(0.8));
    grid.grid(content, room, (step, step))?;
    grid.outline(content, room)?;
    content.end_marked();
    Ok(())
}

/// The first page: the timetable, its outlines, what it says of itself and a
/// note on every cell. Hands back the page and the elements standing for what
/// it says.
fn first_page(
    font: &FontHandle,
    words: &Words,
    sign: &hqf_pdf::DrawingHandle,
    logo: &hqf_pdf::ImageHandle,
    heading_fill: &Paint,
) -> Result<(Page, Vec<StructElement>), Box<dyn std::error::Error>> {
    let mut content = Content::new();
    let mut marks = Marks::new();
    let mut said = Vec::new();
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    let heading = marks.next_id();
    content.begin_tagged(&Name::new("H1"), heading);
    content.begin_text();
    content.set_font(font, HEADING)?;
    content.text_origin(MARGIN, HEAD_TOP)?;
    content.show_glyphs(&font.glyphs(words.title));
    content.end_text();
    content.end_marked();
    said.push(StructElement::new("H1").content(0, heading));
    let mut y = HEAD_TOP - 22.0;
    for line in words.intro {
        said.push(paragraph(
            &mut content,
            &mut marks,
            0,
            font,
            BODY,
            (MARGIN, y),
            line,
        )?);
        y -= LINE_STEP;
    }

    let (table, caption_side) = timetable(font, words, sign, logo, heading_fill)?;
    let placed = table.fit(TableFrame::new(MARGIN, TABLE_TOP, TABLE_ROOM), 0)?;
    said.push(placed.draw_tagged(&mut content, 0, &mut marks)?);

    let mut y = placed
        .caption_box()
        .map_or_else(|| placed.bottom(), |caption| caption.y())
        - 20.0;
    #[allow(
        clippy::match_same_arms,
        reason = "a side the library adds later reads as below"
    )]
    let set_on = match caption_side {
        CaptionSide::Above => words.sides[0],
        CaptionSide::Below => words.sides[1],
        _ => words.sides[1],
    };
    let mut lines = if placed.is_empty() {
        Vec::new()
    } else {
        summary(&table, &placed, words)
    };
    lines.push(words.caption_side.replace("{side}", set_on));
    lines.push(words.notes.to_owned());
    for line in &lines {
        said.push(paragraph(
            &mut content,
            &mut marks,
            0,
            font,
            BODY,
            (MARGIN, y),
            line,
        )?);
        y -= LINE_STEP;
    }

    // The room left under the last line, down to the foot margin.
    let under = y + LINE_STEP - 8.0;
    let room = Rect::new(MARGIN, 60.0, WIDTH, under - 60.0);
    outline(&mut content, &table, &placed, room)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    let reports = placed.cell_reports();
    for report in &reports {
        page.annotations.push(Annotation::StickyNote(report.note()));
    }
    // The picture's cell, in the words the library reports it in.
    let column = table.cell_column(4, 1).unwrap_or_default();
    if let Some(report) = reports
        .iter()
        .find(|report| report.row == 4 && report.column == column)
    {
        println!("{}", report.describe());
    }
    Ok((page, said))
}

/// A table of three columns laid out despite its faults: its first row fills
/// two of them, its second is taller than the box it is given alone.
fn damaged<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(Columns::equal(3, 230.0)?);
    table.draw_damaged(true).header_links(HeaderLinks::Never);
    table
        .rule(Rule::Frame, Stroke::black(0.6))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.6)));
    let [monday, closed, tuesday, line, diverted] = words.damaged;
    table.push(Row::new().cell(cell(font, monday)).cell(cell(font, closed)));
    table.push(
        Row::new()
            .cell(cell(font, tuesday))
            .cell(cell(font, line))
            .cell(cell(font, diverted)),
    );
    Ok(table)
}

/// A table of two columns whose one row is cut across boxes, three lines kept
/// on each side, its caption over the first box only.
fn split<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(Columns::new(
        [ColumnWidth::Points(60.0), ColumnWidth::Fraction(1.0)],
        230.0,
    )?);
    table.split_rows(true);
    table.caption(
        Caption::above(TextFlow::new(font, BODY), words.split_caption)
            .gap(4.0)
            .first_box_only(),
    );
    table
        .rule(Rule::Frame, Stroke::black(0.6))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.6)));
    let [remark, text] = words.split;
    table.push(
        Row::new()
            .cell(cell(font, remark).heading(Scope::Row))
            .cell(cell(font, text).keep_lines(3)),
    );
    Ok(table)
}

/// A table of two columns that shares the room under its last row among its
/// rows, so that the last of them ends on the bottom of its box. The second
/// cell of each row holds a field the reader may type over, the time already in
/// it, standing over the box the cell is laid out in.
fn shared<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(Columns::equal(2, 230.0)?);
    table.fill_frame(true).header_links(HeaderLinks::Deduced);
    table
        .rule(Rule::Frame, Stroke::black(0.6))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .fill(Area::EvenRows, Rgb::gray(0.95));
    for (index, pair) in words.shared.chunks(2).enumerate() {
        let [day, time] = pair else {
            continue;
        };
        table.push(Row::new().cell(cell(font, day)).cell(cell(font, "")));
        table.cell_field(
            index,
            1,
            TextField::new(
                format!("departure_{}", index + 1),
                0.0,
                0.0,
                0.0,
                0.0,
                font.name(),
                BODY,
            )
            .value(*time)
            .border(FieldBorder::solid(Rgb::gray(0.45), 0.6)),
        )?;
    }
    Ok(table)
}

/// A table of three columns 160 points wide each, a heading row over five
/// departures, twice as wide as the box it is shrunk into.
fn shrunk<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(Columns::new([ColumnWidth::Points(160.0); 3], 480.0)?);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::black(0.6))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .fill(Area::Header, Rgb::gray(0.9));
    let mut heads = Row::new();
    for text in words.shrunk {
        heads = heads.cell(cell(font, text));
    }
    table.push(heads);
    for ((time, line), platform) in TIMES.iter().zip(LINES).zip(PLATFORMS) {
        table.push(
            Row::new()
                .cell(cell(font, time))
                .cell(cell(font, line))
                .cell(cell(font, platform)),
        );
    }
    Ok(table)
}

/// The damaged table, in a box too short for its second row and a second box
/// shorter still, each outlined, and a line for every fault it was laid out
/// despite. Hands back the elements standing for what it draws.
fn faults(
    content: &mut Content,
    marks: &mut Marks,
    font: &FontHandle,
    words: &Words,
) -> Result<Vec<StructElement>, Box<dyn std::error::Error>> {
    let mut said = Vec::new();
    let frames = Guides::new(
        Stroke::new(0.6, Rgb::new(0.0, 0.45, 0.85))
            .styled(LineStyle::new().dash(Dash::on_off(3.0, 2.0)?)),
    );
    let damaged = damaged(font, words)?;
    let first = damaged.fit(TableFrame::new(MARGIN, 750.0, 60.0), 0)?;
    let next_row = match first.outcome() {
        FitProgress::BoxFull { next_row } => next_row,
        _ => 1,
    };
    let second = damaged.fit(TableFrame::new(MARGIN + 253.0, 750.0, 40.0), next_row)?;
    let mut found = Vec::new();
    let mut described = TaggedTable::new("damaged");
    for placed in [&first, &second] {
        described.add(placed, content, 1, marks)?;
        found.extend_from_slice(placed.damage());
    }
    said.push(described.finish());
    content.begin_artifact(Artifact::Layout);
    frames.outline(content, Rect::new(MARGIN, 690.0, 230.0, 60.0))?;
    frames.outline(content, Rect::new(MARGIN + 253.0, 710.0, 230.0, 40.0))?;
    content.end_marked();

    let mut y = 580.0;
    for fault in found {
        let line = match fault {
            Damage::RowOfAnotherWidth {
                row: at,
                covered: filled,
                columns: of,
            } => words
                .other_width
                .replace("{row}", &at.to_string())
                .replace("{covered}", &filled.to_string())
                .replace("{columns}", &of.to_string()),
            Damage::RowPastTheBox { row: at } => {
                words.past_the_box.replace("{row}", &at.to_string())
            }
            _ => continue,
        };
        said.push(paragraph(
            content,
            marks,
            1,
            font,
            BODY,
            (MARGIN, y),
            &line,
        )?);
        y -= LINE_STEP;
    }
    Ok(said)
}

/// The shrunk table, scaled down whole into its box, the box outlined, and a
/// line saying the factor it was scaled by. Hands back the elements standing
/// for what it draws.
fn shrunk_into_its_box(
    content: &mut Content,
    marks: &mut Marks,
    font: &FontHandle,
    words: &Words,
) -> Result<Vec<StructElement>, Box<dyn std::error::Error>> {
    let mut said = vec![paragraph(
        content,
        marks,
        1,
        font,
        BODY,
        (MARGIN, 140.0),
        words.shrunk_title,
    )?];
    let placed = shrunk(font, words)?.shrink_into(SHRUNK_AREA, SHRUNK_FLOOR)?;
    let mut described = TaggedTable::new("shrunk");
    described.add(&placed, content, 1, marks)?;
    said.push(described.finish());
    content.begin_artifact(Artifact::Layout);
    Guides::new(
        Stroke::new(0.6, Rgb::new(0.0, 0.45, 0.85))
            .styled(LineStyle::new().dash(Dash::on_off(3.0, 2.0)?)),
    )
    .outline(content, SHRUNK_AREA)?;
    content.end_marked();
    let line = words
        .shrunk_said
        .replace("{percent}", &format!("{:.0}", placed.scale() * 100.0));
    said.push(paragraph(
        content,
        marks,
        1,
        font,
        BODY,
        (MARGIN + 253.0, 110.0),
        &line,
    )?);
    Ok(said)
}

/// The second page: the damaged table in two boxes, the table whose row is cut,
/// the table sharing its room and the table shrunk into its box, each with what
/// it says of itself. Hands back the page and the elements standing for what it
/// says.
fn second_page(
    font: &FontHandle,
    words: &Words,
) -> Result<(Page, Vec<StructElement>), Box<dyn std::error::Error>> {
    let mut content = Content::new();
    let mut marks = Marks::new();
    let mut said = Vec::new();
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    let heading = marks.next_id();
    content.begin_tagged(&Name::new("H1"), heading);
    content.begin_text();
    content.set_font(font, HEADING)?;
    content.text_origin(MARGIN, HEAD_TOP)?;
    content.show_glyphs(&font.glyphs(words.more_title));
    content.end_text();
    content.end_marked();
    said.push(StructElement::new("H1").content(1, heading));
    said.push(paragraph(
        &mut content,
        &mut marks,
        1,
        font,
        BODY,
        (MARGIN, HEAD_TOP - 24.0),
        words.damaged_title,
    )?);

    said.extend(faults(&mut content, &mut marks, font, words)?);

    let split = split(font, words)?;
    let placements = split.paginate(
        TableFrame::new(MARGIN, 530.0, 90.0),
        TableFrame::new(MARGIN + 253.0, 530.0, 150.0),
    )?;
    let division = marks.next_id();
    content.begin_tagged(&Name::new("Div"), division);
    for placed in &placements {
        placed.draw(&mut content)?;
    }
    content.end_marked();
    said.push(StructElement::new("Div").content(1, division));
    let line = words
        .split_said
        .replace("{boxes}", &placements.len().to_string());
    said.push(paragraph(
        &mut content,
        &mut marks,
        1,
        font,
        BODY,
        (MARGIN, 360.0),
        &line,
    )?);

    said.push(paragraph(
        &mut content,
        &mut marks,
        1,
        font,
        BODY,
        (MARGIN, 320.0),
        words.shared_title,
    )?);
    let shared = shared(font, words)?;
    let placed = shared.fit(TableFrame::new(MARGIN, 305.0, 110.0), 0)?;
    let mut described = TaggedTable::new("shared");
    described.add(&placed, &mut content, 1, &mut marks)?;
    said.push(described.finish());
    let fields = shared.fields(&placed);
    let mut y = 175.0;
    for line in settled_lines(&placed.cell_reports(), words) {
        said.push(paragraph(
            &mut content,
            &mut marks,
            1,
            font,
            BODY,
            (MARGIN, y),
            &line,
        )?);
        y -= LINE_STEP;
    }

    said.extend(shrunk_into_its_box(&mut content, &mut marks, font, words)?);

    let mut page = Page::a4();
    page.content = content.into_bytes();
    page.fields = fields;
    Ok((page, said))
}

/// The notice's table: a stop and a departure on each row, the notice run down
/// the cells of the column between them. Every row but the last is
/// [`NOTICE_ROW`] high, and the last grows to take what the notice has left.
fn notice<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        [
            ColumnWidth::LongestWord,
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(44.0),
        ],
        WIDTH,
    )?;
    let mut table = Table::new(columns);
    table.header(1).header_links(HeaderLinks::Always);
    table
        .rule(Rule::Frame, Stroke::black(0.8))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .fill(Area::Header, Rgb::gray(0.9))
        .fill(Area::Column(1), Rgb::new(1.0, 0.98, 0.9));
    table.push(
        Row::new()
            .cell(cell(font, words.headings[0]).heading(Scope::Column))
            .cell(cell(font, words.notice_head).heading(Scope::Column))
            .cell(cell(font, words.headings[3]).heading(Scope::Column)),
    );
    let thread = Thread::new(words.notice, TextFlow::new(font, CELL));
    let last = words.stops.len() - 1;
    for (index, (stop, time)) in words.stops.iter().zip(TIMES).enumerate() {
        let row = Row::new()
            .cell(cell(font, stop).heading(Scope::Row))
            .cell(Cell::threaded(&thread).padding(Padding::uniform(PADDING)))
            .cell(cell(font, time));
        table.push(if index == last {
            row
        } else {
            row.min_height(NOTICE_ROW)
        });
    }
    Ok(table)
}

/// The notice run through the two cells of one row, the row as tall as the
/// first half of the notice's lines and less than one line more, so that the
/// first cell takes that half and the second the rest.
fn two_columns<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(Columns::equal(2, WIDTH)?);
    table
        .rule(Rule::Frame, Stroke::black(0.8))
        .rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.6)))
        .fill(Area::Whole, Rgb::new(1.0, 0.98, 0.9));
    let padding = Padding::uniform(PADDING);
    let flow = TextFlow::new(font, CELL);
    let lines = flow.break_lines(words.notice, WIDTH / 2.0 - PADDING - PADDING);
    let half = lines.len().div_ceil(2);
    let tall = f64::midpoint(
        flow.height(&lines[..half]),
        flow.height(&lines[..(half + 1).min(lines.len())]),
    );
    let thread = Thread::new(words.notice, flow);
    table.push(
        Row::new()
            .cell(Cell::threaded(&thread).padding(padding))
            .cell(Cell::threaded(&thread).padding(padding))
            .min_height(tall + PADDING + PADDING),
    );
    Ok(table)
}

/// The third page: the notice run down the cells of its table, then through the
/// two cells of one row, under what the page says of each. Hands back the page
/// and the elements standing for what it says.
fn third_page(
    font: &FontHandle,
    words: &Words,
) -> Result<(Page, Vec<StructElement>), Box<dyn std::error::Error>> {
    let mut content = Content::new();
    let mut marks = Marks::new();
    let mut said = Vec::new();
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    let heading = marks.next_id();
    content.begin_tagged(&Name::new("H1"), heading);
    content.begin_text();
    content.set_font(font, HEADING)?;
    content.text_origin(MARGIN, HEAD_TOP)?;
    content.show_glyphs(&font.glyphs(words.notice_title));
    content.end_text();
    content.end_marked();
    said.push(StructElement::new("H1").content(2, heading));
    let mut y = HEAD_TOP - 24.0;
    for line in words.notice_intro {
        said.push(paragraph(
            &mut content,
            &mut marks,
            2,
            font,
            BODY,
            (MARGIN, y),
            line,
        )?);
        y -= LINE_STEP;
    }

    let placed = notice(font, words)?.fit(TableFrame::new(MARGIN, TABLE_TOP, NOTICE_ROOM), 0)?;
    if placed.outcome() != FitProgress::Done {
        return Err("the notice's table does not fit its page".into());
    }
    let mut described = TaggedTable::new("notice");
    described.add(&placed, &mut content, 2, &mut marks)?;
    said.push(described.finish());

    let y = placed.bottom() - LINE_STEP - LINE_STEP;
    said.push(paragraph(
        &mut content,
        &mut marks,
        2,
        font,
        BODY,
        (MARGIN, y),
        words.columns_said,
    )?);
    let placed =
        two_columns(font, words)?.fit(TableFrame::new(MARGIN, y - 10.0, y - 10.0 - 56.0), 0)?;
    if placed.outcome() != FitProgress::Done {
        return Err("the notice's two columns do not fit their page".into());
    }
    let mut described = TaggedTable::new("columns");
    described.add(&placed, &mut content, 2, &mut marks)?;
    said.push(described.finish());

    let mut page = Page::a4();
    page.content = content.into_bytes();
    Ok((page, said))
}

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 path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("table_report")));
    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"), words.title);
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let sign = doc.add_drawing(sign()?);
    let logo = doc.add_image(Image::parse(fs::read(picture())?)?);

    // The heading row's background is one fade stated across the unit square
    // and stretched onto each heading cell, whatever its width.
    let heading_fill = Paint::fitted(&doc.add_shading(&Shading::from(Axial::rgb(
        (0.0, 0.0),
        (1.0, 0.0),
        Rgb::gray(0.93),
        Rgb::gray(0.76),
    )))?);
    let (page, mut said) = first_page(&font, words, &sign, &logo, &heading_fill)?;
    doc.add_page(page)?;
    let (page, more) = second_page(&font, words)?;
    doc.add_page(page)?;
    said.extend(more);
    let (page, notice) = third_page(&font, words)?;
    doc.add_page(page)?;
    said.extend(notice);

    let mut body = StructElement::new("Document");
    for element in said {
        body = body.child(element);
    }
    doc.set_structure(StructureTree::new().lang(words.lang).child(body));

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

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

    use hqf_pdf::layout::{FitProgress, Holds, TableFrame, TextFlow};

    use super::{
        BODY, CELL, HEADING, MARGIN, NOTICE_ROOM, PADDING, TABLE_TOP, WIDTH, WORDS, default_font,
        language, notice, two_columns,
    };

    /// The lines two languages are allowed to write the same way: a line number
    /// and the times, which read alike everywhere.
    const SPARED: [&str; 4] = [
        "\"12\"",
        "\"07:40\"",
        "\"07:45\"",
        // Written the same way in Portuguese.
        r#""Porto""#,
    ];

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

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

    /// `line` with its placeholders filled with the widest figures the pages
    /// give them.
    fn filled(line: &str) -> String {
        line.replace("{count}", "4")
            .replace("{width}", "483")
            .replace("{widths}", "90 + 40 + 280 + 73")
            .replace("{span}", "443")
            .replace("{place}", "3")
            .replace("{heads}", "1")
            .replace("{bodies}", "5")
            .replace("{feet}", "1")
            .replace("{texts}", "22")
            .replace("{pictures}", "1")
            .replace("{drawings}", "1")
            .replace("{cells}", "22")
            .replace("{row}", "1")
            .replace("{covered}", "2")
            .replace("{columns}", "3")
            .replace("{boxes}", "2")
            .replace("{needed}", "120")
            .replace("{across}", "3")
            .replace("{percent}", "48")
    }

    /// The notice runs down every row of its table, and the table ends on the
    /// page it is given.
    #[test]
    fn every_language_runs_its_notice_down_the_whole_table_within_its_page() {
        let mut doc = Document::new();
        let text = 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 code = named.code();
            let table = notice(&text, words).expect("the notice's columns are valid");
            let placed = table
                .fit(TableFrame::new(MARGIN, TABLE_TOP, NOTICE_ROOM), 0)
                .expect("the notice's table is laid out");

            assert_eq!(
                placed.outcome(),
                FitProgress::Done,
                "the {code} notice runs past its page"
            );
            let reports = placed.cell_reports();
            let empty: Vec<_> = reports
                .iter()
                .filter(|report| {
                    report.column == 1
                        && report.row > 0
                        && matches!(report.holds, Holds::Text { lines: 0 })
                })
                .map(|report| report.row)
                .collect();
            assert!(
                empty.is_empty(),
                "the {code} notice leaves the cells of rows {empty:?} empty"
            );

            let flow = TextFlow::new(&text, CELL);
            let lines = flow
                .break_lines(words.notice, WIDTH / 2.0 - PADDING - PADDING)
                .len();
            let placed = two_columns(&text, words)
                .expect("the two columns are valid")
                .fit(TableFrame::new(MARGIN, TABLE_TOP, NOTICE_ROOM), 0)
                .expect("the two columns are laid out");
            let held: Vec<_> = placed
                .cell_reports()
                .iter()
                .map(|report| match report.holds {
                    Holds::Text { lines } => lines,
                    _ => 0,
                })
                .collect();
            assert_eq!(
                held,
                [lines.div_ceil(2), lines / 2],
                "the {code} notice is not shared out evenly between its two columns"
            );
        }
    }

    /// No line set outside a table is broken to a width: a line longer than the
    /// room between the margins runs off the sheet.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut doc = Document::new();
        let text = 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 code = named.code();
            let mut lines = vec![
                (HEADING, words.title.to_owned()),
                (HEADING, words.more_title.to_owned()),
                (HEADING, words.notice_title.to_owned()),
            ];
            let body = words.intro.iter().chain(&words.notice_intro).chain([
                &words.columns_said,
                &words.shape,
                &words.span,
                &words.resolved,
                &words.tallest,
                &words.roles,
                &words.holds,
                &words.notes,
                &words.damaged_title,
                &words.other_width,
                &words.past_the_box,
                &words.split_said,
                &words.shared_title,
                &words.shrunk_title,
            ]);
            lines.extend(body.map(|line| (BODY, filled(line))));
            for name in words.settled_names {
                lines.push((BODY, filled(&words.settled.replace("{what}", name))));
            }
            for word in words.sides {
                lines.push((BODY, words.caption_side.replace("{side}", word)));
            }

            for (size, line) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= WIDTH,
                    "the {code} pages set {line:?} over {measured:.1} points, and \
                     they have {WIDTH:.1}"
                );
            }

            // The line beside the shrunk table has the right half of the page.
            let beside = filled(words.shrunk_said);
            let measured = text.measure(&beside, BODY);
            assert!(
                measured <= WIDTH - 253.0,
                "the {code} pages set {beside:?} over {measured:.1} points beside the \
                 shrunk table"
            );
        }
    }
}