write_devicen.py

Die Python-Datei des Beispiels „Mehrere Platten zugleich, jede in eigener Stärke“. Acht Plattenkombinationen aus den vier üblichen Druckfarben, jede mit dem kleinen Programm darunter gedruckt, das sie zeigt, und zwei Druckfarben, die die Maschine selbst führt, gemeinsam verwendet, jede Stärke der einen gegen jede Stärke der anderen.

Python 453 Zeilen

Wofür dieses Beispiel da ist

Manche Druckmaschinen führen sechs oder acht Druckfarben statt vier. Manche Aufträge müssen Schwarz über ein Bild legen, ohne die drei Farbplatten darunter anzutasten. Beides lässt sich auf die gewöhnliche Art, eine Farbe zu nennen, nicht sagen, denn die gewöhnliche Art spricht alle Platten zugleich an, ob man es wollte oder nicht.

Was dieses Beispiel zeigt

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"""Several named colorants at once, each on a plate of its own.

The Python twin of the `write_devicen` example in Rust. A colour in such a space
is one tint per colorant, and one program says what the lot of them look like
where those plates are not to hand. Naming some of the process plates and no
others lays ink on those and leaves the rest as they stand; naming inks of its
own is how a press that carries more than four is painted in.

The space's attributes say the rest: each subset's plates are the components of the
process space, and each of the two inks is described alone, as the colour it lays down
at full strength, for a preview that shows one plate at a time. The line under the grid
names the inks the attributes describe.

The words the page draws are held in `Words`, one set per language, and `HQF_PDF_LANG`
picks which set is drawn. The colorants are not words: their names are written into the
file and drawn back from it.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The left edge of everything.
LEFT = 70.0


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

    What is not language stays out of it: a colorant's name is written into the file and
    drawn back from it, and so are the programs and the tints.
    """

    # The title across the top of the page.
    title: str
    # The two lines under the title, each already broken to the page.
    lead: tuple[str, str]
    # The heading of the panel of subsets.
    subsets: str
    # The heading of the panel of two inks, and the line under it.
    inks: str
    inks_under: str
    # The line under the grid, before the names of the inks described alone.
    described: str


# The page in English.
ENGLISH = Words(
    title="Several plates at once, each with a tint of its own",
    lead=(
        "Naming some of the process plates and no others lays ink on those and "
        "leaves the rest as",
        "they stand, which painting in full CMYK cannot do. One program fills in "
        "the plates left out.",
    ),
    subsets="Subsets of the process plates, and the program each one is shown through",
    inks="Two inks of the press's own on one space, every tint of each against the other",
    inks_under="Down the side, Corporate Blue. Across the top, Corporate Gold. "
    "Two numbers say a colour here.",
    described=(
        "Each ink is also described alone, for a reader that lays one plate at a time:"
    ),
)

# The page in French.
FRENCH = Words(
    title="Plusieurs plaques à la fois, chacune à son intensité",
    lead=(
        ("Ne nommer que certaines plaques de quadrichromie dépose l’encre sur "
         "celles-ci et laisse"),
        ("les autres intactes, impossible en quadrichromie complète. Un programme "
         "remplit le reste."),
    ),
    subsets=("Sous-ensembles des plaques de quadrichromie, et le programme qui affiche"
             " chacun"),
    inks=("Deux tons directs dans un espace, chaque intensité de l’un croisée avec "
          "l’autre"),
    inks_under=("Sur le côté, Corporate Blue. En haut, Corporate Gold. Ici, une "
                "couleur tient en deux nombres."),
    described="Chaque encre est aussi décrite seule, pour un aperçu plaque par plaque :",
)

