Un montant qui dit de quels titres il dépend

Les recettes de trente agences, trimestre par trimestre, sur deux pages. Chaque montant de la feuille porte les titres dont il dépend : l'agence à côté de lui, le trimestre au-dessus de lui, et l'année au-dessus des quatre trimestres réunis. Lu à voix haute, un montant est annoncé par sa ville, son trimestre et son année avant la somme elle-même.

Cette page est le programme entier, pour celui qui écrit vos logiciels. Il n'y a rien d'autre à y lire. Revenir au document qu'il écrit.

Rust write_table_headers.rs 553 lignes
  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
//! Writes a table of quarterly takings whose every figure carries the headings
//! that reach it.
//!
//! A figure alone says nothing: `118 400` is a number until something says
//! which branch and which quarter it belongs to. The table names its heading
//! rows and its heading column, and the engine works out, cell by cell, which
//! headings reach each figure — so a reader that reads the sheet aloud
//! announces the town, the quarter and the year before the amount.
//!
//! The table runs onto a second page, and it is one table there: the heading is
//! drawn again at the top of the page, and the document still says there is one
//! of it.
//!
//! Every word is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is set. The branches and their takings are not words: they stand
//! in one table, shared by both languages.
//!
//! Usage: `cargo run --example write_table_headers -- tmp/takings.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_table_headers`

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

use hqf_pdf::color::Rgb;
use hqf_pdf::content::{Artifact, Content};
use hqf_pdf::cos::Name;
use hqf_pdf::layout::{
    Align, Area, Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TableFrame,
    TaggedTable, TextFlow, VAlign,
};
use hqf_pdf::metadata::xmp::{Metadata, PdfUa};
use hqf_pdf::{Document, Font, FontHandle, Marks, Page, StructElement, StructureTree};

#[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: 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")
}

/// Where the sheet's text begins, in points from the left edge of the page.
const LEFT: f64 = 56.0;
/// How wide it runs.
const WIDTH: f64 = 483.0;
/// The size the heading is set in.
const TITLE_SIZE: f64 = 20.0;
/// The size the opening paragraph is set in.
const INTRO_SIZE: f64 = 10.0;
/// The size a line of the table is set in.
const ROW_SIZE: f64 = 9.0;
/// The size the foot of the page is set in.
const FOOT_SIZE: f64 = 8.5;
/// The top of the heading's box.
const TITLE_TOP: f64 = 790.0;
/// The top of the opening paragraph.
const INTRO_TOP: f64 = 752.0;
/// The top of the table on the first page, under the opening paragraph.
const FIRST_TOP: f64 = 668.0;
/// The top of the table on every page after it.
const NEXT_TOP: f64 = 790.0;
/// How far down the page the table may reach.
const FOOT: f64 = 90.0;
/// The baseline the foot of the page is set on.
const FOOT_BASELINE: f64 = 60.0;
/// How wide each of the four quarter columns is, in points.
const QUARTER_WIDTH: f64 = 90.0;
/// When the sheet was drawn up. The library never reads the clock: a document
/// that stamped itself with the time would be a different file on every build.
const DRAWN_UP: &str = "2026-08-08T09:30:00+02:00";

/// The words the sheet is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The BCP 47 tag the document states.
    lang: &'static str,
    /// What stands across the head of the sheet.
    title: &'static str,
    /// The paragraph under it, which says what the sheet is showing.
    intro: &'static str,
    /// The heading of the column the branches stand in.
    branch: &'static str,
    /// What the four quarter columns are called.
    quarters: [&'static str; 4],
    /// What stands against the sum of every branch.
    every_branch: &'static str,
    /// What opens the foot of the page, the page number following it.
    foot: &'static str,
}

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

    /// What the foot of page `index` reads, the pages counting from zero.
    fn page_number(&self, index: usize) -> String {
        format!("{} {}", self.foot, index + 1)
    }
}

/// The sheet in English.
const ENGLISH: Words = Words {
    lang: "en-GB",
    title: "Takings by branch, quarter by quarter",
    intro: "Every figure below carries the headings that reach it: the branch \
it stands beside, the quarter it stands under, and the year over the four \
quarters together. Nothing here was written by hand — the sheet says which \
rows and which column hold its headings, and the engine works out the rest. \
Read aloud, the first figure of the first line is announced as the town, the \
first quarter, the year, and then the amount.",
    branch: "Branch",
    quarters: [
        "First quarter",
        "Second quarter",
        "Third quarter",
        "Fourth quarter",
    ],
    every_branch: "Every branch together",
    foot: "Takings by branch, page",
};

