write_image_gallery.rs

Le fichier Rust de l'exemple « Une galerie de formats d'image ». Les quatre formats d'image lus — JPEG, PNG, BMP et TIFF — montrés sur toutes les images livrées avec la bibliothèque, chacune légendée par ce que déclare son propre fichier.

Rust 600 lignes

À quoi sert cet exemple

Avant de choisir une bibliothèque, la question est presque toujours la même : est-ce qu'elle lira les images qu'on a déjà ? Nous lisons ces quatre formats. Le JPEG, celui que produisent un appareil photo et un téléphone. Le PNG, celui dans lequel arrive une copie d'écran, et dans lequel arrive un logo avec des parties transparentes. Le BMP, le format simple et non compressé que d'anciens logiciels écrivent encore. Et le TIFF, celui qu'écrivent un scanner et un télécopieur, des piles entières de feuilles à la fois. À eux quatre, ils couvrent ce qui sort d'un appareil photo, ce qui sort d'un écran, ce qui sort d'un scanner et ce qui sort d'une machine ancienne, c'est-à-dire à peu près tout ce dont un document de travail est fait.

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
//! Lays every image the tests ship with on one page, each captioned with what
//! the file itself declares.
//!
//! Nothing in the captions is written by hand: each line is read back out of
//! the image after it was parsed, so the page is a statement of what the
//! library understood rather than of what the example was told. A file that
//! declares nothing says so, which is the point of showing it next to the ones
//! that do.
//!
//! What each caption says is written in the language `HQF_PDF_LANG` names. The
//! names of the files are not, and neither is `sRGB`: both are what is written
//! on the disk and in the file.
//!
//! Usage: `cargo run --example write_image_gallery -- tmp/gallery.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_image_gallery`

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

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{Document, Font, FontHandle, Image, ImageHandle, ImageSpace, 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 page, and the grid laid over it.
const MARGIN: f64 = 30.0;
/// See [`MARGIN`].
const COLUMNS: usize = 4;
/// See [`MARGIN`].
const ROWS: usize = 6;

/// The tallest and widest a thumbnail is drawn.
const THUMBNAIL: (f64, f64) = (110.0, 92.0);

/// The caption under each thumbnail.
const CAPTION_SIZE: f64 = 5.6;
/// See [`CAPTION_SIZE`].
const CAPTION_LEADING: f64 = 7.4;

/// Ink.
const TEXT: Rgb = Rgb::new(0.15, 0.16, 0.2);
/// See [`TEXT`].
const FADED: Rgb = Rgb::new(0.42, 0.44, 0.5);
/// See [`TEXT`].
const TILE: Rgb = Rgb::new(0.95, 0.96, 0.97);

/// Converts a count of rows, columns or lines to a float. Such counts never
/// approach the point where a `usize` loses precision as an `f64`.
#[expect(
    clippy::cast_precision_loss,
    reason = "grid and line counts are far below f64's exact-integer range"
)]
const fn count_f64(n: usize) -> f64 {
    n as f64
}

/// The name of the colour profile a file may declare it was read through. It is
/// what the profile is called, not a word of any language.
const SRGB: &str = "sRGB";

/// A word in its two numbers. English and French both keep the singular for one
/// and take the plural from two upwards, which is the whole of the rule the
/// captions need: a count of bits is never nought, and a table of colours never
/// holds fewer than two.
#[derive(Debug)]
struct Plural {
    one: &'static str,
    many: &'static str,
}

impl Plural {
    /// The form this word takes for `count`.
    const fn of(&self, count: usize) -> &'static str {
        if count == 1 { self.one } else { self.many }
    }
}

