write_press_sheet.rs

Le fichier Rust de l'exemple « Une feuille telle qu'elle part à l'impression ». Un dessin sur trois pages : une feuille de presse qui indique où l'encre court, où la lame tombe et ce qui mérite d'être gardé, avec les traits de coupe ; la même feuille rognée à la page finie ; et une page à l'italienne qui indique un quart de tour horaire sur une feuille à la française.

Rust 792 lignes

À quoi sert cet exemple

Envoyez à une imprimerie un fichier dont la page fait exactement la taille finie, et le travail s'arrête là. Ils ne peuvent pas le couper : une lame ne tombe jamais exactement où il faudrait, et il n'y a pas de couleur au-delà du trait pour rattraper l'écart. La feuille doit être plus grande que la page, et le fichier doit dire de combien, et où passe vraiment le bord fini.

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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! A sheet as it goes to the press, and what each box a page states does to it.
//!
//! A page has always had a sheet. It now also has the four boxes a printer
//! reads: what the ink runs to, where the blade falls, what is worth keeping,
//! and what reading software shows. The three pages below are the same drawing
//! three times over, and what changes is the boxes they state.
//!
//! What the sheet says is written in the language `HQF_PDF_LANG` names. The
//! prices are not, and neither are the measurements: the two the note quotes
//! are read off the sheet the page is drawn on.
//!
//! Usage: `cargo run --example write_press_sheet -- tmp/press.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_press_sheet`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Color, Document, Error, Font, FontHandle, Page, PageTurn, Rect, 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")
}

/// How far past the blade the ink runs.
const BLEED_OVER: f64 = 9.0;
/// How much sheet is left outside the ink for the marks.
const MARK_ROOM: f64 = 27.0;
/// How long one arm of a corner mark is.
const MARK_LENGTH: f64 = 18.0;

/// How much sheet stands outside the finished page on every side.
const MARGIN: f64 = BLEED_OVER + MARK_ROOM;

/// The finished page: where the blade falls, in the sheet's own coordinates.
const TRIM: (f64, f64, f64, f64) = (MARGIN, MARGIN, 400.0, 560.0);

/// The whole sheet: the finished page, the ink that runs past it, and the room
/// the marks stand in.
const SHEET: (f64, f64) = (TRIM.2 + MARGIN + MARGIN, TRIM.3 + MARGIN + MARGIN);

/// How far inside the blade the drawing itself keeps.
const ART_INSET: f64 = 40.0;

/// The colour the band across the top is laid in.
const BAND: Rgb = Rgb {
    r: 0.11,
    g: 0.26,
    b: 0.44,
};

/// The company whose list is being printed, which no language renames.
const COMPANY: &str = "HQF Development";

/// The sizes the sheet is set in, in points.
const TITLE_SIZE: f64 = 22.0;
const BODY_SIZE: f64 = 10.0;
const FOOT_SIZE: f64 = 8.0;
const NOTE_SIZE: f64 = 7.0;
const CAPTION_SIZE: f64 = 8.0;
const TURNED_TITLE_SIZE: f64 = 18.0;

/// How far one line of body stands under the one above it, in points.
const BODY_STEP: f64 = 16.0;

/// Where the label over the arrow between the two sketches begins.
const ARROW_LABEL_LEFT: f64 = 288.0;

/// What each row of the list costs, in the order the rows are drawn. A price is
/// not language.
const PRICES: [&str; 6] = ["18.40", "6.90", "42.00", "31.50", "12.75", "9.20"];

