Columns measured from their cells

One parts list twice: four columns sharing the width equally, then the reference, the quantity and the price each as wide as their own widest cell and the description given everything they leave.

Rust write_measured_columns.rs 368 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
//! Draws one parts list twice: columns of equal width, then columns measured
//! from what they hold.
//!
//! The rows are the same in both. In the first table the four columns share the
//! width equally, so the references and the figures sit in far more room than
//! they need and the descriptions wrap for want of it. In the second the
//! reference, the quantity and the price are each as wide as their own widest
//! cell, and the description is given everything they leave.
//!
//! What the page reads is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set is drawn. The references, the quantities and
//! the prices are not language: they are the same figures whoever reads the
//! list.
//!
//! Usage: `cargo run --example write_measured_columns --
//! tmp/measured_columns.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_measured_columns --
//! tmp/colonnes_mesurees.pdf`

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, VAlign};
use hqf_pdf::{Align, Document, Font, Page, Rgb};

#[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.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The margin around the tables, in points.
const MARGIN: f64 = 56.0;
/// The top of the first table.
const TOP: f64 = 740.0;
/// The room left between the two tables, in points.
const GAP: f64 = 64.0;

/// A4's width, which the tables are fitted across.
const PAGE_WIDTH: f64 = 595.276;

/// The width left to a table between the margins.
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;

/// How many parts the list holds.
const PARTS_COUNT: usize = 5;

/// One line of the parts list, save what it is called.
struct Part {
    /// The catalogue reference.
    reference: &'static str,
    /// How many are ordered.
    quantity: &'static str,
    /// What one costs.
    price: &'static str,
}

/// The figures the list holds. They are short and all of a length, whatever
/// language the list is read in; what each part is called is in [`Words`].
const PARTS: [Part; PARTS_COUNT] = [
    Part {
        reference: "HQF-1042",
        quantity: "2",
        price: "48.00",
    },
    Part {
        reference: "HQF-1043",
        quantity: "2",
        price: "26.50",
    },
    Part {
        reference: "HQF-2210",
        quantity: "1",
        price: "9.20",
    },
    Part {
        reference: "HQF-3007",
        quantity: "1",
        price: "142.00",
    },
    Part {
        reference: "HQF-3011",
        quantity: "3",
        price: "11.75",
    },
];

/// The words the page is written in, one set per language.
///
/// The references, the quantities and the prices are not here: they are the
/// same figures in every language, and they are what the two narrow columns are
/// measured from.
#[derive(Debug)]
struct Words {
    /// The line over each of the two tables.
    captions: [&'static str; 2],
    /// The four column headings, in the order the columns are drawn.
    headings: [&'static str; 4],
    /// What each part is, in the order the rows are drawn.
    descriptions: [&'static str; PARTS_COUNT],
}

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 {
    captions: [
        "Columns of equal width",
        "Columns measured from their cells",
    ],
    headings: ["Reference", "Description", "Qty", "Unit price"],
    descriptions: [
        "Aluminium mounting plate, drilled for the four-point thread",
        "Quick-release shoe",
        "Sealing ring, nitrile, sold in packs of ten",
        "Bench supply, twelve volts, regulated",
        "Adapter lead, two metres",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    captions: [
        "Des colonnes de largeur égale",
        "Des colonnes mesurées sur leurs cellules",
    ],
    headings: ["Référence", "Désignation", "Qté", "Prix unitaire"],
    descriptions: [
        "Plaque de montage en aluminium, percée pour la fixation quatre points",
        "Sabot à dégagement rapide",
        "Joint torique en nitrile, vendu par dix",
        "Alimentation d'établi, douze volts, régulée",
        "Cordon adaptateur, deux mètres",
    ],
};

/// 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 parts list, laid out across `columns`.
fn parts_list<'a>(
    text: &'a hqf_pdf::FontHandle,
    words: &'static Words,
    columns: Columns,
) -> Table<'a> {
    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::VerticalOther, 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| {
        Cell::new(text, 9.0, label)
            .padding(pad)
            .valign(VAlign::Middle)
            .fill(Rgb::gray(0.88))
    };

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

    for (part, description) in PARTS.iter().zip(words.descriptions) {
        table.push(
            Row::new()
                .cell(Cell::new(text, 9.0, part.reference).padding(pad))
                .cell(Cell::new(text, 9.0, description).padding(pad))
                .cell(
                    Cell::new(text, 9.0, part.quantity)
                        .padding(pad)
                        .align(Align::Right),
                )
                .cell(
                    Cell::new(text, 9.0, part.price)
                        .padding(pad)
                        .align(Align::Right)
                        .align_on('.'),
                )
                .min_height(18.0),
        );
    }

    table
}

/// Draws `label` at `(MARGIN, y)` in 11pt.
fn caption(
    content: &mut Content,
    text: &hqf_pdf::FontHandle,
    label: &str,
    y: f64,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(text.name(), 11.0)?;
    content.text_origin(MARGIN, y)?;
    content.show_glyphs(&text.glyphs(label));
    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("measured_columns")));
    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 text = doc.add_font(font);

