write_filled_frame.rs

Le programme Rust de Deux commandes, un cadre, un même bas de page. Une commande de quatre lignes et une de sept, dans des cadres de même hauteur, qui finissent toutes les deux sur le même bas. Dessous, deux mentions de longueurs différentes dont les lignes sont écartées jusqu'à ce que chacune atteigne le pied de son cadre.

Rust 600 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
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
//! Prints two orders of unequal length side by side in frames of one height,
//! and ends both of them on the same bottom edge.
//!
//! A pad of pre-printed stationery has the frame already on the paper: a box
//! for the lines, a rule under it, and the total below that rule. What goes in
//! the box is a different length every time. Left alone, an order of four lines
//! leaves a hand's breadth of white above the rule and an order of seven fills
//! it, and the pad looks like two different documents.
//!
//! So the box is filled instead. The rows of the order share whatever room the
//! frame has left, in equal parts, once they have all been measured, and the
//! last of them ends on the bottom edge. The headings and the total are left
//! exactly where the stationery puts them.
//!
//! The notes at the foot of the page do the same for words rather than rows:
//! the lines of each note are moved apart until they reach the bottom of their
//! box, so two notes of unequal length end on one line. A limit is given with
//! the box, and a note far too short for it keeps the spacing it came with
//! rather than being stretched into a ladder.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The amounts are the same in both.
//!
//! Usage: `cargo run --example write_filled_frame -- [out.pdf] [face.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_filled_frame`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Cell, ColumnWidth, Columns, FirstBaseline, LastBaseline, Padding, Row, Rule, Stroke, Table,
    TableFrame, VAlign,
};
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 page is set in when none is given on the command line: the one
/// committed for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// How many lines the shorter order bills.
const SHORT_COUNT: usize = 4;

/// How many lines the longer order bills.
const LONG_COUNT: usize = 7;

/// What the shorter order's lines cost, in euros.
const SHORT_AMOUNTS: [f64; SHORT_COUNT] = [420.0, 96.0, 158.0, 240.0];

