"""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.

The Python twin of the `write_table_report` example in Rust: the same pages, through the
binding rather than through the library directly.

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; and 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.

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: python examples/write_table_report.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_table_report.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The picture one cell of the timetable holds.
PICTURE = _out.ROOT / "crates" / "hqf-pdf" / "tests" / "images" / "logo.png"

# How far in from the left edge of the sheet everything starts, in points.
MARGIN = 56.0

# How wide the text and the timetable run, in points.
WIDTH = 483.0

# Where the baseline of a page's heading sits, in points up from the foot of the sheet.
HEAD_TOP = 790.0

# The size a page's heading is set at, in points.
HEADING = 16.0

# The size the lines under a heading and under a table are set at, in points.
BODY = 9.5

# How far below one line the next one sits, in points.
LINE_STEP = 13.0

# The size the cells are set at, in points.
CELL = 9.0

# Where the timetable's top edge sits, in points up from the foot of the sheet.
TABLE_TOP = 735.0

# How far down the page the timetable may reach, in points.
TABLE_ROOM = 330.0

# How far under the timetable its caption stands, in points.
CAPTION_GAP = 5.0

# The colour every cell's outline is drawn in.
MAGENTA = hqf_pdf.Rgb(0.85, 0.0, 0.6)

# The departure times of the timetable's five rows, which read the same in every
# language.
TIMES = ("07:40", "07:52", "08:05", "08:07", "08:20")

# The line numbers of the timetable's five rows.
LINES = ("12", "12", "12", "31", "31")

# The platforms of the shrunk table's five rows.
PLATFORMS = ("1", "2", "1", "3", "2")

# The box the shrunk table is shrunk into.
SHRUNK_AREA = hqf_pdf.Rect(MARGIN, 60.0, 230.0, 68.0)

# The smallest factor the shrunk table may be scaled down to.
SHRUNK_FLOOR = 0.4

# How tall each row of the notice's table is but the last, in points.
NOTICE_ROW = 40.0

# How far a cell's text is kept from its edges, in points.
PADDING = 2.5

# How far down the page the notice's table may run, in points.
NOTICE_ROOM = 600.0


@dataclass(frozen=True)
class Words:
    """Every word the pages say, in one language."""

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


# The pages in English.
ENGLISH = 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}",
    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.",
    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",
)

# The pages in French.
FRENCH = 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}"
    ),
    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.",
    resolved="Résolues seules, avant toute mesure des cellules : {widths} pt",
    tallest="La cellule la plus haute demande {needed} pt, sur {across} des colonnes",
)

# The pages in Dutch.
DUTCH = 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}",
    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.",
    resolved="Op zichzelf bepaald, voordat een cel gemeten wordt: {widths} pt",
    tallest="De hoogste cel vraagt {needed} pt, over {across} van de kolommen",
)

# The pages in Portuguese.
PORTUGUESE = 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}",
    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.",
    resolved="Resolvidas sozinhas, antes de medir qualquer célula: {widths} pt",
    tallest="A célula mais alta pede {needed} pt, sobre {across} das colunas",
)

# The pages in Italian.
ITALIAN = 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}",
    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.",
    resolved="Risolte da sole, prima di misurare qualsiasi cella: {widths} pt",
    tallest="La cella più alta chiede {needed} pt, su {across} delle colonne",
)

# The pages in Spanish.
SPANISH = 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}",
    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} % 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.",
    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",
)

# The pages in German.
GERMAN = 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}",
    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.",
    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",
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}

# The kinds of settling, in the order `Words.settled_names` names them.
SETTLED = (
    hqf_pdf.Settled.ThisCell,
    hqf_pdf.Settled.AnotherCell,
    hqf_pdf.Settled.RowFloor,
    hqf_pdf.Settled.FixedRow,
    hqf_pdf.Settled.SpanningCell,
    hqf_pdf.Settled.SharedRoom,
    hqf_pdf.Settled.SpannedRows,
)


def paragraph(content, marks, page, handle, size, at, line) -> hqf_pdf.StructElement:
    """Set `line` at `at` in `handle` at `size` points, as a paragraph of its own, and
    hand back the element standing for it."""
    mcid = marks.next_id()
    content.begin_tagged("P", mcid)
    content.draw_text(handle, size, at[0], at[1], line)
    content.end_marked()
    return hqf_pdf.StructElement("P", children=[(page, mcid)])


def heading(content, marks, page, handle, title) -> hqf_pdf.StructElement:
    """Set a page's heading `title`, and hand back the element standing for it."""
    mcid = marks.next_id()
    content.begin_tagged("H1", mcid)
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, title)
    content.end_marked()
    return hqf_pdf.StructElement("H1", children=[(page, mcid)])


