write_stack_by_hand.rs

Le fichier Rust de l’exemple « Une pile mise en page à la main, cadre par cadre ». Un bon de livraison réparti dans deux cadres, le second reprenant là où le premier s’est arrêté, et une affiche dont l’image ne tient dans aucun cadre ; chaque cadre indique ce qu’il est advenu de sa pile.

Rust 469 lignes

À quoi sert cet exemple

Le rapport de l’exemple voisin se met en page tout seul : le moteur décide où couper chaque page. Parfois, c’est à vous de choisir les cadres — une colonne à côté d’une image, un panneau de formulaire, l’espace laissé sous un en-tête — et le texte doit les remplir l’un après l’autre.

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
//! Lays a stack out by hand, one box at a time, and says under each box what
//! became of the stack in it.
//!
//! A delivery slip holding a heading, a picture, a paragraph, a rule and a
//! closing line is fitted into a first box too short for it, which says where
//! the slip resumes; the rest goes into a second box from the cursor the first
//! hands back, and that one says it is done. A poster whose picture is taller
//! than its box says so and places nothing. Each box is outlined, each block it
//! placed is outlined inside it, and under each a line says what became of the
//! stack and how much of the box it took.
//!
//! Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The heights and the ordinates are figures, and stand the
//! same in every language.
//!
//! Usage: `cargo run --example write_stack_by_hand -- tmp/stack_by_hand.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_stack_by_hand --
//! tmp/pile_a_la_main.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Block, Guides, Rect, Stack, StackCursor, StackFrame, StackProgress, Stacked, Stroke,
};
use hqf_pdf::{Document, Font, FontHandle, Image, ImageHandle, Page, Rgb, TextFlow};