/// The words the captions are written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the page is called, drawn at its head.
    title: &'static str,
    /// What the document is called in what the file says of itself, which is a
    /// name rather than the sentence drawn on the page.
    file_title: &'static str,
    /// What stands between the two sides of a picture, in pixels and in dots.
    by: &'static str,
    /// What a measurement in pixels is called.
    pixels: &'static str,
    /// What a depth of one and of more than one is called.
    bits: Plural,
    /// What a resolution is called.
    dots: &'static str,
    /// What one pixel of a grey picture stands for.
    grey: &'static str,
    /// What one pixel of a three-channel picture stands for.
    rgb: &'static str,
    /// What one pixel of a four-ink picture stands for.
    cmyk: &'static str,
    /// What stands before the size of a palette.
    table_of: &'static str,
    /// What a palette holds, of one colour and of more.
    colours: Plural,
    /// What a picture in a space of none of those kinds stands for.
    other_space: &'static str,
    /// What stands before the way up a file declares.
    seen: &'static str,
    /// The ways up, in the order of the numbers a file names them by: mirrored
    /// left to right, upside down, mirrored top to bottom, mirrored and turned
    /// left, turned right, mirrored and turned right, turned left, and last the
    /// one a number nothing names falls back to.
    ways_up: [&'static str; 8],
    /// What a picture that carries an opacity for every pixel declares.
    alpha: &'static str,
    /// What a picture that drops one colour declares.
    color_key: &'static str,
    /// What stands before the name of the profile a picture was read through.
    read_through: &'static str,
    /// What a file that declares nothing beyond its shape says instead.
    nothing_else: &'static str,
}

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

/// The captions in English.
const ENGLISH: Words = Words {
    title: "Every picture the tests ship with, and what each file says about itself",
    file_title: "hqf-pdf image gallery",
    by: "by",
    pixels: "pixels",
    bits: Plural {
        one: "bit",
        many: "bits",
    },
    dots: "dots to the inch",
    grey: "grey",
    rgb: "red, green, blue",
    cmyk: "four inks",
    table_of: "a table of",
    colours: Plural {
        one: "colour",
        many: "colours",
    },
    other_space: "colours of some other kind",
    seen: "seen",
    ways_up: [
        "mirrored left to right",
        "upside down",
        "mirrored top to bottom",
        "mirrored, turned left",
        "turned right",
        "mirrored, turned right",
        "turned left",
        "the way it is stored",
    ],
    alpha: "opacity per pixel",
    color_key: "one colour left out",
    read_through: "read through",
    nothing_else: "declaring nothing else of itself",
};

/// The captions in French.
const FRENCH: Words = Words {
    title: "Toutes les images livrées avec les tests, et ce que chaque fichier dit de lui-même",
    file_title: "galerie d'images hqf-pdf",
    by: "sur",
    pixels: "pixels",
    bits: Plural {
        one: "bit",
        many: "bits",
    },
    dots: "points par pouce",
    grey: "du gris",
    rgb: "du rouge, du vert, du bleu",
    cmyk: "quatre encres",
    table_of: "une table de",
    colours: Plural {
        one: "couleur",
        many: "couleurs",
    },
    other_space: "des couleurs d'un autre genre",
    seen: "vue",
    ways_up: [
        "en miroir gauche-droite",
        "à l'envers",
        "en miroir haut-bas",
        "en miroir, tournée à gauche",
        "tournée à droite",
        "en miroir, tournée à droite",
        "tournée à gauche",
        "telle qu'elle est stockée",
    ],
    alpha: "opacité par pixel",
    color_key: "une couleur laissée de côté",
    read_through: "lue à travers",
    nothing_else: "ne déclarant rien d'autre",
};

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

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

/// Every image committed for the tests, in the order their names sort.
fn corpus() -> Result<Vec<PathBuf>, std::io::Error> {
    let images = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("images");

    let mut paths: Vec<PathBuf> = fs::read_dir(images)?
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .filter(|path| path.is_file())
        .collect();
    paths.sort();
    Ok(paths)
}

/// What one pixel of the image stands for, in the fewest words that still say
/// it.
fn colour_of(image: &Image, words: &'static Words) -> String {
    match image.color_space() {
        ImageSpace::Gray => words.grey.to_owned(),
        ImageSpace::Rgb => words.rgb.to_owned(),
        ImageSpace::Cmyk => words.cmyk.to_owned(),
        ImageSpace::Indexed(palette) => {
            let colours = palette.len() / 3;
            format!("{} {colours} {}", words.table_of, words.colours.of(colours))
        }
        _ => words.other_space.to_owned(),
    }
}