def cell(handle, text, **settings) -> hqf_pdf.Cell:
    """A cell holding `text`, set at the cells' size."""
    return hqf_pdf.Cell(
        handle, CELL, text, padding=hqf_pdf.Padding.uniform(PADDING), **settings
    )


def sign() -> hqf_pdf.Drawing:
    """A small drawing of a bus-stop sign: a pole under a disc."""
    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.12, 0.35, 0.65))
    content.rect(8.5, 0.0, 1.0, 12.0)
    content.fill()
    content.circle(9.0, 14.0, 5.0)
    content.fill()
    return hqf_pdf.Drawing(content, hqf_pdf.Rect(0.0, 0.0, 18.0, 19.0))


def rule_stroke(width: float) -> hqf_pdf.Stroke:
    """A grey line of `width` points, drawn between the cells."""
    return hqf_pdf.Stroke(width, color=hqf_pdf.Rgb.gray(0.6))


def black(width: float) -> hqf_pdf.Stroke:
    """A black line of `width` points."""
    return hqf_pdf.Stroke(width)


def timetable(handle, words, stop_sign, logo, heading_fill) -> hqf_pdf.Table:
    """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."""
    width = hqf_pdf.ColumnWidth
    table = hqf_pdf.Table(
        hqf_pdf.Columns(
            [
                width.longest_word(),
                width.points(40.0),
                width.fraction(1.0),
                width.content(),
            ],
            WIDTH,
        )
    )
    table.header(1)
    table.footer(1)
    table.header_links(hqf_pdf.HeaderLinks.Always)
    table.caption_below(
        hqf_pdf.TextFlow(handle, BODY), words.caption, gap=CAPTION_GAP
    )
    area = hqf_pdf.Area
    table.fill(area.whole(), hqf_pdf.Rgb(0.99, 0.99, 0.97))
    table.fill(area.odd_rows(), hqf_pdf.Rgb.gray(0.95))
    table.fill(area.column(0), hqf_pdf.Rgb(0.95, 0.97, 1.0))
    table.fill(area.column_from_end(0), hqf_pdf.Rgb(1.0, 0.97, 0.9))
    table.fill(area.row_from_end(1), hqf_pdf.Rgb(0.96, 1.0, 0.95))
    table.fill(area.header(), heading_fill)
    table.fill(area.footer(), hqf_pdf.Rgb.gray(0.92))
    rule = hqf_pdf.Rule
    table.rule(rule.frame(), black(0.8))
    table.rule(rule.horizontal_other(), rule_stroke(0.25))
    table.rule(rule.vertical_other(), rule_stroke(0.25))
    table.rule(rule.vertical_from_end(1), black(0.8))

    column, row = hqf_pdf.Scope.Column, hqf_pdf.Scope.Row
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, text, character_spacing=0.8, heading=column)
                for text in words.headings
            ]
        )
    )
    harbour, market, square, university = words.stops
    boarding, tram, school = words.remarks
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, harbour, heading=row),
                cell(handle, LINES[0]),
                cell(handle, boarding),
                cell(handle, TIMES[0]),
            ]
        )
    )
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, market, heading=row),
                cell(handle, LINES[1]),
                hqf_pdf.Cell.drawing(
                    stop_sign, alt=words.sign_alt, padding=hqf_pdf.Padding.uniform(PADDING)
                ),
                cell(handle, TIMES[1]),
            ],
            min_height=26.0,
        )
    )
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, square, heading=row, span_rows=2),
                cell(handle, LINES[2]),
                cell(handle, tram),
                cell(handle, TIMES[2]),
            ]
        )
    )
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, LINES[3]),
                hqf_pdf.Cell.image(
                    logo, alt=words.logo_alt, padding=hqf_pdf.Padding.uniform(PADDING)
                ),
                cell(handle, TIMES[3]),
            ]
        )
    )
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, university, heading=row),
                cell(handle, LINES[4]),
                cell(handle, school, horizontal_scaling=80.0),
                cell(handle, TIMES[4]),
            ],
            fixed_height=(14.0, 6.0),
        )
    )
    table.push(hqf_pdf.Row(cells=[cell(handle, words.foot, span=4)]))
    return table


