"""Draws one plan on six layers a reader can show and hide.

The Python twin of the `write_layers` example in Rust. The walls are the page's own ink
and are always there. Everything else belongs to a layer: the furniture and the
dimensions start shown, the notes start hidden, and the draft mark is looked at but
never printed. The file also says what three of the layers are: the draft mark is a
watermark, a grid laid over the plan says it is an aid for whoever drew it and asks to
start hidden, and the crop marks at the corners of the sheet are printer's marks. The
furniture layer names the program it came from, Plan Studio, and says it holds a
technical design. The chairs are one drawing placed six times, and the drawing itself belongs to the furniture
layer, so hiding that layer hides every chair. Open the file and reading software's
layers panel lists all six; print it and the draft mark is gone without anyone touching
that panel. The name of the notes layer in the legend is a switch of its own: clicking
it shows the notes, and clicking it again hides them.

The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. A layer's name is language too: reading software's panel shows it, and the legend
under the plan names the same field, so the panel and the page can never disagree.

The second page sends the plan out as a sheet whose every part says what it is: the
paper tint is a background left out of the panel, the title block a header locked under
a heading of its own, the studio's mark a logo that says who drew it, two stamps a
family shown one at a time, and a trap line is for the printer. Four marks are each
shown under one policy over the title block and the logo, a second set of states is
offered for review, and one link switches three layers at once.

The file opens with the layers panel shown, and shows it again after full screen.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Callable

import _language
import _licence
import _out

import hqf_pdf

# The plan's outer wall: where it sits on the page and how big it is.
PLAN = (80.0, 380.0, 435.0, 320.0)

# The two distances the plan is measured at. Neither is language.
ALONG = "7.25 m"
ACROSS = "5.00 m"

# Where each chair stands, by its lower left corner: three along each long side of the
# table.
CHAIRS = (
    (140.0, 662.0),
    (173.0, 662.0),
    (206.0, 662.0),
    (140.0, 578.0),
    (173.0, 578.0),
    (206.0, 578.0),
)

# The corners of the trimmed sheet the crop marks point at.
TRIM = (36.0, 36.0, 559.0, 806.0)


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

    A layer's name is here: reading software's panel shows it, and so does the legend.
    The two distances are not: a metre is a metre.
    """

    # The line at the head of the page.
    title: str
    # What stands under it, saying what a layer is.
    intro: str
    # What each layer is called, in the order they are added. Reading software's panel
    # lists these, and the legend names them again.
    layers: tuple[str, str, str, str, str, str]
    # What the legend says each layer holds and how it starts.
    holdings: tuple[str, str, str, str, str, str]
    # The notes the hidden layer holds, in the order they are placed.
    notes: tuple[str, str, str]
    # The word the draft mark is stamped in.
    draft: str
    # The two lines under the legend, saying that the draft mark takes itself off the
    # printed page.
    printing: tuple[str, str]
    # The second page's title.
    sheet_title: str
    # What the second page's layers are called: the paper, the title block, the logo,
    # the trap line.
    sheet_layers: tuple[str, str, str, str]
    # The heading the title block is filed under in the panel.
    heading: str
    # The two stamps, shown one at a time.
    stamps: tuple[str, str]
    # The name the panel offers the second set of layer states under.
    review: str
    # What each of the four marks under a rule says of when it shows.
    rules: tuple[str, str, str, str]
    # What the title block says under the sheet's title.
    title_block: str
    # The line that switches three layers at once.
    switches: str


