"""Inks the press carries on plates of their own, at every tint.

The Python twin of the `write_spot_color` example in Rust. A spot colour is not
mixed out of the process inks: it is an ink of its own, and a colour in its space
is one number — how much of it goes down. What that number looks like where the
ink is not to hand, on a screen or on a press that does not carry it, is what the
tint transform says.

The second page sets a run list in those same two inks and in nothing else: the
heading on a full-strength plate, every other line on a tint of it, the total on
the second ink, the rules in both, and a closing paragraph whose runs each name
an ink. Everything that paints takes a colour the document carries exactly where
it takes a device one — a cell's background, a cell's text, a row, a table's
rules, a run of styled text, a stamp.

The third and fourth pages are the first sheet separated: one page per plate, each
painting the tints of its own ink and saying which ink it is and which sheet it belongs
to, the blue plate also naming the space its tints are read through.

What the two sheets say is written in the language `HQF_PDF_LANG` names. The names
of the inks are not: a colorant is what the plate answers to, the file writes it,
and a page that renamed it would name a plate the press has not got. Neither are
the sheet counts, the prices or the tints.

Usage: python examples/write_spot_color.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_spot_color.py
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge of everything, and the width of the sheet the page shows.
LEFT = 70.0
WIDTH = 445.0

# The left edge of each tint swatch, and the size of one.
TINT_X = (70.0, 115.0, 160.0, 205.0, 250.0, 295.0, 340.0, 385.0, 430.0, 475.0)
TINT_SIZE = (40.0, 56.0)

# The top of the run list on the second page.
LIST_TOP = 700.0

# Where the head of a sheet sits, and where the two lines under it do.
HEAD_BASELINE = 780.0
LEAD_BASELINES = (762.0, 748.0)

# Where the rule at the foot of the second sheet is drawn.
CLOSING_RULE = 92.0

# The size the closing paragraph is set at, and how far apart its lines sit.
PROSE_SIZE = 10.5
PROSE_LEADING = 15.0

# The two inks the work is set in, and the colorant every plate answers to. A colorant
# is what the plate is called on the press: the file writes it, and no language renames
# it.
BLUE = "Corporate Blue"
GOLD = "Corporate Gold"
ALL_PLATES = "All"

# The tint the panel behind the heading is laid at, which the caption under it spells
# out in words.
PANEL_TINT = 0.15

# The tint the shaded lines of the run list are laid at, which the note under it spells
# out in words.
SHADED_TINT = 0.08

# The strength the closing paragraph is drawn at, which it says of itself.
PROSE_TINT = 0.9

# The sizes the two sheets are set in, in points.
HEAD_SIZE = 15.0
LEAD_SIZE = 10.0
SWATCH_SIZE = 7.0
CAPTION_SIZE = 10.0
SHEET_TITLE_SIZE = 26.0
SHEET_LINE_SIZE = 11.0
MARK_SIZE = 9.0
CELL_SIZE = 9.0
TOTAL_SIZE = 9.5
CLOSING_SIZE = 8.5

# The ten tints each ink is shown at. What each is called is read off the tint itself,
# so no language can label a swatch with a strength it is not laid at.
TINTS = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)

# What the nine lines come to.
TOTAL = "3 061.00"


def crosshairs(bottom: float, height: float) -> tuple[tuple[float, float], ...]:
    """Where the crosshairs stand around a sheet whose foot is at `bottom` and which is
    `height` tall.

    A page says how many there are, so the count and the word have to agree.
    """
    return (
        (LEFT - 16.0, bottom - 16.0),
        (LEFT + WIDTH + 16.0, bottom - 16.0),
        (LEFT - 16.0, bottom + height + 16.0),
        (LEFT + WIDTH + 16.0, bottom + height + 16.0),
    )


def tint_name(tint: float) -> str:
    """What one tint is called under its swatch."""
    return f"{tint * 100.0:.0f}%"


class Plates(Enum):
    """Which plates a line of the run list takes."""

    FIRST = 0
    SECOND = 1
    BOTH = 2

    def named(self, words: Words) -> str:
        """What this run of plates is called, in the words of a language."""
        return words.plates[self.value]


# One line of the run list: how many sheets it runs to, which plates it takes and what
# it comes to. What is being printed is a word, and it lives with the other words of its
# language.
ITEMS = (
    ("5 000", Plates.FIRST, "412.00"),
    ("2 000", Plates.FIRST, "196.00"),
    ("2 000", Plates.BOTH, "268.00"),
    ("3 000", Plates.SECOND, "184.00"),
    ("1 000", Plates.BOTH, "590.00"),
    ("750", Plates.BOTH, "445.00"),
    ("5 000", Plates.FIRST, "388.00"),
    ("1 500", Plates.FIRST, "242.00"),
    ("12", Plates.BOTH, "336.00"),
)


@dataclass(frozen=True)
class Words:
    """The words the two sheets are written in, one set per language.

    The names of the inks are not among them, nor the sheet counts, the prices or the
    tints.
    """

    # What the first sheet is called.
    title: str
    # The two lines under it, which say what a spot colour is.
    lead: tuple[str, ...]
    # What stands after the name of the first ink over its ramp of tints.
    first_ramp: str
    # What stands after the name of the second over its own.
    second_ramp: str
    # What stands after the name of an ink over its ramp on its own plate.
    plate: str
    # What the piece of work set in the two inks is called.
    sheet_title: str
    # The line inside it, which says what is laid over what.
    sheet_line: str
    # The line under it, which says what the crosshairs are for.
    marks: str
    # What the second sheet is called.
    list_title: str
    # The two lines under it, which say how far a carried colour reaches.
    list_lead: tuple[str, ...]
    # What heads each column of the run list, left to right.
    headings: tuple[str, ...]
    # What each line of the run list is printing, in the order `ITEMS` runs them.
    items: tuple[str, ...]
    # What each run of plates is called: the first alone, the second alone, then both.
    plates: tuple[str, ...]
    # What the last row of the run list is called.
    total: str
    # The three runs of the note under the list, the middle one of which is set in the
    # second ink.
    note: tuple[str, ...]
    # The paragraph under it, drawn in one flow.
    prose: str
    # The mark laid across the whole of the run list.
    stamp: str
    # What stands before the name of the first ink in the closing line.
    quoted_before: str
    # What stands between the two names.
    quoted_between: str
    # What stands after the second.
    quoted_after: str


# The two sheets in English.
ENGLISH = Words(
    title="Inks the press carries, on plates of their own",
    lead=(
        "A spot colour is one number, not four: how much of that ink goes down. "
        "Where the ink is not",
        "to hand, the tint transform the file carries shows it — which is what "
        "these swatches are.",
    ),
    first_ramp=", one plate, ten tints",
    second_ramp=", a second plate",
    plate=", sheet 1 separated: this page is the plate of that ink",
    sheet_title="Two inks, one sheet",
    sheet_line="Set in the second ink, over a fifteen percent tint of the first.",
    marks="The four crosshairs are set in the colorant every plate answers to, "
    "which is what lines them up.",
    list_title="The same two inks, through the layout",
    list_lead=(
        "A colour the document carries reaches a cell, a row, a rule and a run "
        "of styled text the",
        "way a colour the device answers for does. Not a drop of process ink "
        "goes down below.",
    ),
    headings=("Item", "Sheets", "Plates", "Price"),
    items=(
        "Letterhead, A4",
        "Letterhead, A5",
        "Business cards, both sides",
        "Compliments slip",
        "Presentation folder",
        "Report cover, laminated",
        "Window envelope, DL",
        "Wallet envelope, C4",
        "Exhibition panel",
    ),
    plates=("First", "Second", "Both"),
    total="Total, nine items, two plates",
    note=(
        "The heading stands on a full plate of the first ink, ",
        "the total on the second",
        ", and the shaded lines on an eight percent tint of the first. One run "
        "of this sentence is set in each of the two.",
    ),
    prose="An ink of its own is what a house colour is bought as: the press "
    "carries it on a plate of its own, so it goes down at the same strength on "
    "every sheet of every run, which four process inks laid over each other "
    "cannot promise. It costs a plate, so it is spent on the marks a reader "
    "recognises the house by — the name, the rule under it, the panel behind a "
    "heading — and the rest of the work is left to the process inks. This "
    "paragraph is one flow of text, drawn in the first ink at ninety percent, "
    "and the words of it were measured and broken to the width of the list "
    "above.",
    stamp="SPECIMEN",
    quoted_before="Quoted in two inks: ",
    quoted_between=" and ",
    quoted_after=", each on a plate of its own.",
)

# The two sheets in French.
FRENCH = Words(
    title="Des encres en machine, chacune sur sa propre plaque",
    lead=(
        ("Un ton direct est un seul nombre, pas quatre : la quantité d’encre déposée. "
         "Là où l’encre"),
        ("manque, la transformation de teinte que contient le fichier la simule : ce "
         "sont ces pastilles."),
    ),
    first_ramp=", une plaque, dix teintes",
    second_ramp=", une seconde plaque",
    plate=", feuille 1 séparée : cette page est la plaque de cette encre",
    sheet_title="Deux encres, une feuille",
    sheet_line="Seconde encre, sur une teinte à quinze pour cent de la première.",
    marks=(("Les croix, en couleur de repérage, s’impriment sur chaque plaque : c’est "
            "ce qui les cale.")),
    list_title="Les deux mêmes encres, dans toute la mise en page",
    list_lead=(
        ("Une couleur définie par le document s’applique à une cellule, une ligne, un "
         "filet, un texte"),
        ("mis en forme, comme une couleur d’appareil. Ci-dessous, pas une goutte de "
         "quadrichromie."),
    ),
    headings=("Article", "Feuilles", "Plaques", "Prix"),
    items=(
        "Papier à en-tête, A4",
        "Papier à en-tête, A5",
        "Cartes de visite, recto verso",
        "Carte de correspondance",
        "Chemise de présentation",
        "Couverture de rapport, pelliculée",
        "Enveloppe à fenêtre, DL",
        "Enveloppe à poche, C4",
        "Panneau d’exposition",
    ),
    plates=("Première", "Seconde", "Les deux"),
    total="Total, neuf articles, deux plaques",
    note=(
        "Le titre repose sur un aplat de la première encre, ",
        "le total sur la seconde",
        (", et les lignes ombrées sur une teinte à huit pour cent de la première. Un "
         "passage de cette phrase est composé dans chacune des deux."),
    ),
    prose=("Une encre à soi, voilà ce qu’on achète avec une couleur maison : la presse"
           " l’imprime sur sa propre plaque, et elle se dépose avec la même intensité "
           "sur chaque feuille de chaque tirage, ce que quatre encres de quadrichromie"
           " superposées ne peuvent pas garantir. Elle coûte une plaque : on la "
           "réserve donc aux signes auxquels un lecteur reconnaît la maison — le nom, "
           "le filet dessous, l’aplat derrière un titre — et on laisse le reste du "
           "travail aux encres de quadrichromie. Ce paragraphe est une seule coulée de"
           " texte, imprimée dans la première encre à quatre-vingt-dix pour cent, et "
           "ses mots ont été mesurés et coupés à la largeur de la liste ci-dessus."),
    stamp="SPÉCIMEN",
    quoted_before="Chiffré en deux encres : ",
    quoted_between=" et ",
    quoted_after=", chacune sur sa plaque.",
)

# The two sheets in Dutch.
DUTCH = Words(
    title="Inkten die de pers meeneemt, op eigen platen",
    lead=(
        "Een steunkleur is één getal, geen vier: hoeveel van die inkt er neerkomt. "
        "Waar de inkt",
        "ontbreekt, toont de tintomzetting in het bestand haar, en dat zijn deze "
        "stalen.",
    ),
    first_ramp=", één plaat, tien tinten",
    second_ramp=", een tweede plaat",
    plate=", blad 1 gescheiden: deze pagina is de plaat van die inkt",
    sheet_title="Twee inkten, één blad",
    sheet_line="Gezet in de tweede inkt, over een tint van vijftien procent van de eerste.",
    marks="De vier paskruisen staan in de pasmerkkleur, die op elke plaat drukt, en "
          "daardoor lijnen ze uit.",
    list_title="Dezelfde twee inkten, via de opmaak",
    list_lead=(
        "Een kleur die in het document zit, bereikt een cel, een rij, een lijn en een "
        "stuk opgemaakte tekst",
        "zoals een kleur waar het apparaat voor instaat. Hieronder komt geen druppel "
        "procesinkt neer.",
    ),
    headings=("Artikel", "Bladen", "Platen", "Prijs"),
    items=(
        "Briefpapier, A4",
        "Briefpapier, A5",
        "Visitekaartjes, beide zijden",
        "Complimentkaart",
        "Presentatiemap",
        "Rapportomslag, gelamineerd",
        "Vensterenvelop, DL",
        "Akte-envelop, C4",
        "Beurspaneel",
    ),
    plates=("Eerste", "Tweede", "Beide"),
    total="Totaal, negen artikelen, twee platen",
    note=(
        "De kop staat op een volle plaat van de eerste inkt,",
        "het totaal op de tweede",
        ", en de gearceerde regels op een tint van acht procent van de eerste. Een "
        "stuk van deze zin staat in elk van beide.",
    ),
    prose="Een eigen inkt is hoe een huiskleur wordt ingekocht: de pers drukt haar "
          "met een eigen plaat, dus komt ze met dezelfde sterkte op elk blad van elke "
          "oplage, wat vier over elkaar gelegde procesinkten niet kunnen beloven. Ze "
          "kost een plaat, dus wordt ze besteed aan de tekens waaraan een lezer het "
          "huis herkent (de naam, de lijn eronder, het vlak achter een kop) en de "
          "rest van het werk blijft voor de procesinkten. Deze alinea is één "
          "tekststroom, getekend in de eerste inkt op negentig procent, en haar "
          "woorden zijn gemeten en afgebroken op de breedte van de lijst hierboven.",
    stamp="SPECIMEN",
    quoted_before="Geoffreerd in twee inkten:",
    quoted_between=" en",
    quoted_after=", elk op een eigen plaat.",
)

# The two sheets in Portuguese.
PORTUGUESE = Words(
    title="Tintas que a máquina leva, em chapas próprias",
    lead=(
        "Uma cor direta é um número, não quatro: quanta dessa tinta se põe. Onde a "
        "tinta não está",
        "à mão, a transformação de tom que o ficheiro leva mostra-a, e é isso que "
        "estas amostras são.",
    ),
    first_ramp=", uma chapa, dez tons",
    second_ramp=", uma segunda chapa",
    plate=", folha 1 separada: esta página é a chapa dessa tinta",
    sheet_title="Duas tintas, uma folha",
    sheet_line="Na segunda tinta, sobre um tom de quinze por cento da primeira.",
    marks="As quatro miras estão no colorante a que todas as chapas respondem, e é "
          "isso que as alinha.",
    list_title="As mesmas duas tintas, através da paginação",
    list_lead=(
        "Uma cor que o documento leva chega a uma célula, uma linha, um filete e um "
        "troço de texto com estilo",
        "tal como uma cor a que o dispositivo responde. Por baixo não cai uma gota de "
        "quadricromia.",
    ),
    headings=("Artigo", "Folhas", "Chapas", "Preço"),
    items=(
        "Papel timbrado, A4",
        "Papel timbrado, A5",
        "Cartões de visita, frente e verso",
        "Cartão de cumprimentos",
        "Pasta de apresentação",
        "Capa de relatório, plastificada",
        "Envelope de janela, DL",
        "Envelope saco, C4",
        "Painel de exposição",
    ),
    plates=("Primeira", "Segunda", "Ambas"),
    total="Total, nove artigos, duas chapas",
    note=(
        "O título assenta numa chapa cheia da primeira tinta,",
        "o total na segunda",
        ", e as linhas sombreadas num tom de oito por cento da primeira. Um troço "
        "desta frase está em cada uma das duas.",
    ),
    prose="Uma tinta própria é a forma de comprar uma cor da casa: a máquina leva-a "
          "numa chapa própria, por isso cai com a mesma intensidade em cada folha de "
          "cada tiragem, o que quatro tintas de quadricromia sobrepostas não podem "
          "prometer. Custa uma chapa, por isso gasta-se nos sinais pelos quais um "
          "leitor reconhece a casa (o nome, o filete por baixo, o painel atrás de um "
          "título) e o resto do trabalho fica para a quadricromia. Este parágrafo é "
          "um só texto, desenhado na primeira tinta a noventa por cento, e as suas "
          "palavras foram medidas e partidas à largura da lista acima.",
    stamp="ESPÉCIME",
    quoted_before="Orçamentado em duas tintas:",
    quoted_between=" e",
    quoted_after=", cada uma numa chapa própria.",
)

# The two sheets in Italian.
ITALIAN = Words(
    title="Inchiostri che porta la macchina, su lastre proprie",
    lead=(
        "Un colore spot è un numero, non quattro: quanto di quell’inchiostro si "
        "stende. Dove l’inchiostro non è",
        "a portata, la trasformazione di tinta che porta il file lo mostra, ed è ciò "
        "che sono questi campioni.",
    ),
    first_ramp=", una lastra, dieci tinte",
    second_ramp=", una seconda lastra",
    plate=", foglio 1 separato: questa pagina è la lastra di quell’inchiostro",
    sheet_title="Due inchiostri, un foglio",
    sheet_line="Nel secondo inchiostro, su una tinta al quindici per cento del primo.",
    marks="I quattro crocini sono nel colorante a cui rispondono tutte le lastre, ed "
          "è ciò che le allinea.",
    list_title="Gli stessi due inchiostri, attraverso l’impaginazione",
    list_lead=(
        "Un colore che porta il documento arriva a una cella, una riga, un filetto e "
        "un tratto di testo con stile",
        "come un colore di cui risponde il dispositivo. Sotto non cade una goccia di "
        "quadricromia.",
    ),
    headings=("Articolo", "Fogli", "Lastre", "Prezzo"),
    items=(
        "Carta intestata, A4",
        "Carta intestata, A5",
        "Biglietti da visita, fronte e retro",
        "Biglietto di cortesia",
        "Cartella di presentazione",
        "Copertina di rapporto, plastificata",
        "Busta a finestra, DL",
        "Busta a sacco, C4",
        "Pannello espositivo",
    ),
    plates=("Primo", "Secondo", "Entrambi"),
    total="Totale, nove articoli, due lastre",
    note=(
        "Il titolo sta su una lastra piena del primo inchiostro,",
        "il totale sul secondo",
        ", e le righe ombreggiate su una tinta all’otto per cento del primo. Un "
        "tratto di questa frase è in ciascuno dei due.",
    ),
    prose="Un inchiostro proprio è come si compra un colore aziendale: la macchina lo "
          "porta su una lastra propria, così si stende con la stessa intensità su "
          "ogni foglio di ogni tiratura, cosa che quattro inchiostri di quadricromia "
          "sovrapposti non possono promettere. Costa una lastra, quindi si spende sui "
          "segni da cui il lettore riconosce la casa (il nome, il filetto sotto, il "
          "pannello dietro un titolo) e il resto del lavoro va alla quadricromia. "
          "Questo paragrafo è un solo testo, disegnato nel primo inchiostro al "
          "novanta per cento, e le sue parole sono state misurate e spezzate alla "
          "larghezza dell’elenco qui sopra.",
    stamp="CAMPIONE",
    quoted_before="Preventivato in due inchiostri:",
    quoted_between=" e",
    quoted_after=", ciascuno su una lastra propria.",
)

# The two sheets in Spanish.
SPANISH = Words(
    title="Tintas que lleva la prensa, en planchas propias",
    lead=(
        "Un color directo es un número, no cuatro: cuánta de esa tinta se pone. Donde "
        "la tinta no está",
        "a mano, la transformación de tono que lleva el archivo la muestra, y eso son "
        "estas muestras.",
    ),
    first_ramp=", una plancha, diez tonos",
    second_ramp=", una segunda plancha",
    plate=", hoja 1 separada: esta página es la plancha de esa tinta",
    sheet_title="Dos tintas, una hoja",
    sheet_line="En la segunda tinta, sobre un tono al quince por ciento de la primera.",
    marks="Las cuatro cruces van en el colorante común a todas las planchas, que es "
          "lo que las alinea.",
    list_title="Las mismas dos tintas, a través de la maqueta",
    list_lead=(
        "Un color que lleva el documento llega a una celda, una fila, un filete y un "
        "tramo de texto con estilo",
        "igual que un color del que responde el dispositivo. Abajo no cae ni una gota "
        "de cuatricromía.",
    ),
    headings=("Artículo", "Hojas", "Planchas", "Precio"),
    items=(
        "Papel con membrete, A4",
        "Papel con membrete, A5",
        "Tarjetas de visita, dos caras",
        "Tarjeta de saludo",
        "Carpeta de presentación",
        "Portada de informe, plastificada",
        "Sobre con ventana, DL",
        "Sobre bolsa, C4",
        "Panel de exposición",
    ),
    plates=("Primera", "Segunda", "Ambas"),
    total="Total, nueve artículos, dos planchas",
    note=(
        "El título está sobre una plancha llena de la primera tinta,",
        "el total sobre la segunda",
        ", y las líneas sombreadas sobre un tono del ocho por ciento de la primera. "
        "Un tramo de esta frase va en cada una de las dos.",
    ),
    prose="Una tinta propia es como se compra un color corporativo: la prensa la "
          "lleva en una plancha propia, así que cae con la misma intensidad en cada "
          "hoja de cada tirada, cosa que cuatro tintas de cuatricromía superpuestas "
          "no pueden prometer. Cuesta una plancha, así que se gasta en las señas por "
          "las que un lector reconoce la casa —el nombre, el filete debajo, el panel "
          "tras un título— y el resto del trabajo queda para la cuatricromía. Este "
          "párrafo es un solo texto, dibujado en la primera tinta al noventa por "
          "ciento, y sus palabras se midieron y cortaron al ancho de la lista de "
          "arriba.",
    stamp="MUESTRA",
    quoted_before="Presupuestado en dos tintas:",
    quoted_between=" y",
    quoted_after=", cada una en una plancha propia.",
)

# The two sheets in German.
GERMAN = Words(
    title="Farben, die die Druckmaschine trägt, auf eigenen Platten",
    lead=(
        "Eine Schmuckfarbe ist eine Zahl, nicht vier: wie viel davon aufgetragen "
        "wird. Wo die Farbe",
        "nicht zur Hand ist, zeigt sie die mitgeführte Tonwertumrechnung: das sind "
        "diese Felder.",
    ),
    first_ramp=", eine Platte, zehn Tonwerte",
    second_ramp=", eine zweite Platte",
    plate=", Bogen 1 separiert: Diese Seite ist die Platte dieser Farbe",
    sheet_title="Zwei Farben, ein Bogen",
    sheet_line="In der zweiten Farbe, über 15 % Tonwert der ersten.",
    marks="Die vier Passkreuze stehen in der Farbe, auf die jede Platte antwortet, "
          "und das richtet sie aus.",
    list_title="Dieselben zwei Farben, über das Layout",
    list_lead=(
        "Eine mitgeführte Farbe erreicht eine Zelle, eine Zeile, eine Linie und "
        "formatierten",
        "Text wie eine Farbe, für die das Gerät einsteht. Unten fällt kein Tropfen "
        "Prozessfarbe.",
    ),
    headings=("Posten", "Bögen", "Platten", "Preis"),
    items=(
        "Briefpapier, A4",
        "Briefpapier, A5",
        "Visitenkarten, beidseitig",
        "Kurzmitteilung",
        "Präsentationsmappe",
        "Berichtsumschlag, laminiert",
        "Fensterumschlag, DL",
        "Versandtasche, C4",
        "Messetafel",
    ),
    plates=("Erste", "Zweite", "Beide"),
    total="Summe, neun Posten, zwei Platten",
    note=(
        "Die Überschrift steht auf einer vollen Platte der ersten Farbe, ",
        "die Summe auf der zweiten",
        ", und die schattierten Zeilen auf einem Tonwert von acht Prozent der ersten. "
        "Je ein Abschnitt dieses Satzes ist in einer der beiden gesetzt.",
    ),
    prose="Eine eigene Farbe ist das, als was eine Hausfarbe gekauft wird: Die "
          "Druckmaschine trägt sie auf einer eigenen Platte, also kommt sie auf jedem "
          "Bogen jeder Auflage in derselben Stärke, was vier übereinandergelegte "
          "Prozessfarben nicht versprechen können. Sie kostet eine Platte, also wird "
          "sie für die Zeichen ausgegeben, an denen ein Leser das Haus erkennt — den "
          "Namen, die Linie darunter, die Fläche hinter einer Überschrift —, und der "
          "Rest der Arbeit bleibt den Prozessfarben. Dieser Absatz ist ein einziger "
          "Textfluss, in der ersten Farbe zu neunzig Prozent gezeichnet, und seine "
          "Wörter wurden auf die Breite der Liste oben gemessen und umbrochen.",
    stamp="MUSTER",
    quoted_before="In zwei Farben angeboten: ",
    quoted_between=" und ",
    quoted_after=", jede auf ihrer eigenen Platte.",
)

# 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}


def ramp_caption(ink: str, after: str) -> str:
    """The caption over a ramp of tints: the ink it shows, then what it shows of it."""
    return f"{ink}{after}"


def quoted(words: Words) -> str:
    """The closing line, which names the two inks the work is quoted in."""
    return (
        f"{words.quoted_before}{BLUE}{words.quoted_between}{GOLD}"
        f"{words.quoted_after}"
    )


def tint_ramp(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    ink: hqf_pdf.ColorSpaceHandle,
    y: float,
    caption: str,
) -> None:
    """Draws the ten tints of one ink, each labelled with how much goes down."""
    width, height = TINT_SIZE

    for x, tint in zip(TINT_X, TINTS):
        content.save_state()
        content.set_fill_space(ink)
        content.set_fill_components([tint])
        content.rect(x, y, width, height)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, SWATCH_SIZE, x, y - 11.0, tint_name(tint))
        content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, CAPTION_SIZE, LEFT, y + height + 8.0, caption)
    content.restore_state()


def registration(content: hqf_pdf.Content, x: float, y: float) -> None:
    """Draws a printer's crosshair centred on `(x, y)`, in the space in force."""
    arm = 7.0
    content.move_to(x - arm, y)
    content.line_to(x + arm, y)
    content.move_to(x, y - arm)
    content.line_to(x, y + arm)
    content.stroke()

    content.rect(x - 4.0, y - 4.0, 8.0, 8.0)
    content.stroke()