/// The sheet in French.
const FRENCH: Words = Words {
    lang: "fr-FR",
    title: "Recettes par agence, trimestre par trimestre",
    intro: "Chaque montant ci-dessous porte les titres qui le concernent : \
l'agence à côté de laquelle il se trouve, le trimestre au-dessus de lui, et \
l'année qui couvre les quatre trimestres. Rien n'a été écrit à la main — la \
feuille dit quelles lignes et quelle colonne portent ses titres, et le moteur \
en déduit le reste. Lu à voix haute, le premier montant de la première ligne \
s'annonce par la ville, le premier trimestre, l'année, puis la somme.",
    branch: "Agence",
    quarters: [
        "1er trimestre",
        "2e trimestre",
        "3e trimestre",
        "4e trimestre",
    ],
    every_branch: "Toutes agences réunies",
    foot: "Recettes par agence, page",
};

/// Every language the sheet is written in.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// The year the four quarter columns stand under.
///
/// A year is not a word: both languages set the same one.
const YEAR: &str = "2026";

/// What every branch took in each of the four quarters, in whole euros.
///
/// Names and figures are not words either: both languages set the same table.
const BRANCHES: [(&str, [i64; 4]); 30] = [
    ("Ashcombe", [118_400, 126_900, 131_250, 142_800]),
    ("Barrowfield", [94_200, 88_750, 96_400, 103_900]),
    ("Coldharbour", [151_300, 148_200, 155_900, 167_400]),
    ("Dunwater", [72_600, 79_450, 81_200, 84_750]),
    ("Eastmarch", [133_800, 129_400, 138_600, 145_100]),
    ("Fernbridge", [86_950, 91_300, 89_700, 97_250]),
    ("Greyharbour", [164_500, 171_200, 168_900, 179_600]),
    ("Hollowmead", [58_300, 61_750, 64_200, 66_800]),
    ("Ivybridge", [107_600, 112_400, 109_850, 118_300]),
    ("Kelburn", [123_900, 118_700, 126_500, 134_200]),
    ("Langmere", [69_400, 73_100, 71_850, 76_900]),
    ("Marchford", [142_700, 147_300, 151_600, 158_400]),
    ("Netherby", [81_200, 84_900, 87_450, 92_100]),
    ("Oakhaven", [176_800, 182_400, 179_300, 191_700]),
    ("Penwick", [63_500, 66_200, 68_900, 71_400]),
    ("Quarrington", [98_700, 103_400, 101_250, 108_600]),
    ("Ravensmoor", [136_200, 141_800, 139_400, 148_900]),
    ("Saltmarsh", [77_300, 81_600, 79_950, 85_200]),
    ("Thornbury", [159_400, 164_900, 162_300, 173_500]),
    ("Upwell", [54_800, 57_200, 59_600, 62_100]),
    ("Vellacourt", [112_500, 117_800, 115_200, 123_700]),
    ("Westhaven", [188_300, 194_600, 191_400, 203_900]),
    ("Yarrowdale", [66_700, 69_300, 71_800, 74_500]),
    ("Applegarth", [104_200, 108_900, 106_400, 114_300]),
    ("Bramblewick", [89_600, 93_200, 91_700, 98_400]),
    ("Cotterill", [147_900, 152_600, 149_800, 160_200]),
    ("Dellmoor", [71_300, 74_800, 76_500, 79_900]),
    ("Eaglestone", [129_700, 134_200, 132_600, 141_300]),
    ("Foxholt", [83_400, 87_100, 85_600, 91_800]),
    ("Greenslade", [155_800, 161_400, 158_900, 169_700]),
];

/// An amount, with a space between its thousands.
fn figure(amount: i64) -> String {
    let digits = amount.to_string();
    let mut out = String::with_capacity(digits.len() + 4);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    out
}

/// What every branch took together in each of the four quarters.
fn totals() -> [i64; 4] {
    let mut sums = [0_i64; 4];
    for (_, quarters) in BRANCHES {
        for (sum, took) in sums.iter_mut().zip(quarters) {
            *sum += took;
        }
    }
    sums
}

/// The five columns: the branches, then one for each quarter.
fn columns() -> Result<Columns, hqf_pdf::Error> {
    let mut widths = vec![ColumnWidth::Fraction(1.0)];
    widths.extend([ColumnWidth::Points(QUARTER_WIDTH); 4]);
    Columns::new(widths, WIDTH)
}

/// A cell of the table, padded the way every cell of it is.
fn cell(font: &FontHandle, text: impl Into<String>, align: Align) -> Cell<'_> {
    Cell::new(font, ROW_SIZE, text)
        .align(align)
        .padding(Padding::symmetric(6.0, 7.0))
}