def settled_lines(reports, words) -> list[str]:
    """The lines that count the cells of `reports` by what settled their height, one
    line for each kind that settled at least one."""
    counts = [0] * len(SETTLED)
    for report in reports:
        counts[SETTLED.index(report.settled)] += 1
    return [
        words.settled.replace("{what}", what).replace("{cells}", str(count))
        for count, what in zip(counts, words.settled_names)
        if count > 0
    ]


def summary(table, placed, words) -> list[str]:
    """What the placed timetable says of itself, one line each."""
    widths = [
        f"{placed.column_width(column):.0f}" for column in range(placed.column_count)
    ]
    shape = (
        words.shape.replace("{count}", str(placed.column_count))
        .replace("{width}", f"{placed.width:.0f}")
        .replace("{widths}", " + ".join(widths))
    )

    columns = table.columns
    picture = table.cell_column(4, 1) or 0
    span = words.span.replace(
        "{span}", f"{columns.span_width(len(columns) - 2, 2):.0f}"
    ).replace("{place}", str(picture + 1))

    roles = [0, 0, 0]
    for index in range(placed.row_count):
        role = placed.row_role(index)
        if role == hqf_pdf.RowRole.Header:
            roles[0] += 1
        elif role == hqf_pdf.RowRole.Body:
            roles[1] += 1
        elif role == hqf_pdf.RowRole.Footer:
            roles[2] += 1
    counted = (
        words.roles.replace("{heads}", str(roles[0]))
        .replace("{bodies}", str(roles[1]))
        .replace("{feet}", str(roles[2]))
    )

    reports = placed.cell_reports()
    held = [0, 0, 0]
    for report in reports:
        if report.holds == hqf_pdf.Holds.Text:
            held[0] += 1
        elif report.holds == hqf_pdf.Holds.Picture:
            held[1] += 1
        elif report.holds == hqf_pdf.Holds.Form:
            held[2] += 1
    holds = (
        words.holds.replace("{texts}", str(held[0]))
        .replace("{pictures}", str(held[1]))
        .replace("{drawings}", str(held[2]))
    )

    alone = [f"{width:.0f}" for width in columns.resolved()]
    resolved = words.resolved.replace("{widths}", " + ".join(alone))

    tallest = None
    for report in reports:
        if tallest is None or report.needed > tallest.needed:
            tallest = report

    lines = [shape, span, counted, holds, resolved]
    if tallest is not None:
        lines.append(
            words.tallest.replace("{needed}", f"{tallest.needed:.0f}").replace(
                "{across}", str(len(tallest.widths))
            )
        )
    return [*lines, *settled_lines(reports, words)]


def dashed_guides() -> hqf_pdf.Guides:
    """Guides drawn as a blue dashed line."""
    return hqf_pdf.Guides(
        hqf_pdf.Stroke(
            0.6,
            color=hqf_pdf.Rgb(0.0, 0.45, 0.85),
            style=hqf_pdf.LineStyle(dash=hqf_pdf.Dash.on_off(3.0, 2.0)),
        )
    )