# The page in Dutch.
DUTCH = Words(
    title="Meerdere platen tegelijk, elk met een eigen tint",
    lead=(
        "Wie alleen sommige procesplaten noemt, zet alleen daarop inkt en laat de "
        "rest zoals",
        "hij is, wat schilderen in volledige CMYK niet kan. Eén programma vult de "
        "weggelaten platen in.",
    ),
    subsets="Deelverzamelingen van de procesplaten, en het programma waarmee elk getoond wordt",
    inks="Twee eigen inkten van de drukpers in één ruimte, elke tint van de een tegen de ander",
    inks_under="Langs de zijkant Corporate Blue. Bovenaan Corporate Gold. Twee "
               "getallen geven hier een kleur aan.",
    described=(
        "Elke inkt wordt ook apart beschreven, voor een lezer die één plaat tegelijk legt:"
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Várias chapas de uma vez, cada uma com o seu tom",
    lead=(
        "Nomear só algumas chapas de quadricromia põe tinta nessas e deixa as outras "
        "como",
        "estão, o que pintar em CMYK completo não faz. Um programa preenche as chapas "
        "omitidas.",
    ),
    subsets="Subconjuntos das chapas de quadricromia, e o programa com que cada um é mostrado",
    inks="Duas tintas próprias da gráfica num espaço, cada tom de uma contra a outra",
    inks_under="Na lateral, Corporate Blue. Em cima, Corporate Gold. Aqui dois "
               "números dizem uma cor.",
    described=(
        "Cada tinta é também descrita à parte, para quem imprime chapa a chapa:"
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Più lastre alla volta, ciascuna con una tinta propria",
    lead=(
        "Nominare solo alcune lastre di quadricromia mette inchiostro su quelle e "
        "lascia le altre come",
        "sono, cosa che dipingere in CMYK completo non fa. Un programma riempie le "
        "lastre omesse.",
    ),
    subsets="Sottoinsiemi delle lastre di quadricromia, e il programma con cui si mostra ciascuno",
    inks="Due inchiostri propri della macchina su uno spazio, ogni tinta dell’uno contro l’altro",
    inks_under="Di lato, Corporate Blue. In alto, Corporate Gold. Qui due numeri "
               "dicono un colore.",
    described=(
        "Ogni inchiostro anche da solo, per chi guarda una lastra alla volta:"
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Varias planchas a la vez, cada una con su propio tono",
    lead=(
        "Nombrar solo algunas planchas de cuatricromía pone tinta en esas y deja el "
        "resto como",
        "está, cosa que no hace pintar en CMYK completo. Un programa rellena las "
        "planchas omitidas.",
    ),
    subsets="Subconjuntos de las planchas de cuatricromía, y el programa con que se muestra cada uno",
    inks="Dos tintas propias de la imprenta en un espacio, cada tono de una frente a la otra",
    inks_under="En el lateral, Corporate Blue. Arriba, Corporate Gold. Aquí dos "
               "números dicen un color.",
    described=(
        "Cada tinta se describe también sola, para quien imprime plancha a plancha:"
    ),
)

# The page in German.
GERMAN = Words(
    title="Mehrere Druckplatten zugleich, jede mit ihrem eigenen Tonwert",
    lead=(
        "Werden nur einige Prozessplatten genannt, kommt Farbe auf diese, die übrigen "
        "bleiben,",
        "wie sie sind – was volles CMYK nicht kann. Ein Programm füllt die fehlenden "
        "Platten.",
    ),
    subsets="Teilmengen der Prozessplatten und das Programm, durch das jede angezeigt wird",
    inks="Zwei Hausfarben in einem Farbraum, jeder Tonwert der einen gegen die andere",
    inks_under="An der Seite Corporate Blue, oben Corporate Gold. Zwei Zahlen ergeben "
               "hier eine Farbe.",
    described=(
        "Jede Farbe auch einzeln beschrieben, für Leser, die Platte für Platte auftragen:"
    ),
)

# 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 subsets():
    """Every subset of the process plates the first panel shows: the plates it
    names, the program that fills in the ones it leaves out, and the tint each
    named plate is shown at."""
    return [
        (
            ["Cyan"],
            [hqf_pdf.Op.integer(0)] * 3,
            [0.8],
        ),
        (
            ["Magenta"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(1), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Yellow"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(2), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Black"],
            [hqf_pdf.Op.integer(0)] * 3
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(3), hqf_pdf.Op.roll()],
            [0.8],
        ),
        (
            ["Cyan", "Magenta"],
            [hqf_pdf.Op.integer(0)] * 2,
            [0.7, 0.7],
        ),
        (
            ["Cyan", "Yellow"],
            [hqf_pdf.Op.integer(0), hqf_pdf.Op.exchange(), hqf_pdf.Op.integer(0)],
            [0.7, 0.7],
        ),
        (
            ["Magenta", "Yellow"],
            [hqf_pdf.Op.integer(0)] * 2
            + [hqf_pdf.Op.integer(4), hqf_pdf.Op.integer(1), hqf_pdf.Op.roll()],
            [0.7, 0.7],
        ),
        (
            ["Cyan", "Magenta", "Yellow"],
            [hqf_pdf.Op.integer(0)],
            [0.6, 0.6, 0.6],
        ),
    ]


# The left edge of each column of the first panel, and the size of one swatch.
SUBSET_X = [70.0, 185.0, 300.0, 415.0]
SUBSET_SIZE = (100.0, 52.0)
# The baseline the first row of swatches sits on, and the drop to the second.
SUBSET_Y = 620.0
SUBSET_DROP = 108.0

# The two inks the second panel paints in, as the process inks show them at full
# strength.
BLUE = [0.92, 0.58, 0.0, 0.06]
GOLD = [0.0, 0.28, 0.95, 0.04]

# The tints the duotone grid runs through, along both of its axes.
DUOTONE_TINTS = [0.0, 0.25, 0.5, 0.75, 1.0]
# The left edge and the top of the duotone grid, and the size of one cell.
DUOTONE_ORIGIN = (110.0, 355.0)
DUOTONE_CELL = 52.0


def mix_two_inks():
    """The program mixing two inks: each output is the first ink's share of that
    process plate taken at the first tint, plus the second ink's taken at the
    second.

    Both tints stay at the bottom of the stack while the four outputs are worked
    out above them, so each one is reached again by counting down past the
    outputs already there; the pair is then turned to the top and thrown away.
    """
    body = []
    for plate, (first, second) in enumerate(zip(BLUE, GOLD)):
        reach = plate + 1
        body += [
            hqf_pdf.Op.integer(reach),
            hqf_pdf.Op.index(),
            hqf_pdf.Op.real(first),
            hqf_pdf.Op.multiply(),
            hqf_pdf.Op.integer(reach),
            hqf_pdf.Op.index(),
            hqf_pdf.Op.real(second),
            hqf_pdf.Op.multiply(),
            hqf_pdf.Op.add(),
        ]
    body += [
        hqf_pdf.Op.integer(6),
        hqf_pdf.Op.integer(4),
        hqf_pdf.Op.roll(),
        hqf_pdf.Op.pop(),
        hqf_pdf.Op.pop(),
    ]
    return hqf_pdf.Calculation([(0.0, 1.0)] * 2, [(0.0, 1.0)] * 4, body)


def subset_transform(colorants, body):
    """The function a subset of the process plates is shown through."""
    return hqf_pdf.Calculation(
        [(0.0, 1.0)] * len(colorants), [(0.0, 1.0)] * 4, body
    )


def subset_swatch(content, font, space, colorants, transform, tints, x, y):
    """Draw one swatch, with the plates it names above it and the program that
    fills in the rest below."""
    width, height = SUBSET_SIZE

    content.save_state()
    content.set_fill_space(space)
    content.set_fill_components(tints)
    content.rect(x, y, width, height)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, 8.0, x, y + height + 7.0, " ".join(colorants))
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    content.draw_text(font, 7.0, x, y - 11.0, transform.program())
    content.restore_state()


def duotone_grid(content, font, space):
    """Draw the grid of the two inks against one another, every tint of the first
    crossed with every tint of the second."""
    left, top = DUOTONE_ORIGIN

    for row, blue in enumerate(DUOTONE_TINTS):
        down = top - row * DUOTONE_CELL
        for column, gold in enumerate(DUOTONE_TINTS):
            across = left + column * DUOTONE_CELL
            content.save_state()
            content.set_fill_space(space)
            content.set_fill_components([blue, gold])
            content.rect(across, down, DUOTONE_CELL - 4.0, DUOTONE_CELL - 4.0)
            content.fill()
            content.restore_state()

        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(
            font, 7.0, LEFT, down + DUOTONE_CELL / 2.0 - 7.0, f"{blue * 100:.0f}%"
        )
        content.restore_state()

    for column, gold in enumerate(DUOTONE_TINTS):
        across = left + column * DUOTONE_CELL
        content.save_state()
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(
            font, 7.0, across, top + DUOTONE_CELL - 1.0, f"{gold * 100:.0f}%"
        )
        content.restore_state()


def heading(content, font, words):
    """Draw the title and the two lines saying what the page is showing."""
    content.draw_text(font, 15.0, LEFT, 780.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(font, 10.0, LEFT, 762.0, words.lead[0])
    content.draw_text(font, 10.0, LEFT, 748.0, words.lead[1])
    content.restore_state()


def panel_heading(content, font, y, title, under):
    """Draw one panel's heading, with the line under it that a panel may have."""
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.2))
    content.draw_text(font, 11.0, LEFT, y, title)
    if under is not None:
        content.set_fill(hqf_pdf.Rgb.gray(0.45))
        content.draw_text(font, 8.0, LEFT, y - 16.0, under)
    content.restore_state()