# The page in English.
ENGLISH = Words(
    title="One plan, six layers",
    intro=(
        "The walls are always there. Everything else is a layer the reader can show "
        "and hide."
    ),
    layers=(
        "Furniture",
        "Dimensions",
        "Notes",
        "Draft",
        "Grid",
        "Crop marks",
    ),
    holdings=(
        "shown; turn it off and the rooms stand empty, chairs too",
        "shown; the distances around the plan",
        "hidden; click its name to show or hide them",
        "shown on screen, never printed; the file calls it a watermark",
        "hidden; an aid for whoever drew the plan, not part of it",
        "shown; the file calls them printer's marks",
    ),
    notes=(
        "Table seats six.",
        "Bed against the party wall.",
        "Counter, waste under.",
    ),
    draft="DRAFT",
    printing=(
        "The draft mark carries its own answer for the printer, so nothing has to",
        "be switched off before the page is printed.",
    ),
    sheet_title="The same plan, as a sheet that goes out",
    sheet_layers=(
        "Paper",
        "Title block",
        "Logo",
        "Traps",
    ),
    heading="Sheet",
    stamps=(
        "Approved",
        "Rejected",
    ),
    review="Review",
    rules=(
        "Shown while the title block and the logo are both shown",
        "Shown while either of them is shown",
        "Shown while either of them is hidden",
        "Shown while both of them are hidden",
    ),
    title_block="Sheet 2 of 2, issued for review",
    switches="Title block on, logo off, the rejection stamp flipped",
)

# The page in French.
FRENCH = Words(
    title="Un plan, six calques",
    intro=(
        "Les murs sont toujours là. Tout le reste est un calque à afficher ou à "
        "masquer."
    ),
    layers=(
        "Mobilier",
        "Cotes",
        "Notes",
        "Brouillon",
        "Grille",
        "Traits de coupe",
    ),
    holdings=(
        "affiché ; désactivez-le et les pièces sont vides, chaises comprises",
        "affiché ; les distances autour du plan",
        "masqué ; cliquez sur son nom pour les afficher ou les masquer",
        "affiché à l’écran, jamais imprimé ; le fichier le nomme filigrane",
        "masqué ; aide au tracé, qui ne fait pas partie du plan",
        "affiché ; le fichier les nomme repères d’imprimeur",
    ),
    notes=(
        "Table pour six personnes.",
        "Lit contre le mur mitoyen.",
        "Plan de travail, poubelle dessous.",
    ),
    draft="BROUILLON",
    printing=(
        "La mention de brouillon contient sa propre consigne d’impression :",
        "rien n’est à masquer avant d’imprimer la page.",
    ),
    sheet_title="Le même plan, en feuille émise",
    sheet_layers=(
        "Papier",
        "Cartouche",
        "Logo",
        "Grossi-maigri",
    ),
    heading="Feuille",
    stamps=(
        "Approuvé",
        "Refusé",
    ),
    review="Relecture",
    rules=(
        "Visible quand le cartouche et le logo sont tous deux visibles",
        "Visible quand l’un des deux est visible",
        "Visible quand l’un des deux est masqué",
        "Visible quand les deux sont masqués",
    ),
    title_block="Feuille 2 sur 2, émise pour relecture",
    switches="Cartouche affiché, logo masqué, tampon de refus basculé",
)