/// What the file says about itself, one statement at a time.
///
/// A file that says nothing beyond its shape says so: the point of the page is
/// that both kinds sit side by side.
fn facts(image: &Image, words: &'static Words) -> Vec<String> {
    let bits = usize::from(image.bits_per_component());
    let mut facts = vec![
        format!(
            "{} {} {} {}",
            image.width(),
            words.by,
            image.height(),
            words.pixels
        ),
        colour_of(image, words),
        format!("{bits} {}", words.bits.of(bits)),
    ];

    let mut stated: Vec<String> = Vec::new();
    if let Some(resolution) = image.resolution() {
        stated.push(format!(
            "{:.0} {} {:.0} {}",
            resolution.x(),
            words.by,
            resolution.y(),
            words.dots
        ));
    }
    if let Some(orientation) = image.orientation() {
        stated.push(format!(
            "{} {}",
            words.seen,
            way_up(words, orientation.tag())
        ));
    }
    if image.has_alpha() {
        stated.push(words.alpha.to_owned());
    }
    if image.color_key().is_some() {
        stated.push(words.color_key.to_owned());
    }
    if image.icc_profile().is_some() {
        stated.push(format!("{} {SRGB}", words.read_through));
    }

    if stated.is_empty() {
        facts.push(words.nothing_else.to_owned());
    } else {
        facts.extend(stated);
    }
    facts
}

/// The statements laid end to end, broken into lines that fit `width`.
///
/// Nothing is dropped: a caption that will not fit on one line takes as many as
/// it needs, which is what keeps the page a full account of what was read.
fn packed(font: &FontHandle, width: f64, facts: &[String]) -> Vec<String> {
    let mut lines: Vec<String> = Vec::new();
    for fact in facts {
        match lines.last_mut() {
            Some(line) if font.measure(&format!("{line}, {fact}"), CAPTION_SIZE) <= width => {
                line.push_str(", ");
                line.push_str(fact);
            }
            _ => lines.push(fact.clone()),
        }
    }
    lines
}