def outline(content, table, placed, room) -> None:
    """Outline 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`."""
    content.begin_artifact(hqf_pdf.Artifact.Layout)
    cells = hqf_pdf.Guides.hairline(MAGENTA)
    cells.outline_all(content, placed.cell_boxes())

    dashed = dashed_guides()
    caption = placed.caption_box()
    # The rows' own box: `box` runs over the caption too, which stands under the rows
    # with its gap between them.
    rows = placed.box
    if caption is not None:
        foot = caption.y + caption.height + CAPTION_GAP
        rows = hqf_pdf.Rect(rows.x, foot, rows.width, placed.top - foot)
    dashed.outline(content, rows)
    if caption is not None:
        dashed.outline(content, caption)

    # Five times the hairline's quarter of a point.
    heavy = hqf_pdf.Guides(hqf_pdf.Stroke(0.25 * 5.0, color=MAGENTA))
    column = table.cell_column(4, 1) or 0
    box = placed.cell_box(4, column)
    if box is not None:
        heavy.outline(content, box)

    crosses = hqf_pdf.Guides.hairline(hqf_pdf.Rgb(0.0, 0.6, 0.2))
    for line in range(placed.column_count + 1):
        crosses.cross(content, placed.column_x(line), placed.top, 4.0)

    step = max(room.height / hqf_pdf.Guides.MOST_LINES, 12.0)
    grid = hqf_pdf.Guides.hairline(hqf_pdf.Rgb.gray(0.8))
    grid.grid(content, room, (step, step))
    grid.outline(content, room)
    content.end_marked()


def first_page(handle, words, stop_sign, logo, heading_fill):
    """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."""
    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    said = [heading(content, marks, 0, handle, words.title)]
    y = HEAD_TOP - 22.0
    for line in words.intro:
        said.append(paragraph(content, marks, 0, handle, BODY, (MARGIN, y), line))
        y -= LINE_STEP

    table = timetable(handle, words, stop_sign, logo, heading_fill)
    placed = table.fit(MARGIN, TABLE_TOP, TABLE_ROOM, 0)
    said.append(placed.draw_tagged(content, 0, marks))

    caption = placed.caption_box()
    y = (placed.bottom if caption is None else caption.y) - 20.0
    # The caption is set under the table.
    side = words.sides[1]
    lines = [] if placed.row_count == 0 else summary(table, placed, words)
    lines.append(words.caption_side.replace("{side}", side))
    lines.append(words.notes)
    for line in lines:
        said.append(paragraph(content, marks, 0, handle, BODY, (MARGIN, y), line))
        y -= LINE_STEP

    # The room left under the last line, down to the foot margin.
    under = y + LINE_STEP - 8.0
    room = hqf_pdf.Rect(MARGIN, 60.0, WIDTH, under - 60.0)
    outline(content, table, placed, room)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    reports = placed.cell_reports()
    for report in reports:
        page.add_annotation(report.note())
    # The picture's cell, in the words the library reports it in.
    column = table.cell_column(4, 1) or 0
    for report in reports:
        if report.row == 4 and report.column == column:
            print(report.describe())
            break
    return page, said


def damaged(handle, words) -> hqf_pdf.Table:
    """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."""
    table = hqf_pdf.Table(hqf_pdf.Columns.equal(3, 230.0))
    table.draw_damaged(True)
    table.header_links(hqf_pdf.HeaderLinks.Never)
    table.rule(hqf_pdf.Rule.frame(), black(0.6))
    table.rule(hqf_pdf.Rule.horizontal_other(), rule_stroke(0.25))
    table.rule(hqf_pdf.Rule.vertical_other(), rule_stroke(0.25))
    monday, closed, tuesday, line, diverted = words.damaged
    table.push(hqf_pdf.Row(cells=[cell(handle, monday), cell(handle, closed)]))
    table.push(
        hqf_pdf.Row(
            cells=[cell(handle, tuesday), cell(handle, line), cell(handle, diverted)]
        )
    )
    return table