#[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 picture the delivery slip and the poster hold.
fn picture() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images")
        .join("logo.png")
}

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

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The heading of the page.
    heading: &'static str,
    /// The delivery slip's heading, its paragraph and its closing line.
    slip: [&'static str; 3],
    /// What became of a stack in a box: every block placed; the box full, the
    /// rest resuming at block `{block}`; a block taller than the box.
    outcomes: [&'static str; 3],
    /// How much of a box its blocks took; `{height}`, `{top}` and `{bottom}`
    /// stand for the figures.
    took: &'static str,
    /// What a box that placed nothing says.
    nothing: &'static str,
}

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

/// The page in English.
const ENGLISH: Words = Words {
    heading: "A stack laid out by hand, one box at a time",
    slip: [
        "Delivery slip",
        "Three parcels left the depot this morning and are due at the site before noon. \
         The driver will ring the bell at the gate; if nobody answers, the parcels go back \
         to the depot and wait there for two days.",
        "Keep this slip until the parcels are signed for.",
    ],
    outcomes: [
        "Every block placed.",
        "The box is full; the rest resumes at block {block}.",
        "A block is taller than the box: nothing more can be placed.",
    ],
    took: "{height} pt taken, from {top} down to {bottom}.",
    nothing: "Nothing placed in this box.",
};

/// The page in French.
const FRENCH: Words = Words {
    heading: "Une pile mise en page à la main, cadre par cadre",
    slip: [
        "Bon de livraison",
        "Trois colis ont quitté le dépôt ce matin et doivent arriver au chantier avant \
midi. Le chauffeur sonnera au portail ; si personne ne répond, les colis \
repartent au dépôt et y attendent deux jours.",
        "Gardez ce bon jusqu’à la signature des colis.",
    ],
    outcomes: [
        "Tous les blocs sont placés.",
        "Le cadre est plein ; la suite reprend au bloc {block}.",
        "Un bloc est plus haut que le cadre : plus rien ne peut être placé.",
    ],
    took: "{height} pt occupés, de {top} jusqu’à {bottom}.",
    nothing: "Rien n’est placé dans ce cadre.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    heading: "Een stapel met de hand opgemaakt, één kader tegelijk",
    slip: [
        "Afleverbon",
        "Drie colli verlieten vanochtend het depot en worden vóór twaalf uur op de bouwplaats verwacht. De chauffeur belt aan bij het hek; als niemand opendoet, gaan de colli terug naar het depot en wachten daar twee dagen.",
        "Bewaar deze bon tot de ontvangst van de colli getekend is.",
    ],
    outcomes: [
        "Elk blok geplaatst.",
        "Het kader is vol; de rest gaat verder bij blok {block}.",
        "Een blok is hoger dan het kader: er kan niets meer geplaatst worden.",
    ],
    took: "{height} pt gebruikt, van {top} tot {bottom}.",
    nothing: "Niets geplaatst in dit kader.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    heading: "Uma pilha disposta à mão, uma caixa de cada vez",
    slip: [
        "Talão de entrega",
        "Três volumes saíram do armazém esta manhã e devem chegar à obra antes do meio-dia. O motorista toca à campainha do portão; se ninguém responder, os volumes voltam ao armazém e esperam lá dois dias.",
        "Guarde este talão até a receção dos volumes ser assinada.",
    ],
    outcomes: [
        "Todos os blocos colocados.",
        "A caixa está cheia; o resto continua no bloco {block}.",
        "Um bloco é mais alto do que a caixa: não se pode colocar mais nada.",
    ],
    took: "{height} pt ocupados, de {top} a {bottom}.",
    nothing: "Nada colocado nesta caixa.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    heading: "Una pila disposta a mano, un riquadro alla volta",
    slip: [
        "Documento di trasporto",
        "Tre colli sono partiti dal deposito stamattina e devono arrivare in cantiere prima di mezzogiorno. L’autista suonerà al cancello; se nessuno risponde, i colli tornano al deposito e ci restano due giorni.",
        "Conservate questo documento finché la consegna non è firmata.",
    ],
    outcomes: [
        "Tutti i blocchi collocati.",
        "Il riquadro è pieno; il resto riprende dal blocco {block}.",
        "Un blocco è più alto del riquadro: non si può collocare altro.",
    ],
    took: "{height} pt occupati, da {top} a {bottom}.",
    nothing: "Nulla collocato in questo riquadro.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    heading: "Una pila colocada a mano, caja a caja",
    slip: [
        "Volante de entrega",
        "Tres paquetes salieron del almacén esta mañana y deben llegar a la obra antes de mediodía. El conductor llamará al timbre de la verja; si nadie responde, los paquetes vuelven al almacén y esperan allí dos días.",
        "Guarde este volante hasta que se firme la recepción de los paquetes.",
    ],
    outcomes: [
        "Todos los bloques colocados.",
        "La caja está llena; el resto sigue en el bloque {block}.",
        "Un bloque es más alto que la caja: no puede colocarse nada más.",
    ],
    took: "{height} pt ocupados, de {top} a {bottom}.",
    nothing: "Nada colocado en esta caja.",
};

/// The page in German.
const GERMAN: Words = Words {
    heading: "Ein Stapel, von Hand aufgebaut, ein Rahmen nach dem anderen",
    slip: [
        "Lieferschein",
        "Drei Pakete haben heute Morgen das Depot verlassen und sollen vor zwölf Uhr auf der Baustelle sein. Der Fahrer klingelt am Tor; öffnet niemand, gehen die Pakete ins Depot zurück und warten dort zwei Tage.",
        "Diesen Schein aufbewahren, bis der Empfang der Pakete unterschrieben ist.",
    ],
    outcomes: [
        "Jeder Block platziert.",
        "Der Rahmen ist voll; der Rest geht bei Block {block} weiter.",
        "Ein Block ist höher als der Rahmen: Nichts weiter kann platziert werden.",
    ],
    took: "{height} pt belegt, von {top} hinunter bis {bottom}.",
    nothing: "Nichts in diesem Rahmen platziert.",
};

/// 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); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// The colour the captions and the slip's rule are set in.
const MUTED: Rgb = Rgb::new(0.45, 0.45, 0.45);

/// How wide the heading may run, in points: the sheet less a margin either
/// side.
const WIDTH: f64 = 483.0;

/// The left edge of everything the page draws.
const LEFT: f64 = 56.0;

/// The delivery slip: a heading, the picture, a paragraph, a rule and a closing
/// line.
fn slip<'a>(font: &'a FontHandle, logo: &ImageHandle, words: &Words) -> Stack<'a> {
    let mut stack = Stack::new();
    stack
        .push(Block::text(TextFlow::new(font, 13.0), words.slip[0]).keep_together())
        .push(Block::space(6.0))
        .push(Block::image(logo, 60.0, 30.0))
        .push(Block::space(6.0))
        .push(Block::text(
            TextFlow::new(font, 9.5).leading(13.0),
            words.slip[1],
        ))
        .push(Block::space(6.0))
        .push(Block::rule(Stroke::new(0.6, MUTED)))
        .push(Block::space(6.0))
        .push(Block::text(
            TextFlow::new(font, 8.5).color(MUTED),
            words.slip[2],
        ));
    stack
}