/// The way up an `Exif` header names by its number, in words. A number nothing
/// names falls to the last of them.
const fn way_up(words: &'static Words, tag: u16) -> &'static str {
    match tag {
        2..=8 => words.ways_up[(tag - 2) as usize],
        _ => words.ways_up[7],
    }
}

/// Draws one line of text, left-aligned.
fn text(content: &mut Content, font: &FontHandle, size: f64, x: f64, y: f64, colour: Rgb, s: &str) {
    let _ = content.set_fill(colour);
    content.begin_text();
    let _ = content.set_font(font, size);
    let _ = content.text_origin(x, y);
    content.show_glyphs(&font.glyphs(s));
    content.end_text();
}

/// Draws one line of text, shortened until it fits the width it is given.
fn text_fitted(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    at: (f64, f64),
    width: f64,
    colour: Rgb,
    s: &str,
) {
    let mut line = s.to_owned();
    while font.measure(&line, size) > width && line.chars().count() > 1 {
        line.pop();
        line.pop();
        line.push('…');
    }
    text(content, font, size, at.0, at.1, colour, &line);
}

/// Draws one tile: the picture inside its box, and what the file says under it.
fn tile(
    content: &mut Content,
    font: &FontHandle,
    handle: &ImageHandle,
    lines: &[String],
    at: (f64, f64),
    cell: (f64, f64),
) -> Result<(), Box<dyn std::error::Error>> {
    let (x, y) = at;
    let (cell_width, cell_height) = cell;
    let caption_height = CAPTION_LEADING * count_f64(lines.len());
    let box_height = cell_height - caption_height - 6.0;

    content.set_fill(TILE)?;
    content.rect(x, y + caption_height + 6.0, cell_width, box_height)?;
    content.fill();

    // The picture keeps its proportions inside the box, and sits in the middle
    // of it.
    let (width, height) = handle.fit_within(
        THUMBNAIL.0.min(cell_width - 8.0),
        THUMBNAIL.1.min(box_height),
    )?;
    content.draw_image(
        handle,
        x + (cell_width - width) / 2.0,
        y + caption_height + 6.0 + (box_height - height) / 2.0,
        width,
        height,
    )?;

    for (index, line) in lines.iter().enumerate() {
        let colour = if index == 0 { TEXT } else { FADED };
        text_fitted(
            content,
            font,
            CAPTION_SIZE,
            (
                x,
                CAPTION_LEADING.mul_add(-count_f64(index + 1), y + caption_height) + 2.0,
            ),
            cell_width,
            colour,
            line,
        );
    }
    Ok(())
}

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

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(Name::new("Title"), words.file_title);
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let page = Page::a4();
    let (page_width, page_height) = (page.width, page.height);
    let cell_width = 2.0_f64.mul_add(-MARGIN, page_width) / count_f64(COLUMNS) - 6.0;

    let paths = corpus()?;
    let mut tiles = Vec::new();
    for path in &paths {
        let image = Image::parse(fs::read(path)?)?;
        let mut lines = vec![
            path.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
        ];
        lines.extend(packed(&font, cell_width, &facts(&image, words)));
        tiles.push((doc.add_image(image), lines));
    }

    let mut content = Content::new();

    text(
        &mut content,
        &font,
        13.0,
        MARGIN,
        page_height - MARGIN - 10.0,
        TEXT,
        words.title,
    );

    let top = page_height - MARGIN - 34.0;
    let cell_height = (top - MARGIN) / count_f64(ROWS);

    for (index, (handle, lines)) in tiles.iter().enumerate() {
        let column = index % COLUMNS;
        let row = index / COLUMNS;
        if row >= ROWS {
            println!(
                "{} pictures do not fit on one page; the rest are left off",
                tiles.len()
            );
            break;
        }

        tile(
            &mut content,
            &font,
            handle,
            lines,
            (
                (cell_width + 6.0).mul_add(count_f64(column), MARGIN),
                top - cell_height * count_f64(row + 1),
            ),
            (cell_width, cell_height - 6.0),
        )?;
    }

    let mut page = page;
    page.content = content.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, {} pictures",
        bytes.len(),
        tiles.len()
    );
    Ok(())
}

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

    use super::{
        CAPTION_SIZE, COLUMNS, MARGIN, ROWS, WORDS, corpus, count_f64, default_font, facts,
        language,
    };

    /// A4, in points, which is the sheet the gallery is laid on.
    const PAGE: (f64, f64) = (595.276, 841.890);

    /// The lines two languages are allowed to write the same way. Both call a
    /// pixel a pixel, and both spell a bit and its plural the same.
    const SPARED: [&str; 3] = ["pixels: \"pixels\"", "one: \"bit\"", "many: \"bits\""];

    /// 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"),
        )
    }

    /// The width of one tile, worked out the way the page works it out.
    fn cell_width() -> f64 {
        2.0_f64.mul_add(-MARGIN, PAGE.0) / count_f64(COLUMNS) - 6.0
    }

    /// The page shows every picture the tests ship with, and it says so; a
    /// picture past the last cell of the grid is left off with a line on the
    /// terminal and nothing on the page.
    #[test]
    fn the_grid_holds_every_picture_the_tests_ship_with() {
        let held = corpus().expect("the committed images are there").len();

        assert!(
            held <= COLUMNS * ROWS,
            "the tests ship {held} pictures and the grid holds {}",
            COLUMNS * ROWS
        );
    }

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

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

    /// A line wider than its tile is shortened until it fits, and the end of it
    /// is replaced by a single character. The page is meant to be a full
    /// account of what was read, so no statement may be one that has to be cut:
    /// a language whose words run longer has to find shorter ones.
    #[test]
    fn no_language_states_a_fact_too_wide_to_be_read_whole() {
        let mut document = Document::new();
        let font = font(&mut document);
        let width = cell_width();

        for (named, words) in WORDS {
            for path in corpus().expect("the committed images are there") {
                let image =
                    Image::parse(std::fs::read(&path).expect("a committed image is readable"))
                        .expect("a committed image parses");

                for fact in facts(&image, words) {
                    let measured = font.measure(&fact, CAPTION_SIZE);

                    assert!(
                        measured <= width,
                        "the {} caption of {} states {fact:?} over {measured:.1} \
                         points, and a tile is {width:.1} wide",
                        named.code(),
                        path.display()
                    );
                }
            }
        }
    }
}