def sheet(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
    registration_ink: hqf_pdf.ColorSpaceHandle,
) -> None:
    """Draws a piece of work set in the two inks, with the marks a printer lines the
    plates up by around it."""
    bottom, height = 250.0, 190.0
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.75))
    content.set_line_width(0.5)
    content.rect(LEFT, bottom, WIDTH, height)
    content.stroke()
    content.restore_state()

    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(
        font, SHEET_TITLE_SIZE, LEFT + 24.0, bottom + 130.0, words.sheet_title
    )
    content.set_fill_components([PANEL_TINT])
    content.rect(LEFT + 24.0, bottom + 40.0, WIDTH - 48.0, 66.0)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill_space(gold)
    content.set_fill_components([1.0])
    content.rect(LEFT + 24.0, bottom + 118.0, 180.0, 3.0)
    content.fill()
    content.draw_text(
        font, SHEET_LINE_SIZE, LEFT + 40.0, bottom + 68.0, words.sheet_line
    )
    content.restore_state()

    content.save_state()
    content.set_stroke_space(registration_ink)
    content.set_stroke_components([1.0])
    content.set_line_width(0.5)
    for x, y in crosshairs(bottom, height):
        registration(content, x, y)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, MARK_SIZE, LEFT, bottom - 40.0, words.marks)
    content.restore_state()