# The page in Dutch.
DUTCH = Words(
    title="Eén plattegrond, zes lagen",
    intro=(
        "De muren zijn er altijd. Al het andere is een laag die de lezer kan tonen en "
        "verbergen."
    ),
    layers=(
        "Meubels",
        "Maten",
        "Notities",
        "Concept",
        "Raster",
        "Snijtekens",
    ),
    holdings=(
        "getoond; zet haar uit en de kamers staan leeg, ook zonder stoelen",
        "getoond; de afstanden rond de plattegrond",
        "verborgen; klik op de naam om haar te tonen of te verbergen",
        "getoond op het scherm, nooit afgedrukt; het bestand noemt haar een watermerk",
        "verborgen; een hulp voor wie de plattegrond tekende, geen deel ervan",
        "getoond; het bestand noemt ze drukkerstekens",
    ),
    notes=(
        "De tafel heeft zes plaatsen.",
        "Bed tegen de scheidingsmuur.",
        "Aanrecht, afvalbak eronder.",
    ),
    draft="CONCEPT",
    printing=(
        "De conceptmarkering bevat haar eigen instructie voor de printer, dus hoeft er",
        "niets uitgezet te worden voordat de pagina wordt afgedrukt.",
    ),
    sheet_title="Dezelfde plattegrond, als blad dat de deur uitgaat",
    sheet_layers=(
        "Papier",
        "Titelblok",
        "Logo",
        "Valkuilen",
    ),
    heading="Blad",
    stamps=(
        "Goedgekeurd",
        "Afgekeurd",
    ),
    review="Beoordeling",
    rules=(
        "Getoond zolang titelblok en logo allebei getoond worden",
        "Getoond zolang een van beide getoond wordt",
        "Getoond zolang een van beide verborgen is",
        "Getoond zolang beide verborgen zijn",
    ),
    title_block="Blad 2 van 2, uitgegeven ter beoordeling",
    switches="Titelblok aan, logo uit, de afkeuringsstempel omgedraaid",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Uma planta, seis camadas",
    intro=(
        "As paredes estão sempre lá. Tudo o resto é uma camada que o leitor pode "
        "mostrar e ocultar."
    ),
    layers=(
        "Mobiliário",
        "Cotas",
        "Notas",
        "Rascunho",
        "Grelha",
        "Marcas de corte",
    ),
    holdings=(
        "visível; desligue-a e as divisões ficam vazias, cadeiras incluídas",
        "visível; as distâncias à volta da planta",
        "oculta; clique no nome para a mostrar ou ocultar",
        "visível no ecrã, nunca impressa; o ficheiro chama-lhe marca de água",
        "oculta; uma ajuda para quem desenhou a planta, não parte dela",
        "visível; o ficheiro chama-lhes marcas de impressão",
    ),
    notes=(
        "A mesa tem seis lugares.",
        "Cama encostada à parede meeira.",
        "Bancada, caixote do lixo por baixo.",
    ),
    draft="RASCUNHO",
    printing=(
        "A marca de rascunho leva a sua própria resposta para a impressora, por isso não é",
        "preciso desligar nada antes de imprimir a página.",
    ),
    sheet_title="A mesma planta, como folha emitida",
    sheet_layers=(
        "Papel",
        "Legenda",
        "Logótipo",
        "Trapping",
    ),
    heading="Folha",
    stamps=(
        "Aprovado",
        "Rejeitado",
    ),
    review="Revisão",
    rules=(
        "Visível enquanto a legenda e o logótipo estão ambos visíveis",
        "Visível enquanto um dos dois está visível",
        "Visível enquanto um dos dois está oculto",
        "Visível enquanto os dois estão ocultos",
    ),
    title_block="Folha 2 de 2, emitida para revisão",
    switches="Legenda visível, logótipo oculto, o carimbo de rejeição invertido",
)

# The page in Italian.
ITALIAN = Words(
    title="Una pianta, sei livelli",
    intro=(
        "I muri ci sono sempre. Tutto il resto è un livello che il lettore può "
        "mostrare e nascondere."
    ),
    layers=(
        "Arredo",
        "Quote",
        "Note",
        "Bozza",
        "Griglia",
        "Segni di taglio",
    ),
    holdings=(
        "visibile; spegnetelo e le stanze restano vuote, sedie comprese",
        "visibile; le distanze intorno alla pianta",
        "nascosto; cliccate sul suo nome per mostrarlo o nasconderlo",
        "visibile a schermo, mai stampato; il file lo chiama filigrana",
        "nascosto; un aiuto per chi ha disegnato la pianta, non parte di essa",
        "visibile; il file li chiama segni di stampa",
    ),
    notes=(
        "Il tavolo ha sei posti.",
        "Letto contro il muro divisorio.",
        "Bancone, pattumiera sotto.",
    ),
    draft="BOZZA",
    printing=(
        "Il segno di bozza porta la propria risposta per la stampante, così non c’è",
        "niente da spegnere prima di stampare la pagina.",
    ),
    sheet_title="La stessa pianta, come tavola emessa",
    sheet_layers=(
        "Carta",
        "Cartiglio",
        "Logo",
        "Trapping",
    ),
    heading="Tavola",
    stamps=(
        "Approvato",
        "Respinto",
    ),
    review="Revisione",
    rules=(
        "Visibile quando il cartiglio e il logo sono entrambi visibili",
        "Visibile quando uno dei due è visibile",
        "Visibile quando uno dei due è nascosto",
        "Visibile quando entrambi sono nascosti",
    ),
    title_block="Tavola 2 di 2, emessa per revisione",
    switches="Cartiglio visibile, logo nascosto, il timbro di rifiuto capovolto",
)