/// The words the sheet is written in, one set per language.
///
/// The prices are not among them, nor the two measurements the last page
/// quotes: those are read off the sheet.
#[derive(Debug)]
struct Words {
    /// What the list being printed is called, in the band at the head.
    title: &'static str,
    /// The line under it, which says what the band does at the blade.
    band: &'static str,
    /// The paragraph that says why a sheet allows for the blade twice over.
    blade: [&'static str; 4],
    /// The paragraph that says what the boxes spare the reader.
    boxes: [&'static str; 3],
    /// What each row of the list is, in the order they are drawn.
    rows: [&'static str; 6],
    /// What stands after the name of the company at the foot.
    foot: &'static str,
    /// What names each guide, in the order they are drawn: the ink, the blade,
    /// then what is worth keeping.
    guides: [&'static str; 3],
    /// The note in the margin of the first sheet, which shows whole.
    first_note: [&'static str; 2],
    /// The note in the margin of the second, which is cropped to the blade.
    second_note: [&'static str; 2],
    /// What the turned page is called.
    turned_title: &'static str,
    /// What stands before the width of the sheet in the first line of the
    /// turned page.
    across_before: &'static str,
    /// What stands between the width and the height.
    across_between: &'static str,
    /// What stands after the height.
    across_after: &'static str,
    /// The rest of that first paragraph, which says what the page adds.
    quarter: &'static str,
    /// The paragraph that says what reading software does with the turn.
    reading_software: [&'static str; 3],
    /// What the sheet drawn as the file holds it is called.
    in_file: &'static str,
    /// What the sheet drawn as reading software shows it is called.
    on_screen: &'static str,
    /// What the arrow between the two sketches says.
    turn: &'static str,
}

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

/// The sheet in English.
const ENGLISH: Words = Words {
    title: "Autumn list",
    band: "The band above runs off the blade: no white edge is left.",
    blade: [
        "The blade never falls exactly where it is",
        "aimed. A sheet allows for that twice over:",
        "the ink runs past the cut, and nothing that",
        "matters stands within a few points of it.",
    ],
    boxes: [
        "The boxes say all three distances, so nobody",
        "has to measure the file to find out where the",
        "page really ends.",
    ],
    rows: [
        "Linen paper, ream",
        "Bookbinder's thread",
        "Corner mark punch",
        "Trim gauge, steel",
        "Bleed guide, acrylic",
        "Press blanket wash",
    ],
    foot: " — one sheet, four boxes",
    guides: ["bleed", "trim", "art"],
    first_note: [
        "Page 1 states the bleed, the trim and the art, and no crop: reading software shows the whole",
        "sheet, marks and all, which is what the press wants to see.",
    ],
    second_note: [
        "Page 2 is the same drawing and the same boxes, plus a crop set to the trim: reading software",
        "shows the finished page alone. Nothing was removed — what is outside is still here.",
    ],
    turned_title: "A landscape page inside an upright document",
    across_before: "This page is the same upright sheet as the two before it: ",
    across_between: " points across, ",
    across_after: " up. What",
    quarter: "it adds is one number saying that reading software turns it a quarter clockwise before showing it.",
    reading_software: [
        "So the words are wider than the sheet they are written on, and nobody has to be handed a",
        "second page size to say so. Reading software printing the file turns the paper rather than the",
        "drawing, and reading software showing it hands you the page the way round it was meant.",
    ],
    in_file: "as it sits in the file",
    on_screen: "as reading software shows it",
    turn: "a quarter clockwise",
};

/// The sheet in French.
const FRENCH: Words = Words {
    title: "Catalogue d'automne",
    band: "Le bandeau déborde la coupe : aucun liseré blanc ne reste.",
    blade: [
        "La lame ne tombe jamais exactement où on",
        "la vise. La feuille s'en garde deux fois :",
        "l'encre déborde la coupe, et rien de ce qui",
        "compte ne s'en approche à quelques points.",
    ],
    boxes: [
        "Les boîtes donnent les trois distances, donc",
        "personne n'a à mesurer le fichier pour savoir",
        "où la page finit vraiment.",
    ],
    rows: [
        "Papier de lin, rame",
        "Fil de relieur",
        "Emporte-pièce à repères",
        "Calibre de coupe, acier",
        "Guide de fond perdu, acrylique",
        "Lavant pour blanchet",
    ],
    foot: " — une feuille, quatre boîtes",
    guides: ["fond perdu", "coupe", "zone utile"],
    first_note: [
        "La page 1 donne le fond perdu, la coupe et la zone utile, sans recadrage : le logiciel de lecture montre",
        "toute la feuille, repères compris, ce que l'imprimeur veut voir.",
    ],
    second_note: [
        "La page 2 est le même dessin et les mêmes boîtes, plus un recadrage sur la coupe : le logiciel de lecture",
        "montre la page finie seule. Rien n'a été retiré — ce qui est dehors y est toujours.",
    ],
    turned_title: "Une page à l'italienne dans un document à la française",
    across_before: "Cette page est la même feuille droite que les deux d'avant : ",
    across_between: " points de large, ",
    across_after: " de haut. Ce",
    quarter: "qu'elle ajoute est un nombre qui dit qu'un logiciel de lecture la tourne d'un quart de tour horaire.",
    reading_software: [
        "Les mots sont donc plus larges que la feuille sur laquelle ils sont écrits, et personne n'a",
        "besoin d'un second format de page pour le dire. Un logiciel de lecture qui imprime le fichier tourne le",
        "papier plutôt que le dessin, et un logiciel de lecture qui l'affiche vous rend la page dans le bon sens.",
    ],
    in_file: "telle qu'elle est dans le fichier",
    on_screen: "telle qu'un logiciel de lecture la montre",
    turn: "un quart de tour horaire",
};

/// 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)];

/// Where the blade falls.
const fn trim() -> Rect {
    Rect::new(TRIM.0, TRIM.1, TRIM.2, TRIM.3)
}

/// What the ink runs to.
const fn bleed() -> Rect {
    Rect::new(
        TRIM.0 - BLEED_OVER,
        TRIM.1 - BLEED_OVER,
        TRIM.2 + BLEED_OVER + BLEED_OVER,
        TRIM.3 + BLEED_OVER + BLEED_OVER,
    )
}

/// What is worth keeping of the page.
const fn art() -> Rect {
    Rect::new(
        TRIM.0 + ART_INSET,
        TRIM.1 + ART_INSET,
        TRIM.2 - ART_INSET - ART_INSET,
        TRIM.3 - ART_INSET - ART_INSET,
    )
}

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

/// Draws the four corner marks, each pair of arms standing outside the ink and
/// pointing at a corner of the finished page.
fn corner_marks(content: &mut Content) -> Result<(), Error> {
    let (left, bottom, width, height) = TRIM;
    let right = left + width;
    let top = bottom + height;
    let near = BLEED_OVER;
    let far = BLEED_OVER + MARK_LENGTH;

    content.save_state();
    content.set_stroke(Color::Gray(0.0))?;
    content.set_line_width(0.4)?;
    for (x, from_x, to_x) in [
        (left, left - near, left - far),
        (right, right + near, right + far),
    ] {
        for (y, from_y, to_y) in [
            (bottom, bottom - near, bottom - far),
            (top, top + near, top + far),
        ] {
            content.move_to(from_x, y)?;
            content.line_to(to_x, y)?;
            content.move_to(x, from_y)?;
            content.line_to(x, to_y)?;
        }
    }
    content.stroke();
    content.restore_state();
    Ok(())
}

/// The line of a page's foot, which names the company and what the page shows.
fn foot(words: &Words) -> String {
    format!("{COMPANY}{}", words.foot)
}

/// Draws the artwork itself: a band that runs off the blade, a title, a few
/// lines of body and a footer, all inside what is worth keeping.
fn artwork(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    let ink = bleed();
    let keep = art();

    content.save_state();
    content.set_fill(Color::Gray(0.96))?;
    content
        .rect(ink.x(), ink.y(), ink.width(), ink.height())?
        .fill();
    content.set_fill(BAND)?;
    content
        .rect(ink.x(), ink.y() + ink.height() - 150.0, ink.width(), 150.0)?
        .fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(
        content,
        font,
        TITLE_SIZE,
        keep.x(),
        keep.y() + keep.height() - 30.0,
        words.title,
    )?;
    content.set_fill(Rgb::new(0.82, 0.86, 0.92))?;
    text(
        content,
        font,
        BODY_SIZE,
        keep.x(),
        keep.y() + keep.height() - 50.0,
        words.band,
    )?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.25))?;
    let mut y = keep.y() + keep.height() - 130.0;
    for line in words.blade {
        text(content, font, BODY_SIZE, keep.x(), y, line)?;
        y -= BODY_STEP;
    }
    // The blank between the two paragraphs is a step of the loop, not a line of
    // the words.
    y -= BODY_STEP;
    for line in words.boxes {
        text(content, font, BODY_SIZE, keep.x(), y, line)?;
        y -= BODY_STEP;
    }
    content.restore_state();

    listing(content, font, words, keep.y() + keep.height() - 290.0, keep)?;

    content.save_state();
    content.set_fill(Color::Gray(0.5))?;
    text(content, font, FOOT_SIZE, keep.x(), keep.y(), &foot(words))?;
    content.restore_state();
    Ok(())
}

/// How far in from the right of what is worth keeping a price stands.
const PRICE_INSET: f64 = 30.0;

/// Draws the list itself, one row a line, each under a hairline that runs the
/// width of what is worth keeping.
fn listing(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    top: f64,
    keep: Rect,
) -> Result<(), Error> {
    let right = keep.x() + keep.width();
    let mut y = top;
    for (item, price) in words.rows.iter().zip(PRICES) {
        content.save_state();
        content.set_fill(Color::Gray(0.25))?;
        text(content, font, BODY_SIZE, keep.x(), y, item)?;
        text(content, font, BODY_SIZE, right - PRICE_INSET, y, price)?;
        content.set_stroke(Color::Gray(0.8))?;
        content.set_line_width(0.4)?;
        content.move_to(keep.x(), y - 8.0)?;
        content.line_to(right, y - 8.0)?;
        content.stroke();
        content.restore_state();
        y -= 26.0;
    }
    Ok(())
}

/// The box each guide is drawn around, and the colour it is drawn in, in the
/// order they are named.
const fn guide_boxes() -> [(Rect, Rgb); 3] {
    [
        (bleed(), Rgb::new(0.85, 0.35, 0.20)),
        (trim(), Rgb::new(0.20, 0.55, 0.35)),
        (art(), Rgb::new(0.45, 0.35, 0.65)),
    ]
}

/// How far in from the right of its box a guide's name stands.
const GUIDE_INSET: f64 = 30.0;

/// Draws the guide showing where each box falls, and names it.
fn guides(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_line_width(0.4)?;
    for ((box_, color), label) in guide_boxes().into_iter().zip(words.guides) {
        content.set_stroke(color)?;
        content
            .rect(box_.x(), box_.y(), box_.width(), box_.height())?
            .stroke();
        content.set_fill(color)?;
        text(
            content,
            font,
            NOTE_SIZE,
            box_.x() + box_.width() - GUIDE_INSET,
            box_.y() - 8.0,
            label,
        )?;
    }
    content.restore_state();
    Ok(())
}

/// Where the lowest line of the note in the margin sits, and how far the one
/// above it stands.
const NOTE_BASELINE: f64 = 8.0;
const NOTE_STEP: f64 = 9.0;

/// The whole sheet: artwork, marks, the guides that name the boxes, and the
/// note in the margin saying what this page states.
fn sheet(font: &FontHandle, words: &Words, note: &[&str; 2]) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    artwork(&mut content, font, words)?;
    corner_marks(&mut content)?;
    guides(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    let mut y = NOTE_BASELINE;
    for line in note.iter().rev() {
        text(&mut content, font, NOTE_SIZE, TRIM.0, y, line)?;
        y += NOTE_STEP;
    }
    content.restore_state();
    Ok(content.into_bytes())
}

/// A4, in points.
const A4: (f64, f64) = (595.276, 841.890);

/// Draws one sheet of the little diagram: an outline, the band that marks the
/// head of the drawing, and a caption under it.
///
/// A sheet taller than it is wide is one reading software has not turned yet,
/// so the head of the drawing runs down its left edge; a wide one has been
/// turned, and the head is along its top.
fn sketch(
    content: &mut Content,
    font: &FontHandle,
    corner: (f64, f64, f64, f64),
    caption: &str,
) -> Result<(), Error> {
    let (x, y, width, height) = corner;
    let head = if height > width {
        (x + 8.0, y + 8.0, 12.0, height - 16.0)
    } else {
        (x + 8.0, y + height - 20.0, width - 16.0, 12.0)
    };

    content.save_state();
    content.set_stroke(Color::Gray(0.55))?;
    content.set_line_width(0.8)?;
    content.rect(x, y, width, height)?.stroke();
    content.set_fill(BAND)?;
    content.rect(head.0, head.1, head.2, head.3)?.fill();
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, CAPTION_SIZE, x, y - 14.0, caption)?;
    content.restore_state();
    Ok(())
}

/// The two sketches: where each stands on the turned page, and how much room
/// the caption under it has before it reaches the next one.
const SKETCHES: [(f64, f64, f64, f64); 2] =
    [(150.0, 140.0, 110.0, 155.0), (400.0, 165.0, 155.0, 110.0)];

/// Where the turned page sets every line from, and the room it leaves on the
/// far side.
const TURNED_LEFT: f64 = 70.0;

/// The first line of the turned page, which quotes the two measurements of the
/// sheet it is drawn on rather than repeating them.
fn how_wide(words: &Words) -> String {
    format!(
        "{}{:.0}{}{:.0}{}",
        words.across_before, A4.0, words.across_between, A4.1, words.across_after
    )
}

/// The third page: a landscape page inside an upright document.
///
/// Everything is laid out in a space as wide as the sheet is tall, and the one
/// transform at the head of the stream puts that space onto the upright sheet.
/// The page then states a quarter turn clockwise, and reading software undoes
/// the transform by turning the paper.
fn turned(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let (across, up) = (A4.1, A4.0);
    let mut content = Content::new();
    content.transform([0.0, 1.0, -1.0, 0.0, A4.0, 0.0])?;

    content.save_state();
    content.set_fill(Color::Gray(0.96))?;
    content.rect(0.0, 0.0, across, up)?.fill();
    content.set_fill(BAND)?;
    content.rect(0.0, up - 90.0, across, 90.0)?.fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(
        &mut content,
        font,
        TURNED_TITLE_SIZE,
        TURNED_LEFT,
        up - 55.0,
        words.turned_title,
    )?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.3))?;
    let mut y = up - 130.0;
    for line in [how_wide(words), words.quarter.to_owned()] {
        text(&mut content, font, BODY_SIZE, TURNED_LEFT, y, &line)?;
        y -= BODY_STEP;
    }
    // The blank between the two paragraphs is a step of the loop, not a line of
    // the words.
    y -= BODY_STEP;
    for line in words.reading_software {
        text(&mut content, font, BODY_SIZE, TURNED_LEFT, y, line)?;
        y -= BODY_STEP;
    }
    content.restore_state();

    for (corner, caption) in SKETCHES.into_iter().zip([words.in_file, words.on_screen]) {
        sketch(&mut content, font, corner, caption)?;
    }

    content.save_state();
    content.set_stroke(Color::Gray(0.55))?;
    content.set_line_width(1.2)?;
    content.move_to(295.0, 218.0)?;
    content.line_to(360.0, 218.0)?;
    content.line_to(348.0, 226.0)?;
    content.move_to(360.0, 218.0)?;
    content.line_to(348.0, 210.0)?;
    content.stroke();
    content.set_fill(Color::Gray(0.45))?;
    text(
        &mut content,
        font,
        CAPTION_SIZE,
        ARROW_LABEL_LEFT,
        234.0,
        words.turn,
    )?;
    content.restore_state();
    Ok(content.into_bytes())
}

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("press")));
    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 = sheet(&font, words, &words.first_note)?;
    first.bleed = Some(bleed());
    first.trim = Some(trim());
    first.art = Some(art());
    doc.add_page(first)?;

    let mut second = Page::new(SHEET.0, SHEET.1);
    second.content = sheet(&font, words, &words.second_note)?;
    second.crop = Some(trim());
    second.bleed = Some(bleed());
    second.trim = Some(trim());
    second.art = Some(art());
    doc.add_page(second)?;

    let mut third = Page::a4();
    third.content = turned(&font, words)?;
    third.turn = PageTurn::Right;
    doc.add_page(third)?;

    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, one drawing on {} pages, each stating its own boxes",
        written.len(),
        doc.page_count()
    );
    Ok(())
}

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

    use super::{
        A4, ARROW_LABEL_LEFT, BODY_SIZE, CAPTION_SIZE, FOOT_SIZE, GUIDE_INSET, NOTE_BASELINE,
        NOTE_SIZE, NOTE_STEP, PRICE_INSET, SHEET, SKETCHES, TITLE_SIZE, TRIM, TURNED_LEFT,
        TURNED_TITLE_SIZE, WORDS, Words, art, bleed, default_font, foot, guide_boxes, how_wide,
        language,
    };

    /// The lines two languages are allowed to write the same way. There are
    /// none: the prices and the two measurements are held outside the words.
    const SPARED: [&str; 0] = [];

    /// The font every measurement here is taken in, which is the one the
    /// example draws with when the command line says nothing.
    fn font(document: &mut Document) -> FontHandle {
        document.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        )
    }

    /// Every line the sheet draws, each with the size it is set at and the room
    /// it has before it reaches whatever stands to its right.
    fn lines(words: &Words) -> Vec<(String, f64, f64)> {
        let keep = art();
        let keep_room = keep.width();
        let row_room = keep.width() - PRICE_INSET - BODY_SIZE;
        let note_room = SHEET.0 - TRIM.0 - TRIM.0;
        let turned_room = A4.1 - TURNED_LEFT - TURNED_LEFT;

        let mut measured = vec![
            (words.title.to_owned(), TITLE_SIZE, keep_room),
            (words.band.to_owned(), BODY_SIZE, keep_room),
            (foot(words), FOOT_SIZE, keep_room),
            (
                words.turned_title.to_owned(),
                TURNED_TITLE_SIZE,
                turned_room,
            ),
            (how_wide(words), BODY_SIZE, turned_room),
            (words.quarter.to_owned(), BODY_SIZE, turned_room),
            (
                words.turn.to_owned(),
                CAPTION_SIZE,
                A4.1 - ARROW_LABEL_LEFT - TURNED_LEFT,
            ),
        ];
        for line in words.blade.iter().chain(&words.boxes) {
            measured.push(((*line).to_owned(), BODY_SIZE, keep_room));
        }
        for row in words.rows {
            measured.push((row.to_owned(), BODY_SIZE, row_room));
        }
        for line in words.first_note.iter().chain(&words.second_note) {
            measured.push(((*line).to_owned(), NOTE_SIZE, note_room));
        }
        // A guide's name stands inside its own box and runs to the edge of the
        // sheet.
        for ((box_, _), label) in guide_boxes().into_iter().zip(words.guides) {
            let from = box_.x() + box_.width() - GUIDE_INSET;
            measured.push((label.to_owned(), NOTE_SIZE, SHEET.0 - from));
        }
        // The caption of the first sketch runs until the second one begins; the
        // second runs to the edge of the sheet the turned page is drawn on.
        let captions = [
            (words.in_file, SKETCHES[1].0 - SKETCHES[0].0),
            (words.on_screen, A4.1 - SKETCHES[1].0),
        ];
        for (caption, room) in captions {
            measured.push((caption.to_owned(), CAPTION_SIZE, room));
        }
        measured
    }

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

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

    /// Nothing on this sheet is broken to a width: every line is drawn where it
    /// is asked for, so a line longer than its room runs over what stands
    /// beside it or off the sheet altogether.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut document = Document::new();
        let font = font(&mut document);

        for (named, words) in WORDS {
            for (line, size, room) in lines(words) {
                let measured = font.measure(&line, size);

                assert!(
                    measured <= room,
                    "the {} sheet draws {line:?} over {measured:.1} points, and \
                     it has {room:.1}",
                    named.code()
                );
            }
        }
    }

    /// The note in the margin is drawn upwards from the foot of the sheet, and
    /// the ink begins where the bleed box does: a note one line taller writes
    /// over the printed sheet instead of standing beside it.
    #[test]
    fn the_note_in_the_margin_stays_under_the_ink() {
        let mut document = Document::new();
        let font = font(&mut document);
        let ink: Rect = bleed();

        let top = NOTE_STEP.mul_add(count(WORDS[0].1.first_note.len() - 1), NOTE_BASELINE)
            + font.ascent(NOTE_SIZE);

        assert!(
            top <= ink.y(),
            "the note reaches {top:.1} points up the sheet, and the ink begins \
             at {:.1}",
            ink.y()
        );
    }

    /// Converts a count of lines to a float. A note is never long enough for a
    /// `usize` to lose precision as an `f64`.
    #[expect(
        clippy::cast_precision_loss,
        reason = "a count of lines is far below f64's exact-integer range"
    )]
    fn count(n: usize) -> f64 {
        n as f64
    }
}