def run_list(
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> hqf_pdf.Table:
    """The run list, set in the two inks and in nothing else.

    The heading stands on a full-strength plate of the first ink, every other line
    on an eight percent tint of it, the total on the second, and every rule in one
    or the other.
    """
    columns = hqf_pdf.Columns(
        [
            hqf_pdf.ColumnWidth.fraction(1.0),
            hqf_pdf.ColumnWidth.points(54.0),
            hqf_pdf.ColumnWidth.points(74.0),
            hqf_pdf.ColumnWidth.points(66.0),
        ],
        WIDTH,
    )
    table = hqf_pdf.Table(columns)
    table.fill(hqf_pdf.Area.even_rows(), hqf_pdf.Paint.named(blue, [SHADED_TINT]))
    table.fill(hqf_pdf.Area.header(), hqf_pdf.Paint.named(blue, [1.0]))
    table.rule(
        hqf_pdf.Rule.frame(),
        hqf_pdf.Stroke(0.8, color=hqf_pdf.Paint.named(blue, [0.55])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.3, color=hqf_pdf.Paint.named(blue, [0.3])),
    )
    table.rule(
        hqf_pdf.Rule.horizontal(1),
        hqf_pdf.Stroke(1.2, color=hqf_pdf.Paint.named(gold, [1.0])),
    )
    table.header(1)

    def heading(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            CELL_SIZE,
            label,
            align=align,
            valign=hqf_pdf.VAlign.Middle,
            color=hqf_pdf.Rgb.gray(1.0),
            padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
        )

    item, sheets, plates, price = words.headings
    table.push(
        hqf_pdf.Row(
            cells=[
                heading(item, hqf_pdf.Align.Left),
                heading(sheets, hqf_pdf.Align.Right),
                heading(plates, hqf_pdf.Align.Left),
                heading(price, hqf_pdf.Align.Right),
            ]
        )
    )

    def line(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            CELL_SIZE,
            label,
            align=align,
            color=hqf_pdf.Paint.named(blue, [0.95]),
            padding=hqf_pdf.Padding.symmetric(6.0, 5.0),
        )

    for index, (sheets, plates, price) in enumerate(ITEMS):
        table.push(
            hqf_pdf.Row(
                cells=[
                    line(words.items[index], hqf_pdf.Align.Left),
                    line(sheets, hqf_pdf.Align.Right),
                    line(plates.named(words), hqf_pdf.Align.Left),
                    line(price, hqf_pdf.Align.Right),
                ]
            )
        )

    def total(label: str, align: hqf_pdf.Align) -> hqf_pdf.Cell:
        return hqf_pdf.Cell(
            font,
            TOTAL_SIZE,
            label,
            align=align,
            color=hqf_pdf.Paint.named(blue, [1.0]),
            padding=hqf_pdf.Padding.symmetric(6.0, 6.0),
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                total(words.total, hqf_pdf.Align.Left),
                total("", hqf_pdf.Align.Right),
                total("", hqf_pdf.Align.Left),
                total(TOTAL, hqf_pdf.Align.Right),
            ],
            fill=hqf_pdf.Paint.named(gold, [0.28]),
        )
    )
    return table