/// A poster holding nothing but a picture taller than any box it is given.
fn poster(logo: &ImageHandle) -> Stack<'_> {
    let mut stack = Stack::new();
    stack.push(Block::image(logo, 200.0, 300.0));
    stack
}

/// The three boxes the page lays out by hand: the first too short for the slip,
/// the second for the rest of it, the third for the poster.
const HAND_BOXES: [StackFrame; 3] = [
    StackFrame::new(LEFT, 730.0, 220.0, 95.0),
    StackFrame::new(LEFT + 263.0, 730.0, 220.0, 260.0),
    StackFrame::new(LEFT, 420.0, 220.0, 150.0),
];

/// Outlines `placed`'s box and each block it placed, draws the blocks, and sets
/// under the box what became of the stack there.
fn laid(
    c: &mut Content,
    font: &FontHandle,
    placed: &Stacked<'_>,
    words: &Words,
) -> Result<(), hqf_pdf::Error> {
    let frame = placed.frame();
    c.save_state();
    c.set_stroke_rgb(0.6, 0.6, 0.6)?
        .set_line_width(0.5)?
        .rect(
            frame.x(),
            frame.top() - frame.height(),
            frame.width(),
            frame.height(),
        )?
        .stroke();
    c.restore_state();
    placed.draw(c)?;
    let boxes: Vec<Rect> = placed.block_boxes().into_iter().map(|(_, at)| at).collect();
    Guides::hairline(Rgb::new(0.85, 0.0, 0.6)).outline_all(c, &boxes)?;

    #[allow(
        clippy::match_same_arms,
        reason = "an outcome the library adds later reads as a block too tall"
    )]
    let outcome = match placed.outcome() {
        StackProgress::Done => words.outcomes[0].to_owned(),
        StackProgress::BoxFull { next } => {
            words.outcomes[1].replace("{block}", &(next.block() + 1).to_string())
        }
        StackProgress::BlockTooTall { .. } => words.outcomes[2].to_owned(),
        _ => words.outcomes[2].to_owned(),
    };
    let took = if placed.is_empty() {
        words.nothing.to_owned()
    } else {
        words
            .took
            .replace("{height}", &format!("{:.0}", placed.height()))
            .replace("{top}", &format!("{:.0}", placed.top()))
            .replace("{bottom}", &format!("{:.0}", placed.bottom()))
    };
    let flow = TextFlow::new(font, 8.0).color(MUTED);
    let mut y = frame.top() - frame.height() - 6.0;
    for line in [outcome, took] {
        let lines = flow.break_lines(&line, frame.width());
        c.begin_text();
        flow.draw(c, &lines, frame.x(), y, frame.width())?;
        c.end_text();
        y -= flow.height(&lines);
    }
    Ok(())
}

