write_slideshow.rs

Le fichier Rust de l'exemple « Un diaporama qui se déroule tout seul ». Une première diapositive sobre et treize autres, chacune énonçant l'effet par lequel elle arrive — les douze que définit la norme PDF (ISO 32000) —, la durée de cet effet et le temps où la diapositive reste avant que la suivante n'arrive. Le fichier demande à s'ouvrir en plein écran, là où les effets se jouent, et un lien posé sur la première diapositive réaffiche l'écran en le faisant apparaître par dissolution.

Rust 579 lignes

À quoi sert cet exemple

Un document qui se déroule tout seul, c'est ce qu'il faut à un écran d'accueil, à un stand de salon ou à une salle d'attente : pas de logiciel de présentation à installer, pas de licence sur la machine, personne pour cliquer. Le fichier est le spectacle, et il passe sur n'importe quel poste, parce que tous savent déjà ouvrir un PDF.

Ce que montre cet exemple

  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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! A slideshow: fourteen pages, each arriving by a different effect.
//!
//! 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.
//!
//! Open it in reading software that honours full screen to see them run.
//!
//! 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.
//!
//! 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.
//!
//! Usage: `cargo run --example write_slideshow -- tmp/slideshow.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_slideshow`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::action::Action;
use hqf_pdf::content::Content;
use hqf_pdf::transition::{Axis, Effect, Heading, Motion, Transition};
use hqf_pdf::{Color, Document, Error, Font, FontHandle, Link, OpenMode, Page, Rgb};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

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

/// How far in from the edge of the slide everything is set.
const MARGIN: f64 = 64.0;

/// How long each slide stands before the next arrives, in seconds.
const STANDS: f64 = 4.0;

/// How long each effect takes, in seconds.
const TAKES: f64 = 1.0;

/// The size a slide's name is set at, in points.
const NAME: f64 = 54.0;

/// The size the line under a slide's name is set at, in points.
const DOES: f64 = 15.0;

/// The size the title slide's heading is set at, in points.
const TITLE: f64 = 42.0;

/// The size the lines of the title slide are set at, in points.
const INTRO: f64 = 12.0;

/// How far apart the lines of the title slide are stacked, in points.
const INTRO_STEP: f64 = 20.0;

/// The baseline of the line on the title slide that a link lies over.
const FOLLOW_AT: f64 = 90.0;

/// How far below its baseline, and how far above, the link over that line
/// reaches.
const FOLLOW_REACH: (f64, f64) = (4.0, 12.0);

/// How wide the link over that line is: the room between the two margins.
const FOLLOW_WIDTH: f64 = SHEET.0 - 2.0 * MARGIN;

/// The words the slides are written in, one set per 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.
#[derive(Debug)]
struct Words {
    /// What the title slide is headed by.
    title: &'static str,
    /// The line under that heading.
    strapline: &'static str,
    /// What the title slide says the file asks reading software for.
    intro: [&'static str; 4],
    /// What the title slide says of itself.
    stands_still: &'static str,
    /// The line on the title slide a link lies over, saying what following it
    /// does.
    follow: &'static str,
    /// What stands between a slide's number and the count of them.
    of: &'static str,
    /// What is written over the entries the file states for a slide.
    states_label: &'static str,
    /// What each effect is called, in the order `EFFECTS` sets them.
    names: [&'static str; EFFECTS.len()],
    /// What each effect does, in the same order.
    does: [&'static str; EFFECTS.len()],
}

impl Words {
    /// The words the slides are written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The slides in English.
const ENGLISH: Words = 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.
const FRENCH: Words = 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.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// Draws one line of text with its baseline at `(x, y)`.
fn text(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    line: &str,
) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// One slide: a wash of colour, the name of the effect that brings it in, what
/// that effect does, and the entries the file states for it.
fn slide(
    font: &FontHandle,
    words: &Words,
    wash: Rgb,
    number: &str,
    name: &str,
    does: &str,
    states: &str,
) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    content.save_state();
    content.set_fill(wash)?;
    content.rect(0.0, 0.0, SHEET.0, SHEET.1)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    content.rect(0.0, SHEET.1 - 8.0, SHEET.0, 8.0)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(&mut content, font, DOES, MARGIN, SHEET.1 - 70.0, number)?;
    text(&mut content, font, NAME, MARGIN, 300.0, name)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.92))?;
    text(&mut content, font, DOES, MARGIN, 254.0, does)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.82))?;
    text(
        &mut content,
        font,
        11.0,
        MARGIN,
        MARGIN + 34.0,
        words.states_label,
    )?;
    text(&mut content, font, 11.0, MARGIN, MARGIN + 16.0, states)?;
    content.restore_state();
    Ok(content.into_bytes())
}