def run_sheet(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    blue: hqf_pdf.ColorSpaceHandle,
    gold: hqf_pdf.ColorSpaceHandle,
) -> None:
    """Draws the run list, the note whose two runs each stand in the ink they
    name, and a specimen mark laid across the whole of it."""
    content.save_state()
    content.set_fill_space(blue)
    content.set_fill_components([1.0])
    content.draw_text(font, HEAD_SIZE, LEFT, HEAD_BASELINE, words.list_title)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    for line, y in zip(words.list_lead, LEAD_BASELINES):
        content.draw_text(font, LEAD_SIZE, LEFT, y, line)
    content.restore_state()

    table = run_list(font, words, blue, gold)
    placed = table.fit(LEFT, LIST_TOP, LIST_TOP - 260.0, 0)
    height = placed.height
    placed.draw(content)

    first_ink = hqf_pdf.Style(
        font, TOTAL_SIZE, color=hqf_pdf.Paint.named(blue, [PROSE_TINT])
    )
    second_ink = hqf_pdf.Style(
        font, TOTAL_SIZE, color=hqf_pdf.Paint.named(gold, [1.0])
    )
    note = hqf_pdf.RichText()
    note.span(words.note[0], first_ink)
    note.span(words.note[1], second_ink)
    note.span(words.note[2], first_ink)
    lines = note.break_lines(WIDTH)
    note_top = LIST_TOP - height - 26.0
    note.draw(content, lines, LEFT, note_top, WIDTH)

    flow = hqf_pdf.TextFlow(
        font,
        PROSE_SIZE,
        color=hqf_pdf.Paint.named(blue, [PROSE_TINT]),
        leading=PROSE_LEADING,
    )
    prose = flow.break_lines(words.prose, WIDTH)
    flow.draw(
        content,
        prose,
        LEFT,
        note_top - hqf_pdf.RichText.height(lines) - 26.0,
        WIDTH,
    )

    stamp = hqf_pdf.Stamp(
        font, words.stamp, color=hqf_pdf.Paint.named(gold, [0.22])
    )
    stamp.draw(content, LEFT, LIST_TOP - height, WIDTH, height)

    content.save_state()
    content.set_stroke_space(gold)
    content.set_stroke_components([1.0])
    content.set_line_width(0.8)
    content.move_to(LEFT, CLOSING_RULE)
    content.line_to(LEFT + WIDTH, CLOSING_RULE)
    content.stroke()
    content.set_fill_space(blue)
    content.set_fill_components([0.55])
    content.draw_text(
        font, CLOSING_SIZE, LEFT, CLOSING_RULE - 14.0, quoted(words)
    )
    content.restore_state()