/// The table: two heading rows, one heading column, a line per branch, and a
/// line adding every branch together.
///
/// The heading of the branch column covers both heading rows, and the year
/// covers the four quarter columns. Neither of those can be read by looking up
/// a column and along a row, so the engine names the headings instead and
/// writes, against every figure, which of them reach it.
fn takings<'a>(font: &'a FontHandle, words: &Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let mut table = Table::new(columns()?);
    table.header(2);
    table.row_headers(1);
    table.fill(Area::Header, Rgb::gray(0.90));
    table.rule(Rule::Frame, Stroke::black(0.8));
    table.rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.75)));
    table.rule(Rule::VerticalOther, Stroke::new(0.25, Rgb::gray(0.75)));
    table.rule(Rule::Horizontal(2), Stroke::black(0.8));

    table.push(
        Row::new()
            .cell(
                cell(font, words.branch, Align::Left)
                    .span_rows(2)
                    .valign(VAlign::Middle),
            )
            .cell(cell(font, YEAR, Align::Center).span(4)),
    );
    let mut quarters = Row::new();
    for name in words.quarters {
        quarters = quarters.cell(cell(font, name, Align::Right));
    }
    table.push(quarters);

    for (branch, took) in BRANCHES {
        let mut line = Row::new().cell(cell(font, branch, Align::Left));
        for amount in took {
            line = line.cell(cell(font, figure(amount), Align::Right));
        }
        table.push(line);
    }

    let mut sum = Row::new().cell(cell(font, words.every_branch, Align::Left));
    for amount in totals() {
        sum = sum.cell(cell(font, figure(amount), Align::Right));
    }
    table.push(sum);

    Ok(table)
}

/// Draws the heading of the first page and hands back the element standing for
/// it.
fn heading(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    marks: &mut Marks,
) -> Result<StructElement, hqf_pdf::Error> {
    let flow = TextFlow::new(font, TITLE_SIZE);
    let lines = flow.break_lines(words.title, WIDTH);
    let id = marks.next_id();
    content.begin_tagged(&Name::new("H1"), id);
    content.begin_text();
    flow.draw(content, &lines, LEFT, TITLE_TOP, WIDTH)?;
    content.end_text();
    content.end_marked();
    Ok(StructElement::new("H1").content(0, id))
}

/// Draws the opening paragraph and hands back the element standing for it.
fn opening(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    marks: &mut Marks,
) -> Result<StructElement, hqf_pdf::Error> {
    let flow = TextFlow::new(font, INTRO_SIZE).align(Align::Justify);
    let lines = flow.break_lines(words.intro, WIDTH);
    let id = marks.next_id();
    content.begin_tagged(&Name::new("P"), id);
    content.begin_text();
    flow.draw(content, &lines, LEFT, INTRO_TOP, WIDTH)?;
    content.end_text();
    content.end_marked();
    Ok(StructElement::new("P").content(0, id))
}

/// Draws the foot of a page, which belongs to the pagination and not to what
/// the document says.
fn foot(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    index: usize,
) -> Result<(), hqf_pdf::Error> {
    let flow = TextFlow::new(font, FOOT_SIZE).align(Align::Right);
    let numbered = words.page_number(index);
    let lines = flow.break_lines(&numbered, WIDTH);
    content.begin_artifact(Artifact::Footer);
    content.begin_text();
    flow.draw(content, &lines, LEFT, FOOT_BASELINE, WIDTH)?;
    content.end_text();
    content.end_marked();
    Ok(())
}

