write_contents.rs

The Rust file of the “A contents page with dot leaders” example. A contents page whose entries are led to their page numbers by dots the layout draws.

Rust 458 lines

What this example is for

Everybody has met the contents page where the dots run right into the page number on one line and stop two centimetres short on the next. It happens because the dots were typed in, and the day a title changes length the count is wrong. Nobody sees it while the document is being written; it shows up on the printed copy, at the customer's.

What this example shows

  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
//! A contents page: every entry led to its page number by a row of dots.
//!
//! The dots are not written into the text. Each entry is a cell that asks for a
//! leader, and the layout fills whatever room the entry leaves — which is why
//! the dots still meet the numbers when an entry is edited, translated or set
//! in another font.
//!
//! What the entries say is written in the language `HQF_PDF_LANG` names. What
//! they are filed under is not: `1`, `2.3` and the page numbers are the shape
//! of the report, and a translation that renumbered them would send the reader
//! elsewhere.
//!
//! Usage: `cargo run --example write_contents -- tmp/contents.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_contents`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TableFrame};
use hqf_pdf::{Align, Document, Font, FontHandle, 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 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")
}

/// A4's width, and the margins the contents are laid out between.
const PAGE_WIDTH: f64 = 595.276;
const MARGIN: f64 = 64.0;
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;

/// The company the report is about, which no language renames.
const COMPANY: &str = "ACME Ltd";

/// How many spaces stand between what an entry is filed under and what it says.
const GAP: &str = "  ";

/// One line of the contents: how deep it sits, what it is filed under, and the
/// page it sends the reader to.
///
/// What the entry says is not here: it is a word, and it lives with the other
/// words of its language.
struct Entry {
    depth: usize,
    /// The number the entry is filed under, or `None` for the appendix, which
    /// is headed by a word rather than a number.
    number: Option<&'static str>,
    page: &'static str,
}

/// The shape of the report this page opens: what each entry is filed under, and
/// where it sends the reader.
const ENTRIES: &[Entry] = &[
    Entry {
        depth: 0,
        number: Some("1"),
        page: "3",
    },
    Entry {
        depth: 1,
        number: Some("1.1"),
        page: "3",
    },
    Entry {
        depth: 1,
        number: Some("1.2"),
        page: "5",
    },
    Entry {
        depth: 0,
        number: Some("2"),
        page: "8",
    },
    Entry {
        depth: 1,
        number: Some("2.1"),
        page: "8",
    },
    Entry {
        depth: 1,
        number: Some("2.2"),
        page: "11",
    },
    Entry {
        depth: 1,
        number: Some("2.3"),
        page: "14",
    },
    Entry {
        depth: 0,
        number: Some("3"),
        page: "17",
    },
    Entry {
        depth: 1,
        number: Some("3.1"),
        page: "17",
    },
    Entry {
        depth: 1,
        number: Some("3.2"),
        page: "20",
    },
    Entry {
        depth: 1,
        number: Some("3.3"),
        page: "23",
    },
    Entry {
        depth: 0,
        number: Some("4"),
        page: "27",
    },
    Entry {
        depth: 1,
        number: Some("4.1"),
        page: "27",
    },
    Entry {
        depth: 1,
        number: Some("4.2"),
        page: "31",
    },
    Entry {
        depth: 0,
        number: None,
        page: "34",
    },
];

/// How far a sub-entry is set in from the margin, in points.
const INDENT: f64 = 18.0;

