write_slideshow.py

The Python file of the “A slideshow that runs itself” example. A plain first slide and thirteen more, each stating the effect it arrives by — the twelve the PDF standard (ISO 32000) defines — how long that effect takes and how long the slide stands before the next one comes. The file asks to open full screen, which is where the effects play, and a link on the first slide shows the screen again, brought in by dissolving.

Python 414 lines

What this example is for

A document that runs itself is what a screen in a reception area, a trade stand or a waiting room actually needs: no presentation software to install, no licence on the machine, nobody to click anything. The file is the show, and it plays on whatever is standing there, because every machine already opens PDF files.

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
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
"""A slideshow: fourteen pages, each arriving by a different effect.

The Python twin of the `write_slideshow` example in Rust. The file opens full screen,
and every page states how it arrives and how long it stands before the next one comes by
itself. Nothing here is drawn by the effect: each page simply names the one that brings
it in, so what reading software does can be checked against what the file asked for.

The slides are written in the language `HQF_PDF_LANG` names: what an effect is called
and what it does are words a person reads. The entries the file writes for it are not
— `/S /Split /Dm /V /M /O` is what reading software parses, and it is the same in every
language, so each slide carries both.

The title slide also carries a link that acts rather than leads: following it asks
reading software to show the screen again, brought in by dissolving. Each slide keeps
the effect it states for itself.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# A slide, laid down sideways: a projected page is wider than it is tall.
SHEET = (720.0, 540.0)

# How far in from the edge of the slide everything is set.
MARGIN = 64.0

# How long each slide stands before the next arrives, in seconds.
STANDS = 4.0

# How long each effect takes, in seconds.
TAKES = 1.0

# The size a slide's name is set at, in points.
NAME = 54.0

# The size the line under a slide's name is set at, in points.
DOES = 15.0

# The size the title slide's heading is set at, in points.
TITLE = 42.0

# The size the lines of the title slide are set at, in points.
INTRO = 12.0

# How far apart the lines of the title slide are stacked, in points.
INTRO_STEP = 20.0

# The baseline of the line on the title slide that a link lies over.
FOLLOW_AT = 90.0

# How far below its baseline, and how far above, the link over that line reaches.
FOLLOW_REACH = (4.0, 12.0)

# How wide the link over that line is: the room between the two margins.
FOLLOW_WIDTH = SHEET[0] - 2.0 * MARGIN


@dataclass(frozen=True)
class Words:
    """Every word the slides are written in, in one language.

    What is not language stays out of it: the entries the file writes for each effect
    are what reading software parses, and the name on the footer is a name.
    """

    # What the title slide is headed by.
    title: str
    # The line under that heading.
    strapline: str
    # What the title slide says the file asks reading software for.
    intro: tuple[str, str, str, str]
    # What the title slide says of itself.
    stands_still: str
    # The line on the title slide a link lies over, saying what following it does.
    follow: str
    # What stands between a slide's number and the count of them.
    of: str
    # What is written over the entries the file states for a slide.
    states_label: str
    # What each effect is called, in the order `effects` sets them.
    names: tuple[str, ...]
    # What each effect does, in the same order.
    does: tuple[str, ...]


# The slides in English.
ENGLISH = Words(
    title="Twelve ways in",
    strapline="Every effect a PDF can ask reading software for, one to a slide.",
    intro=(
        "This file opens full screen, and each slide states how it arrives and how "
        "long",
        "it stands before the next one comes by itself. Reading software that honours",
        "all of it runs the whole thing unattended; one that honours none of it shows",
        "fourteen pages, and nothing is lost.",
    ),
    stands_still=(
        "This first slide arrives by nothing at all: it is the one already on "
        "the screen."
    ),
    follow="Click this line and the screen you are on is shown again, dissolving in.",
    of="of",
    states_label="the file states",
    names=(
        "Split",
        "Blinds",
        "Box",
        "Wipe",
        "Dissolve",
        "Glitter",
        "Fly",
        "Fly, at the reader",
        "Push",
        "Cover",
        "Uncover",
        "Fade",
        "Replace",
    ),
    does=(
        "Two lines sweep apart to reveal the slide.",
        "Many lines sweep across at once, like a blind opening.",
        "A rectangle opens out of the middle of the slide.",
        "One line sweeps left to right.",
        "The slide before it dissolves into this one.",
        "The dissolve travels from the top-left corner down.",
        "The slide before it flies off downwards.",
        "What has changed flies out of the screen, starting small.",
        "Both slides slide together, the old one pushing this on.",
        "This slide slides up over the one before it.",
        "The slide before it slides down off this one.",
        "The slide fades up out of reading software's own background.",
        "Nothing sweeps or fades: the slide is simply there.",
    ),
)

# The slides in French.
FRENCH = Words(
    title="Douze façons d'entrer",
    strapline=(
        "Tous les effets qu'un PDF demande au logiciel de lecture, un par diapositive."
    ),
    intro=(
        "Ce fichier s'ouvre en plein écran, et chaque diapositive dit comment elle "
        "arrive et",
        "combien de temps elle reste avant que la suivante vienne d'elle-même. Un "
        "logiciel",
        "de lecture qui suit tout cela déroule l'ensemble sans personne ; celui qui "
        "n'en suit",
        "rien montre quatorze pages, et rien n'est perdu.",
    ),
    stands_still=(
        "Cette première diapositive n'arrive par rien du tout : elle est déjà à "
        "l'écran."
    ),
    follow="Cliquez cette ligne : l'écran où vous êtes est réaffiché par dissolution.",
    of="sur",
    states_label="ce que le fichier écrit",
    names=(
        "Séparation",
        "Stores",
        "Boîte",
        "Balayage",
        "Dissolution",
        "Scintillement",
        "Envol",
        "Envol vers l'avant",
        "Poussée",
        "Recouvrement",
        "Dévoilement",
        "Fondu",
        "Remplacement",
    ),
    does=(
        "Deux traits s'écartent et découvrent la diapositive.",
        "Plusieurs traits balaient l'écran d'un coup, comme un store qui s'ouvre.",
        "Un rectangle s'ouvre depuis le milieu de la diapositive.",
        "Un trait balaie l'écran de la gauche vers la droite.",
        "La diapositive précédente se dissout dans celle-ci.",
        "La dissolution part du coin haut gauche et descend.",
        "La diapositive précédente s'envole vers le bas.",
        "Ce qui a changé sort de l'écran, petit d'abord puis grand.",
        "Les deux diapositives glissent ensemble, l'ancienne poussant celle-ci.",
        "Cette diapositive glisse vers le haut par-dessus la précédente.",
        "La diapositive précédente glisse vers le bas et libère celle-ci.",
        "La diapositive apparaît en fondu depuis le fond du logiciel de lecture.",
        "Rien ne balaie ni ne s'estompe : la diapositive est là.",
    ),
)

# 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 slide(font, words, wash, number, name, does, states):
    """One slide: a wash of colour, the effect that brings it in, and its entries."""
    content = hqf_pdf.Content()
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(wash[0], wash[1], wash[2]))
    content.rect(0.0, 0.0, SHEET[0], SHEET[1])
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.rect(0.0, SHEET[1] - 8.0, SHEET[0], 8.0)
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.draw_text(font, DOES, MARGIN, SHEET[1] - 70.0, number)
    content.draw_text(font, NAME, MARGIN, 300.0, name)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.92))
    content.draw_text(font, DOES, MARGIN, 254.0, does)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.82))
    content.draw_text(font, 11.0, MARGIN, MARGIN + 34.0, words.states_label)
    content.draw_text(font, 11.0, MARGIN, MARGIN + 16.0, states)
    content.restore_state()
    return content


def title(font, words):
    """The title slide, which nothing brings in: it is the one already there."""
    content = hqf_pdf.Content()
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.09, 0.11, 0.16))
    content.rect(0.0, 0.0, SHEET[0], SHEET[1])
    content.fill()
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
    content.draw_text(font, TITLE, MARGIN, 330.0, words.title)
    content.set_fill(hqf_pdf.Color.gray(0.72))
    content.draw_text(font, DOES, MARGIN, 286.0, words.strapline)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.55))
    y = 210.0
    for line in words.intro:
        content.draw_text(font, INTRO, MARGIN, y, line)
        y -= INTRO_STEP

    # The line that speaks of this slide alone stands a blank line clear of the ones
    # that speak of the file.
    y -= INTRO_STEP
    content.draw_text(font, INTRO, MARGIN, y, words.stands_still)
    content.draw_text(font, INTRO, MARGIN, FOLLOW_AT, words.follow)
    content.restore_state()

    content.save_state()
    content.set_fill(hqf_pdf.Color.gray(0.4))
    content.draw_text(font, 11.0, MARGIN, MARGIN, "HQF Development")
    content.restore_state()
    return content


def effects():
    """The thirteen slides after the title one, one to an effect.

    The twelve effects the format defines, `Fly` standing on two of them. Each entry
    is how the slide arrives, the wash it is laid on, and the entries the file writes
    for it. What the effect is called and what it does are words a person reads, and
    are held in `Words`.
    """
    return [
        (
            hqf_pdf.Effect.split(hqf_pdf.Axis.Vertical, hqf_pdf.Motion.Outward),
            (0.13, 0.29, 0.36),
            "/S /Split /Dm /V /M /O",
        ),
        (
            hqf_pdf.Effect.blinds(hqf_pdf.Axis.Horizontal),
            (0.16, 0.34, 0.31),
            "/S /Blinds /Dm /H",
        ),
        (
            hqf_pdf.Effect.box(hqf_pdf.Motion.Outward),
            (0.24, 0.33, 0.22),
            "/S /Box /M /O",
        ),
        (
            hqf_pdf.Effect.wipe(hqf_pdf.Heading.Rightwards),
            (0.36, 0.32, 0.16),
            "/S /Wipe /Di 0",
        ),
        (
            hqf_pdf.Effect.dissolve(),
            (0.40, 0.26, 0.16),
            "/S /Dissolve",
        ),
        (
            hqf_pdf.Effect.glitter(hqf_pdf.Heading.Diagonally),
            (0.42, 0.20, 0.20),
            "/S /Glitter /Di 315",
        ),
        (
            hqf_pdf.Effect.fly(hqf_pdf.Heading.Downwards),
            (0.38, 0.17, 0.30),
            "/S /Fly /Di 270 /B true",
        ),
        (
            hqf_pdf.Effect.fly(None, 0.6, False),
            (0.31, 0.18, 0.38),
            "/S /Fly /Di /None /SS 0.6 /B false",
        ),
        (
            hqf_pdf.Effect.push(hqf_pdf.Heading.Leftwards),
            (0.21, 0.20, 0.42),
            "/S /Push /Di 180",
        ),
        (
            hqf_pdf.Effect.cover(hqf_pdf.Heading.Upwards),
            (0.14, 0.26, 0.42),
            "/S /Cover /Di 90",
        ),
        (
            hqf_pdf.Effect.uncover(hqf_pdf.Heading.Downwards),
            (0.11, 0.31, 0.38),
            "/S /Uncover /Di 270",
        ),
        (
            hqf_pdf.Effect.fade(),
            (0.20, 0.20, 0.22),
            "/S /Fade",
        ),
        (
            hqf_pdf.Effect.replace(),
            (0.09, 0.11, 0.16),
            "/S /R",
        ),
    ]


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

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

    first = hqf_pdf.Page(SHEET[0], SHEET[1])
    first.set_content(title(font, words))
    first.set_duration(STANDS)
    first.add_link(
        hqf_pdf.Link.acting(
            MARGIN,
            FOLLOW_AT - FOLLOW_REACH[0],
            FOLLOW_WIDTH,
            FOLLOW_REACH[0] + FOLLOW_REACH[1],
            hqf_pdf.Action.transition(
                hqf_pdf.Transition(hqf_pdf.Effect.dissolve()).seconds(TAKES)
            ),
        )
    )
    document.add_page(first)

    all_effects = effects()
    total = len(all_effects) + 1
    for index, (effect, wash, states) in enumerate(all_effects):
        number = f"{index + 2} {words.of} {total}"
        page = hqf_pdf.Page(SHEET[0], SHEET[1])
        page.set_content(
            slide(
                font,
                words,
                wash,
                number,
                words.names[index],
                words.does[index],
                states,
            )
        )
        page.set_transition(hqf_pdf.Transition(effect).seconds(TAKES))
        page.set_duration(STANDS)
        document.add_page(page)

    # A transition is read in full screen and nowhere else, so a slideshow that does not
    # ask for full screen asks for nothing.
    document.set_open_mode(hqf_pdf.OpenMode.FullScreen)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {document.page_count} slides, each "
        f"arriving by a different effect"
    )


if __name__ == "__main__":
    main()