/// Builds the whole document: the heading, the opening paragraph, the table
/// over as many pages as it needs, and the branch of the tree that says what
/// all of it is.
fn build(words: &Words, font_path: &Path) -> Result<Document, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    // The accessibility claim, which is what a buyer's validator is pointed at:
    // it is judged against the tree, the artifacts, the embedded font and the
    // title all at once.
    doc.set_ua_conformance(PdfUa::One);
    doc.set_metadata(Metadata {
        title: Some(words.title.to_owned()),
        producer: Some("hqf-pdf".to_owned()),
        created: Some(DRAWN_UP.to_owned()),
        ..Metadata::default()
    });
    doc.set_info(Name::new("Title"), words.title);
    let font = doc.add_font(Font::parse(fs::read(font_path)?)?);

    let table = takings(&font, words)?;
    let boxes = table.paginate(
        TableFrame::new(LEFT, FIRST_TOP, FIRST_TOP - FOOT),
        TableFrame::new(LEFT, NEXT_TOP, NEXT_TOP - FOOT),
    )?;

    // One table, however many pages draw it: every box is added to the same
    // description, and the heading drawn again at the top of each page is the
    // heading it already stands for.
    let mut described = TaggedTable::new("takings");
    let mut body = StructElement::new("Document");
    for (index, placement) in boxes.iter().enumerate() {
        let mut content = Content::new();
        let mut marks = Marks::new();
        if index == 0 {
            body = body.child(heading(&mut content, &font, words, &mut marks)?);
            body = body.child(opening(&mut content, &font, words, &mut marks)?);
        }
        described.add(placement, &mut content, index, &mut marks)?;
        foot(&mut content, &font, words, index)?;
        let mut page = Page::a4();
        page.content = content.into_bytes();
        doc.add_page(page)?;
    }
    body = body.child(described.finish());
    doc.set_structure(StructureTree::new().lang(words.lang).child(body));
    Ok(doc)
}

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

    let doc = build(words, &font_path)?;
    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::{Align, TextFlow};
    use hqf_pdf::{Document, Font};

    use super::{
        BRANCHES, QUARTER_WIDTH, ROW_SIZE, WIDTH, WORDS, YEAR, build, default_font, figure,
        language, totals,
    };

    /// The test font, added to a document so that a flow can be built on it.
    fn handle() -> (Document, hqf_pdf::FontHandle) {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let handle = doc.add_font(font);
        (doc, handle)
    }

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

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

    /// A branch name that wrapped would make its line twice as tall as the
    /// lines around it, and the table would no longer read as a grid.
    #[test]
    fn every_branch_stands_on_one_line_of_its_column() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, ROW_SIZE);
        // The room the branch column has: the table less the four quarter
        // columns, less the padding either side of the cell.
        let room = QUARTER_WIDTH.mul_add(-4.0, WIDTH) - 12.0;

        for (branch, _) in BRANCHES {
            assert_eq!(
                flow.break_lines(branch, room).len(),
                1,
                "{branch:?} does not fit its column"
            );
        }
        for (_, words) in WORDS {
            assert_eq!(
                flow.break_lines(words.every_branch, room).len(),
                1,
                "the line adding every branch together does not fit its column"
            );
            assert_eq!(flow.break_lines(words.branch, room).len(), 1);
        }
    }

    /// A quarter heading is set against the right edge of its column, over the
    /// figures it heads; one that wrapped would stand two lines tall and push
    /// the year off the top of the sheet.
    #[test]
    fn every_quarter_heading_fits_the_column_it_stands_over() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, ROW_SIZE).align(Align::Right);
        let room = QUARTER_WIDTH - 12.0;

        for (named, words) in WORDS {
            for name in words.quarters {
                assert_eq!(
                    flow.break_lines(name, room).len(),
                    1,
                    "the {} heading {name:?} does not fit its column",
                    named.code()
                );
            }
        }
    }

    /// A space between the thousands, and nothing else touched.
    #[test]
    fn an_amount_is_written_with_a_space_between_its_thousands() {
        assert_eq!(figure(0), "0");
        assert_eq!(figure(999), "999");
        assert_eq!(figure(1_000), "1\u{00A0}000");
        assert_eq!(figure(118_400), "118\u{00A0}400");
        assert_eq!(figure(1_234_567), "1\u{00A0}234\u{00A0}567");
    }

    /// The sum stands under the column it adds, and is the sum of it.
    #[test]
    fn every_branch_together_is_every_branch_added_up() {
        let mut wanted = [0_i64; 4];
        for (_, quarters) in BRANCHES {
            for (sum, took) in wanted.iter_mut().zip(quarters) {
                *sum += took;
            }
        }

        assert_eq!(totals(), wanted);
        assert_eq!(totals()[0], 3_320_950);
    }

    /// The point of the sheet: it runs onto a second page, it is still one
    /// table there, and every figure names the headings that reach it.
    #[test]
    fn the_sheet_is_one_table_over_more_than_one_page_and_names_its_headings() {
        for (named, words) in WORDS {
            let mut doc = build(words, &default_font()).expect("the document builds");
            doc.set_compression(false);
            assert!(
                doc.page_count() > 1,
                "the {} sheet fits one page, and proves nothing",
                named.code()
            );
            let pdf =
                String::from_utf8_lossy(&doc.to_bytes().expect("the document writes")).into_owned();

            assert_eq!(
                pdf.matches("/S /Table").count(),
                1,
                "one table, however many pages drew it"
            );
            assert!(pdf.contains("/IDTree"), "the file lists the names");
            assert!(pdf.contains("/Headers ["), "a figure names its headings");
            // The heading of the year covers the four quarter columns, and the
            // heading of the branch column covers both heading rows.
            assert!(pdf.contains("/ColSpan 4"), "{YEAR} covers four columns");
            assert!(pdf.contains("/RowSpan 2"), "the branch heading covers both");
        }
    }
}