# The page in Spanish.
SPANISH = Words(
    title="Un plano, seis capas",
    intro=(
        "Los muros se ven siempre. Todo lo demás es una capa que el lector puede "
        "mostrar y ocultar."
    ),
    layers=(
        "Muebles",
        "Cotas",
        "Notas",
        "Borrador",
        "Cuadrícula",
        "Marcas de corte",
    ),
    holdings=(
        "visible; al apagarla las habitaciones quedan vacías, sillas incluidas",
        "visible; las distancias alrededor del plano",
        "oculta; haga clic en su nombre para mostrarla u ocultarla",
        "visible en pantalla, nunca impresa; el archivo la llama marca de agua",
        "oculta; una ayuda para quien dibujó el plano, no parte de él",
        "visible; el archivo las llama marcas de imprenta",
    ),
    notes=(
        "La mesa tiene seis plazas.",
        "Cama contra el muro medianero.",
        "Encimera, cubo debajo.",
    ),
    draft="BORRADOR",
    printing=(
        "La marca de borrador lleva su propia respuesta para la impresora, así que no hay",
        "que apagar nada antes de imprimir la página.",
    ),
    sheet_title="El mismo plano, como hoja emitida",
    sheet_layers=(
        "Papel",
        "Cajetín",
        "Logotipo",
        "Reventado",
    ),
    heading="Hoja",
    stamps=(
        "Aprobado",
        "Rechazado",
    ),
    review="Revisión",
    rules=(
        "Visible mientras el cajetín y el logotipo están visibles",
        "Visible mientras uno de los dos está visible",
        "Visible mientras uno de los dos está oculto",
        "Visible mientras los dos están ocultos",
    ),
    title_block="Hoja 2 de 2, emitida para revisión",
    switches="Cajetín visible, logotipo oculto, el sello de rechazo invertido",
)

# The page in German.
GERMAN = Words(
    title="Ein Plan, sechs Ebenen",
    intro=(
        "Die Wände sind immer da. Alles andere ist eine Ebene, die der Leser ein- und "
        "ausblenden kann."
    ),
    layers=(
        "Möbel",
        "Maße",
        "Notizen",
        "Entwurf",
        "Raster",
        "Schnittmarken",
    ),
    holdings=(
        "sichtbar; ausgeschaltet stehen die Räume leer, nicht einmal Stühle bleiben",
        "sichtbar; die Abstände rund um den Plan",
        "verborgen; auf den Namen klicken, um sie ein- oder auszublenden",
        "auf dem Bildschirm sichtbar, nie gedruckt; die Datei nennt es ein Wasserzeichen",
        "verborgen; eine Hilfe für den Zeichner des Plans, nicht Teil davon",
        "sichtbar; die Datei nennt sie Druckermarken",
    ),
    notes=(
        "Tisch für sechs.",
        "Bett an der Brandwand.",
        "Theke, Mülleimer darunter.",
    ),
    draft="ENTWURF",
    printing=(
        "Der Entwurfsvermerk bringt seine eigene Antwort für den Drucker mit, also muss",
        "vor dem Drucken der Seite nichts ausgeschaltet werden.",
    ),
    sheet_title="Derselbe Plan als Blatt für den Versand",
    sheet_layers=(
        "Papier",
        "Schriftfeld",
        "Logo",
        "Überfüllungen",
    ),
    heading="Blatt",
    stamps=(
        "Freigegeben",
        "Abgelehnt",
    ),
    review="Prüfung",
    rules=(
        "Sichtbar, solange Schriftfeld und Logo beide sichtbar sind",
        "Sichtbar, solange eines von beiden sichtbar ist",
        "Sichtbar, solange eines von beiden verborgen ist",
        "Sichtbar, solange beide verborgen sind",
    ),
    title_block="Blatt 2 von 2, zur Prüfung ausgegeben",
    switches="Schriftfeld an, Logo aus, der Ablehnungsstempel umgeschaltet",
)

