A report that lays itself out

A title, a rule, two paragraphs, a heading, a table of twenty-six rows and a footnote, handed over in reading order and broken across two pages by the engine.

Rust write_stack.rs 429 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
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
//! Lays a whole report out by stacking blocks, without writing a single
//! ordinate by hand.
//!
//! The page holds a title, a rule, two paragraphs, a heading, a table of
//! twenty-six rows and a footnote, and they are pushed onto a stack in the
//! order they are read. The stack breaks them across as many pages as they
//! need: the table is cut row by row, its heading row repeated, and the closing
//! paragraph is kept together so that it is never left with one line on a page
//! of its own.
//!
//! The only ordinate the example writes is the one the page number sits on,
//! which belongs to the sheet rather than to what is said on it. Everything
//! else follows whatever the block above it came to, so a paragraph that grows
//! in translation pushes the rest down instead of being drawn over.
//!
//! Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The hours and the amounts are figures, and stand the
//! same in every language.
//!
//! Usage: `cargo run --example write_stack -- tmp/stack.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_stack -- tmp/pile.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Align, Block, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stack, StackFrame, Stacked,
    Stroke, Table, VAlign,
};
use hqf_pdf::{Document, Font, FontHandle, Page, Rgb, TextFlow};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

use language::Language;

/// 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 report is written in, one set per language.
///
/// What is not language stays out of it: every hour and every amount is a
/// figure, and the row numbers run from one whatever the words say.
#[derive(Debug)]
struct Words {
    /// The report's title.
    title: &'static str,
    /// The paragraph under the title.
    intro: &'static str,
    /// The heading over the table.
    section: &'static str,
    /// The three column headings of the table.
    headings: [&'static str; 3],
    /// What each row of the table is called, before its number.
    task: &'static str,
    /// The paragraph under the table, kept together.
    closing: &'static str,
    /// The line at the foot of the report.
    footnote: &'static str,
    /// The word the page number opens with.
    page: &'static str,
    /// The word between a page's number and how many pages there are.
    of: &'static str,
}

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

    /// What the foot of page `index` of `total` reads.
    fn page_label(&self, index: usize, total: usize) -> String {
        let number = index + 1;
        format!("{} {number} {} {total}", self.page, self.of)
    }

    /// What row `index` of the table is called.
    fn row_label(&self, index: usize) -> String {
        let number = index + 1;
        format!("{} {number:02}", self.task)
    }
}

/// The report in English.
const ENGLISH: Words = Words {
    title: "Work carried out this quarter",
    intro: "Every block on this page was pushed onto a stack in the order it \
        is read, and the stack decided where each of them goes. Nothing here \
        was placed against a measured height: a paragraph that grows pushes \
        what follows it down the page, and onto the next one when the room \
        runs out.",
    section: "What was done, task by task",
    headings: ["Task", "Hours", "Amount"],
    task: "Task",
    closing: "The table above was cut wherever the room ran out, and its \
        heading row was drawn again at the top of every page it was carried \
        onto. This paragraph was kept together, so it is never left with a \
        single line at the foot of a page while the rest of it starts the \
        next one.",
    footnote: "Hours are billed at 85.00 € each, and the amounts are exclusive \
        of tax.",
    page: "Page",
    of: "of",
};

/// The report in French.
const FRENCH: Words = Words {
    title: "Les travaux du trimestre",
    intro: "Chaque bloc de cette page a été empilé dans l'ordre où on le lit, \
        et c'est la pile qui a décidé où chacun se pose. Rien n'a été placé \
        contre une hauteur mesurée à la main : un paragraphe qui s'allonge \
        pousse la suite vers le bas, et sur la page suivante quand la place \
        vient à manquer.",
    section: "Le détail, tâche par tâche",
    headings: ["Tâche", "Heures", "Montant"],
    task: "Tâche",
    closing: "Le tableau ci-dessus a été coupé là où la place manquait, et sa \
        rangée de titres redessinée en haut de chaque page où il se poursuit. \
        Ce paragraphe, lui, tient d'un seul tenant : il ne laisse jamais une \
        ligne seule en bas d'une page pendant que le reste ouvre la suivante.",
    footnote: "L'heure est facturée 85.00 € et les montants s'entendent hors \
        taxes.",
    page: "Page",
    of: "sur",
};

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

/// How many rows of work the table carries.
const ROWS: usize = 26;

/// The colour of the rule under the title.
const ACCENT: Rgb = Rgb::new(0.12, 0.33, 0.55);

/// The colour the footnote and the page number are set in.
const MUTED: Rgb = Rgb::new(0.45, 0.45, 0.45);

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

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

/// The ordinate the page number sits on, which belongs to the sheet rather than
/// to what is said on it.
const FOOT: f64 = 40.0;

/// The box the first page gives the report.
const fn first_box() -> StackFrame {
    StackFrame::new(LEFT, 780.0, WIDTH, 700.0)
}

/// The box every page after the first gives it.
const fn next_box() -> StackFrame {
    StackFrame::new(LEFT, 780.0, WIDTH, 700.0)
}

/// The hours row `index` took, and what they came to.
fn work(index: usize) -> (u32, u32) {
    let hours = 2 + u32::try_from(index % 5).unwrap_or(0);
    (hours, hours * 85)
}