    // Four columns sharing the width equally, and the same four with three of
    // them measured from their own cells.
    let equal = parts_list(&text, words, Columns::equal(4, TABLE_WIDTH)?);
    let measured = parts_list(
        &text,
        words,
        Columns::new(
            vec![
                ColumnWidth::Content,
                ColumnWidth::Fraction(1.0),
                ColumnWidth::Content,
                ColumnWidth::Content,
            ],
            TABLE_WIDTH,
        )?,
    );

    let mut content = Content::new();

    caption(&mut content, &text, words.captions[0], TOP + 18.0)?;
    let first = equal.fit(MARGIN, TOP, TOP - MARGIN, 0)?;
    first.draw(&mut content)?;

    let second_top = first.bottom() - GAP;
    caption(&mut content, &text, words.captions[1], second_top + 18.0)?;
    let second = measured.fit(MARGIN, second_top, second_top - MARGIN, 0)?;
    second.draw(&mut content)?;

    let mut page = Page::a4();
    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, {} rows twice",
        bytes.len(),
        equal.row_count()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::layout::{ColumnWidth, Columns};
    use hqf_pdf::{Document, Font};

    use super::{MARGIN, TABLE_WIDTH, TOP, WORDS, Words, default_font, language, parts_list};

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a heading, a caption or the name of a part, and no two languages
    /// write one alike.
    const SPARED: [&str; 0] = [];

    /// How far down the page each of the two tables reaches, in `words`.
    fn bottoms(words: &'static Words) -> (f64, f64) {
        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 text = doc.add_font(font);

        let equal = parts_list(
            &text,
            words,
            Columns::equal(4, TABLE_WIDTH).expect("four columns share the width"),
        );
        let measured = parts_list(
            &text,
            words,
            Columns::new(
                vec![
                    ColumnWidth::Content,
                    ColumnWidth::Fraction(1.0),
                    ColumnWidth::Content,
                    ColumnWidth::Content,
                ],
                TABLE_WIDTH,
            )
            .expect("three measured columns and one that takes the rest"),
        );

        let fit = |table: &hqf_pdf::layout::Table<'_>| {
            table
                .fit(MARGIN, TOP, TOP - MARGIN, 0)
                .expect("the list is short enough for one page")
                .bottom()
        };
        (fit(&equal), fit(&measured))
    }

    #[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 page is here to show that measuring the narrow columns leaves the
    /// description room it had to wrap for. Names short enough to sit on one
    /// line in the equal table make the two tables the same height, and the
    /// page then shows nothing.
    #[test]
    fn every_language_names_parts_the_equal_columns_have_to_wrap() {
        for (named, words) in WORDS {
            let (equal, measured) = bottoms(words);

            assert!(
                equal < measured,
                "the {} equal columns are no taller than the measured ones, \
                 so no name wraps for want of room",
                named.code()
            );
        }
    }
}