/// The page: the delivery slip laid down two boxes by hand, the second taking
/// up where the first stopped, and the poster that fits no box.
fn by_hand(
    font: &FontHandle,
    logo: &ImageHandle,
    words: &Words,
) -> Result<Content, hqf_pdf::Error> {
    let mut c = Content::new();
    let heading = TextFlow::new(font, 14.0);
    let lines = heading.break_lines(words.heading, WIDTH);
    c.begin_text();
    heading.draw(&mut c, &lines, LEFT, 780.0, WIDTH)?;
    c.end_text();

    let slip = slip(font, logo, words);
    if !slip.is_empty() {
        let first = slip.fit(HAND_BOXES[0], StackCursor::start())?;
        laid(&mut c, font, &first, words)?;
        if let StackProgress::BoxFull { next } = first.outcome() {
            let rest = slip.fit(HAND_BOXES[1], next)?;
            laid(&mut c, font, &rest, words)?;
        }
    }
    let placed = poster(logo).fit(HAND_BOXES[2], StackCursor::start())?;
    laid(&mut c, font, &placed, words)?;
    Ok(c)
}

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("stack_by_hand")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

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

    let logo = doc.add_image(Image::parse(fs::read(picture())?)?);

    let c = by_hand(&handle, &logo, words)?;
    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!("wrote {out}: {} bytes", bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::layout::{StackCursor, StackProgress};
    use hqf_pdf::{Document, Font, FontHandle, Image, ImageHandle};

    use super::{HAND_BOXES, WIDTH, WORDS, default_font, language, picture, poster, slip};

    /// The lines two languages are allowed to write the same way, where two
    /// languages spell a word alike.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#"took: "{height} pt ocupados, de {top} a {bottom}.""#,
    ];

    /// A handle to the committed font and to the picture, and the document that
    /// keeps them alive.
    fn handles() -> (Document, FontHandle, ImageHandle) {
        let mut doc = Document::new();
        let bytes = std::fs::read(default_font()).expect("the committed font is readable");
        let font = doc.add_font(Font::parse(bytes).expect("the committed font parses"));
        let image = std::fs::read(picture()).expect("the committed picture is readable");
        let logo = doc.add_image(Image::parse(image).expect("the committed picture parses"));
        (doc, font, logo)
    }

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

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

    #[test]
    fn every_language_fills_the_first_box_ends_in_the_second_and_refuses_the_poster() {
        let (_doc, font, logo) = handles();
        for &(name, words) in &WORDS {
            let laid_out = slip(&font, &logo, words);
            let first = laid_out
                .fit(HAND_BOXES[0], StackCursor::start())
                .expect("the slip fits its first box");
            let StackProgress::BoxFull { next } = first.outcome() else {
                panic!("{name:?}: the first box holds the whole slip");
            };
            assert!(!first.is_empty(), "{name:?}: the first box placed nothing");

            let rest = laid_out
                .fit(HAND_BOXES[1], next)
                .expect("the slip fits its second box");
            assert!(
                matches!(rest.outcome(), StackProgress::Done),
                "{name:?}: the second box does not finish the slip"
            );

            let placed = poster(&logo)
                .fit(HAND_BOXES[2], StackCursor::start())
                .expect("the poster is fitted");
            assert!(
                matches!(placed.outcome(), StackProgress::BlockTooTall { .. }),
                "{name:?}: the poster's picture fits its box"
            );
            assert!(placed.is_empty(), "{name:?}: the poster placed something");
        }
    }

    #[test]
    fn every_heading_fits_the_width_of_the_page() {
        let (_doc, font, _logo) = handles();
        for &(name, words) in &WORDS {
            let width = font.measure(words.heading, 14.0);
            assert!(
                width <= WIDTH,
                "{name:?}: the heading is {width} points wide in {WIDTH}"
            );
        }
    }
}