/// The words the contents are written in, one set per language.
///
/// What each entry is filed under is not among them: the numbers and the page
/// they send the reader to are the shape of the report, and they are held with
/// the entries themselves.
#[derive(Debug)]
struct Words {
    /// What the page is called, both drawn at its head and in what the file
    /// says of itself.
    title: &'static str,
    /// What stands before the name of the company in the line under the title.
    subtitle_before: &'static str,
    /// What stands after it.
    subtitle_after: &'static str,
    /// What heads the entry that carries no number.
    appendix: &'static str,
    /// What each entry says, in the order [`ENTRIES`] files them.
    entries: [&'static str; 15],
}

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

/// The contents in English.
const ENGLISH: Words = Words {
    title: "Contents",
    subtitle_before: "Audit of document production — ",
    subtitle_after: ", second quarter",
    appendix: "Appendix",
    entries: [
        "Scope of the audit",
        "What was examined",
        "What was left out, and why",
        "How the documents are produced today",
        "The invoicing run",
        "The nightly statement of accounts",
        "Documents produced on demand from the counter",
        "What the archival standard asks for",
        "Fonts that travel with the file",
        "Colour that means the same on every screen",
        "Text a reading machine can follow",
        "What it would cost to change",
        "The work, month by month",
        "What is saved once it is done",
        "Files read for this report",
    ],
};

/// The contents in French.
const FRENCH: Words = Words {
    title: "Sommaire",
    subtitle_before: "Audit de la production documentaire — ",
    subtitle_after: ", deuxième trimestre",
    appendix: "Annexe",
    entries: [
        "Périmètre de l'audit",
        "Ce qui a été examiné",
        "Ce qui a été laissé de côté, et pourquoi",
        "Comment les documents sont produits aujourd'hui",
        "La passe de facturation",
        "Le relevé de comptes de la nuit",
        "Documents produits à la demande au guichet",
        "Ce que la norme d'archivage exige",
        "Les polices qui voyagent avec le fichier",
        "Une couleur qui dit la même chose sur tous les écrans",
        "Un texte qu'une machine de lecture peut suivre",
        "Ce que le changement coûterait",
        "Le travail, mois par mois",
        "Ce qu'on économise une fois que c'est fait",
        "Fichiers lus pour ce rapport",
    ],
};

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

/// What one entry reads on the page: what it is filed under, then what it says.
fn label(words: &Words, entry: &Entry, index: usize) -> String {
    let filed = entry.number.unwrap_or(words.appendix);
    format!("{filed}{GAP}{}", words.entries[index])
}

/// The line under the title, which names the company the report is about.
fn subtitle(words: &Words) -> String {
    format!("{}{COMPANY}{}", words.subtitle_before, words.subtitle_after)
}

/// The width of the column the page numbers stand in, in points.
const NUMBER_COLUMN: f64 = 28.0;

/// How much of the row an entry leaves free on its right, in points.
const RIGHT_PADDING: f64 = 4.0;

/// The size an entry is set at, top level first.
const SIZES: [f64; 2] = [10.5, 9.5];

/// The contents, as one table: the entry, led by dots to its page number.
fn contents<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(NUMBER_COLUMN),
        ],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.rule(Rule::Horizontal(0), Stroke::new(0.5, Rgb::gray(0.7)));

    for (index, entry) in ENTRIES.iter().enumerate() {
        let top = entry.depth == 0;
        let size = if top { SIZES[0] } else { SIZES[1] };
        let color = if top { Rgb::BLACK } else { Rgb::gray(0.25) };
        let padding = Padding {
            left: INDENT * count(entry.depth),
            right: RIGHT_PADDING,
            top: if top { 7.0 } else { 2.0 },
            bottom: 2.0,
        };

        table.push(
            Row::new()
                .cell(
                    Cell::new(font, size, label(words, entry, index))
                        .color(color)
                        .padding(padding)
                        // The dots are drawn by the layout, in the room the
                        // entry leaves.
                        .leader('.'),
                )
                .cell(
                    Cell::new(font, size, entry.page)
                        .color(color)
                        .align(Align::Right)
                        .padding(padding),
                ),
        );
    }

    Ok(table)
}

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

/// Where the head of the table sits, and how much room it is given below.
const TABLE_TOP: f64 = 730.0;
const TABLE_ROOM: f64 = 660.0;

/// The sizes the two lines above the table are set at, in points.
const TITLE_SIZE: f64 = 20.0;
const SUBTITLE_SIZE: f64 = 8.5;

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("contents")));
    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 c = Content::new();

    let title = TextFlow::new(&font, TITLE_SIZE);
    let title_lines = title.break_lines(words.title, TABLE_WIDTH);
    c.begin_text();
    title.draw(&mut c, &title_lines, MARGIN, 790.0, TABLE_WIDTH)?;
    c.end_text();

    let under_title = TextFlow::new(&font, SUBTITLE_SIZE).color(Rgb::gray(0.4));
    let under_title_lines = under_title.break_lines(&subtitle(words), TABLE_WIDTH);
    c.begin_text();
    under_title.draw(&mut c, &under_title_lines, MARGIN, 762.0, TABLE_WIDTH)?;
    c.end_text();

    let table = contents(&font, words)?;
    table
        .fit(TableFrame::new(MARGIN, TABLE_TOP, TABLE_ROOM), 0)?
        .draw(&mut c)?;

    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::{Document, Font, FontHandle};

    use super::{
        ENTRIES, INDENT, NUMBER_COLUMN, RIGHT_PADDING, SIZES, SUBTITLE_SIZE, TABLE_WIDTH,
        TITLE_SIZE, WORDS, count, default_font, label, language, subtitle,
    };

    /// The room an entry set `depth` deep has before it reaches the page
    /// numbers.
    fn room(depth: usize) -> f64 {
        INDENT.mul_add(-count(depth), TABLE_WIDTH - NUMBER_COLUMN - RIGHT_PADDING)
    }

    /// The lines two languages are allowed to write the same way. There are
    /// none: what an entry is filed under is 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"),
        )
    }

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

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

    /// An entry that fills its column wraps to a second line, and the dots then
    /// lead from the middle of a sentence instead of from its end. Every entry
    /// is asked to leave room for four dots as well as for itself.
    #[test]
    fn every_language_leaves_an_entry_room_for_the_dots_that_follow_it() {
        let mut document = Document::new();
        let font = font(&mut document);

        for (named, words) in WORDS {
            for (index, entry) in ENTRIES.iter().enumerate() {
                let size = if entry.depth == 0 { SIZES[0] } else { SIZES[1] };
                let line = label(words, entry, index);
                let measured = font.measure(&line, size) + font.measure("....", size);
                let room = room(entry.depth);

                assert!(
                    measured <= room,
                    "the {} contents draw {line:?} and its dots over {measured:.1} \
                     points, and the column is {room:.1} wide",
                    named.code()
                );
            }
        }
    }

    /// The two lines above the table are flowed into the width of the table, so
    /// a language that runs past it gets a second line the page has no room
    /// for: the head would then reach down over the first entry.
    #[test]
    fn every_language_keeps_the_head_of_the_page_on_two_lines() {
        let mut document = Document::new();
        let font = font(&mut document);

        for (named, words) in WORDS {
            for (line, size) in [
                (words.title.to_owned(), TITLE_SIZE),
                (subtitle(words), SUBTITLE_SIZE),
            ] {
                let measured = font.measure(&line, size);

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