/// The title slide, which nothing brings in: it is the one already there.
fn title(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    content.save_state();
    content.set_fill(Rgb::new(0.09, 0.11, 0.16))?;
    content.rect(0.0, 0.0, SHEET.0, SHEET.1)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(&mut content, font, TITLE, MARGIN, 330.0, words.title)?;
    content.set_fill(Color::Gray(0.72))?;
    text(&mut content, font, DOES, MARGIN, 286.0, words.strapline)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.55))?;
    let mut y = 210.0;
    for line in words.intro {
        text(&mut content, 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;
    text(&mut content, font, INTRO, MARGIN, y, words.stands_still)?;
    text(&mut content, font, INTRO, MARGIN, FOLLOW_AT, words.follow)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.4))?;
    text(&mut content, font, 11.0, MARGIN, MARGIN, "HQF Development")?;
    content.restore_state();
    Ok(content.into_bytes())
}

/// One slide's worth: how it 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`.
type Slide = (Effect, Rgb, &'static str);

/// The thirteen slides after the title one: the twelve effects the format
/// defines, `Fly` standing on two of them.
const EFFECTS: [Slide; 13] = [
    (
        Effect::Split {
            axis: Axis::Vertical,
            motion: Motion::Outward,
        },
        Rgb::new(0.13, 0.29, 0.36),
        "/S /Split /Dm /V /M /O",
    ),
    (
        Effect::Blinds {
            axis: Axis::Horizontal,
        },
        Rgb::new(0.16, 0.34, 0.31),
        "/S /Blinds /Dm /H",
    ),
    (
        Effect::Box {
            motion: Motion::Outward,
        },
        Rgb::new(0.24, 0.33, 0.22),
        "/S /Box /M /O",
    ),
    (
        Effect::Wipe {
            heading: Heading::Rightwards,
        },
        Rgb::new(0.36, 0.32, 0.16),
        "/S /Wipe /Di 0",
    ),
    (Effect::Dissolve, Rgb::new(0.40, 0.26, 0.16), "/S /Dissolve"),
    (
        Effect::Glitter {
            heading: Heading::Diagonally,
        },
        Rgb::new(0.42, 0.20, 0.20),
        "/S /Glitter /Di 315",
    ),
    (
        Effect::Fly {
            heading: Some(Heading::Downwards),
            scale: None,
            whole_page: true,
        },
        Rgb::new(0.38, 0.17, 0.30),
        "/S /Fly /Di 270 /B true",
    ),
    (
        Effect::Fly {
            heading: None,
            scale: Some(0.6),
            whole_page: false,
        },
        Rgb::new(0.31, 0.18, 0.38),
        "/S /Fly /Di /None /SS 0.6 /B false",
    ),
    (
        Effect::Push {
            heading: Heading::Leftwards,
        },
        Rgb::new(0.21, 0.20, 0.42),
        "/S /Push /Di 180",
    ),
    (
        Effect::Cover {
            heading: Heading::Upwards,
        },
        Rgb::new(0.14, 0.26, 0.42),
        "/S /Cover /Di 90",
    ),
    (
        Effect::Uncover {
            heading: Heading::Downwards,
        },
        Rgb::new(0.11, 0.31, 0.38),
        "/S /Uncover /Di 270",
    ),
    (Effect::Fade, Rgb::new(0.20, 0.20, 0.22), "/S /Fade"),
    (Effect::Replace, Rgb::new(0.09, 0.11, 0.16), "/S /R"),
];

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("slideshow")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut first = Page::new(SHEET.0, SHEET.1);
    first.content = title(&font, words)?;
    first.duration = Some(STANDS);
    first.links.push(Link::acting(
        MARGIN,
        FOLLOW_AT - FOLLOW_REACH.0,
        FOLLOW_WIDTH,
        FOLLOW_REACH.0 + FOLLOW_REACH.1,
        Action::Transition(Transition::new(Effect::Dissolve).seconds(TAKES)),
    ));
    doc.add_page(first)?;

    let total = EFFECTS.len() + 1;
    for (index, (effect, wash, states)) in EFFECTS.into_iter().enumerate() {
        let number = format!("{} {} {total}", index + 2, words.of);
        let mut page = Page::new(SHEET.0, SHEET.1);
        page.content = slide(
            &font,
            words,
            wash,
            &number,
            words.names[index],
            words.does[index],
            states,
        )?;
        page.transition = Some(Transition::new(effect).seconds(TAKES));
        page.duration = Some(STANDS);
        doc.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.
    doc.set_open_mode(OpenMode::FullScreen);

    let written = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &written)?;
    println!(
        "wrote {out}: {} bytes, {} slides, each arriving by a different effect",
        written.len(),
        doc.page_count()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font};

    use super::{DOES, EFFECTS, INTRO, MARGIN, NAME, SHEET, TITLE, WORDS, default_font, language};

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side of the slide.
    const ROOM: f64 = SHEET.0 - 2.0 * MARGIN;

    /// The lines two languages are allowed to write the same way. There are
    /// none: the entries the file writes for each effect are held outside the
    /// words, and so is the name on the footer.
    const SPARED: [&str; 0] = [];

    #[test]
    fn every_language_writes_the_slides_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the slides say these in more than one language: {untranslated:?}"
        );
    }

    /// Nothing on a slide is broken to a width: a line longer than the slide
    /// runs off the edge of it, and the name of an effect is set at 54 points,
    /// where a word or two more is all it takes.
    #[test]
    fn every_language_writes_lines_that_fit_the_slide() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            let lines = [(TITLE, words.title), (DOES, words.strapline)]
                .into_iter()
                .chain(words.intro.map(|line| (INTRO, line)))
                .chain([(INTRO, words.stands_still), (INTRO, words.follow)])
                .chain(words.names.map(|name| (NAME, name)))
                .chain(words.does.map(|does| (DOES, does)));

            for (size, line) in lines {
                let measured = font.measure(line, size);
                assert!(
                    measured <= ROOM,
                    "the {} slides draw {line:?} over {measured:.1} points, \
                     and they have {ROOM:.1}",
                    named.code()
                );
            }
        }
    }

    /// The strapline of the title slide promises every effect the format
    /// defines, one to a slide. Each slide is named here by the entries the
    /// file writes for it, which are the same in every language.
    #[test]
    fn every_effect_the_format_defines_stands_on_a_slide() {
        const DEFINED: [&str; 12] = [
            "/S /R",
            "/S /Split",
            "/S /Blinds",
            "/S /Box",
            "/S /Wipe",
            "/S /Dissolve",
            "/S /Glitter",
            "/S /Fly",
            "/S /Push",
            "/S /Cover",
            "/S /Uncover",
            "/S /Fade",
        ];

        let missing: Vec<&str> = DEFINED
            .into_iter()
            .filter(|entries| {
                !EFFECTS
                    .iter()
                    .any(|(_, _, states)| states.starts_with(*entries))
            })
            .collect();

        assert!(missing.is_empty(), "no slide arrives by {missing:?}");
    }

    /// The heading of the title slide counts the effects in words, and the
    /// lines under it count the pages the same way. Neither can be worked out
    /// from the table, so an effect added or dropped has to be carried into
    /// every language by hand — and this is what says so.
    #[test]
    fn the_counts_written_in_words_are_the_counts_the_file_has() {
        assert_eq!(
            EFFECTS.len(),
            13,
            "the title slide says twelve effects, and `Fly` stands on two slides"
        );
        assert_eq!(EFFECTS.len() + 1, 14, "the title slide says fourteen pages");
    }
}