# 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 walls(content: hqf_pdf.Content) -> None:
    """Draws the walls: the outer room and the partition that splits it."""
    x, y, width, height = PLAN
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.15))
    content.set_line_width(3.0)
    content.rect(x, y, width, height)
    content.stroke()
    content.move_to(x + 265.0, y)
    content.line_to(x + 265.0, y + 190.0)
    content.stroke()
    content.restore_state()


def furniture(content: hqf_pdf.Content) -> None:
    """Draws the furniture: a table, a bed and a counter, each a filled outline."""
    x, y, _, height = PLAN
    pieces = [
        (x + 40.0, y + height - 110.0, 120.0, 70.0),
        (x + 300.0, y + height - 130.0, 90.0, 110.0),
        (x + 290.0, y + 30.0, 110.0, 40.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.85, 0.88, 0.93))
    content.set_stroke(hqf_pdf.Rgb(0.35, 0.45, 0.6))
    content.set_line_width(1.0)
    for px, py, pw, ph in pieces:
        content.rect(px, py, pw, ph)
        content.fill()
        content.rect(px, py, pw, ph)
        content.stroke()
    content.restore_state()


def grid(content: hqf_pdf.Content) -> None:
    """Draws the grid: a line every 29 points across the plan and every 32 up it."""
    x, y, width, height = PLAN
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.55, 0.75, 0.9))
    content.set_line_width(0.3)
    across = x
    for __ in range(1, 15):
        across += 29.0
        content.move_to(across, y)
        content.line_to(across, y + height)
    up = y
    for __ in range(1, 10):
        up += 32.0
        content.move_to(x, up)
        content.line_to(x + width, up)
    content.stroke()
    content.restore_state()


def chair() -> hqf_pdf.Drawing:
    """The chair every place at the table shows: a filled outline in the colours of
    the furniture."""
    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.85, 0.88, 0.93))
    content.set_stroke(hqf_pdf.Rgb(0.35, 0.45, 0.6))
    content.set_line_width(1.0)
    content.rect(0.5, 0.5, 13.0, 9.0)
    content.fill()
    content.rect(0.5, 0.5, 13.0, 9.0)
    content.stroke()
    return hqf_pdf.Drawing(content, hqf_pdf.Rect(0.0, 0.0, 14.0, 10.0))


def crop_marks(content: hqf_pdf.Content) -> None:
    """Draws the crop marks: two short lines at each corner of the trimmed sheet,
    standing off it."""
    left, bottom, right, top = TRIM
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.0))
    content.set_line_width(0.5)
    for corner_x, corner_y, out_x, out_y in (
        (left, bottom, -1.0, -1.0),
        (right, bottom, 1.0, -1.0),
        (left, top, -1.0, 1.0),
        (right, top, 1.0, 1.0),
    ):
        content.move_to(corner_x + out_x * 6.0, corner_y)
        content.line_to(corner_x + out_x * 24.0, corner_y)
        content.move_to(corner_x, corner_y + out_y * 6.0)
        content.line_to(corner_x, corner_y + out_y * 24.0)
    content.stroke()
    content.restore_state()


