A gallery of picture formats

Every picture the tests ship with, on one page, each captioned with what its own file declares.

Rust write_image_gallery.rs 326 lines
  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
//! 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.
//!
//! Usage: `cargo run --example write_image_gallery -- tmp/gallery.pdf
//! [font.ttf]`

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;

/// The page, and the grid laid over it.
const MARGIN: f64 = 30.0;
/// See [`MARGIN`].
const COLUMNS: usize = 4;
/// See [`MARGIN`].
const ROWS: usize = 5;

/// 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 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) -> String {
    match image.color_space() {
        ImageSpace::Gray => "grey".to_owned(),
        ImageSpace::Rgb => "red, green, blue".to_owned(),
        ImageSpace::Cmyk => "four inks".to_owned(),
        ImageSpace::Indexed(palette) => format!("a table of {} colours", palette.len() / 3),
        _ => "colours of some other kind".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) -> Vec<String> {
    let bits = image.bits_per_component();
    let mut facts = vec![
        format!("{} by {} pixels", image.width(), image.height()),
        colour_of(image),
        format!("{bits} bit{}", if bits == 1 { "" } else { "s" }),
    ];

    let mut stated: Vec<String> = Vec::new();
    if let Some(resolution) = image.resolution() {
        stated.push(format!(
            "{:.0} by {:.0} dots to the inch",
            resolution.x, resolution.y
        ));
    }
    if let Some(orientation) = image.orientation() {
        stated.push(format!("seen {}", way_up(orientation.tag())));
    }
    if image.has_alpha() {
        stated.push("opacity per pixel".to_owned());
    }
    if image.color_key().is_some() {
        stated.push("one colour left out".to_owned());
    }
    if image.icc_profile().is_some() {
        stated.push("read through sRGB".to_owned());
    }

    if stated.is_empty() {
        facts.push("declaring nothing else of itself".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.
const fn way_up(tag: u16) -> &'static str {
    match tag {
        2 => "mirrored left to right",
        3 => "upside down",
        4 => "mirrored top to bottom",
        5 => "mirrored, turned left",
        6 => "turned right",
        7 => "mirrored, turned right",
        8 => "turned left",
        _ => "the way it is stored",
    }
}

/// 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.name(), 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)?;
    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() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = env::args().skip(1);
    let out = args
        .next()
        .unwrap_or_else(|| 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"), "hqf-pdf image gallery");
    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)));
        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,
        "Every picture the tests ship with, and what each file says about itself",
    );

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