write_text_path.py

Die Python-Datei des Beispiels „Wörter, die einer Kurve folgen“. Ein Siegel, dessen Umschrift auf seinem Ring läuft, und eine zweite, an seinem Fuß gebogen, damit diese Wörter aufrecht stehen, ein über einen Bogen gekrümmter Titel und derselbe Satz, an drei Stellen entlang eines geraden Pfads begonnen.

Python 426 Zeilen

Wofür dieses Beispiel da ist

Ein Stempel, ein Siegel, eine Medaille, eine Münze: Die Wörter darauf laufen um den Rand, und das tun sie, seit es Siegel gibt. Als gewöhnliche Zeile gesetzt, liegen dieselben Wörter flach quer über der Mitte, und der Gegenstand ist nicht mehr der Gegenstand. Hier werden sie entlang eines Pfads gelegt, angegeben mit genau den Mitteln, mit denen auch der Umriss eines Buchstabens angegeben wird, und jeder Buchstabe wird gedreht, damit er darauf steht. Das Siegel auf dieser Seite trägt seinen Namen oben über seinem Ring; am Fuß biegt sich der Pfad in die andere Richtung, sodass die Wörter dort aufrecht stehen, statt kopfüber zu hängen.

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
"""Sets lines of text along paths: round a seal, over an arch, straight across.

The Python twin of the `write_text_path` example in Rust. A path is given as a run of
pieces: the first says where it starts, and every one after it draws. Two numbers are a
point, six are a cubic curve's two control points followed by the point it arrives at.
The path is walked by length, so two letters an inch apart along it are an inch apart on
the page whatever the curve does between them.

The page below draws a seal with a legend curving over its top and another bowed inside
its foot, a title bent over an arch, and three straight paths that show where a line
begins: at the head of the path, halfway along it, or at its far end. The straight paths
are drawn as thin rules, so the line and the path it follows can be read against each
other.

The title, the legends and the captions are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The margin the page is laid out inside.
MARGIN = 56.0

# How far the page runs across, between the margins.
WIDTH = 483.0

# Where the seal stands.
SEAL = (297.5, 620.0)

# The outer ring of the seal, in points.
RING = 118.0

# The inner ring, which the legend is written between.
INNER_RING = 98.0

# The circle the legend over the seal is set on.
LEGEND = 101.0

# How far a circle's control points stand from its quarter marks, as a share of the
# radius: the number that turns four cubics into a circle.
KAPPA = 0.5522847498307934

# The four quarter marks of a circle of radius one, anticlockwise from due east.
MARKS = ((1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0))

# Where each of the three straight paths runs.
RULES = (250.0, 200.0, 150.0)

# Where each caption's box starts, in the order `Words` holds them.
CAPTIONS = (480.0, 300.0, 118.0)


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

    # The line at the head of the page.
    title: str
    # The legend curving over the top of the seal.
    seal_over: str
    # The legend bowed inside the foot of the seal.
    seal_under: str
    # The line bent over the arch.
    arch: str
    # What is set along each of the three straight paths.
    starts: tuple[str, str, str]
    # What is written under the seal, the arch and the three rules.
    captions: tuple[str, str, str]


# The page in English.
ENGLISH = Words(
    title="Text set along a path",
    seal_over="HQF DEVELOPMENT",
    seal_under="CERTIFIED COPY",
    arch="A line bent over an arch",
    starts=(
        "At the head of the path",
        "Halfway along it",
        "Stopping where it stops",
    ),
    captions=(
        "The legend follows the ring: over the top it curves with the seal, and "
        "at the foot the path bows the other way, so that the words there stand "
        "upright instead of hanging upside down.",
        "One curve, one line. The path is a single cubic, and the line is set "
        "from its middle, so that what is written stays centred on the arch "
        "however long the words are.",
        "The same words on the same path, begun in three places: at its head, "
        "halfway along it, and stopping where it stops. The rule under each is "
        "the path itself.",
    ),
)

# The page in French.
FRENCH = Words(
    title="Du texte posé le long d’un chemin",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIE CERTIFIÉE",
    arch="Une ligne courbée sur une arche",
    starts=(
        "Au départ du chemin",
        "À mi-chemin",
        "Jusqu’au bout du chemin",
    ),
    captions=(
        ("La légende suit l’anneau : au-dessus, elle épouse le sceau ; au pied, le "
         "chemin se creuse dans l’autre sens, pour que les mots s’y tiennent droits au"
         " lieu de pendre à l’envers."),
        ("Une courbe, une ligne. Le chemin est une seule cubique, et la ligne est "
         "centrée sur son milieu : le texte reste centré sur l’arche, quelle que soit "
         "la longueur des mots."),
        ("Les mêmes mots sur le même chemin, placés de trois façons : dès son départ, "
         "à mi-chemin, et jusqu’à son bout. Le filet sous chacun est le chemin "
         "lui-même."),
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Tekst gezet langs een pad",
    seal_over="HQF DEVELOPMENT",
    seal_under="GEWAARMERKTE KOPIE",
    arch="Een regel gebogen over een boog",
    starts=(
        "Aan het begin van het pad",
        "Halverwege",
        "Stoppend waar het stopt",
    ),
    captions=(
        "Het onderschrift volgt de ring: bovenaan buigt het met het zegel mee, en "
        "onderaan buigt het pad de andere kant op, zodat de woorden daar rechtop "
        "staan in plaats van ondersteboven te hangen.",
        "Eén curve, één regel. Het pad is één kubische curve, en de regel wordt "
        "vanuit het midden gezet, zodat wat er staat gecentreerd blijft op de boog, "
        "hoe lang de woorden ook zijn.",
        "Dezelfde woorden op hetzelfde pad, op drie plekken begonnen: aan het begin, "
        "halverwege, en stoppend waar het stopt. De lijn onder elk is het pad zelf.",
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Texto composto ao longo de um traçado",
    seal_over="HQF DEVELOPMENT",
    seal_under="CÓPIA CERTIFICADA",
    arch="Uma linha dobrada sobre um arco",
    starts=(
        "No início do traçado",
        "A meio caminho",
        "A parar onde ele para",
    ),
    captions=(
        "A legenda segue o anel: por cima curva com o selo, e no pé o traçado "
        "dobra-se ao contrário, para que as palavras aí fiquem direitas em vez de "
        "penderem de pernas para o ar.",
        "Uma curva, uma linha. O traçado é uma única cúbica, e a linha é composta a "
        "partir do seu meio, para que o que está escrito fique centrado no arco seja "
        "qual for o comprimento das palavras.",
        "As mesmas palavras no mesmo traçado, começadas em três sítios: no início, a "
        "meio caminho, e a parar onde ele para. O filete sob cada uma é o próprio "
        "traçado.",
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Testo composto lungo un tracciato",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIA CONFORME",
    arch="Una riga curvata su un arco",
    starts=(
        "All’inizio del tracciato",
        "A metà strada",
        "Fermandosi dove si ferma",
    ),
    captions=(
        "La legenda segue l’anello: sopra si curva con il sigillo, e al piede il "
        "tracciato si piega al contrario, così le parole lì stanno dritte invece di "
        "pendere capovolte.",
        "Una curva, una riga. Il tracciato è una sola cubica, e la riga è composta "
        "dal suo centro, così ciò che è scritto resta centrato sull’arco per quanto "
        "lunghe siano le parole.",
        "Le stesse parole sullo stesso tracciato, iniziate in tre punti: all’inizio, "
        "a metà strada, e fermandosi dove si ferma. Il filetto sotto ciascuna è il "
        "tracciato stesso.",
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Texto compuesto a lo largo de un trazado",
    seal_over="HQF DEVELOPMENT",
    seal_under="COPIA CERTIFICADA",
    arch="Una línea curvada sobre un arco",
    starts=(
        "Al principio del trazado",
        "A mitad de camino",
        "Acabando donde acaba",
    ),
    captions=(
        "La leyenda sigue el anillo: por arriba se curva con el sello, y en el pie el "
        "trazado se arquea al revés, para que las palabras de ahí queden derechas en "
        "vez de colgar cabeza abajo.",
        "Una curva, una línea. El trazado es una sola cúbica, y la línea se compone "
        "desde su centro, para que lo escrito quede centrado en el arco sea cual sea "
        "la longitud de las palabras.",
        "Las mismas palabras en el mismo trazado, empezadas en tres sitios: al "
        "principio, a mitad de camino, y acabando donde acaba el trazado. La raya "
        "bajo cada una es el propio trazado.",
    ),
)

# The page in German.
GERMAN = Words(
    title="Text entlang eines Pfads gesetzt",
    seal_over="HQF DEVELOPMENT",
    seal_under="BEGLAUBIGTE KOPIE",
    arch="Eine Zeile, über einen Bogen gelegt",
    starts=(
        "Am Anfang des Pfads",
        "Auf halber Strecke",
        "Endet, wo er endet",
    ),
    captions=(
        "Die Umschrift folgt dem Ring: Oben krümmt sie sich mit dem Siegel, und am "
        "Fuß biegt sich der Pfad andersherum, sodass die Wörter dort aufrecht stehen, "
        "statt kopfüber zu hängen.",
        "Eine Kurve, eine Zeile. Der Pfad ist eine einzige kubische Kurve, und die "
        "Zeile wird von ihrer Mitte aus gesetzt, sodass das Geschriebene auf dem "
        "Bogen zentriert bleibt, wie lang die Wörter auch sind.",
        "Dieselben Wörter auf demselben Pfad, an drei Stellen begonnen: an seinem "
        "Anfang, auf halber Strecke und so, dass sie enden, wo er endet. Die Linie "
        "unter jedem ist der Pfad selbst.",
    ),
)


# 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 beginnings() -> tuple[hqf_pdf.PathStart, hqf_pdf.PathStart, hqf_pdf.PathStart]:
    """The three places along a path a line can begin, in the order the rules are
    drawn."""
    return (
        hqf_pdf.PathStart.Beginning,
        hqf_pdf.PathStart.Middle,
        hqf_pdf.PathStart.End,
    )


def arc(
    radius: float, mark: tuple[float, float], nxt: tuple[float, float]
) -> tuple[float, float, float, float, float, float]:
    """A quarter of a circle of radius `radius` about the seal, running from the quarter
    mark `mark` to the quarter mark `nxt`.

    The two marks are a quarter turn apart, in either order, so the same arithmetic
    draws the circle anticlockwise and the legend clockwise over the top of it.
    """
    pull = KAPPA * radius
    return (
        nxt[0] * pull + (SEAL[0] + mark[0] * radius),
        nxt[1] * pull + (SEAL[1] + mark[1] * radius),
        mark[0] * pull + (SEAL[0] + nxt[0] * radius),
        mark[1] * pull + (SEAL[1] + nxt[1] * radius),
        SEAL[0] + nxt[0] * radius,
        SEAL[1] + nxt[1] * radius,
    )


def over_the_seal() -> list[tuple[float, ...]]:
    """The path the legend over the seal follows: the left of the ring, over the top, to
    the right of it."""
    return [
        (SEAL[0] - LEGEND, SEAL[1]),
        arc(LEGEND, MARKS[2], MARKS[1]),
        arc(LEGEND, MARKS[1], MARKS[0]),
    ]


def under_the_seal() -> list[tuple[float, ...]]:
    """The path the legend at the foot of the seal follows: one curve bowing downward,
    so that the words along it stand upright."""
    return [
        (SEAL[0] - 80.0, SEAL[1] - 36.0),
        (
            SEAL[0] - 34.0,
            SEAL[1] - 96.0,
            SEAL[0] + 34.0,
            SEAL[1] - 96.0,
            SEAL[0] + 80.0,
            SEAL[1] - 36.0,
        ),
    ]


def the_arch() -> list[tuple[float, ...]]:
    """The arch the title is bent over."""
    return [
        (MARGIN, 330.0),
        (
            MARGIN + 145.0,
            420.0,
            MARGIN + WIDTH - 145.0,
            420.0,
            MARGIN + WIDTH,
            330.0,
        ),
    ]


def straight(y: float) -> list[tuple[float, ...]]:
    """A path running straight across the page at `y`."""
    return [(MARGIN, y), (MARGIN + WIDTH, y)]


def ring(content: hqf_pdf.Content, radius: float) -> None:
    """Draws a ring of the seal."""
    content.move_to(SEAL[0] + radius, SEAL[1])
    for turn in range(len(MARKS)):
        content.curve_to(*arc(radius, MARKS[turn], MARKS[(turn + 1) % len(MARKS)]))
    content.close_path()
    content.stroke()


def rule(content: hqf_pdf.Content, y: float) -> None:
    """Draws a rule where a straight path runs."""
    content.move_to(MARGIN, y)
    content.line_to(MARGIN + WIDTH, y)
    content.stroke()


def caption(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, top: float, color: hqf_pdf.Rgb, text: str
) -> None:
    """Writes a caption in a column the width of the page."""
    flow = hqf_pdf.TextFlow(font, 8.5, leading=12.0, color=color)
    lines = flow.break_lines(text, WIDTH)
    flow.draw(content, lines, MARGIN, top, WIDTH)


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

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

    content = hqf_pdf.Content()
    content.draw_text(font, 14.0, MARGIN, 800.0, words.title)

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb(0.25, 0.35, 0.7))
    content.set_line_width(1.5)
    ring(content, RING)
    ring(content, INNER_RING)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.25, 0.35, 0.7))
    hqf_pdf.TextPath(
        font,
        words.seal_over,
        14.0,
        over_the_seal(),
        start=hqf_pdf.PathStart.Middle,
    ).draw(content)
    hqf_pdf.TextPath(
        font,
        words.seal_under,
        12.0,
        under_the_seal(),
        start=hqf_pdf.PathStart.Middle,
    ).draw(content)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.1, 0.45, 0.25))
    hqf_pdf.TextPath(
        font, words.arch, 20.0, the_arch(), start=hqf_pdf.PathStart.Middle
    ).draw(content)
    content.restore_state()

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.8))
    content.set_line_width(0.5)
    for y in RULES:
        rule(content, y)
    content.restore_state()

    for y, start, text in zip(RULES, beginnings(), words.starts):
        hqf_pdf.TextPath(font, text, 12.0, straight(y), start=start).draw(content)

    for top, text in zip(CAPTIONS, words.captions):
        caption(content, font, top, hqf_pdf.Rgb.gray(0.35), text)

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

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {3 + len(RULES)} lines along a path")


if __name__ == "__main__":
    main()