def dimensions(content: hqf_pdf.Content, font: hqf_pdf.FontHandle) -> None:
    """Draws a line under the plan and one beside it, each with the distance it
    stands for."""
    x, y, width, height = PLAN
    below = y - 26.0
    beside = x - 46.0

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_fill(hqf_pdf.Rgb(0.2, 0.5, 0.35))
    content.set_line_width(0.8)

    content.move_to(x, below)
    content.line_to(x + width, below)
    content.move_to(x, below - 5.0)
    content.line_to(x, below + 5.0)
    content.move_to(x + width, below - 5.0)
    content.line_to(x + width, below + 5.0)
    content.move_to(beside, y)
    content.line_to(beside, y + height)
    content.move_to(beside - 5.0, y)
    content.line_to(beside + 5.0, y)
    content.move_to(beside - 5.0, y + height)
    content.line_to(beside + 5.0, y + height)
    content.stroke()

    content.draw_text(font, 9.0, x + width / 2.0 - 18.0, below + 8.0, ALONG)
    content.draw_text(font, 9.0, beside + 6.0, y + height / 2.0, ACROSS)
    content.restore_state()


def notes(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws what someone reading the plan wants said, and a reader who is only
    looking at the rooms does not."""
    x, y, _, height = PLAN
    places = [
        (x + 44.0, y + height - 130.0),
        (x + 292.0, y + height - 148.0),
        (x + 292.0, y + 16.0),
    ]
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.7, 0.25, 0.1))
    for (nx, ny), line in zip(places, words.notes):
        content.draw_text(font, 8.0, nx, ny, line)
    content.restore_state()


# The baseline of the legend's first row, and how far each row stands below the one
# before.
LEGEND_TOP = 300.0
LEGEND_STEP = 18.0


def legend(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the legend under the plan: what each layer holds and how it starts."""
    baseline = LEGEND_TOP
    for name, what in zip(words.layers, words.holdings):
        content.draw_text(font, 10.0, 80.0, baseline, name)
        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 10.0, 170.0, baseline, what)
        content.restore_state()
        baseline -= LEGEND_STEP

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        baseline - 12.0,
        words.printing[0],
    )
    content.draw_text(font, 10.0, 80.0, baseline - 26.0, words.printing[1])
    content.restore_state()


def on_layer(
    content: hqf_pdf.Content,
    layer: hqf_pdf.LayerHandle,
    body: Callable[[hqf_pdf.Content], None],
) -> None:
    """Draws `body` inside `layer`, so reading software shows and hides all of it at
    once."""
    content.begin_layer(layer)
    body(content)
    content.end_marked()


@dataclass(frozen=True)
class Sheet:
    """The layers of the second page, and the rules built on them."""

    # The paper tint behind everything, left out of the panel.
    paper: hqf_pdf.LayerHandle
    # The title block across the foot, locked and filed under a heading.
    title_block: hqf_pdf.LayerHandle
    # The studio's mark, which says what it is and who made it.
    logo: hqf_pdf.LayerHandle
    # The two stamps a reader shows one of at a time.
    stamps: tuple[hqf_pdf.LayerHandle, hqf_pdf.LayerHandle]
    # The trap line round the walls, for whoever prints the sheet.
    traps: hqf_pdf.LayerHandle
    # The four marks each shown under one policy over the title block and the logo.
    rules: tuple[hqf_pdf.LayerHandle, ...]


