"""Sets five short samples twice each — once as the font is read straight off its
`cmap`, once with one typographic feature turned on — so the difference each
feature makes can be seen side by side.

The Python twin of the `write_typography` example in Rust. The five are the
ligatures a font offers, small capitals, old-style figures, the forms the font
draws for one language, and kerning. Nothing is on unless it is asked for, so the
two settings of a sample differ in exactly one thing. The forms of one language
are the font's `locl` feature read for Serbian, the Cyrillic script and the
`SRB ` language.

The font here is Spectral, which offers all five.

The closing lines are measured off the fonts themselves rather than written down:
how many glyphs the ligature sample takes each way, how much narrower kerning
draws its own, and how many of the face's glyphs no character leads to. The first
of those are drawn last, asked for by their number in the file and centred on the
width measured off them.

A second page sets the ligature sample with ligatures and kerning on, then with
ligatures alone turned back off, draws the face's `fi` glyph by its number, stated to
stand for the two letters it joins, and sets three fractions twice: the face's `frac`
feature draws each figure before the slash as a numerator and each after it as a
denominator, by the glyphs around it. Last come capitals each followed by a combining
accent, set twice: the face's `mark` feature sets each accent over or under the letter
before it, at the anchors the face gives the two. Then the upper and the lower half
of a circle in turn, set twice in `HqfJoined.ttf`: its `curs` feature starts each one
exactly where the one before it ends, into one wave. Then an Arabic lam, a fatha and
an alef set twice in `DejaVuSans.ttf` with ligatures on: the face joins the two
letters into one glyph across the fatha, which without the `mark` feature is left
after the ligature, and with it is set over the lam it followed. Last, a family, a
flag, a thumb in a skin tone and a keycap, each typed as several characters, set
once in `HqfEmoji.ttf`: the font composes each into one glyph with no feature asked
for.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set is drawn.

Usage: python examples/write_typography.py [out.pdf]
       HQF_PDF_LANG=fr python examples/write_typography.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# Where the committed fonts sit.
FONT_DIR = _out.ROOT / "crates" / "hqf-pdf" / "tests" / "fonts"


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

    # The line across the top of the page.
    title: str
    # What the page shows, in two sentences.
    why: str
    # The heading over each of the five samples.
    headings: tuple[str, str, str, str, str]
    # What each feature does, one line each.
    explanations: tuple[str, str, str, str, str]
    # The five samples, each set twice.
    samples: tuple[str, str, str, str, str]
    # What is written beside the setting with nothing turned on.
    off: str
    # What is written beside the setting with the feature turned on.
    on: str
    # The line about the ligature sample, cut where the two counts go into it.
    glyphs_before: str
    glyphs_between: str
    glyphs_after: str
    # The line about the kerning sample, cut where the width goes into it.
    kerned_before: str
    kerned_after: str
    # The line over the glyphs drawn by number, cut where the count of the face's
    # glyphs, the count no character leads to and the count drawn go into it.
    numbered_before: str
    numbered_between: str
    numbered_then: str
    numbered_after: str
    # The line at the head of the second page.
    back_title: str
    # What the second page shows.
    back_why: str
    # What is written beside the sample set with ligatures and kerning.
    both: str
    # What is written beside it with ligatures turned back off.
    without: str
    # What stands over the glyph drawn by its number.
    by_number: str
    # The heading over the fraction sample.
    fraction_heading: str
    # What the `frac` feature does, in one line.
    fraction_explanation: str
    # The heading over the accent sample.
    mark_heading: str
    # What the `mark` feature does, in one line.
    mark_explanation: str
    # The heading over the joined sample.
    joined_heading: str
    # What the `curs` feature does, in one line.
    joined_explanation: str
    # The heading over the sample of an accent inside a ligature.
    inside_heading: str
    # What `mark` does to an accent a ligature joins across, in one line.
    inside_explanation: str
    # The heading over the emoji sample.
    emoji_heading: str
    # What the font does to an emoji typed as several characters, in one line.
    emoji_explanation: str

    def glyph_line(self, apart: int, joined: int) -> str:
        """Return the line about the ligature sample, with the two counts in it."""
        return (
            f"{self.glyphs_before}{apart}{self.glyphs_between}"
            f"{joined}{self.glyphs_after}"
        )

    def kerned_line(self, saved: float) -> str:
        """Return the line about the kerning sample, with the width it saves."""
        return f"{self.kerned_before}{saved:.1f}{self.kerned_after}"

    def numbered_line(self, held: int, unreached: int, drawn: int) -> str:
        """Return the line over the glyphs drawn by number, with its three counts."""
        return (
            f"{self.numbered_before}{held}{self.numbered_between}{unreached}"
            f"{self.numbered_then}{drawn}{self.numbered_after}"
        )


# The page in English.
ENGLISH = Words(
    title="Five things a font knows about its own letters",
    why=(
        "A font file carries more than one glyph per character. It says which "
        "letters are drawn joined, which figures hang below the line, which "
        "letters have a small capital of their own, which letters take another "
        "form in one language, and how far apart each pair of glyphs should "
        "stand.\n"
        "None of it is used unless it is asked for, so a document written "
        "before these settings existed comes out byte for byte as it did. Each "
        "sample below is set twice, and only the setting differs."
    ),
    headings=(
        "Ligatures",
        "Small capitals",
        "Old-style figures",
        "Local forms",
        "Kerning",
    ),
    explanations=(
        "Letters that meet are drawn as one glyph the font designer cut for them.",
        "Lowercase letters drawn as capitals no taller than an x.",
        "Figures that rise and fall around the x-height instead of standing at cap height.",
        "The same Cyrillic letters, in the forms the font draws for Serbian.",
        "Each pair of glyphs moved as far apart as the font asks.",
    ),
    samples=(
        "office filing affidavit",
        "reprinted quarterly",
        "1 234 567 890",
        "пут, град, беседа",
        "Wavy TAXI Today",
    ),
    off="off",
    on="on",
    glyphs_before="The first sample takes ",
    glyphs_between=" glyphs as it stands and ",
    glyphs_after=(
        " with the ligatures on: the pairs the font joins are one glyph each."
    ),
    kerned_before="The last sample is drawn ",
    kerned_after=(
        " points narrower with kerning on, and it is measured that way too, so "
        "the line is as wide as it looks."
    ),
    numbered_before="Spectral holds ",
    numbered_between=" glyphs, and no character leads to ",
    numbered_then=(
        " of them: the forms a feature or a language puts in a letter's place. "
        "The first "
    ),
    numbered_after=(
        ", asked for by their number in the file and centred on their measured "
        "width:"
    ),
    back_title="One feature turned back off, one glyph by its number",
    back_why="Ligatures and kerning are turned on together, then ligatures alone are turned back off: the letters come apart again, and the pairs stay kerned.",
    both="both",
    without="no liga",
    by_number="The glyph the face names fi, asked for by its number and stated to stand for the two letters it joins, so that the text copies out as those two letters:",
    fraction_heading="Fractions",
    fraction_explanation="Figures on either side of a slash, set as a numerator and a denominator around a fraction bar.",
    mark_heading="Accents placed by the font",
    mark_explanation="Separately typed accents, set over or under the previous letter, where the font places them.",
    joined_heading="Strokes joined by the font",
    joined_explanation="Each sign of HqfJoined starts exactly where the previous one ends, at points the font defines.",
    inside_heading="An accent inside a ligature",
    inside_explanation="A fatha typed between lam and alef: the font joins the two letters across it and sets it over the lam.",
    emoji_heading="Emoji typed as several characters",
    emoji_explanation="A family, a flag, a thumb in a skin tone, a keycap: several characters each, one glyph without being asked.",
)

# The page in French.
FRENCH = Words(
    title="Cinq choses qu’une police sait de ses propres lettres",
    why=(
        (
            "Un fichier de police contient plus d’un glyphe par caractère. Il indique "
            "quelles lettres se lient, quels chiffres descendent sous la ligne, quelles "
            "lettres ont leur propre petite capitale, lesquelles changent de forme dans "
            "une langue donnée, et quel écart laisser entre chaque paire de "
            "glyphes.\nRien de tout cela ne sert tant qu’on ne le demande pas : un "
            "document écrit avant que ces réglages existent sort à l’octet près comme "
            "avant. Chaque échantillon ci-dessous est composé deux fois, et seul le "
            "réglage change."
        )
    ),
    headings=(
        "Ligatures",
        "Petites capitales",
        "Chiffres elzéviriens",
        "Formes locales",
        "Crénage",
    ),
    explanations=(
        (
            "Les lettres qui se touchent forment un seul glyphe, prévu pour elles par le "
            "créateur de la police."
        ),
        "Des minuscules dessinées en capitales pas plus hautes qu’un x.",
        (
            "Des chiffres qui montent et descendent autour de la hauteur d’x au lieu de "
            "s’aligner sur les capitales."
        ),
        "Les mêmes lettres cyrilliques, dans les formes que la police dessine pour le serbe.",
        "Chaque paire de glyphes écartée autant que la police le demande.",
    ),
    samples=(
        "affiche officielle du greffe",
        "réédition trimestrielle",
        "1 234 567 890",
        "пут, град, беседа",
        "Wagon TAXI Toiture",
    ),
    off="sans",
    on="avec",
    glyphs_before="Le premier échantillon compte ",
    glyphs_between=" glyphes tel quel et ",
    glyphs_after=(" avec les ligatures : chaque paire liée ne fait plus qu’un glyphe."),
    kerned_before="Le dernier échantillon est composé ",
    kerned_after=(
        (
            " points plus étroit avec le crénage, et il est aussi mesuré ainsi : la ligne"
            " fait bien la largeur qu’elle paraît faire."
        )
    ),
    numbered_before="Spectral contient ",
    numbered_between=" glyphes, et aucun caractère ne mène à ",
    numbered_then=(
        (
            " d’entre eux : les formes qu’un réglage ou une langue met à la place d’une "
            "lettre. Les "
        )
    ),
    numbered_after=(
        (
            " premiers, demandés par leur numéro dans le fichier et centrés sur leur "
            "largeur mesurée :"
        )
    ),
    back_title="Une fonction désactivée, un glyphe par son numéro",
    back_why=(
        "Ligatures et crénage sont activés ensemble, puis les ligatures seules sont "
        "désactivées : les lettres se séparent de nouveau, et les paires restent "
        "crénées."
    ),
    both="les deux",
    without="sans liga",
    by_number="Le glyphe que la police nomme fi, demandé par son numéro et déclaré tenir lieu des deux lettres qu’il joint, pour que le texte se copie en ces deux lettres :",
    fraction_heading="Fractions",
    fraction_explanation="Les chiffres de part et d’autre d’une barre oblique, composés en numérateur et en dénominateur.",
    mark_heading="Accents placés par la police",
    mark_explanation="Les accents saisis à part, posés sur ou sous la lettre précédente, où la police le prévoit.",
    joined_heading="Tracés raccordés par la police",
    joined_explanation="Chaque signe de HqfJoined commence là où finit le précédent, aux points exacts que fixe la police.",
    inside_heading="Accent pris dans une ligature",
    inside_explanation="Une fatha saisie entre lam et alif n’empêche pas la ligature : la police la pose sur le lam.",
    emoji_heading="Émojis formés de plusieurs caractères",
    emoji_explanation="Famille, drapeau, pouce à la couleur de peau choisie, touche de clavier : plusieurs caractères chacun, un seul glyphe.",
)

# The page in Dutch.
DUTCH = Words(
    title="Vijf dingen die een lettertype over zijn eigen letters weet",
    why=(
        "Een lettertypebestand bevat meer dan één glyph per teken. Het zegt welke "
        "letters verbonden getekend worden, welke cijfers onder de regel hangen, "
        "welke letters een eigen kleinkapitaal hebben, welke letters in een bepaalde "
        "taal een andere vorm krijgen, en hoe ver elk paar glyphs uit elkaar moet "
        "staan.\nNiets ervan wordt gebruikt tenzij erom gevraagd wordt, dus een "
        "document dat geschreven is voordat deze instellingen bestonden, komt er byte "
        "voor byte uit zoals vroeger. Elk voorbeeld hieronder is twee keer gezet, en "
        "alleen de instelling verschilt."
    ),
    headings=(
        "Ligaturen",
        "Kleinkapitalen",
        "Mediëvalcijfers",
        "Lokale vormen",
        "Kerning",
    ),
    explanations=(
        "Letters die elkaar raken, worden getekend als één glyph die de ontwerper ervoor sneed.",
        "Kleine letters getekend als hoofdletters niet hoger dan een x.",
        "Cijfers die rond de x-hoogte stijgen en dalen in plaats van op kapitaalhoogte te staan.",
        "Dezelfde Cyrillische letters, in de vormen die het lettertype voor het Servisch tekent.",
        "Elk paar glyphs zo ver uit elkaar gezet als het lettertype vraagt.",
    ),
    samples=(
        "officiële flessenafvulling",
        "elk kwartaal herdrukt",
        "1 234 567 890",
        "пут, град, беседа",
        "Wafel TAXI Toren",
    ),
    off="uit",
    on="aan",
    glyphs_before="Het eerste voorbeeld neemt",
    glyphs_between=" glyphs zoals het is en",
    glyphs_after=(
        " met de ligaturen aan: de paren die het lettertype verbindt, zijn elk één glyph."
    ),
    kerned_before="Het laatste voorbeeld wordt",
    kerned_after=(
        " punten smaller getekend met kerning aan, en het wordt ook zo gemeten, dus "
        "is de regel zo breed als hij lijkt."
    ),
    numbered_before="Spectral bevat",
    numbered_between=" glyphs, en bij",
    numbered_then=(
        " ervan komt geen teken uit: de vormen die een functie of een taal in de "
        "plaats van een letter zet. De eerste"
    ),
    numbered_after=(
        ", opgevraagd bij hun nummer in het bestand en gecentreerd op hun gemeten "
        "breedte:"
    ),
    back_title="Eén functie weer uitgezet, één glyph bij zijn nummer",
    back_why="Ligaturen en kerning worden samen aangezet, dan worden alleen de ligaturen weer uitgezet: de letters gaan weer uit elkaar, en de paren blijven gekerned.",
    both="beide",
    without="zonder liga",
    by_number="De glyph die het lettertype fi noemt, opgevraagd bij zijn nummer en opgegeven als de twee letters die hij verbindt, zodat de tekst als die twee letters gekopieerd wordt:",
    fraction_heading="Breuken",
    fraction_explanation="Cijfers aan weerszijden van een schuine streep, gezet als teller en noemer rond een breukstreep.",
    mark_heading="Accentplaatsing door het lettertype",
    mark_explanation="Los getypte accenten, boven of onder de voorgaande letter, waar het lettertype ze plaatst.",
    joined_heading="Lijnverbinding door het lettertype",
    joined_explanation="Elk teken van HqfJoined begint precies waar het vorige eindigt, op de punten van het lettertype.",
    inside_heading="Accent binnen een ligatuur",
    inside_explanation="Een tussen lam en alif getypte fatha: het lettertype verbindt beide letters eroverheen en zet hem boven de lam.",
    emoji_heading="Emoji uit meerdere tekens",
    emoji_explanation="Een gezin, een vlag, een duim met huidskleur en een toets: elk meerdere tekens, ongevraagd als één glyph gezet.",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Cinco coisas que um tipo de letra sabe sobre as suas letras",
    why=(
        "Um ficheiro de tipo de letra leva mais de um glifo por carácter. Diz que "
        "letras se desenham unidas, que algarismos descem abaixo da linha, que letras "
        "têm versaletes próprios, que letras tomam outra forma numa língua e a que "
        "distância deve ficar cada par de glifos.\nNada disto é usado sem ser pedido, "
        "por isso um documento escrito antes de estas definições existirem sai byte a "
        "byte como saía. Cada amostra abaixo é composta duas vezes, e só muda a "
        "definição."
    ),
    headings=(
        "Ligaduras",
        "Versaletes",
        "Algarismos de estilo antigo",
        "Formas locais",
        "Crenagem",
    ),
    explanations=(
        "As letras que se tocam são desenhadas como um glifo que o desenhador do tipo cortou para elas.",
        "Minúsculas desenhadas como maiúsculas não mais altas do que um x.",
        "Algarismos que sobem e descem em torno da altura do x em vez de ficarem à altura das maiúsculas.",
        "As mesmas letras cirílicas, nas formas que o tipo desenha para o sérvio.",
        "Cada par de glifos afastado tanto quanto o tipo pede.",
    ),
    samples=(
        "ficha oficial do filiado",
        "reimpresso a cada trimestre",
        "1 234 567 890",
        "пут, град, беседа",
        "Vagão TAXI Torta",
    ),
    off="não",
    on="sim",
    glyphs_before="A primeira amostra ocupa",
    glyphs_between=" glifos tal como está e",
    glyphs_after=(" com as ligaduras: os pares que o tipo une são um glifo cada."),
    kerned_before="A última amostra é desenhada",
    kerned_after=(
        " pontos mais estreita com crenagem, e também é medida assim, por isso a "
        "linha é tão larga como parece."
    ),
    numbered_before="O Spectral tem",
    numbered_between=" glifos, e",
    numbered_then=(
        " deles não levam nenhum carácter: as formas que uma funcionalidade ou uma "
        "língua põem no lugar de uma letra. Os primeiros"
    ),
    numbered_after=(
        ", pedidos pelo seu número no ficheiro e centrados na largura medida:"
    ),
    back_title="Funcionalidade desligada de novo; glifo por número",
    back_why="Ligaduras e crenagem são ligadas juntas, e depois só as ligaduras são desligadas: as letras voltam a separar-se, e os pares continuam com crenagem.",
    both="ambas",
    without="sem liga",
    by_number="O glifo a que o tipo chama fi, pedido pelo seu número e indicado como representante das duas letras que une, para que o texto se copie como essas duas letras:",
    fraction_heading="Frações",
    fraction_explanation="Os algarismos de cada lado de uma barra, compostos como numerador e denominador em volta de um traço de fração.",
    mark_heading="Acentos posicionados pelo tipo de letra",
    mark_explanation="Acentos escritos à parte, postos sobre ou sob a letra anterior, onde o tipo de letra indica.",
    joined_heading="Traços ligados pelo tipo de letra",
    joined_explanation="Cada sinal de HqfJoined começa onde acaba o anterior, nos pontos exatos que o tipo de letra define.",
    inside_heading="Acento dentro de uma ligadura",
    inside_explanation="Fatha escrita entre lam e alif: o tipo de letra une as duas letras apesar dela e põe-na sobre o lam.",
    emoji_heading="Emojis de vários caracteres",
    emoji_explanation="Uma família, uma bandeira, um polegar com tom de pele e uma tecla: vários caracteres, um só glifo sem o pedir.",
)

# The page in Italian.
ITALIAN = Words(
    title="Cinque cose che un font sa delle proprie lettere",
    why=(
        "Un file di font porta più di un glifo per carattere. Dice quali lettere si "
        "disegnano unite, quali cifre scendono sotto la riga, quali lettere hanno un "
        "maiuscoletto proprio, quali lettere prendono un’altra forma in una lingua e "
        "quanto distante deve stare ogni coppia di glifi.\nNiente di tutto ciò è "
        "usato se non lo si chiede, così un documento scritto prima che queste "
        "impostazioni esistessero esce byte per byte come usciva. Ogni campione qui "
        "sotto è composto due volte, e cambia solo l’impostazione."
    ),
    headings=(
        "Legature",
        "Maiuscoletto",
        "Cifre in stile antico",
        "Forme locali",
        "Crenatura",
    ),
    explanations=(
        "Le lettere che si toccano sono disegnate come un glifo che il disegnatore del carattere ha tagliato per loro.",
        "Minuscole disegnate come maiuscole non più alte di una x.",
        "Cifre che salgono e scendono intorno all’altezza della x anziché stare all’altezza delle maiuscole.",
        "Le stesse lettere cirilliche, nelle forme che il carattere disegna per il serbo.",
        "Ogni coppia di glifi distanziata quanto chiede il font.",
    ),
    samples=(
        "ufficio affiliato fluviale",
        "ristampato ogni trimestre",
        "1 234 567 890",
        "пут, град, беседа",
        "Vagone TAXI Torta",
    ),
    off="no",
    on="sì",
    glyphs_before="Il primo campione occupa",
    glyphs_between=" glifi così com’è e",
    glyphs_after=(
        " con le legature: le coppie che il font unisce sono un glifo ciascuna."
    ),
    kerned_before="L’ultimo campione è disegnato",
    kerned_after=(
        " punti più stretto con la crenatura, ed è misurato così: la riga è larga "
        "quanto sembra."
    ),
    numbered_before="Spectral contiene",
    numbered_between=" glifi, e a",
    numbered_then=(
        " di essi non corrisponde alcun carattere: le forme che una funzione o una "
        "lingua mettono al posto di una lettera. I primi"
    ),
    numbered_after=(
        ", chiesti per numero nel file e centrati sulla larghezza misurata:"
    ),
    back_title="Una funzione disattivata di nuovo, un glifo per numero",
    back_why="Legature e crenatura si attivano insieme, poi si disattivano solo le legature: le lettere si separano di nuovo, e le coppie restano crenate.",
    both="entrambe",
    without="senza liga",
    by_number="Il glifo che il carattere chiama fi, chiesto per numero e indicato come rappresentante delle due lettere che unisce, così il testo si copia come quelle due lettere:",
    fraction_heading="Frazioni",
    fraction_explanation="Le cifre ai due lati di una barra, composte come numeratore e denominatore attorno a una barra di frazione.",
    mark_heading="Accenti posizionati dal font",
    mark_explanation="Accenti digitati a parte, posti sopra o sotto la lettera precedente, dove il font lo prevede.",
    joined_heading="Tratti uniti dal font",
    joined_explanation="Ogni segno di HqfJoined inizia esattamente dove finisce il precedente, nei punti indicati dal font.",
    inside_heading="Accento dentro una legatura",
    inside_explanation="Fatha digitata tra lam e alif: il font unisce le due lettere scavalcandola e la pone sopra il lam.",
    emoji_heading="Emoji di più caratteri",
    emoji_explanation="Famiglia, bandiera, pollice con tonalità della pelle, tasto: più caratteri, un solo glifo senza chiederlo.",
)

# The page in Spanish.
SPANISH = Words(
    title="Cinco cosas que una fuente sabe de sus propias letras",
    why=(
        "Un archivo de fuente lleva más de un glifo por carácter. Dice qué letras se "
        "dibujan unidas, qué cifras bajan de la línea, qué letras tienen versalita "
        "propia, qué letras toman otra forma en un idioma y a qué distancia debe "
        "estar cada par de glifos.\nNada de ello se usa si no se pide, así que un "
        "documento escrito antes de que existieran estos ajustes sale byte a byte "
        "como salía. Cada muestra de abajo se compone dos veces, y solo cambia el "
        "ajuste."
    ),
    headings=(
        "Ligaduras",
        "Versalitas",
        "Cifras elzevirianas",
        "Formas locales",
        "Interletraje",
    ),
    explanations=(
        "Las letras que se tocan se dibujan como un glifo que el diseñador de la fuente cortó para ellas.",
        "Minúsculas dibujadas como mayúsculas no más altas que una x.",
        "Cifras que suben y bajan alrededor de la altura de la x en vez de alinearse con las mayúsculas.",
        "Las mismas letras cirílicas, en las formas que la fuente dibuja para el serbio.",
        "Cada par de glifos separado tanto como pide la fuente.",
    ),
    samples=(
        "ficha oficial del afiliado",
        "reimpreso cada trimestre",
        "1 234 567 890",
        "пут, град, беседа",
        "Vagón TAXI Tarta",
    ),
    off="no",
    on="sí",
    glyphs_before="La primera muestra ocupa",
    glyphs_between=" glifos tal cual y",
    glyphs_after=(
        " con las ligaduras: los pares que une la fuente son un glifo cada uno."
    ),
    kerned_before="La última muestra se dibuja",
    kerned_after=(
        " puntos más estrecha con interletraje, y también se mide así, así que la "
        "línea es tan ancha como parece."
    ),
    numbered_before="Spectral tiene",
    numbered_between=" glifos, y",
    numbered_then=(
        " de ellos no corresponden a ningún carácter: las formas que una función o un "
        "idioma ponen en lugar de una letra. Los primeros"
    ),
    numbered_after=(
        ", pedidos por su número en el archivo y centrados en su ancho medido:"
    ),
    back_title="Una función desactivada otra vez, un glifo por su número",
    back_why="Ligaduras e interletraje se activan juntos, y luego se desactivan solo las ligaduras: las letras se separan de nuevo, y los pares siguen con interletraje.",
    both="ambos",
    without="sin liga",
    by_number="El glifo que la fuente llama fi, pedido por su número e indicado como representante de las dos letras que une, para que el texto se copie como esas dos letras:",
    fraction_heading="Fracciones",
    fraction_explanation="Las cifras a cada lado de una barra, compuestas como numerador y denominador alrededor de una barra de fracción.",
    mark_heading="Acentos colocados por la fuente",
    mark_explanation="Acentos tecleados aparte, encima o debajo de la letra anterior, donde la fuente lo indica.",
    joined_heading="Trazos enlazados por la fuente",
    joined_explanation="Cada signo de HqfJoined empieza justo donde acaba el anterior, en los puntos que fija la fuente.",
    inside_heading="Acento dentro de una ligadura",
    inside_explanation="Fatha tecleada entre lam y álif: la fuente une las dos letras por encima y la coloca sobre la lam.",
    emoji_heading="Emojis de varios caracteres",
    emoji_explanation="Una familia, una bandera, un pulgar con tono de piel y una tecla: varios caracteres, un solo glifo sin pedirlo.",
)

# The page in German.
GERMAN = Words(
    title="Was eine Schrift über ihre Buchstaben weiß",
    why=(
        "Eine Schriftdatei trägt mehr als einen Glyphen je Zeichen. Sie sagt, welche "
        "Buchstaben verbunden gezeichnet werden, welche Ziffern unter die Zeile "
        "hängen, welche Buchstaben ein eigenes Kapitälchen haben, welche Buchstaben "
        "in einer Sprache eine andere Form annehmen und wie weit jedes Glyphenpaar "
        "auseinanderstehen soll.\nNichts davon wird genutzt, wenn es nicht verlangt "
        "wird, also kommt ein Dokument, das vor diesen Einstellungen geschrieben "
        "wurde, Byte für Byte so heraus wie damals. Jedes Muster unten ist zweimal "
        "gesetzt, und nur die Einstellung unterscheidet sich."
    ),
    headings=(
        "Ligaturen",
        "Kapitälchen",
        "Mediävalziffern",
        "Lokale Formen",
        "Unterschneidung",
    ),
    explanations=(
        "Sich berührende Buchstaben werden zu einem eigens geschnittenen Glyphen.",
        "Kleinbuchstaben als Versalien, nicht höher als ein x.",
        "Ziffern, die um die x-Höhe auf- und absteigen, statt auf Versalhöhe zu stehen.",
        "Dieselben kyrillischen Buchstaben in ihren serbischen Formen.",
        "Jedes Glyphenpaar so weit gerückt, wie die Schrift verlangt.",
    ),
    samples=(
        "offizielle Kaffeefilter",
        "vierteljährlich nachgedruckt",
        "1 234 567 890",
        "пут, град, беседа",
        "Wagen TAXI Torte",
    ),
    off="aus",
    on="an",
    glyphs_before="Das erste Muster braucht ",
    glyphs_between=" Glyphen, wie es ist, und ",
    glyphs_after=(
        " mit Ligaturen: Die Paare, die die Schrift verbindet, sind je ein Glyph."
    ),
    kerned_before="Das letzte Muster ist mit Unterschneidung ",
    kerned_after=(
        " Punkt schmaler gezeichnet und wird auch so gemessen, also ist die Zeile so "
        "breit, wie sie aussieht."
    ),
    numbered_before="Spectral enthält ",
    numbered_between=" Glyphen, und kein Zeichen führt zu ",
    numbered_then=(
        " davon: die Formen, die ein Feature oder eine Sprache an die Stelle eines "
        "Buchstabens setzt. Die ersten "
    ),
    numbered_after=(
        ", über ihre Nummer in der Datei verlangt und auf ihre gemessene Breite "
        "zentriert:"
    ),
    back_title="Feature wieder ausgeschaltet, Glyph per Nummer",
    back_why="Ligaturen und Unterschneidung werden zusammen eingeschaltet, dann werden nur die Ligaturen wieder ausgeschaltet: Die Buchstaben trennen sich wieder, und die Paare bleiben unterschnitten.",
    both="beide",
    without="ohne liga",
    by_number="Der Glyph, den der Schnitt fi nennt, über seine Nummer verlangt und als Stellvertreter der zwei Buchstaben angegeben, die er verbindet, sodass der Text als diese zwei Buchstaben herauskopiert wird:",
    fraction_heading="Brüche",
    fraction_explanation="Ziffern links und rechts eines Schrägstrichs, gesetzt als Zähler und Nenner um einen Bruchstrich.",
    mark_heading="Von der Schrift platzierte Akzente",
    mark_explanation="Separat getippte Akzente über oder unter dem Buchstaben davor, wo die Schrift sie vorsieht.",
    joined_heading="Von der Schrift verbundene Striche",
    joined_explanation="Jedes Zeichen von HqfJoined beginnt genau am Ende des vorigen, an Punkten, die die Schrift vorgibt.",
    inside_heading="Akzent mitten in einer Ligatur",
    inside_explanation="Die Schrift verbindet Lam und Alif über ein dazwischen getipptes Fatha hinweg und setzt es über das Lam.",
    emoji_heading="Emojis aus mehreren Zeichen",
    emoji_explanation="Familie, Flagge, Daumen mit Hautton, Zifferntaste: jeweils mehrere Zeichen, automatisch ein Symbol.",
)


# 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 left edge of everything on the page.
X = 60.0

# The width every block is broken to.
ROOM = 475.0

# The baseline the title sits on.
TITLE_TOP = 780.0

# The top of the block that says what the page shows.
WHY_TOP = 748.0

# The top of each of the five samples, in the order they are drawn.
TOPS = (650.0, 550.0, 450.0, 350.0, 250.0)

# How far the line that explains a feature sits below its heading.
EXPLAIN_DROP = 16.0

# How far the setting with nothing turned on sits below the heading.
OFF_DROP = 42.0

# How far the setting with the feature turned on sits below the heading.
ON_DROP = 68.0

# Where the word beside a setting is written, and where the sample begins.
LABEL_X = X
SAMPLE_X = X + 46.0

# The size the samples are set in.
SAMPLE_SIZE = 18.0

# The size the headings are set in.
HEADING_SIZE = 12.0

# The size everything that is not a heading or a sample is set in.
SMALL = 9.0

# The top of the two closing lines.
CLOSING_TOP = 150.0

# How far the second closing line sits below the first.
CLOSING_DROP = 30.0

# How far the closing line over the glyphs drawn by number sits below the first.
NUMBERED_DROP = 60.0

# The baseline of the glyphs drawn by number.
NUMBERED_BASELINE = 28.0

# How many of the glyphs no character leads to are drawn.
NUMBERED_SHOWN = 12


def unreached(font: hqf_pdf.Font) -> list[int]:
    """Return the glyphs of `font` no character of its map leads to, by number,
    leaving out the empty box at zero."""
    reached = {glyph for __, glyph in font.coverage}
    held = min(font.glyph_count, 65535)
    return [number for number in range(1, held) if number not in reached]


def line(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    text: str,
    size: float,
    x: float,
    top: float,
) -> None:
    """Draw one line of text at `size`, left-aligned at `x`, below `top`."""
    flow = hqf_pdf.TextFlow(handle, size)
    flow.draw(content, flow.break_lines(text, ROOM), x, top, ROOM)


# The name the face gives the glyph joining `f` and `i`.
JOINED = "fi"

# The tops of the second page's two settings, and of the line over the glyph drawn by
# its number, and that glyph's baseline.
BACK_TOPS = (680.0, 650.0)
BY_NUMBER_TOP = 610.0
BY_NUMBER_BASELINE = 550.0

# The top of the fraction sample on the second page.
FRACTION_TOP = 480.0

# The fraction sample, written the same way in every language.
FRACTIONS = "1/2 3/4 15/16"

# The top of the accent sample on the second page.
MARK_TOP = 380.0

# The accent sample, written the same way in every language: capitals each followed by a
# combining acute, caron, ring, dot below and tilde.
ACCENTED = "H\u0301 K\u030c R\u030a G\u0323 L\u0303"

# The top of the joined sample on the second page.
WAVE_TOP = 280.0

# The joined sample, written the same way in every language: the upper and the lower
# half of a circle in turn, six times, which `HqfJoined.ttf` joins into one wave.
WAVE = "\u25e0\u25e1" * 6

# The top of the sample of an accent inside a ligature on the second page.
INSIDE_TOP = 180.0

# The sample of an accent inside a ligature, written the same way in every language: an
# initial lam, a fatha, then a final alef with madda, which `DejaVuSans.ttf` joins into
# one glyph across the fatha.
INSIDE = "\ufedf\u064e\ufe82"

# The top of the emoji sample on the second page.
EMOJI_TOP = 80.0

# The emoji sample, written the same way in every language: a woman, a man and a girl
# joined by zero width joiners, the regional indicators F and R, a thumb up followed by
# the medium skin tone, and the digit one followed by the combining enclosing keycap, a
# space between each, which `HqfEmoji.ttf` sets as four glyphs and three spaces.
EMOJI = (
    "\U0001f469\u200d\U0001f468\u200d\U0001f467 \U0001f1eb\U0001f1f7 "
    "\U0001f44d\U0001f3fd 1\u20e3"
)


def emoji_block(
    content: hqf_pdf.Content,
    plain: hqf_pdf.FontHandle,
    emoji: hqf_pdf.FontHandle,
    words: Words,
) -> None:
    """Draw the emoji block from `EMOJI_TOP` down: its heading and its explanation in
    `plain`, then the emoji sample once, set in `emoji`."""
    line(content, plain, words.emoji_heading, HEADING_SIZE, X, EMOJI_TOP)
    line(content, plain, words.emoji_explanation, SMALL, X, EMOJI_TOP - EXPLAIN_DROP)
    line(content, emoji, EMOJI, SAMPLE_SIZE, SAMPLE_X, EMOJI_TOP - OFF_DROP)


def back_page(
    plain: hqf_pdf.FontHandle,
    waves: hqf_pdf.FontHandle,
    arabic: hqf_pdf.FontHandle,
    emoji: hqf_pdf.FontHandle,
    words: Words,
    joined: int | None,
) -> hqf_pdf.Page:
    """The second page: the ligature sample with ligatures and kerning, then with
    ligatures turned back off, the glyph numbered `joined` stated to stand for the two
    letters it joins, the fraction sample without and with the `frac` feature, the
    accent sample without and with the `mark` feature, and the joined sample set in
    `waves` without and with the `curs` feature, and the sample of an accent inside a
    ligature set in `arabic` with ligatures on, without and with the `mark` feature,
    and the emoji sample set once in `emoji`."""
    content = hqf_pdf.Content()
    line(content, plain, words.back_title, 18.0, X, TITLE_TOP)
    why = hqf_pdf.TextFlow(plain, 10.0, leading=14.0)
    why.draw(content, why.break_lines(words.back_why, ROOM), X, WHY_TOP, ROOM)

    both = plain.with_ligatures().kerning()
    apart = both.without_feature("liga")
    for (label, handle), top in zip(
        ((words.both, both), (words.without, apart)), BACK_TOPS
    ):
        line(content, plain, label, SMALL, LABEL_X, top)
        line(content, handle, words.samples[0], SAMPLE_SIZE, SAMPLE_X, top)

    if joined is not None:
        over = hqf_pdf.TextFlow(plain, 10.0, leading=14.0)
        over.draw(
            content, over.break_lines(words.by_number, ROOM), X, BY_NUMBER_TOP, ROOM
        )
        glyph = plain.numbered_glyph_standing_for(joined, JOINED)
        content.begin_text()
        content.set_font(plain, SAMPLE_SIZE)
        content.text_origin(X, BY_NUMBER_BASELINE)
        content.show_glyphs(glyph)
        content.end_text()

    line(content, plain, words.fraction_heading, HEADING_SIZE, X, FRACTION_TOP)
    line(
        content,
        plain,
        words.fraction_explanation,
        SMALL,
        X,
        FRACTION_TOP - EXPLAIN_DROP,
    )
    fractions = plain.with_feature("frac")
    for drop, label, handle in (
        (OFF_DROP, words.off, plain),
        (ON_DROP, words.on, fractions),
    ):
        line(content, plain, label, SMALL, LABEL_X, FRACTION_TOP - drop)
        line(content, handle, FRACTIONS, SAMPLE_SIZE, SAMPLE_X, FRACTION_TOP - drop)

    line(content, plain, words.mark_heading, HEADING_SIZE, X, MARK_TOP)
    line(content, plain, words.mark_explanation, SMALL, X, MARK_TOP - EXPLAIN_DROP)
    marks = plain.with_feature("mark")
    for drop, label, handle in (
        (OFF_DROP, words.off, plain),
        (ON_DROP, words.on, marks),
    ):
        line(content, plain, label, SMALL, LABEL_X, MARK_TOP - drop)
        line(content, handle, ACCENTED, SAMPLE_SIZE, SAMPLE_X, MARK_TOP - drop)

    line(content, plain, words.joined_heading, HEADING_SIZE, X, WAVE_TOP)
    line(content, plain, words.joined_explanation, SMALL, X, WAVE_TOP - EXPLAIN_DROP)
    joined = waves.with_feature("curs")
    for drop, label, handle in (
        (OFF_DROP, words.off, waves),
        (ON_DROP, words.on, joined),
    ):
        line(content, plain, label, SMALL, LABEL_X, WAVE_TOP - drop)
        line(content, handle, WAVE, SAMPLE_SIZE, SAMPLE_X, WAVE_TOP - drop)

    line(content, plain, words.inside_heading, HEADING_SIZE, X, INSIDE_TOP)
    line(content, plain, words.inside_explanation, SMALL, X, INSIDE_TOP - EXPLAIN_DROP)
    joined_across = arabic.with_ligatures()
    set_inside = joined_across.with_feature("mark")
    for drop, label, handle in (
        (OFF_DROP, words.off, joined_across),
        (ON_DROP, words.on, set_inside),
    ):
        line(content, plain, label, SMALL, LABEL_X, INSIDE_TOP - drop)
        line(content, handle, INSIDE, SAMPLE_SIZE, SAMPLE_X, INSIDE_TOP - drop)

    emoji_block(content, plain, emoji, words)

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


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

    out = _out.output_path(Path(_language.file_name("typography.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = hqf_pdf.Font.from_path(FONT_DIR / "Spectral-Regular.ttf")
    held = font.glyph_count
    numbers = unreached(font)
    ligature = font.glyph_named(JOINED)
    plain = document.add_font(font)
    waves = document.add_font(hqf_pdf.Font.from_path(FONT_DIR / "HqfJoined.ttf"))
    arabic = document.add_font(hqf_pdf.Font.from_path(FONT_DIR / "DejaVuSans.ttf"))
    emoji = document.add_font(hqf_pdf.Font.from_path(FONT_DIR / "HqfEmoji.ttf"))

    # One handle per feature, each turned on alone: the two settings of a sample then
    # differ in exactly one thing.
    with_feature = (
        plain.with_ligatures(),
        plain.with_small_capitals(),
        plain.with_oldstyle_figures(),
        plain.with_feature("locl").with_language_system("cyrl", "SRB "),
        plain.kerning(),
    )

    content = hqf_pdf.Content()

    line(content, plain, words.title, 18.0, X, TITLE_TOP)

    why = hqf_pdf.TextFlow(plain, 10.0, leading=14.0)
    why.draw(content, why.break_lines(words.why, ROOM), X, WHY_TOP, ROOM)

    for index, top in enumerate(TOPS):
        line(content, plain, words.headings[index], HEADING_SIZE, X, top)
        line(content, plain, words.explanations[index], SMALL, X, top - EXPLAIN_DROP)

        for drop, label, handle in (
            (OFF_DROP, words.off, plain),
            (ON_DROP, words.on, with_feature[index]),
        ):
            line(content, plain, label, SMALL, LABEL_X, top - drop)
            line(
                content, handle, words.samples[index], SAMPLE_SIZE, SAMPLE_X, top - drop
            )

    # The closing lines are read off the fonts, not written down.
    apart = sum(len(run.glyphs) for run in plain.runs(words.samples[0]))
    joined = sum(len(run.glyphs) for run in with_feature[0].runs(words.samples[0]))
    saved = plain.measure(words.samples[4], SAMPLE_SIZE) - with_feature[4].measure(
        words.samples[4], SAMPLE_SIZE
    )

    shown = numbers[:NUMBERED_SHOWN]

    closing = hqf_pdf.TextFlow(plain, 10.0, leading=14.0)
    for drop, text in (
        (0.0, words.glyph_line(apart, joined)),
        (CLOSING_DROP, words.kerned_line(saved)),
        (NUMBERED_DROP, words.numbered_line(held, len(numbers), len(shown))),
    ):
        closing.draw(
            content, closing.break_lines(text, ROOM), X, CLOSING_TOP - drop, ROOM
        )

    # Drawn by their number, since no character leads to them.
    row = plain.numbered_glyphs(shown)
    row_width = plain.measure_glyphs(row, SAMPLE_SIZE)
    content.begin_text()
    content.set_font(plain, SAMPLE_SIZE)
    content.text_origin(X + (ROOM - row_width) / 2.0, NUMBERED_BASELINE)
    content.show_glyphs(row)
    content.end_text()

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    document.add_page(back_page(plain, waves, arabic, emoji, words, ligature))

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


if __name__ == "__main__":
    main()
