A page whose letters cost one byte each

The same three lines written twice over — the ordinary way, then with each letter held as a single byte — and the page states what each of the two came to. The short way also lets the words of a line be pushed apart, which the ordinary way leaves nothing to push.

This page is the whole program, for whoever writes your software. There is nothing here to read otherwise. Go back to the document it writes.

Python write_simple_encoding.py 315 lines
  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
"""Sets a page whose every letter is one byte in the stream rather than two.

The Python twin of the `write_simple_encoding` example in Rust. A font is reached by
glyph index unless it is told otherwise: two bytes a glyph, and every glyph the face
holds within reach. Reached through a simple encoding it is addressed by one-byte codes
instead, at most 255 of them, and the file states which character each code stands for.
The page weighs the same three lines both ways and prints the two figures it measured.

The single byte also gives word spacing something to reach: the operator moves the pen
at the byte 32 and at no other code, so the last two lines of the page are the same
words drawn without it and with it.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


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

    # The page's title.
    title: str
    # What the page is about.
    lead: str
    # The label over the three lines set through one-byte codes.
    shown: str
    # The three lines, drawn through the encoding.
    samples: tuple[str, str, str]
    # The label over the codes the encoding settled.
    codes: str
    # The sentence the first of those codes are put into.
    settled: str
    # The label over what the two streams weigh.
    weight: str
    # The sentence the two weights are put into.
    weighed: str
    # The label over the two lines that show word spacing.
    spacing: str
    # The line drawn twice, once with word spacing and once without.
    pushed: str
    # What those two lines show.
    spread: str
    # What an encoding of one byte cannot do.
    caveat: str

    def drawn(self) -> str:
        """Every character the page draws through the encoding, the samples first.

        The encoding hands out its codes in the order it meets its characters, so the
        lines the page lists the codes of are the ones that take the first codes.
        """
        return "".join(self.samples) + self.pushed


# The page in English.
ENGLISH = Words(
    title="A page addressed by one-byte codes",
    lead=(
        "Every letter on the three lines below costs one byte of this file's page "
        "stream instead of two. A font is reached by glyph index unless it is told "
        "otherwise, two bytes a glyph, which puts every glyph the face holds within "
        "reach. Reached through an encoding it is addressed by one-byte codes instead: "
        "at most 255 of them, each standing for one character, and the file states "
        "which character each of them stands for."
    ),
    shown="Set through one-byte codes",
    samples=(
        "HQF Development",
        "An invoice, a payslip, a delivery note.",
        "One byte a letter, and the file says which.",
    ),
    codes="The codes it settled",
    settled=(
        "The encoding is fitted to the words this page draws: the space keeps code 32, "
        "and every other character takes the lowest code free from 33 up, so nothing "
        "in the stream is a byte a reader has to escape. The first of them are %codes%."
    ),
    weight="What the stream weighs",
    weighed=(
        "Drawn by glyph index, the three lines above cost %identity% bytes of page "
        "stream; drawn through one-byte codes, %simple% bytes, which is %saved% less. "
        "Both figures are measured by the program that drew this page, not written in "
        "by hand."
    ),
    spacing="What the single byte 32 buys",
    pushed="Words a reader can push apart.",
    spread=(
        "The two lines above hold the same characters. The second is drawn with word "
        "spacing set, which moves the pen at the single byte 32 and at no other code. "
        "Under glyph indices no code is a single byte 32, so the operator has nothing "
        "to reach and the words never move; the space of this encoding sits at 32, so "
        "they do."
    ),
    caveat=(
        "One byte addresses 255 characters at a time, so a page of several alphabets "
        "is still reached by glyph index. No ligature and no small capital is drawn "
        "through an encoding either: those are glyphs no character stands for, and a "
        "code stands for a character. A file that claims archival conformance states "
        "the Windows encoding as the one its codes are read against, which this one "
        "does."
    ),
)

# The page in French.
FRENCH = Words(
    title="Une page adressée par des codes d'un octet",
    lead=(
        "Chaque lettre des trois lignes ci-dessous coûte un octet du flux de cette "
        "page, et non deux. Une police est atteinte par indice de dessin tant qu'on ne "
        "dit rien d'autre, deux octets par dessin, ce qui met à portée tous les "
        "dessins qu'elle porte. Atteinte par un encodage, elle est adressée par des "
        "codes d'un octet : 255 au plus, chacun représentant un caractère, et le "
        "fichier dit quel caractère chacun d'eux représente."
    ),
    shown="Composé avec des codes d'un octet",
    samples=(
        "HQF Development",
        "Une facture, un bulletin, un bon de livraison.",
        "Un octet par lettre, et le fichier dit lequel.",
    ),
    codes="Les codes qu'il a fixés",
    settled=(
        "L'encodage est ajusté aux mots que cette page dessine : l'espace garde le "
        "code 32, et chaque autre caractère prend le plus petit code libre à partir de "
        "33, si bien qu'aucun octet du flux n'est à protéger à la lecture. Les "
        "premiers sont %codes%."
    ),
    weight="Ce que le flux pèse",
    weighed=(
        "Dessinées par indice, les trois lignes ci-dessus coûtent %identity% octets de "
        "flux de page ; dessinées par des codes d'un octet, %simple% octets, soit "
        "%saved% de moins. Les deux chiffres sont mesurés par le programme qui a "
        "dessiné cette page, pas écrits à la main."
    ),
    spacing="Ce que l'octet 32 rapporte",
    pushed="Des mots qu'un lecteur peut écarter.",
    spread=(
        "Les deux lignes ci-dessus portent les mêmes caractères. La seconde est "
        "dessinée avec l'écartement des mots, qui pousse la plume sur l'octet 32 et "
        "sur aucun autre code. Par indice de dessin, aucun code ne vaut l'octet 32 "
        "seul : l'opérateur n'a rien à atteindre et les mots ne bougent jamais ; "
        "l'espace de cet encodage est en 32, donc ils bougent."
    ),
    caveat=(
        "Un octet adresse 255 caractères à la fois : une page qui mêle plusieurs "
        "alphabets reste atteinte par indice de dessin. Aucune ligature ni aucune "
        "petite capitale ne se dessine non plus par un encodage : ce sont des dessins "
        "qu'aucun caractère ne représente, et un code représente un caractère. Un "
        "fichier qui revendique l'archivage annonce l'encodage de Windows comme celui "
        "contre lequel ses codes se lisent, ce que celui-ci fait."
    ),
)

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

# The left edge of everything on the page.
LEFT = 72.0

# How wide a block of text is.
WIDTH = 450.0

# The size the three samples are drawn at.
SAMPLE = 14.0

# The size the two lines showing word spacing are drawn at.
SPACED = 12.0

# How far apart the second of those two lines pushes its words.
WORD_SPACING = 6.0


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def spaced(count: int) -> str:
    """A count with a no-break space between its thousands."""
    digits = str(count)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(" ")
        out.append(digit)
    return "".join(out)


def stream_bytes(handle: hqf_pdf.FontHandle, words: Words) -> int:
    """What the three samples cost in a page stream, drawn through one handle.

    The two handles write the same operators around the same three lines, so what one
    weighs against the other is what the codes weigh against the indices.
    """
    content = hqf_pdf.Content()
    top = 700.0
    for sample in words.samples:
        top = block(content, handle, SAMPLE, top, sample) - 10.0
    return len(content.to_bytes())


def settled(encoding: hqf_pdf.SimpleEncoding, words: Words, count: int) -> str:
    """The first `count` characters of the samples, each beside the code that reaches
    it."""
    seen: list[str] = []
    for character in "".join(words.samples):
        if character != " " and character not in seen:
            seen.append(character)
    listed = []
    for character in seen:
        code = encoding.code(character)
        if code is not None:
            listed.append(f"{character} {code}")
        if len(listed) == count:
            break
    return " · ".join(listed)


def build(words: Words, font: hqf_pdf.Font, encoding: hqf_pdf.SimpleEncoding) -> bytes:
    """Draws the whole page."""
    coded = font.with_encoding(hqf_pdf.Encoding.simple(encoding))

    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    text = doc.add_font(font)
    drawn = doc.add_font(coded)

    content = hqf_pdf.Content()
    top = 780.0
    top = block(content, text, 18.0, top, words.title) - 14.0
    top = block(content, text, 10.0, top, words.lead) - 22.0

    top = block(content, text, 12.0, top, words.shown) - 12.0
    for sample in words.samples:
        top = block(content, drawn, SAMPLE, top, sample) - 8.0

    top -= 14.0
    top = block(content, text, 12.0, top, words.codes) - 10.0
    listed = words.settled.replace("%codes%", settled(encoding, words, 8))
    top = block(content, text, 10.0, top, listed) - 20.0

    indices = stream_bytes(text, words)
    codes = stream_bytes(drawn, words)
    top = block(content, text, 12.0, top, words.weight) - 10.0
    said = (
        words.weighed.replace("%identity%", spaced(indices))
        .replace("%simple%", spaced(codes))
        .replace("%saved%", spaced(indices - codes))
    )
    top = block(content, text, 10.0, top, said) - 20.0

    top = block(content, text, 12.0, top, words.spacing) - 12.0
    top = block(content, drawn, SPACED, top, words.pushed) - 8.0
    content.set_word_spacing(WORD_SPACING)
    top = block(content, drawn, SPACED, top, words.pushed) - 18.0
    content.set_word_spacing(0.0)
    top = block(content, text, 10.0, top, words.spread) - 20.0

    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    block(content, text, 9.0, top, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    doc.add_page(page)
    return doc.to_bytes()


def main() -> None:
    """Writes the page."""
    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("simple_encoding.pdf", language)).stem
    )
    font = hqf_pdf.Font.from_path(_out.font_path())
    encoding = hqf_pdf.SimpleEncoding.fitting(font, words.drawn())
    drawn = build(words, font, encoding)

    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(drawn)
    print(f"wrote {out}: {len(drawn)} bytes")


if __name__ == "__main__":
    main()