def second_sheet_layers(document, words, notes) -> Sheet:
    """Adds the second page's layers to `document`, with the family, the configuration
    and the four rules built on them."""
    paper = document.add_layer(
        hqf_pdf.Layer(words.sheet_layers[0])
        .page_role(hqf_pdf.PageRole.Background)
        .listed(False)
    )
    title_block = document.add_layer(
        hqf_pdf.Layer(words.sheet_layers[1])
        .page_role(hqf_pdf.PageRole.HeaderFooter)
        .heading(words.heading)
        .locked(True)
        .exported(True)
    )
    facts = hqf_pdf.Metadata(title=words.sheet_layers[2], creator="HQF Development")
    logo = document.add_layer(
        hqf_pdf.Layer(words.sheet_layers[2])
        .page_role(hqf_pdf.PageRole.Logo)
        .made_by("HQF Development", hqf_pdf.LayerWork.Artwork)
        .metadata(hqf_pdf.Xmp.facts(facts))
    )
    approved = document.add_layer(
        hqf_pdf.Layer(words.stamps[0]).page_role(hqf_pdf.PageRole.Foreground)
    )
    rejected = document.add_layer(
        hqf_pdf.Layer(words.stamps[1])
        .page_role(hqf_pdf.PageRole.Foreground)
        .visible(False)
    )
    traps = document.add_layer(
        hqf_pdf.Layer(words.sheet_layers[3])
        .purpose(hqf_pdf.LayerPurpose.Trapping)
        .intent(hqf_pdf.LayerIntent.View)
        .exported(False)
    )
    document.add_layer_family(hqf_pdf.LayerFamily().holding(approved).holding(rejected))
    document.add_layer_configuration(
        hqf_pdf.LayerConfiguration(words.review).showing(notes).showing(rejected)
    )
    rules = tuple(
        document.add_layer_rule(hqf_pdf.LayerRule(policy).over(title_block).over(logo))
        for policy in (
            hqf_pdf.LayerPolicy.AllVisible,
            hqf_pdf.LayerPolicy.AnyVisible,
            hqf_pdf.LayerPolicy.AnyHidden,
            hqf_pdf.LayerPolicy.AllHidden,
        )
    )
    return Sheet(paper, title_block, logo, (approved, rejected), traps, rules)


def kept_on_layer(content, layer, body) -> None:
    """Draws `body` inside `layer`, with the graphics state saved around it so the
    colours it sets stay inside the layer's run."""

    def kept(target):
        target.save_state()
        body(target)
        target.restore_state()

    on_layer(content, layer, kept)