/// The table of work, one row per task, its heading row repeated on every page
/// it is carried onto.
fn work_table<'a>(font: &'a FontHandle, words: &'static Words) -> Table<'a> {
    let columns = Columns::new(
        vec![
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(70.0),
            ColumnWidth::Points(90.0),
        ],
        WIDTH,
    )
    .expect("three columns fit the report's width");

    let mut table = Table::new(columns);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::black(0.8))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.75)))
        .rule(Rule::Horizontal(1), Stroke::black(0.8));

    let pad = Padding::symmetric(6.0, 5.0);
    let heading = |label: &str, align: Align| {
        Cell::new(font, 9.0, label)
            .align(align)
            .padding(pad)
            .valign(VAlign::Middle)
            .fill(Rgb::gray(0.88))
    };

    table.push(
        Row::new()
            .cell(heading(words.headings[0], Align::Left))
            .cell(heading(words.headings[1], Align::Right))
            .cell(heading(words.headings[2], Align::Right))
            .min_height(20.0),
    );

    for index in 0..ROWS {
        let (hours, amount) = work(index);
        table.push(
            Row::new()
                .cell(Cell::new(font, 9.0, words.row_label(index)).padding(pad))
                .cell(
                    Cell::new(font, 9.0, format!("{hours}"))
                        .align(Align::Right)
                        .padding(pad),
                )
                .cell(
                    Cell::new(font, 9.0, format!("{amount}.00"))
                        .align(Align::Right)
                        .padding(pad),
                ),
        );
    }
    table
}

/// The whole report, block by block, in the order it is read.
fn report<'a>(font: &'a FontHandle, words: &'static Words) -> Stack<'a> {
    let mut stack = Stack::new();
    stack
        .push(Block::text(TextFlow::new(font, 16.0), words.title).keep_together())
        .push(Block::space(8.0))
        .push(Block::rule(Stroke::new(1.2, ACCENT)))
        .push(Block::space(14.0))
        .push(Block::text(
            TextFlow::new(font, 10.5)
                .leading(15.0)
                .align(Align::Justify),
            words.intro,
        ))
        .push(Block::space(18.0))
        .push(Block::text(TextFlow::new(font, 12.0), words.section).keep_together())
        .push(Block::space(8.0))
        .push(Block::table(work_table(font, words)))
        .push(Block::space(18.0))
        .push(
            Block::text(
                TextFlow::new(font, 10.5)
                    .leading(15.0)
                    .align(Align::Justify),
                words.closing,
            )
            .keep_together(),
        )
        .push(Block::space(14.0))
        .push(Block::rule(Stroke::new(0.6, MUTED)))
        .push(Block::space(8.0))
        .push(Block::text(
            TextFlow::new(font, 8.0).color(MUTED),
            words.footnote,
        ));
    stack
}

/// Draws the page number at the foot of the sheet.
fn page_number(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    index: usize,
    total: usize,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(font, 8.0).color(MUTED).align(Align::Center);
    let label = words.page_label(index, total);
    let lines = flow.break_lines(&label, WIDTH);
    content.begin_text();
    flow.draw(content, &lines, LEFT, FOOT, WIDTH)?;
    content.end_text();
    Ok(())
}

fn main() -> 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")));
    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 stack = report(&handle, words);
    let pages: Vec<Stacked<'_>> = stack.paginate(first_box(), next_box())?;

    for (index, placed) in pages.iter().enumerate() {
        let mut c = Content::new();
        placed.draw(&mut c)?;
        page_number(&mut c, &handle, words, index, pages.len())?;

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

    use super::{FOOT, ROWS, WIDTH, WORDS, default_font, first_box, language, next_box, report};

    /// The lines two languages are allowed to write the same way. "Page" reads
    /// the same in both, and the word a reader looks for at the foot of a sheet
    /// is not a place to be inventive.
    const SPARED: [&str; 1] = ["page: \"Page\""];

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

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

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

    #[test]
    fn every_language_keeps_every_block_inside_the_box_it_was_given() {
        let (_doc, handle) = font();
        for &(name, words) in &WORDS {
            let pages = report(&handle, words)
                .paginate(first_box(), next_box())
                .expect("the report paginates");

            assert!(pages.len() > 1, "{name:?}: the report runs over one page");
            for (index, placed) in pages.iter().enumerate() {
                let frame: StackFrame = if index == 0 { first_box() } else { next_box() };
                let floor = frame.top - frame.height;
                for (block, area) in placed.block_boxes() {
                    assert!(
                        area.y() + area.height() <= frame.top + 1e-9,
                        "{name:?}: block {block} starts above its box on page {index}"
                    );
                    assert!(
                        area.y() >= floor - 1e-9,
                        "{name:?}: block {block} reaches below its box on page {index}"
                    );
                    assert!(
                        area.y() > FOOT,
                        "{name:?}: block {block} lands on the page number"
                    );
                }
            }
        }
    }

    #[test]
    fn every_line_the_report_writes_on_one_line_fits_the_room_it_has() {
        let (_doc, handle) = font();
        for &(name, words) in &WORDS {
            let single: [(&str, f64, String); 5] = [
                ("title", 16.0, words.title.to_owned()),
                ("section", 12.0, words.section.to_owned()),
                ("page number", 8.0, words.page_label(9, 10)),
                ("first row", 9.0, words.row_label(0)),
                ("last row", 9.0, words.row_label(ROWS - 1)),
            ];
            for (what, size, text) in &single {
                let width = handle.measure(text, *size);
                assert!(
                    width <= WIDTH,
                    "{name:?}: the {what} is {width} points wide in {WIDTH}"
                );
            }

            // A heading sits in a column of its own, and the two figure columns
            // are the narrowest room on the page.
            let headings: [(&str, f64); 3] = [
                (words.headings[0], WIDTH - 160.0),
                (words.headings[1], 70.0),
                (words.headings[2], 90.0),
            ];
            for (heading, room) in &headings {
                // The cells are padded six points either side.
                let width = handle.measure(heading, 9.0) + 12.0;
                assert!(
                    width <= *room,
                    "{name:?}: the heading {heading:?} is {width} points wide in {room}"
                );
            }
        }
    }
}