"""Writes pictures made in memory and read from files, each drawn under a setting of its
own, with what the image says of itself under it.

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

The first page builds its pictures from samples: red, green and blue; cyan, magenta,
yellow and black; four-bit places in a table of colours; and samples carrying their own
opacity. It then shows them through a colour key, a soft mask, a stencil mask and as a
stencil, decoded upside down, smoothed and not, read through a colour profile under a
rendering intent, stripped of their opacity, laid down in one and in two inks named for
the press, and held within a clipping path. The pictures that let the page through stand
over a grey band, so what they leave out shows.

The second page turns one picture every way a camera may have stored it, and reads
pictures from files through the constructor made for each format, saying what size they
come out at a given resolution and what resolution they state; the last of them lies on
a layer a reader can hide. Its last picture is read as measured colour, CIE 1976 L*a*b*
against the D50 white.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set the
pages are written in.

Usage: python examples/write_image_settings.py [out.pdf]
       HQF_PDF_LANG=fr python examples/write_image_settings.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 and pictures are.
TESTS = _out.ROOT / "crates" / "hqf-pdf" / "tests"

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

# How far apart two cells of the grid are across, in points.
ACROSS = 124.0

# How far apart two rows of the grid are down, in points.
DOWN = 170.0

# How wide and tall a picture is drawn, in points.
SIDE = 90.0

# Where the top of the first row of pictures sits, in points up from the foot of the
# sheet.
FIRST_ROW = 740.0

# The size the captions are set at, in points.
CAPTION = 7.5

# How many pixels across and down the pictures made in memory are.
TILE = 32


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

    # The first page's heading, and what the file says of itself.
    title: str
    # The second page's heading.
    files: str
    # What each picture of the first page is, in the order it is drawn.
    made: tuple[str, ...]
    # Yes, then no.
    yes_no: tuple[str, str]
    # A picture's size and components; `{width}`, `{height}` and `{count}` stand for
    # them.
    size: str
    # The width of a component; `{bits}` stands for it.
    bits: str
    # Whether a picture carries a soft mask; `{answer}` stands for it.
    soft: str
    # The ranges a colour key leaves out; `{ranges}` stands for them.
    keyed: str
    # Whether a picture carries a stencil mask; `{answer}` stands for it.
    stencil_mask: str
    # Whether a picture is a stencil; `{answer}` stands for it.
    stencil: str
    # The ranges a picture is decoded through; `{ranges}` stands for them.
    decoded: str
    # Whether a picture is smoothed; `{answer}` stands for it.
    smoothed: str
    # A picture's profile and intent; `{bytes}` and `{intent}` stand for how long the
    # profile is and the intent.
    profile: str
    # The four rendering intents: perceptual, relative colorimetric, saturation,
    # absolute colorimetric.
    intents: tuple[str, str, str, str]
    # How many components a pixel carries; `{count}` stands for them.
    components: str
    # A clipping path; `{contours}` and `{knots}` stand for how many.
    path: str
    # What each orientation is, in the order of the tags one to eight.
    orientations: tuple[str, ...]
    # An orientation's tag and whether it swaps the axes; `{tag}` and `{swap}` stand for
    # them.
    tag: str
    # Whether the axes are swapped: yes, then no.
    swaps: tuple[str, str]
    # The start of an orientation's matrix; `{matrix}` stands for it.
    matrix: str
    # What each file picture is, in the order it is drawn.
    read: tuple[str, str, str, str]
    # A picture's size at 300 dots to the inch; `{width}` and `{height}` stand for it.
    at_dpi: str
    # The resolution a picture states; `{x}`, `{y}` and `{square}` stand for it.
    stated: str
    # Whether it is the same both ways: yes, then no.
    square: tuple[str, str]
    # What a picture stating no resolution is said to state.
    unstated: str
    # How many extra channels a TIFF names; `{count}` stands for them.
    channels: str
    # The name of the layer the last picture lies on.
    layer: str
    # Where the last picture lies; `{layer}` stands for the layer.
    on_layer: str
    # What stands under the letter drawn inline.
    inline: str
    # What stands under the picture read as measured colour.
    measured: str


# The pages in English.
ENGLISH = Words(
    title="Pictures made in memory, and what each is told",
    files="One picture turned eight ways, and pictures read from files",
    made=(
        "From red, green and blue",
        "From four process inks",
        "From a table of colours",
        "From samples with opacity",
        "Through a colour key",
        "Through a soft mask",
        "Through a stencil mask",
        "A stencil in the page's colour",
        "Decoded upside down",
        "Smoothed when enlarged",
        "Left as its pixels",
        "A profile and an intent",
        "Its opacity dropped",
        "In one press ink",
        "In two press inks",
        "Held within a clipping path",
    ),
    yes_no=(
        "yes",
        "no",
    ),
    size="{width} × {height} px, {count} components",
    bits="{bits} bits a component",
    soft="soft mask: {answer}",
    keyed="keyed out: {ranges}",
    stencil_mask="stencil mask: {answer}",
    stencil="stencil: {answer}",
    decoded="decoded: {ranges}",
    smoothed="smoothed: {answer}",
    profile="profile {bytes} bytes, {intent}",
    intents=(
        "perceptual",
        "relative colorimetric",
        "saturation",
        "absolute colorimetric",
    ),
    components="components a pixel: {count}",
    path="contours: {contours}; knots: {knots}",
    orientations=(
        "Upright",
        "Mirrored left to right",
        "Upside down",
        "Mirrored top to bottom",
        "Mirrored, turned left",
        "Turned right",
        "Mirrored, turned right",
        "Turned left",
    ),
    tag="tag {tag}; {swap}",
    swaps=(
        "axes swapped",
        "axes kept",
    ),
    matrix="matrix [{matrix}]",
    read=(
        "A PNG, read as a PNG",
        "A JPEG, read as a JPEG",
        "A BMP, read as a BMP",
        "A TIFF, read as a TIFF",
    ),
    at_dpi="at 300 dpi: {width} × {height} pt",
    stated="{x} × {y} dpi, {square}",
    square=(
        "square",
        "not square",
    ),
    unstated="states no resolution",
    channels="extra channels named: {count}",
    layer="Photographs",
    on_layer="on the layer “{layer}”",
    inline="the letter, written into the page's own stream",
    measured="Read as measured colour, L*a*b*",
)

# The pages in French.
FRENCH = Words(
    title="Des images créées en mémoire, et ce qu’on dit à chacune",
    files="Une image en huit sens, et des images de fichiers",
    made=(
        "En rouge, vert et bleu",
        "En quadrichromie",
        "D’après une table de couleurs",
        "Avec sa propre opacité",
        "Par une clé de couleur",
        "Par un masque progressif",
        "Par un masque au pochoir",
        "En pochoir, couleur de la page",
        "Décodée à l’envers",
        "Lissée quand on l’agrandit",
        "Laissée en pixels",
        "Un profil et une intention",
        "Son opacité retirée",
        "En une encre d’imprimerie",
        "En deux encres d’imprimerie",
        "Dans un tracé de détourage",
    ),
    yes_no=(
        "oui",
        "non",
    ),
    size="{width} × {height} px, {count} composantes",
    bits="{bits} bits par composante",
    soft="masque progressif : {answer}",
    keyed="exclues : {ranges}",
    stencil_mask="masque au pochoir : {answer}",
    stencil="pochoir : {answer}",
    decoded="décodage : {ranges}",
    smoothed="lissée : {answer}",
    profile="profil {bytes} octets, {intent}",
    intents=(
        "perceptuelle",
        "colorimétrique relative",
        "saturation",
        "colorimétrique absolue",
    ),
    components="composantes par pixel : {count}",
    path="contours : {contours} ; nœuds : {knots}",
    orientations=(
        "À l’endroit",
        "En miroir de gauche à droite",
        "À l’envers",
        "En miroir de haut en bas",
        "En miroir, tournée à gauche",
        "Tournée à droite",
        "En miroir, tournée à droite",
        "Tournée à gauche",
    ),
    tag="étiquette {tag} ; {swap}",
    swaps=(
        "axes échangés",
        "axes gardés",
    ),
    matrix="matrice [{matrix}]",
    read=(
        "Un PNG, lu comme un PNG",
        "Un JPEG, lu comme un JPEG",
        "Un BMP, lu comme un BMP",
        "Un TIFF, lu comme un TIFF",
    ),
    at_dpi="à 300 ppp : {width} × {height} pt",
    stated="{x} × {y} ppp, {square}",
    square=(
        "carrée",
        "non carrée",
    ),
    unstated="n’indique aucune résolution",
    channels="autres canaux nommés : {count}",
    layer="Photographies",
    on_layer="sur le calque « {layer} »",
    inline="la lettre, écrite dans le flux de la page même",
    measured="Lue en couleur mesurée, L*a*b*",
)

# The pages in Dutch.
DUTCH = Words(
    title="Afbeeldingen uit het geheugen, en hun instellingen",
    files="Eén afbeelding in acht standen, en beelden uit bestanden",
    made=(
        "Uit rood, groen en blauw",
        "Uit vier procesinkten",
        "Uit een kleurentabel",
        "Uit waarden met dekking",
        "Via een kleursleutel",
        "Via een zacht masker",
        "Via een sjabloonmasker",
        "Sjabloon in paginakleur",
        "Ondersteboven gedecodeerd",
        "Gladgemaakt bij vergroten",
        "Als pixels gelaten",
        "Een profiel en een intentie",
        "Dekking verlaagd",
        "In één persinkt",
        "In twee persinkten",
        "Binnen een uitknippad",
    ),
    yes_no=(
        "ja",
        "nee",
    ),
    size="{width} × {height} px, {count} componenten",
    bits="{bits} bits per component",
    soft="zacht masker: {answer}",
    keyed="sleutel: {ranges}",
    stencil_mask="sjabloonmasker: {answer}",
    stencil="sjabloon: {answer}",
    decoded="gedecodeerd: {ranges}",
    smoothed="gladgemaakt: {answer}",
    profile="profiel {bytes} bytes, {intent}",
    intents=(
        "perceptueel",
        "relatief colorimetrisch",
        "verzadiging",
        "absoluut colorimetrisch",
    ),
    components="componenten per pixel: {count}",
    path="contouren: {contours}; knopen: {knots}",
    orientations=(
        "Rechtop",
        "Links-rechts gespiegeld",
        "Ondersteboven",
        "Boven-onder gespiegeld",
        "Gespiegeld, linksom gedraaid",
        "Rechtsom gedraaid",
        "Gespiegeld, rechtsom gedraaid",
        "Linksom gedraaid",
    ),
    tag="tag {tag}; {swap}",
    swaps=(
        "assen verwisseld",
        "assen behouden",
    ),
    matrix="matrix [{matrix}]",
    read=(
        "Een PNG, gelezen als PNG",
        "Een JPEG, gelezen als JPEG",
        "Een BMP, gelezen als BMP",
        "Een TIFF, gelezen als TIFF",
    ),
    at_dpi="op 300 dpi: {width} × {height} pt",
    stated="{x} × {y} dpi, {square}",
    square=(
        "vierkant",
        "niet vierkant",
    ),
    unstated="vermeldt geen resolutie",
    channels="extra kanalen met een naam: {count}",
    layer="Foto’s",
    on_layer="op de laag „{layer}”",
    inline="de letter, geschreven in de eigen stroom van de pagina",
    measured="Gelezen als gemeten L*a*b*-kleur",
)

# The pages in Portuguese.
PORTUGUESE = Words(
    title="Imagens feitas em memória, e o que se diz a cada uma",
    files="Uma imagem em oito orientações e imagens de ficheiros",
    made=(
        "De vermelho, verde e azul",
        "De quadricromia",
        "De uma tabela de cores",
        "De amostras com opacidade",
        "Com uma chave de cor",
        "Com uma máscara suave",
        "Com uma máscara de estêncil",
        "Um estêncil na cor da página",
        "Descodificada invertida",
        "Suavizada ao ampliar",
        "Deixada nos seus píxeis",
        "Um perfil e uma intenção",
        "Opacidade reduzida",
        "Numa tinta de gráfica",
        "Em duas tintas de gráfica",
        "Num traçado de recorte",
    ),
    yes_no=(
        "sim",
        "não",
    ),
    size="{width} × {height} px, {count} componentes",
    bits="{bits} bits por componente",
    soft="máscara suave: {answer}",
    keyed="exclui {ranges}",
    stencil_mask="máscara de estêncil: {answer}",
    stencil="estêncil: {answer}",
    decoded="descodificada: {ranges}",
    smoothed="suavizada: {answer}",
    profile="perfil {bytes} bytes, {intent}",
    intents=(
        "percetual",
        "colorimétrica relativa",
        "saturação",
        "colorimétrica absoluta",
    ),
    components="componentes por píxel: {count}",
    path="contornos: {contours}; nós: {knots}",
    orientations=(
        "Na posição normal",
        "Espelhada na horizontal",
        "De pernas para o ar",
        "Espelhada na vertical",
        "Espelhada, rodada à esquerda",
        "Rodada à direita",
        "Espelhada, rodada à direita",
        "Rodada à esquerda",
    ),
    tag="etiqueta {tag}; {swap}",
    swaps=(
        "eixos trocados",
        "eixos mantidos",
    ),
    matrix="matriz [{matrix}]",
    read=(
        "Um PNG, lido como PNG",
        "Um JPEG, lido como JPEG",
        "Um BMP, lido como BMP",
        "Um TIFF, lido como TIFF",
    ),
    at_dpi="a 300 ppp: {width} × {height} pt",
    stated="{x} × {y} ppp, {square}",
    square=(
        "quadrado",
        "não quadrado",
    ),
    unstated="não indica resolução",
    channels="canais extra com nome: {count}",
    layer="Fotografias",
    on_layer="na camada «{layer}»",
    inline="a letra, escrita no próprio fluxo da página",
    measured="Lida como cor medida em L*a*b*",
)

# The pages in Italian.
ITALIAN = Words(
    title="Immagini create in memoria, e ciò che si dice a ciascuna",
    files="Un’immagine ruotata in otto modi, e immagini lette da file",
    made=(
        "Da rosso, verde e blu",
        "In quadricromia",
        "Da una tabella di colori",
        "Da campioni con opacità",
        "Con una chiave di colore",
        "Con una maschera morbida",
        "Con una maschera a stencil",
        "Stencil nel colore di pagina",
        "Decodificata capovolta",
        "Smussata quando ingrandita",
        "Non smussata",
        "Profilo e intento di rendering",
        "Opacità ridotta",
        "In un inchiostro da stampa",
        "In due inchiostri da stampa",
        "In un tracciato di ritaglio",
    ),
    yes_no=(
        "sì",
        "no",
    ),
    size="{width} × {height} px, {count} componenti",
    bits="{bits} bit per componente",
    soft="maschera morbida: {answer}",
    keyed="esclude {ranges}",
    stencil_mask="maschera a stencil: {answer}",
    stencil="stencil: {answer}",
    decoded="decodificata: {ranges}",
    smoothed="smussata: {answer}",
    profile="profilo: {bytes} byte, {intent}",
    intents=(
        "percettivo",
        "colorimetrico relativo",
        "saturazione",
        "colorimetrico assoluto",
    ),
    components="componenti per pixel: {count}",
    path="contorni: {contours}; nodi: {knots}",
    orientations=(
        "Diritta",
        "Specchiata in orizzontale",
        "Capovolta",
        "Specchiata in verticale",
        "Specchiata, ruotata a sinistra",
        "Ruotata a destra",
        "Specchiata, ruotata a destra",
        "Ruotata a sinistra",
    ),
    tag="tag {tag}; {swap}",
    swaps=(
        "assi scambiati",
        "assi mantenuti",
    ),
    matrix="matrice [{matrix}]",
    read=(
        "Un PNG, letto come PNG",
        "Un JPEG, letto come JPEG",
        "Un BMP, letto come BMP",
        "Un TIFF, letto come TIFF",
    ),
    at_dpi="a 300 dpi: {width} × {height} pt",
    stated="{x} × {y} dpi, {square}",
    square=(
        "quadrati",
        "non quadrati",
    ),
    unstated="non indica risoluzione",
    channels="canali extra con nome: {count}",
    layer="Fotografie",
    on_layer="sul livello «{layer}»",
    inline="la lettera, scritta nel flusso proprio della pagina",
    measured="Letta come colore CIE L*a*b*",
)

# The pages in Spanish.
SPANISH = Words(
    title="Imágenes en memoria y lo que se indica a cada una",
    files="Una imagen en ocho orientaciones, e imágenes de archivos",
    made=(
        "De rojo, verde y azul",
        "De cuatricromía",
        "De una tabla de colores",
        "De muestras con opacidad",
        "Con una clave de color",
        "Con una máscara suave",
        "Con una máscara de estarcido",
        "Estarcido en color de página",
        "Decodificada cabeza abajo",
        "Suavizada al ampliarse",
        "Dejada en sus píxeles",
        "Un perfil y una intención",
        "Su opacidad rebajada",
        "En una tinta de imprenta",
        "En dos tintas de imprenta",
        "En un trazado de recorte",
    ),
    yes_no=(
        "sí",
        "no",
    ),
    size="{width} × {height} px, {count} componentes",
    bits="{bits} bits por componente",
    soft="máscara suave: {answer}",
    keyed="excluye {ranges}",
    stencil_mask="máscara de estarcido: {answer}",
    stencil="estarcido: {answer}",
    decoded="decodificada: {ranges}",
    smoothed="suavizada: {answer}",
    profile="perfil: {bytes} bytes, {intent}",
    intents=(
        "perceptual",
        "colorimétrica relativa",
        "saturación",
        "colorimétrica absoluta",
    ),
    components="componentes por píxel: {count}",
    path="contornos: {contours}; nodos: {knots}",
    orientations=(
        "Sin girar",
        "Volteada en horizontal",
        "Cabeza abajo",
        "Volteada en vertical",
        "Reflejada, girada a la izquierda",
        "Girada a la derecha",
        "Reflejada, girada a la derecha",
        "Girada a la izquierda",
    ),
    tag="etiqueta {tag}; {swap}",
    swaps=(
        "ejes intercambiados",
        "ejes conservados",
    ),
    matrix="matriz [{matrix}]",
    read=(
        "Un PNG, leído como PNG",
        "Un JPEG, leído como JPEG",
        "Un BMP, leído como BMP",
        "Un TIFF, leído como TIFF",
    ),
    at_dpi="a 300 ppp: {width} × {height} pt",
    stated="{x} × {y} ppp, {square}",
    square=(
        "cuadrado",
        "no cuadrado",
    ),
    unstated="no indica resolución",
    channels="canales extra con nombre: {count}",
    layer="Fotografías",
    on_layer="en la capa «{layer}»",
    inline="la letra, escrita en el propio flujo de la página",
    measured="Leída como color medido, L*a*b*",
)

# The pages in German.
GERMAN = Words(
    title="Bilder aus dem Speicher und was jedem mitgegeben wird",
    files="Ein Bild, achtfach gedreht, und Bilder aus Dateien",
    made=(
        "Aus Rot, Grün und Blau",
        "Aus vier Prozessfarben",
        "Aus einer Farbtabelle",
        "Aus Werten mit Deckkraft",
        "Über einen Farbschlüssel",
        "Über eine weiche Maske",
        "Über eine Schablonenmaske",
        "Schablone in Seitenfarbe",
        "Invertiert dekodiert",
        "Beim Vergrößern geglättet",
        "Als Pixel belassen",
        "Profil und Wiedergabeabsicht",
        "Mit verringerter Deckkraft",
        "In einer Druckfarbe",
        "In zwei Druckfarben",
        "In einem Schnittpfad",
    ),
    yes_no=(
        "ja",
        "nein",
    ),
    size="{width} × {height} px, {count} Komponenten",
    bits="{bits} Bit je Komponente",
    soft="weiche Maske: {answer}",
    keyed="ausgespart: {ranges}",
    stencil_mask="Schablonenmaske: {answer}",
    stencil="Schablone: {answer}",
    decoded="dekodiert: {ranges}",
    smoothed="geglättet: {answer}",
    profile="Profil {bytes} Bytes, {intent}",
    intents=(
        "perzeptiv",
        "relativ farbmetrisch",
        "Sättigung",
        "absolut farbmetrisch",
    ),
    components="Komponenten je Pixel: {count}",
    path="Konturen: {contours}; Knoten: {knots}",
    orientations=(
        "Aufrecht",
        "Links-rechts gespiegelt",
        "Auf dem Kopf",
        "Oben-unten gespiegelt",
        "Gespiegelt, links gedreht",
        "Nach rechts gedreht",
        "Gespiegelt, rechts gedreht",
        "Nach links gedreht",
    ),
    tag="Wert {tag}; {swap}",
    swaps=(
        "Achsen vertauscht",
        "Achsen beibehalten",
    ),
    matrix="Matrix [{matrix}]",
    read=(
        "Ein PNG, als PNG gelesen",
        "Ein JPEG, als JPEG gelesen",
        "Ein BMP, als BMP gelesen",
        "Ein TIFF, als TIFF gelesen",
    ),
    at_dpi="bei 300 dpi: {width} × {height} pt",
    stated="{x} × {y} dpi, {square}",
    square=(
        "quadratisch",
        "rechteckig",
    ),
    unstated="gibt keine Auflösung an",
    channels="benannte Zusatzkanäle: {count}",
    layer="Fotos",
    on_layer="auf der Ebene „{layer}“",
    inline="der Buchstabe, in den eigenen Datenstrom der Seite geschrieben",
    measured="Als L*a*b*-Messwerte gelesen",
)

# 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 four rendering intents, in the order `Words.intents` names them.
INTENTS = (
    hqf_pdf.RenderingIntent.perceptual(),
    hqf_pdf.RenderingIntent.relative_colorimetric(),
    hqf_pdf.RenderingIntent.saturation(),
    hqf_pdf.RenderingIntent.absolute_colorimetric(),
)


def number(value: float) -> str:
    """`value` written the shortest way that reads back as it, a whole number without
    its point."""
    return str(int(value)) if value == int(value) else repr(value)


def rgb_samples() -> bytes:
    """Red rising across the tile, green rising down it, a steady blue."""
    return bytes(
        value
        for y in range(TILE)
        for x in range(TILE)
        for value in (min(x * 8, 255), min(y * 8, 255), 128)
    )


def cmyk_samples() -> bytes:
    """Cyan rising across the tile, magenta rising down it, no yellow, no black."""
    return bytes(
        value
        for y in range(TILE)
        for x in range(TILE)
        for value in (min(x * 8, 255), min(y * 8, 255), 0, 0)
    )


def gray_ramp() -> bytes:
    """A grey rising across the tile."""
    return bytes(min(x * 8, 255) for __ in range(TILE) for x in range(TILE))


def lab_samples() -> bytes:
    """A steady lightness, the green-to-red number rising across the tile and the
    blue-to-yellow one rising down it, each byte read over the range of `lab_space`."""
    return bytes(
        value
        for y in range(TILE)
        for x in range(TILE)
        for value in (180, min(x * 8, 255), min(y * 8, 255))
    )


def lab_space() -> hqf_pdf.ImageSpace:
    """CIE 1976 L*a*b* against the D50 white, both colour numbers running from −128 to
    127."""
    return hqf_pdf.ImageSpace.lab(
        hqf_pdf.Lab((0.9642, 1.0, 0.8249)).range((-128.0, 127.0, -128.0, 127.0))
    )


def checker_bits() -> bytes:
    """Squares of eight pixels, one bit a pixel, alternately set and clear."""
    return bytes(
        0xFF if (column + y // 8) % 2 == 0 else 0x00
        for y in range(TILE)
        for column in range(TILE // 8)
    )


def indexed() -> tuple[bytes, bytes]:
    """A table of sixteen colours, and the tile's pixels as four-bit places in it, two
    to a byte."""
    palette = bytes(
        value
        for entry in range(16)
        for value in (entry * 16, 255 - entry * 16, entry * 8)
    )
    samples = bytes(
        ((x + y) % 16) << 4 | ((x + 1 + y) % 16)
        for y in range(TILE)
        for x in range(0, TILE, 2)
    )
    return palette, samples


def letter_f() -> bytes:
    """A letter F on white, eight pixels by twelve, which shows which way it was
    turned."""
    rows = ["########", "########"] + ["##......"] * 2 + ["######.."] * 2
    rows += ["##......"] * 6
    return bytes(
        value
        for row in rows
        for mark in row
        for value in ((20, 20, 20) if mark == "#" else (255, 255, 255))
    )


def two_inks() -> hqf_pdf.DeviceN:
    """Two inks named for the press, and the program laying them down on the four
    process plates: the first ink is all cyan, the second all yellow."""
    body = [hqf_pdf.Op.integer(0), hqf_pdf.Op.exchange(), hqf_pdf.Op.integer(0)]
    return hqf_pdf.DeviceN(
        ["Harbour Cyan", "Harbour Yellow"],
        hqf_pdf.DeviceSpace.Cmyk,
        hqf_pdf.Calculation([(0.0, 1.0)] * 2, [(0.0, 1.0)] * 4, body),
    )


def yes_no(answer: bool, words: Words) -> str:
    """`answer` in `words`."""
    return words.yes_no[0] if answer else words.yes_no[1]


def ranges(pairs) -> str:
    """`pairs` as the page writes them."""
    return ", ".join(f"{number(low)}–{number(high)}" for low, high in pairs)


def diamond() -> hqf_pdf.ClippingPath:
    """A clipping path with one contour: a diamond whose sides bow outwards."""
    knots = [
        hqf_pdf.Knot((0.2, 0.95), (0.5, 1.0), (0.8, 0.95)),
        hqf_pdf.Knot((0.95, 0.8), (1.0, 0.5), (0.95, 0.2)),
        hqf_pdf.Knot((0.8, 0.05), (0.5, 0.0), (0.2, 0.05)),
        hqf_pdf.Knot((0.05, 0.2), (0.0, 0.5), (0.05, 0.8)),
    ]
    return hqf_pdf.ClippingPath([hqf_pdf.Contour(knots)])


def made(words: Words) -> list[tuple[hqf_pdf.Image, str]]:
    """The sixteen pictures of the first page, each with the one line it says of
    itself."""
    image = hqf_pdf.Image
    rgb = image.from_rgb(TILE, TILE, rgb_samples())
    cmyk = image.from_cmyk(TILE, TILE, cmyk_samples())
    palette, places = indexed()
    table = image.from_raw(TILE, TILE, 4, hqf_pdf.ImageSpace.indexed(palette), places)
    rgba_samples = bytearray()
    ramp = gray_ramp()
    colours = rgb_samples()
    for place, alpha in enumerate(ramp):
        rgba_samples += colours[place * 3 : place * 3 + 3]
        rgba_samples.append(alpha)
    rgba = image.from_rgba(TILE, TILE, bytes(rgba_samples))
    keyed = rgb.with_color_key([(0, 90), (0, 90), (0, 255)])
    soft = rgb.with_soft_mask(image.from_gray(TILE, TILE, ramp))
    checker = image.from_raw(TILE, TILE, 1, hqf_pdf.ImageSpace.gray(), checker_bits())
    masked = rgb.with_stencil_mask(checker.as_stencil())
    stencil = checker.as_stencil()
    decoded = rgb.with_decode([(1.0, 0.0), (1.0, 0.0), (1.0, 0.0)])
    small = image.from_rgb(4, 4, colours[:48])
    profiled = rgb.with_icc_profile(hqf_pdf.srgb_icc_profile()).with_rendering_intent(
        hqf_pdf.RenderingIntent.perceptual()
    )
    dropped = rgba.without_transparency()
    ink = hqf_pdf.Separation.ink("Harbour Blue", hqf_pdf.Cmyk(0.9, 0.5, 0.0, 0.1))
    one_ink = image.from_gray(TILE, TILE, ramp).in_named_inks(
        hqf_pdf.ImageSpace.separation(ink)
    )
    paired = bytes(value for pair in zip(ramp, reversed(ramp)) for value in pair)
    two = image.from_raw(
        TILE, TILE, 8, hqf_pdf.ImageSpace.device_n(two_inks()), paired
    )
    clipped = rgb.with_clipping_path(diamond())
    smoothed = small.with_interpolation(True)

    def size(picture) -> str:
        return (
            words.size.replace("{width}", str(picture.width))
            .replace("{height}", str(picture.height))
            .replace("{count}", str(picture.color_space.components))
        )

    path = clipped.clipping_path
    knots = sum(len(contour.knots) for contour in path.contours)
    intent = profiled.rendering_intent
    said = [
        size(rgb),
        size(cmyk),
        words.bits.replace("{bits}", str(table.bits_per_component)),
        words.soft.replace("{answer}", yes_no(rgba.soft_mask is not None, words)),
        words.keyed.replace("{ranges}", ranges(keyed.color_key or [])),
        words.soft.replace("{answer}", yes_no(soft.soft_mask is not None, words)),
        words.stencil_mask.replace(
            "{answer}", yes_no(masked.stencil_mask is not None, words)
        ),
        words.stencil.replace("{answer}", yes_no(stencil.is_stencil, words)),
        words.decoded.replace("{ranges}", ranges(decoded.decode or [])),
        words.smoothed.replace("{answer}", yes_no(smoothed.is_interpolated, words)),
        words.smoothed.replace("{answer}", yes_no(small.is_interpolated, words)),
        words.profile.replace("{bytes}", str(len(profiled.icc_profile or b""))).replace(
            "{intent}", "" if intent is None else words.intents[INTENTS.index(intent)]
        ),
        words.soft.replace("{answer}", yes_no(dropped.soft_mask is not None, words)),
        words.components.replace("{count}", str(one_ink.color_space.components)),
        words.components.replace("{count}", str(two.color_space.components)),
        words.path.replace("{contours}", str(len(path.contours))).replace(
            "{knots}", str(knots)
        ),
    ]
    pictures = [
        rgb,
        cmyk,
        table,
        rgba,
        keyed,
        soft,
        masked,
        stencil,
        decoded,
        smoothed,
        small,
        profiled,
        dropped,
        one_ink,
        two,
        clipped,
    ]
    return list(zip(pictures, said))


def caption(content, font, at, line: str) -> None:
    """Set `line` at `at` in `font` at the captions' size."""
    content.draw_text(font, CAPTION, at[0], at[1], line)