/// What the longer order's lines cost, in euros.
const LONG_AMOUNTS: [f64; LONG_COUNT] = [180.0, 64.0, 112.0, 45.0, 320.0, 88.0, 150.0];

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The page's title.
    title: &'static str,
    /// What the page is about.
    lead: &'static str,
    /// The label over the two orders.
    orders: &'static str,
    /// What each order is called, over its own frame.
    short_order: &'static str,
    long_order: &'static str,
    /// The two column headings of an order.
    item: &'static str,
    amount: &'static str,
    /// What the shorter order bills.
    short_items: [&'static str; SHORT_COUNT],
    /// What the longer order bills.
    long_items: [&'static str; LONG_COUNT],
    /// The label on the last row of an order.
    total: &'static str,
    /// The label over the two notes.
    notes: &'static str,
    /// What each note says.
    short_note: &'static str,
    long_note: &'static str,
    /// What the page leaves the reader with.
    caveat: &'static str,
}

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

/// The page in English.
const ENGLISH: Words = Words {
    title: "Two orders, one frame, one bottom edge",
    lead: "The two frames below are the same height, and the orders in them are \
           not the same length. Each frame is filled: whatever room the lines \
           leave is shared out among them in equal parts, once they have all been \
           measured, so the last line of an order of four ends where the last line \
           of an order of seven ends. The headings and the total stay where the \
           stationery puts them, and only the billed lines grow.",
    orders: "Four lines and seven, ending together",
    short_order: "Order 4412",
    long_order: "Order 4413",
    item: "Item",
    amount: "Amount",
    short_items: [
        "Site survey",
        "Cable, 40 m",
        "Wall boxes",
        "Fitting, one day",
    ],
    long_items: [
        "Site survey",
        "Cable, 15 m",
        "Wall boxes",
        "Junction box",
        "Fitting, two days",
        "Cover plates",
        "Test and report",
    ],
    total: "Total",
    notes: "Two notes of unequal length, ending together",
    short_note: "Goods stay ours until they are paid for in full. Anything found \
                 broken is to be written on the driver's sheet before it is \
                 signed, and told to us the same week. A pallet left with a \
                 neighbour is left at the buyer's own risk.",
    long_note: "Payment is due thirty days from the date of issue, by transfer to \
                the account named at the foot of the invoice. A line queried in \
                writing suspends nothing but the line itself, and the rest of the \
                invoice falls due on the day it always did. Work already booked \
                is held for a fortnight after that day and released afterwards.",
    caveat: "The lines of a note are moved apart, and nothing else: the room kept \
             around a paragraph, the drop under the last line and the height of \
             the words themselves stand where they are. A limit is given along \
             with the box, so two lines in a tall box keep the spacing they came \
             with rather than being stretched into a ladder.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Deux commandes, un seul cadre, un seul bas de page",
    lead: "Les deux cadres ci-dessous ont la même hauteur, et les commandes qu'ils \
           portent n'ont pas la même longueur. Chaque cadre est rempli : la place \
           que les lignes laissent est partagée entre elles en parts égales, une \
           fois qu'elles ont toutes été mesurées, si bien que la dernière ligne \
           d'une commande de quatre finit là où finit la dernière ligne d'une \
           commande de sept. Les en-têtes et le total restent où le papier les \
           pose, et seules les lignes facturées grandissent.",
    orders: "Quatre lignes et sept, qui finissent ensemble",
    short_order: "Commande 4412",
    long_order: "Commande 4413",
    item: "Poste",
    amount: "Montant",
    short_items: [
        "Visite des lieux",
        "Câble, 40 m",
        "Boîtiers muraux",
        "Pose, une journée",
    ],
    long_items: [
        "Visite des lieux",
        "Câble, 15 m",
        "Boîtiers muraux",
        "Boîte de dérivation",
        "Pose, deux journées",
        "Plaques de finition",
        "Essais et rapport",
    ],
    total: "Total",
    notes: "Deux mentions de longueurs différentes, qui finissent ensemble",
    short_note: "La marchandise nous appartient jusqu'au paiement intégral. Tout \
                 élément trouvé cassé se porte sur la feuille du chauffeur avant \
                 signature, et nous est signalé dans la semaine. Une palette \
                 laissée chez un voisin l'est aux risques de l'acheteur.",
    long_note: "Le paiement est dû trente jours après la date d'émission, par \
                virement au compte indiqué au bas de la facture. Une ligne \
                contestée par écrit ne suspend que cette ligne, et le reste de la \
                facture reste dû au jour prévu. Les travaux déjà réservés sont \
                tenus quinze jours après ce jour, puis rendus.",
    caveat: "Les lignes d'une mention sont écartées, et rien d'autre : la place \
             gardée autour d'un paragraphe, la retombée sous la dernière ligne et \
             la hauteur des mots eux-mêmes restent où elles sont. Une limite est \
             donnée avec le cadre : deux lignes dans un grand cadre gardent donc \
             l'espacement qu'elles avaient, au lieu d'être étirées en échelle.",
};

/// 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 left edge of everything on the page.
const LEFT: f64 = 72.0;

/// How wide a block of text is, and how wide the two frames are together.
const WIDTH: f64 = 451.0;

/// How wide one frame is.
const FRAME_WIDTH: f64 = 216.0;

/// How far apart the two frames stand.
const FRAME_GAP: f64 = WIDTH - 2.0 * FRAME_WIDTH;

/// How tall each of the two order frames is.
const FRAME_HEIGHT: f64 = 200.0;

/// How tall each of the two note boxes is.
const NOTE_HEIGHT: f64 = 110.0;

/// The size a note is set at.
const NOTE_SIZE: f64 = 8.5;

/// The furthest apart the lines of a note are ever moved.
const NOTE_LIMIT: f64 = 26.0;

/// The size an order is set at.
const ORDER_SIZE: f64 = 8.5;

/// The least tall a billed line is before the frame is shared out.
const ROW_HEIGHT: f64 = 16.0;

/// The grey the page draws its second-rank words in.
const GREY: Rgb = Rgb::gray(0.42);

/// The grey a note's box is outlined in.
const OUTLINE: Rgb = Rgb::gray(0.72);

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    flow: &TextFlow,
    x: f64,
    top: f64,
    width: f64,
    text: &str,
) -> Result<f64, Box<dyn std::error::Error>> {
    let lines = flow.break_lines(text, width);
    c.begin_text();
    flow.draw(c, &lines, x, top, width)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// An amount, as an order writes it: "1 158.00".
fn amount(value: f64) -> String {
    let fixed = format!("{value:.2}");
    let (units, hundredths) = fixed.split_once('.').unwrap_or((fixed.as_str(), "00"));

    let mut grouped = String::new();
    for (index, digit) in units.chars().enumerate() {
        if index > 0 && (units.len() - index) % 3 == 0 {
            grouped.push('\u{00A0}');
        }
        grouped.push(digit);
    }
    format!("{grouped}.{hundredths}")
}

/// One of the two orders: a heading row, the billed lines, and the total.
fn order<'a>(
    handle: &'a FontHandle,
    words: &'static Words,
    items: &'static [&'static str],
    amounts: &'static [f64],
) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(62.0)],
        FRAME_WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.header(1);
    table.footer(1);
    // Every box the table is fitted into is filled to its bottom edge.
    table.fill_frame(true);
    table
        .rule(Rule::Frame, Stroke::black(0.7))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.78)))
        .rule(Rule::Horizontal(1), Stroke::black(0.7))
        .rule(Rule::HorizontalFromEnd(1), Stroke::black(0.7));

    let pad = Padding::symmetric(5.0, 4.0);
    table.push(
        Row::new()
            .cell(
                Cell::new(handle, ORDER_SIZE, words.item)
                    .padding(pad)
                    .fill(Rgb::gray(0.9))
                    .valign(VAlign::Middle),
            )
            .cell(
                Cell::new(handle, ORDER_SIZE, words.amount)
                    .padding(pad)
                    .align(Align::Right)
                    .fill(Rgb::gray(0.9))
                    .valign(VAlign::Middle),
            )
            .min_height(18.0),
    );

    let mut total = 0.0;
    for (label, value) in items.iter().zip(amounts) {
        total += value;
        table.push(
            Row::new()
                .cell(
                    Cell::new(handle, ORDER_SIZE, *label)
                        .padding(pad)
                        .valign(VAlign::Middle),
                )
                .cell(
                    Cell::new(handle, ORDER_SIZE, amount(*value))
                        .padding(pad)
                        .align(Align::Right)
                        .valign(VAlign::Middle),
                )
                .min_height(ROW_HEIGHT),
        );
    }

    table.push(
        Row::new()
            .cell(
                Cell::new(handle, ORDER_SIZE, words.total)
                    .padding(pad)
                    .valign(VAlign::Middle),
            )
            .cell(
                Cell::new(handle, ORDER_SIZE, amount(total))
                    .padding(pad)
                    .align(Align::Right)
                    .valign(VAlign::Middle),
            )
            .min_height(18.0),
    );

    Ok(table)
}