def subset_panel(document, content, font):
    """Draw every subset of the process plates, four to a row."""
    for place, (colorants, body, tints) in enumerate(subsets()):
        transform = subset_transform(colorants, body)
        # The plates a subset names are the components of the process space, which the
        # attributes say under the names the space takes them by.
        space = document.add_color_space(
            hqf_pdf.DeviceN(
                colorants, hqf_pdf.DeviceSpace.Cmyk, transform
            ).with_attributes(
                hqf_pdf.DeviceNAttributes().with_process(
                    hqf_pdf.DeviceSpace.Cmyk, ["Cyan", "Magenta", "Yellow", "Black"]
                )
            )
        )
        x = SUBSET_X[place % len(SUBSET_X)]
        y = SUBSET_Y - (place // len(SUBSET_X)) * SUBSET_DROP
        subset_swatch(content, font, space, colorants, transform, tints, x, y)


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

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

    content = hqf_pdf.Content()
    heading(content, font, words)
    panel_heading(content, font, 700.0, words.subsets, None)
    subset_panel(document, content, font)

    panel_heading(content, font, 440.0, words.inks, words.inks_under)
    # Each ink is also said on its own, as the colour it lays down at full strength, for
    # a reader that shows one plate at a time.
    blue, gold = (
        hqf_pdf.Separation.ink(name, hqf_pdf.Cmyk(*full))
        for name, full in (("Corporate Blue", BLUE), ("Corporate Gold", GOLD))
    )
    two_inks = hqf_pdf.DeviceN(
        ["Corporate Blue", "Corporate Gold"],
        hqf_pdf.DeviceSpace.Cmyk,
        mix_two_inks(),
    ).with_attributes(hqf_pdf.DeviceNAttributes().with_colorant(blue).with_colorant(gold))
    attributes = two_inks.attributes
    described = (
        []
        if attributes is None
        else [
            ink.colorant
            for ink in (attributes.colorant(name) for name in two_inks.colorants)
            if ink is not None
        ]
    )
    line = f"{words.described} {', '.join(described)}"
    inks = document.add_color_space(two_inks)
    duotone_grid(content, font, inks)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    content.draw_text(font, 8.0, LEFT, 110.0, line)
    content.restore_state()

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

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(subsets())} subsets of the "
        "process plates and two inks of its own"
    )


if __name__ == "__main__":
    main()