def second_sheet(font, words, sheet) -> hqf_pdf.Page:
    """The second page: a sheet whose paper, title block, logo, stamps and trap line
    each sit on a layer that says what it is, four marks each shown under its own rule
    over two of them, and a link that switches three at once."""
    content = hqf_pdf.Content()

    def paper(target):
        target.set_fill(hqf_pdf.Rgb(0.97, 0.96, 0.92))
        target.rect(20.0, 20.0, 555.0, 802.0)
        target.fill()

    kept_on_layer(content, sheet.paper, paper)
    content.draw_text(font, 15.0, 80.0, 750.0, words.sheet_title)

    x, y, width, height = PLAN
    walls(content)

    def traps(target):
        target.set_stroke(hqf_pdf.Rgb(0.9, 0.2, 0.6))
        target.set_line_width(0.3)
        target.rect(x - 1.0, y - 1.0, width + 2.0, height + 2.0)
        target.stroke()

    kept_on_layer(content, sheet.traps, traps)

    for layer, word, color in zip(
        sheet.stamps,
        words.stamps,
        (hqf_pdf.Rgb(0.1, 0.55, 0.2), hqf_pdf.Rgb(0.8, 0.15, 0.15)),
    ):

        def stamp(target, word=word, color=color):
            target.set_stroke(color)
            target.set_line_width(2.0)
            target.rect(x + 20.0, y + height - 50.0, 140.0, 34.0)
            target.stroke()
            target.set_fill(color)
            target.draw_text(font, 16.0, x + 32.0, y + height - 38.0, word)

        kept_on_layer(content, layer, stamp)

    # The four marks, each shown only while its rule over the title block and the logo
    # holds.
    top = y - 30.0
    for layer, said in zip(sheet.rules, words.rules):

        def mark(target, top=top):
            target.set_fill(hqf_pdf.Rgb(0.15, 0.35, 0.8))
            target.rect(80.0, top - 2.0, 10.0, 10.0)
            target.fill()

        kept_on_layer(content, layer, mark)
        content.draw_text(font, 9.0, 98.0, top, said)
        top -= 18.0

    def title_block(target):
        target.set_line_width(0.8)
        target.rect(80.0, 60.0, 435.0, 50.0)
        target.stroke()
        target.draw_text(font, 11.0, 90.0, 90.0, words.sheet_title)
        target.draw_text(font, 8.0, 90.0, 72.0, words.title_block)

    kept_on_layer(content, sheet.title_block, title_block)

    def logo(target):
        target.set_fill(hqf_pdf.Rgb(0.15, 0.3, 0.6))
        target.rect(455.0, 68.0, 34.0, 34.0)
        target.fill()
        target.set_fill(hqf_pdf.Rgb.gray(1.0))
        target.draw_text(font, 11.0, 460.0, 80.0, "HQF")

    kept_on_layer(content, sheet.logo, logo)

    content.draw_text(font, 10.0, 80.0, top - 10.0, words.switches)
    page = hqf_pdf.Page.a4()
    page.set_content(content)
    page.add_link(
        hqf_pdf.Link.acting(
            78.0,
            top - 14.0,
            font.measure(words.switches, 10.0) + 4.0,
            16.0,
            hqf_pdf.Action.switch_layers(
                hqf_pdf.LayerSwitches()
                .switch(hqf_pdf.LayerSwitch.On, sheet.title_block)
                .switch(hqf_pdf.LayerSwitch.Off, sheet.logo)
                .switch(hqf_pdf.LayerSwitch.Toggle, sheet.stamps[1])
                .ignoring_radio_groups()
            ),
        )
    )
    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("layers.pdf", language)).stem)

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

    furniture_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[0]).made_by("Plan Studio", hqf_pdf.LayerWork.Technical)
    )
    dimensions_layer = document.add_layer(hqf_pdf.Layer(words.layers[1]))
    notes_layer = document.add_layer(hqf_pdf.Layer(words.layers[2]).visible(False))
    draft_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[3])
        .on_screen(True)
        .printed(False)
        .purpose(hqf_pdf.LayerPurpose.Watermark)
    )
    grid_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[4]).visible(False).intent(hqf_pdf.LayerIntent.Design)
    )
    marks_layer = document.add_layer(
        hqf_pdf.Layer(words.layers[5]).purpose(hqf_pdf.LayerPurpose.PrintersMarks)
    )
    placed_chair = document.add_drawing(chair().layer(furniture_layer))

    content = hqf_pdf.Content()
    content.draw_text(font, 15.0, 80.0, 750.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        80.0,
        730.0,
        words.intro,
    )
    content.restore_state()

    walls(content)
    on_layer(content, grid_layer, grid)
    on_layer(content, furniture_layer, furniture)
    # The chairs are placed outside any layer's run: the drawing names its layer itself.
    for x, y in CHAIRS:
        content.draw_form(placed_chair, x, y, 1.0)
    on_layer(content, dimensions_layer, lambda target: dimensions(target, font))
    on_layer(content, notes_layer, lambda target: notes(target, font, words))

    def draft(target: hqf_pdf.Content) -> None:
        x, y, width, height = PLAN
        stamp = hqf_pdf.Stamp(
            font,
            words.draft,
            slant=hqf_pdf.Slant.Up,
            color=hqf_pdf.Rgb(0.8, 0.3, 0.3),
        )
        stamp.draw(target, x, y, width, height)

    on_layer(content, draft_layer, draft)
    on_layer(content, marks_layer, crop_marks)
    legend(content, font, words)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    # The notes layer's name in the legend, the third row, flips the layer.
    page.add_link(
        hqf_pdf.Link.acting(
            78.0,
            LEGEND_TOP - LEGEND_STEP * 2.0 - 4.0,
            80.0,
            16.0,
            hqf_pdf.Action.switch_layers(hqf_pdf.LayerSwitches().toggle(notes_layer)),
        )
    )
    document.add_page(page)

    sheet = second_sheet_layers(document, words, notes_layer)
    document.add_page(second_sheet(font, words, sheet))

    document.set_open_mode(hqf_pdf.OpenMode.Layers)

    document.set_viewer_preferences(

        hqf_pdf.ViewerPreferences().after_full_screen(hqf_pdf.SidePanel.Layers)

    )

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


if __name__ == "__main__":
    main()