/// Draws one note in a box `NOTE_HEIGHT` points tall, its lines moved apart
/// until the last of them reaches the bottom.
fn note(
    c: &mut Content,
    handle: &FontHandle,
    x: f64,
    top: f64,
    text: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    c.set_stroke(OUTLINE)?;
    c.set_line_width(0.4)?;
    c.rect(x, top - NOTE_HEIGHT, FRAME_WIDTH, NOTE_HEIGHT)?;
    c.stroke();

    // The box is filled from the top of the letters to the foot of them, so the
    // block the spread is measured against is the block a reader sees.
    let flow = TextFlow::new(handle, NOTE_SIZE)
        .first_baseline(FirstBaseline::Ascender)
        .last_baseline(LastBaseline::Descender);
    let lines = flow.break_lines(text, FRAME_WIDTH - 12.0);
    let spread = flow
        .clone()
        .leading(flow.fill_leading(&lines, NOTE_HEIGHT, NOTE_LIMIT));
    c.begin_text();
    spread.draw(c, &lines, x + 6.0, top, FRAME_WIDTH - 12.0)?;
    c.end_text();
    Ok(())
}

/// Draws the whole page.
fn build(words: &'static Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handle = doc.add_font(font);

    let title = TextFlow::new(&handle, 18.0);
    let lead = TextFlow::new(&handle, 10.0);
    let label = TextFlow::new(&handle, 12.0);
    let small = TextFlow::new(&handle, 8.5).color(GREY);

    let mut c = Content::new();
    let mut top = 790.0;
    top = block(&mut c, &title, LEFT, top, WIDTH, words.title)? - 12.0;
    top = block(&mut c, &lead, LEFT, top, WIDTH, words.lead)? - 22.0;
    top = block(&mut c, &label, LEFT, top, WIDTH, words.orders)? - 12.0;

    let right = LEFT + FRAME_WIDTH + FRAME_GAP;
    block(&mut c, &small, LEFT, top, FRAME_WIDTH, words.short_order)?;
    top = block(&mut c, &small, right, top, FRAME_WIDTH, words.long_order)? - 6.0;

    for (x, items, amounts) in [
        (LEFT, words.short_items.as_slice(), SHORT_AMOUNTS.as_slice()),
        (right, words.long_items.as_slice(), LONG_AMOUNTS.as_slice()),
    ] {
        let table = order(&handle, words, items, amounts)?;
        let placed = table.fit(TableFrame::new(x, top, FRAME_HEIGHT), 0)?;
        placed.draw(&mut c)?;
    }
    top -= FRAME_HEIGHT + 26.0;

    top = block(&mut c, &label, LEFT, top, WIDTH, words.notes)? - 14.0;
    note(&mut c, &handle, LEFT, top, words.short_note)?;
    note(&mut c, &handle, right, top, words.long_note)?;
    top -= NOTE_HEIGHT + 24.0;

    let closing = TextFlow::new(&handle, 9.0).color(GREY);
    block(&mut c, &closing, LEFT, top, WIDTH, words.caveat)?;

    let mut page = Page::a4();
    page.content = c.into_bytes();
    doc.add_page(page)?;
    Ok(doc.to_bytes()?)
}

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

    let font = Font::parse(fs::read(&face)?)?;
    let drawn = build(words, font)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &drawn)?;
    println!("wrote {out}: {} bytes", drawn.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::layout::{FirstBaseline, LastBaseline, TableFrame};
    use hqf_pdf::{Document, Font, TextFlow};

    use super::{
        FRAME_HEIGHT, FRAME_WIDTH, LONG_AMOUNTS, LONG_COUNT, NOTE_HEIGHT, NOTE_LIMIT, NOTE_SIZE,
        SHORT_AMOUNTS, SHORT_COUNT, WORDS, Words, amount, default_font, language, order,
    };

    /// The lines two languages are allowed to write the same way: an order is
    /// named by its number, and a total is a total in both.
    const SPARED: [&str; 3] = [
        "short_order: \"Order 4412\"",
        "long_order: \"Order 4413\"",
        "total: \"Total\"",
    ];

    /// The committed font, parsed.
    fn fixture() -> Font {
        Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses")
    }

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

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

    /// The whole point of the page: two orders of unequal length, fitted into
    /// frames of one height, place the same number of rows and both reach the
    /// bottom edge.
    #[test]
    fn both_orders_fill_the_frame_they_are_given() {
        let mut doc = Document::new();
        let handle = doc.add_font(fixture());

        for (named, words) in WORDS {
            for (items, amounts, count) in [
                (
                    words.short_items.as_slice(),
                    SHORT_AMOUNTS.as_slice(),
                    SHORT_COUNT,
                ),
                (
                    words.long_items.as_slice(),
                    LONG_AMOUNTS.as_slice(),
                    LONG_COUNT,
                ),
            ] {
                let table = order(&handle, words, items, amounts).expect("the order lays out");
                let placed = table
                    .fit(TableFrame::new(0.0, FRAME_HEIGHT, FRAME_HEIGHT), 0)
                    .expect("the order fits its frame");

                assert_eq!(
                    placed.row_count(),
                    count + 2,
                    "the {} order of {count} lines placed {} rows of {}",
                    named.code(),
                    placed.row_count(),
                    count + 2
                );
                assert!(
                    (placed.height() - FRAME_HEIGHT).abs() < 1e-6,
                    "the {} order of {count} lines reaches {:.3} of {FRAME_HEIGHT:.3}",
                    named.code(),
                    placed.height()
                );
            }
        }
    }

    /// The two notes are what makes the second half worth drawing: they are of
    /// unequal length, and the spread brings both to the bottom of the box
    /// without ever passing the limit.
    #[test]
    fn both_notes_reach_the_bottom_of_their_box_within_the_limit() {
        let mut doc = Document::new();
        let handle = doc.add_font(fixture());
        let flow = TextFlow::new(&handle, NOTE_SIZE)
            .first_baseline(FirstBaseline::Ascender)
            .last_baseline(LastBaseline::Descender);

        for (named, words) in WORDS {
            let mut counts = Vec::new();
            for text in [words.short_note, words.long_note] {
                let lines = flow.break_lines(text, FRAME_WIDTH - 12.0);
                counts.push(lines.len());

                let leading = flow.fill_leading(&lines, NOTE_HEIGHT, NOTE_LIMIT);
                assert!(
                    leading <= NOTE_LIMIT,
                    "the {} note is spread to {leading:.2}, over the limit of {NOTE_LIMIT:.2}",
                    named.code()
                );

                let spread = flow.clone().leading(leading);
                assert!(
                    (spread.height(&lines) - NOTE_HEIGHT).abs() < 1e-6,
                    "the {} note reaches {:.3} of {NOTE_HEIGHT:.3}",
                    named.code(),
                    spread.height(&lines)
                );
            }
            assert_ne!(
                counts[0],
                counts[1],
                "the two {} notes are the same length, and the page says they are not",
                named.code()
            );
        }
    }

    /// The two orders have to differ, or the frames prove nothing.
    #[test]
    fn the_two_orders_bill_a_different_number_of_lines() {
        assert_ne!(SHORT_COUNT, LONG_COUNT);
        assert_eq!(SHORT_AMOUNTS.len(), SHORT_COUNT);
        assert_eq!(LONG_AMOUNTS.len(), LONG_COUNT);
    }

    #[test]
    fn an_amount_is_written_with_a_space_between_its_thousands() {
        assert_eq!(amount(96.0), "96.00");
        assert_eq!(amount(1158.5), "1\u{00A0}158.50");
    }

    /// The words are read through a reference of the same life as the tables
    /// built from them, which is what `order` asks for.
    #[test]
    fn the_words_of_a_language_outlive_the_order_they_bill() {
        let words: &'static Words = language::pick(&WORDS, language::Language::English);
        assert_eq!(words.short_items.len(), SHORT_COUNT);
    }
}