write_text_path.py

The Python file of the “Words that follow a curve” example. A seal whose legend rides its ring and a second one bowed at its foot so those words stand upright, a title bent over an arch, and the same sentence begun at three places along one straight path.

Python 307 lines

What this example is for

A stamp, a seal, a medal, a coin: the words on them run round the edge, and they have run round the edge for as long as there have been seals. Set as an ordinary line, those same words lie flat across the middle and the object is no longer the object. Here they are laid along a path, given in the very words a letter's own outline is given in, and each letter is turned to stand on it. The seal on this page carries its name over the top of its ring; at the foot, the path bows the other way, so the words there stand upright instead of hanging upside down.

What this example shows

  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
"""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",
        "S'arrêtant où il s'arrête",
    ),
    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 "
        "part de son milieu : ce qui est écrit reste centré sur l'arche quelle "
        "que soit la longueur des mots.",
        "Les mêmes mots sur le même chemin, commencés à trois endroits : à son "
        "départ, à mi-chemin, et s'arrêtant où il s'arrête. Le filet sous "
        "chacun est le chemin lui-même.",
    ),
)


# 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}


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()