def plate(font, words, ink: str, space, separation) -> hqf_pdf.Page:
    """The plate of the first sheet printed in `ink`, whose space is `space`: its ramp
    of tints alone, under what the plate is."""
    content = hqf_pdf.Content()
    tint_ramp(content, font, space, 640.0, ramp_caption(ink, words.plate))
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    page.set_separation(separation)
    return page


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("spot.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    blue = document.add_color_space(
        hqf_pdf.Separation.ink(BLUE, hqf_pdf.Cmyk(0.92, 0.58, 0.0, 0.06))
    )
    gold = document.add_color_space(
        hqf_pdf.Separation.ink(GOLD, hqf_pdf.Cmyk(0.0, 0.28, 0.95, 0.04))
    )

    # The colorant every plate answers to: a mark set in it goes down on all of them,
    # which is how a printer sees whether they line up. It is shown as black where no
    # press is involved, so the tint transform runs from the paper to the ink.
    registration_ink = document.add_color_space(
        hqf_pdf.Separation(
            ALL_PLATES,
            hqf_pdf.DeviceSpace.Gray,
            hqf_pdf.Function.exponential(
                (0.0, 1.0), 1.0, endpoints=([1.0], [0.0]), range=[(0.0, 1.0)]
            ),
        )
    )

    content = hqf_pdf.Content()
    content.draw_text(font, HEAD_SIZE, LEFT, HEAD_BASELINE, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    for line, y in zip(words.lead, LEAD_BASELINES):
        content.draw_text(font, LEAD_SIZE, LEFT, y, line)
    content.restore_state()

    tint_ramp(content, font, blue, 640.0, ramp_caption(BLUE, words.first_ramp))
    tint_ramp(content, font, gold, 530.0, ramp_caption(GOLD, words.second_ramp))

    sheet(content, font, words, blue, gold, registration_ink)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    second = hqf_pdf.Content()
    run_sheet(second, font, words, blue, gold)
    page = hqf_pdf.Page.a4()
    page.set_content(second)
    document.add_page(page)

    separated = hqf_pdf.PageSeparation(BLUE, 1, space=blue)
    document.add_page(plate(font, words, BLUE, blue, separated))
    document.add_page(plate(font, words, GOLD, gold, hqf_pdf.PageSeparation(GOLD, 1)))

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, 4 pages, two inks at {len(TINTS)} "
        f"tints each, {len(ITEMS)} priced lines"
    )


if __name__ == "__main__":
    main()