def split(handle, words) -> hqf_pdf.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."""
    width = hqf_pdf.ColumnWidth
    table = hqf_pdf.Table(
        hqf_pdf.Columns([width.points(60.0), width.fraction(1.0)], 230.0)
    )
    table.split_rows(True)
    table.caption_above(
        hqf_pdf.TextFlow(handle, BODY),
        words.split_caption,
        gap=4.0,
        first_box_only=True,
    )
    table.rule(hqf_pdf.Rule.frame(), black(0.6))
    table.rule(hqf_pdf.Rule.vertical_other(), rule_stroke(0.25))
    remark, text = words.split
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, remark, heading=hqf_pdf.Scope.Row),
                cell(handle, text, keep_lines=3),
            ]
        )
    )
    return table


def shared(handle, words) -> hqf_pdf.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."""
    table = hqf_pdf.Table(hqf_pdf.Columns.equal(2, 230.0))
    table.fill_frame(True)
    table.header_links(hqf_pdf.HeaderLinks.Deduced)
    table.rule(hqf_pdf.Rule.frame(), black(0.6))
    table.rule(hqf_pdf.Rule.horizontal_other(), rule_stroke(0.25))
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Rgb.gray(0.95))
    cells = words.shared
    for index in range(0, len(cells), 2):
        day, time = cells[index : index + 2]
        table.push(hqf_pdf.Row(cells=[cell(handle, day), cell(handle, "")]))
        table.cell_field(
            index // 2,
            1,
            hqf_pdf.TextField(
                f"departure_{index // 2 + 1}",
                0.0,
                0.0,
                0.0,
                0.0,
                handle,
                BODY,
                value=time,
                frame=hqf_pdf.FieldBorder.solid(hqf_pdf.Rgb.gray(0.45), 0.6),
            ),
        )
    return table