# How wide the line tracing a clipping path over its picture is, in points.
TRACE = 0.6


def cell(index: int) -> tuple[float, float]:
    """Where cell `index` of a grid four across starts: its left edge and the top of its
    picture."""
    return LEFT + ACROSS * (index % 4), FIRST_ROW - DOWN * (index // 4)


def first_page(doc, font, words: Words) -> hqf_pdf.Page:
    """The first page: the sixteen pictures made in memory, each over its title and the
    line it says of itself."""
    content = hqf_pdf.Content()
    content.draw_text(font, 16.0, LEFT, 790.0, words.title)
    for index, (picture, said) in enumerate(made(words)):
        x, top = cell(index)
        bottom = top - SIDE
        # A band behind the pictures that leave the page showing through.
        if 3 <= index <= 7 or index == 15:
            content.set_fill(hqf_pdf.Rgb(0.75, 0.75, 0.75))
            content.rect(x, bottom + SIDE / 3.0, SIDE, SIDE / 3.0)
            content.fill()
        content.set_fill(hqf_pdf.Rgb(0.85, 0.35, 0.1))
        clipped = picture.clipping_path is not None
        handle = doc.add_image(picture)
        if clipped:
            content.draw_image_clipped(handle, x, bottom, SIDE, SIDE)
            # The path itself, traced over the picture it holds: its points are
            # fractions of the picture, so it is traced into the same square.
            path = handle.clipping_path
            if path is not None:
                content.save_state()
                content.transform((SIDE, 0.0, 0.0, SIDE, x, bottom))
                content.set_line_width(TRACE / SIDE)
                content.set_stroke(hqf_pdf.Rgb(0.1, 0.1, 0.1))
                content.trace_clipping_path(path)
                content.stroke()
                content.restore_state()
        else:
            content.draw_image(handle, x, bottom, SIDE, SIDE)
        content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
        caption(content, font, (x, bottom - 12.0), words.made[index])
        caption(content, font, (x, bottom - 22.0), said)
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page


def second_page(doc, font, words: Words) -> hqf_pdf.Page:
    """The second page: the letter turned by each of the eight orientations, and four
    pictures read from files, the last on a layer, then the letter written inline and a
    picture read as measured colour."""
    content = hqf_pdf.Content()
    content.draw_text(font, 16.0, LEFT, 790.0, words.files)

    letter = hqf_pdf.Image.from_rgb(8, 12, letter_f())
    for tag in range(1, 9):
        index = tag - 1
        x, top = cell(index)
        orientation = hqf_pdf.Orientation.from_tag(tag)
        if orientation is None:
            continue
        turned = letter.with_orientation(orientation)
        # The box is the picture as it is seen: turned a quarter, it is as wide as it
        # was tall.
        if orientation.swaps_axes:
            width, height = SIDE, SIDE * 8.0 / 12.0
        else:
            width, height = SIDE * 8.0 / 12.0, SIDE
        handle = doc.add_image(turned)
        content.draw_image(handle, x, top - height, width, height)
        swap = words.swaps[0 if orientation.swaps_axes else 1]
        said = words.tag.replace("{tag}", str(orientation.tag)).replace("{swap}", swap)
        matrix = " ".join(number(entry) for entry in orientation.matrix[:4])
        caption(content, font, (x, top - SIDE - 12.0), words.orientations[index])
        caption(content, font, (x, top - SIDE - 22.0), said)
        caption(
            content,
            font,
            (x, top - SIDE - 32.0),
            words.matrix.replace("{matrix}", matrix),
        )

    x, top = cell(12)
    content.draw_inline_image(letter, x, top - SIDE, SIDE * 8.0 / 12.0, SIDE)
    caption(content, font, (x, top - SIDE - 12.0), words.inline)

    measured = hqf_pdf.Image.from_rgb(TILE, TILE, lab_samples()).in_measured_color(
        lab_space()
    )
    components = words.components.replace(
        "{count}", str(measured.color_space.components)
    )
    x, top = cell(15)
    handle = doc.add_image(measured)
    content.draw_image(handle, x, top - SIDE, SIDE, SIDE)
    caption(content, font, (x, top - SIDE - 12.0), words.measured)
    caption(content, font, (x, top - SIDE - 22.0), components)

    images = TESTS / "images"
    layer = doc.add_layer(hqf_pdf.Layer(words.layer))
    image = hqf_pdf.Image
    pictures = [
        image.from_png((images / "logo.png").read_bytes()),
        image.from_jpeg((images / "jfif_300dpi.jpg").read_bytes()),
        image.from_bmp((images / "truecolour.bmp").read_bytes()),
        image.from_tiff((images / "photograph.tif").read_bytes()).layer(layer),
    ]
    channels = len(image.tiff_channel_names((images / "pages.tif").read_bytes(), 0))
    for place, picture in enumerate(pictures):
        x, top = cell(8 + place)
        wide, tall = picture.size_at_dpi(300.0)
        at_dpi = words.at_dpi.replace("{width}", f"{wide:.0f}").replace(
            "{height}", f"{tall:.0f}"
        )
        dpi = picture.resolution
        if dpi is None:
            stated = words.unstated
        else:
            same = hqf_pdf.Resolution.square(dpi.x) == dpi
            stated = (
                words.stated.replace("{x}", f"{dpi.x:.0f}")
                .replace("{y}", f"{dpi.y:.0f}")
                .replace("{square}", words.square[0 if same else 1])
            )
        last = words.channels.replace("{count}", str(channels)) if place == 3 else ""
        handle = doc.add_image(picture)
        width, height = handle.fit_within(SIDE, SIDE)
        content.draw_image(handle, x, top - height, width, height)
        caption(content, font, (x, top - SIDE - 12.0), words.read[place])
        caption(content, font, (x, top - SIDE - 22.0), at_dpi)
        caption(content, font, (x, top - SIDE - 32.0), stated)
        if last:
            caption(content, font, (x, top - SIDE - 42.0), last)
            caption(
                content,
                font,
                (x, top - SIDE - 52.0),
                words.on_layer.replace("{layer}", words.layer),
            )

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    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("image_settings.pdf", language)).stem
    )

    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    doc.set_info("Title", words.title)
    font = doc.add_font(hqf_pdf.Font.from_path(TESTS / "fonts" / "DejaVuSans.ttf"))
    doc.add_page(first_page(doc, font, words))
    doc.add_page(second_page(doc, font, words))

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


if __name__ == "__main__":
    main()