def shrunk(handle, words) -> hqf_pdf.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."""
    width = hqf_pdf.ColumnWidth.points(160.0)
    table = hqf_pdf.Table(hqf_pdf.Columns([width, width, width], 480.0))
    table.header(1)
    table.rule(hqf_pdf.Rule.frame(), black(0.6))
    table.rule(hqf_pdf.Rule.horizontal_other(), rule_stroke(0.25))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Rgb.gray(0.9))
    table.push(hqf_pdf.Row(cells=[cell(handle, text) for text in words.shrunk]))
    for time, line, platform in zip(TIMES, LINES, PLATFORMS):
        table.push(
            hqf_pdf.Row(
                cells=[cell(handle, time), cell(handle, line), cell(handle, platform)]
            )
        )
    return table


def faults(content, marks, handle, words) -> list[hqf_pdf.StructElement]:
    """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."""
    said = []
    frames = dashed_guides()
    table = damaged(handle, words)
    first = table.fit(MARGIN, 750.0, 60.0, 0)
    next_row = first.next_row if first.next_row is not None else 1
    second = table.fit(MARGIN + 253.0, 750.0, 40.0, next_row)
    found = []
    described = hqf_pdf.TaggedTable("damaged")
    for placed in (first, second):
        described.add(placed, content, 1, marks)
        found.extend(placed.damage())
    said.append(described.finish())
    content.begin_artifact(hqf_pdf.Artifact.Layout)
    frames.outline(content, hqf_pdf.Rect(MARGIN, 690.0, 230.0, 60.0))
    frames.outline(content, hqf_pdf.Rect(MARGIN + 253.0, 710.0, 230.0, 40.0))
    content.end_marked()

    y = 580.0
    for fault in found:
        if fault.past_the_box:
            line = words.past_the_box.replace("{row}", str(fault.row))
        else:
            line = (
                words.other_width.replace("{row}", str(fault.row))
                .replace("{covered}", str(fault.covered))
                .replace("{columns}", str(fault.columns))
            )
        said.append(paragraph(content, marks, 1, handle, BODY, (MARGIN, y), line))
        y -= LINE_STEP
    return said


def shrunk_into_its_box(content, marks, handle, words) -> list[hqf_pdf.StructElement]:
    """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."""
    said = [
        paragraph(content, marks, 1, handle, BODY, (MARGIN, 140.0), words.shrunk_title)
    ]
    placed = shrunk(handle, words).shrink_into(SHRUNK_AREA, SHRUNK_FLOOR)
    described = hqf_pdf.TaggedTable("shrunk")
    described.add(placed, content, 1, marks)
    said.append(described.finish())
    content.begin_artifact(hqf_pdf.Artifact.Layout)
    dashed_guides().outline(content, SHRUNK_AREA)
    content.end_marked()
    line = words.shrunk_said.replace("{percent}", f"{placed.scale * 100.0:.0f}")
    said.append(
        paragraph(content, marks, 1, handle, BODY, (MARGIN + 253.0, 110.0), line)
    )
    return said


def second_page(handle, words):
    """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."""
    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    said = [heading(content, marks, 1, handle, words.more_title)]
    said.append(
        paragraph(
            content,
            marks,
            1,
            handle,
            BODY,
            (MARGIN, HEAD_TOP - 24.0),
            words.damaged_title,
        )
    )

    said.extend(faults(content, marks, handle, words))

    placements = split(handle, words).paginate(
        hqf_pdf.TableFrame(MARGIN, 530.0, 90.0),
        hqf_pdf.TableFrame(MARGIN + 253.0, 530.0, 150.0),
    )
    division = marks.next_id()
    content.begin_tagged("Div", division)
    for placed in placements:
        placed.draw(content)
    content.end_marked()
    said.append(hqf_pdf.StructElement("Div", children=[(1, division)]))
    line = words.split_said.replace("{boxes}", str(len(placements)))
    said.append(paragraph(content, marks, 1, handle, BODY, (MARGIN, 360.0), line))

    said.append(
        paragraph(content, marks, 1, handle, BODY, (MARGIN, 320.0), words.shared_title)
    )
    table = shared(handle, words)
    placed = table.fit(MARGIN, 305.0, 110.0, 0)
    described = hqf_pdf.TaggedTable("shared")
    described.add(placed, content, 1, marks)
    said.append(described.finish())
    fields = table.fields(placed)
    y = 175.0
    for line in settled_lines(placed.cell_reports(), words):
        said.append(paragraph(content, marks, 1, handle, BODY, (MARGIN, y), line))
        y -= LINE_STEP

    said.extend(shrunk_into_its_box(content, marks, handle, words))

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    for field in fields:
        page.add_field(field)
    return page, said


def notice(handle, words) -> hqf_pdf.Table:
    """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."""
    width = hqf_pdf.ColumnWidth
    table = hqf_pdf.Table(
        hqf_pdf.Columns(
            [width.longest_word(), width.fraction(1.0), width.points(44.0)], WIDTH
        )
    )
    table.header(1)
    table.header_links(hqf_pdf.HeaderLinks.Always)
    rule = hqf_pdf.Rule
    table.rule(rule.frame(), black(0.8))
    table.rule(rule.horizontal_other(), rule_stroke(0.25))
    table.rule(rule.vertical_other(), rule_stroke(0.25))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Rgb.gray(0.9))
    table.fill(hqf_pdf.Area.column(1), hqf_pdf.Rgb(1.0, 0.98, 0.9))
    column, row = hqf_pdf.Scope.Column, hqf_pdf.Scope.Row
    table.push(
        hqf_pdf.Row(
            cells=[
                cell(handle, words.headings[0], heading=column),
                cell(handle, words.notice_head, heading=column),
                cell(handle, words.headings[3], heading=column),
            ]
        )
    )
    thread = hqf_pdf.Thread(words.notice, hqf_pdf.TextFlow(handle, CELL))
    last = len(words.stops) - 1
    for index, (stop, time) in enumerate(zip(words.stops, TIMES)):
        table.push(
            hqf_pdf.Row(
                cells=[
                    cell(handle, stop, heading=row),
                    hqf_pdf.Cell.threaded(
                        thread, padding=hqf_pdf.Padding.uniform(PADDING)
                    ),
                    cell(handle, time),
                ],
                min_height=0.0 if index == last else NOTICE_ROW,
            )
        )
    return table


def two_columns(handle, words) -> hqf_pdf.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."""
    table = hqf_pdf.Table(hqf_pdf.Columns.equal(2, WIDTH))
    table.rule(hqf_pdf.Rule.frame(), black(0.8))
    table.rule(hqf_pdf.Rule.vertical_other(), rule_stroke(0.25))
    table.fill(hqf_pdf.Area.whole(), hqf_pdf.Rgb(1.0, 0.98, 0.9))
    flow = hqf_pdf.TextFlow(handle, CELL)
    lines = flow.break_lines(words.notice, WIDTH / 2.0 - PADDING - PADDING)
    half = (len(lines) + 1) // 2
    tall = (
        flow.height(lines.sub(0, half))
        + flow.height(lines.sub(0, min(half + 1, len(lines))))
    ) / 2.0
    thread = hqf_pdf.Thread(words.notice, flow)
    padding = hqf_pdf.Padding.uniform(PADDING)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell.threaded(thread, padding=padding),
                hqf_pdf.Cell.threaded(thread, padding=padding),
            ],
            min_height=tall + PADDING + PADDING,
        )
    )
    return table


def third_page(handle, words):
    """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."""
    content = hqf_pdf.Content()
    marks = hqf_pdf.Marks()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    said = [heading(content, marks, 2, handle, words.notice_title)]
    y = HEAD_TOP - 24.0
    for line in words.notice_intro:
        said.append(paragraph(content, marks, 2, handle, BODY, (MARGIN, y), line))
        y -= LINE_STEP

    placed = notice(handle, words).fit(MARGIN, TABLE_TOP, NOTICE_ROOM, 0)
    if not placed.done:
        raise SystemExit("the notice's table does not fit its page")
    described = hqf_pdf.TaggedTable("notice")
    described.add(placed, content, 2, marks)
    said.append(described.finish())

    y = placed.bottom - LINE_STEP - LINE_STEP
    said.append(
        paragraph(content, marks, 2, handle, BODY, (MARGIN, y), words.columns_said)
    )
    placed = two_columns(handle, words).fit(MARGIN, y - 10.0, y - 10.0 - 56.0, 0)
    if not placed.done:
        raise SystemExit("the notice's two columns do not fit their page")
    described = hqf_pdf.TaggedTable("columns")
    described.add(placed, content, 2, marks)
    said.append(described.finish())

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page, said


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("table_report.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", words.title)
    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    stop_sign = document.add_drawing(sign())
    logo = document.add_image(hqf_pdf.Image.from_path(PICTURE))

    # The heading row's background is one fade stated across the unit square and
    # stretched onto each heading cell, whatever its width.
    heading_fill = hqf_pdf.Paint.fitted(
        document.add_shading(
            hqf_pdf.Axial.rgb(
                (0.0, 0.0), (1.0, 0.0), hqf_pdf.Rgb.gray(0.93), hqf_pdf.Rgb.gray(0.76)
            )
        )
    )
    page, said = first_page(handle, words, stop_sign, logo, heading_fill)
    document.add_page(page)
    page, more = second_page(handle, words)
    document.add_page(page)
    said.extend(more)
    page, more = third_page(handle, words)
    document.add_page(page)
    said.extend(more)

    document.set_structure(
        hqf_pdf.StructureTree(
            children=[hqf_pdf.StructElement("Document", children=said)],
            lang=words.lang,
        )
    )

    written = document.write(out)
    print(f"wrote {out} ({written} bytes)")


if __name__ == "__main__":
    main()
