Tabulations and their stops

The same tabulated rows under each of the three methods, then a contents block whose dots run out to a stop on the right. A tabulation can step on from wherever the text stopped, land on the regular grid of a typewriter, or aim at a stop of its own, on which the text that follows starts, centres, or lines up by its decimal point.

Rust write_tab_stops.rs 392 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
//! Sets the same tabulated text under each of the three tab methods, then a
//! table of contents whose dots run out to a right-hand stop, so what each
//! method does to a column can be read off the page.
//!
//! A grey rule is drawn at every stop the block was told to use, so the runs
//! can be seen landing on them. The relative method steps the pen on from
//! wherever it stands, so its columns never line up; the typewriter method
//! steps to the next multiple of the tab size, so they do; a ruler sends each
//! tabulation to a stop of its own and sets the run on it, centred over it, or
//! lined up on its decimal point.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is labelled in. The step the typewriter panel works in is
//! not one of them: its label is set around the very number the panel is given,
//! so no language can announce a grid the page does not land on.
//!
//! Usage: `cargo run --example write_tab_stops -- tmp/tab_stops.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_tab_stops --
//! tmp/tabulations.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Page, TabAlign, TabMethod, TabSize, 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 left edge every panel is set from.
const X: f64 = 80.0;

/// The room every panel has to fill.
const COLUMN: f64 = 430.0;

/// The distance from a panel's heading down to the block below it.
const DROP: f64 = 20.0;

/// The reference, the quantity and the unit price of each row the first three
/// panels set. What each row is a category of is a word, and stands in
/// [`Words`] under the same order.
const ROWS: [[&str; 3]; 3] = [
    ["A-1180", "12", "18.50"],
    ["B-2050", "4", "7.05"],
    ["C-9004", "120", "1 250.00"],
];

/// The page each entry of the table of contents is on.
const PAGES: [&str; 5] = ["7", "18", "34", "61", "112"];

/// The step the typewriter panel works in, which is the grid its columns land
/// on and the number its label spells out.
const GRID: f64 = 96.0;

/// How much of a line one tabulation opens when a flow is told nothing, as the
/// first panel's label spells it out.
const SHARE: &str = "7.5%";

/// The stops the ruler panel sends its three tabulations to.
const RULER: [f64; 3] = [130.0, 260.0, 380.0];

/// The words the page is labelled in, one set per language.
#[derive(Debug)]
struct Words {
    /// The label over the relative panel, set around the share of a line one
    /// tabulation opens under the default.
    relative: [&'static str; 2],
    /// The label over the typewriter panel, set around the step it works in.
    typewriter: [&'static str; 2],
    /// The label over the ruler panel.
    ruler: &'static str,
    /// The label over the table of contents.
    listing: &'static str,
    /// What each of the four columns is called.
    columns: [&'static str; 4],
    /// What each row of [`ROWS`] is a category of.
    categories: [&'static str; 3],
    /// The entries of the table of contents, each set on the page [`PAGES`]
    /// gives it.
    contents: [&'static str; 5],
}

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

    /// The label over the relative panel, around the share it opens.
    fn relative_label(&self) -> String {
        format!("{}{SHARE}{}", self.relative[0], self.relative[1])
    }

    /// The label over the typewriter panel, around the step it works in.
    fn typewriter_label(&self) -> String {
        format!("{}{GRID}{}", self.typewriter[0], self.typewriter[1])
    }

    /// The four columns the first three panels set, a tabulation between each
    /// pair and a heading over them.
    fn rows(&self) -> String {
        let mut lines = vec![self.columns.join("\t")];
        for (row, category) in ROWS.iter().zip(self.categories) {
            lines.push(format!("{}\t{category}\t{}\t{}", row[0], row[1], row[2]));
        }
        lines.join("\n")
    }

    /// The table of contents, each entry with its page number behind a
    /// tabulation.
    fn contents(&self) -> String {
        self.contents
            .iter()
            .zip(PAGES)
            .map(|(entry, page)| format!("{entry}\t{page}"))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    relative: [
        "Relative, the default: each tabulation steps the pen on by ",
        " of the column from where it stands, so the rows do not line up.",
    ],
    typewriter: [
        "Typewriter: each tabulation lands on the next multiple of ",
        " points, so the rows line up on that grid.",
    ],
    ruler: "Ruler: a stop of its own for each tabulation, the second centred on it and the third \
            lined up on its decimal point, the heading, which carries none, ending on the stop.",
    listing: "A ruler stop at the far edge, the run ending on it and the leader filling the room \
              the tabulation opened.",
    columns: ["Reference", "Category", "Quantity", "Unit price"],
    categories: ["Binding", "Cover", "Paper"],
    contents: [
        "Getting started",
        "The page model",
        "Fonts and the text engine",
        "Tables and their columns",
        "Digital signatures",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    relative: [
        "Relative, par défaut : chaque tabulation avance la plume de ",
        " de la colonne depuis où elle est, donc les lignes ne s'alignent pas.",
    ],
    typewriter: [
        "Machine à écrire : chaque tabulation tombe sur le multiple suivant de ",
        " points, donc les lignes s'alignent sur cette grille.",
    ],
    ruler: "Règle : un taquet par tabulation, le deuxième centré dessus et le troisième aligné sur \
            son point décimal, l'en-tête, qui n'en porte pas, finissant sur le taquet.",
    listing: "Un taquet de règle au bord, la course finissant dessus et les points de conduite \
              remplissant la place que la tabulation a ouverte.",
    columns: ["Référence", "Catégorie", "Quantité", "Prix unitaire"],
    categories: ["Reliure", "Couverture", "Papier"],
    contents: [
        "Pour commencer",
        "Le modèle de page",
        "Les polices et le moteur de texte",
        "Les tableaux et leurs colonnes",
        "Les signatures numériques",
    ],
};

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

/// Draws one panel: its heading, the tabulated block below it, and a grey rule
/// at every stop the block was told to use.
fn panel(
    c: &mut Content,
    handle: &FontHandle,
    top: f64,
    label: &str,
    flow: &TextFlow<'_>,
    text: &str,
    stops: &[f64],
) -> Result<(), Box<dyn std::error::Error>> {
    let heading = TextFlow::new(handle, 8.0);
    let heading_lines = heading.break_lines(label, COLUMN);
    c.begin_text();
    heading.draw(c, &heading_lines, X, top, COLUMN)?;
    c.end_text();

    let text_top = top - DROP;
    let lines = flow.break_lines(text, COLUMN);
    let height = flow.height(&lines);

    // The stops first, so the text is read over them rather than under them.
    c.save_state();
    c.set_stroke_rgb(0.78, 0.78, 0.82)?.set_line_width(0.5)?;
    for stop in stops {
        c.move_to(X + stop, text_top)?
            .line_to(X + stop, text_top - height)?
            .stroke();
    }
    c.restore_state();

    c.begin_text();
    flow.draw(c, &lines, X, text_top, COLUMN)?;
    c.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("tab_stops")));
    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 mut c = Content::new();
    let rows = words.rows();

    // Relative, which is what a flow does when it is told nothing: every
    // tabulation steps the pen on by the tab size from wherever it stands, so a
    // longer entry pushes the whole row along with it.
    let relative = TextFlow::new(&handle, 11.0).leading(16.0);
    panel(
        &mut c,
        &handle,
        780.0,
        &words.relative_label(),
        &relative,
        &rows,
        &[],
    )?;

    // A typewriter's tab bar: every tabulation lands on the next multiple of
    // the tab size, so the rows line up on a grid however wide their entries
    // are.
    let typewriter = TextFlow::new(&handle, 11.0)
        .leading(16.0)
        .tab_method(TabMethod::Typewriter)
        .tab_size(TabSize::Points(GRID));
    panel(
        &mut c,
        &handle,
        660.0,
        &words.typewriter_label(),
        &typewriter,
        &rows,
        &[GRID, GRID * 2.0, GRID * 3.0, GRID * 4.0],
    )?;

    // A ruler names its stops, and each one says how the run it opens sits
    // about it: the quantities are centred, the prices line up on their decimal
    // point.
    let ruler = TextFlow::new(&handle, 11.0)
        .leading(16.0)
        .tab_method(TabMethod::Ruler)
        .tab_ruler(RULER)
        .tab_alignments([TabAlign::Left, TabAlign::Center, TabAlign::Decimal]);
    panel(&mut c, &handle, 540.0, words.ruler, &ruler, &rows, &RULER)?;

    // The stop sits at the far edge and the run ends on it, so the numbers are
    // flush right whatever they are worth, and the leader fills the room the
    // tabulation opened.
    let contents = TextFlow::new(&handle, 11.0)
        .leading(16.0)
        .tab_method(TabMethod::Ruler)
        .tab_ruler([COLUMN])
        .tab_alignments([TabAlign::Right])
        .leader('.');
    panel(
        &mut c,
        &handle,
        420.0,
        words.listing,
        &contents,
        &words.contents(),
        &[COLUMN],
    )?;

    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, TabSize};

    use super::{RULER, SHARE, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line in
    /// `Words` is a label, a column heading, a category or a chapter title, and
    /// no two languages write one alike; the references, the figures and the
    /// page numbers are not in `Words` at all.
    const SPARED: [&str; 0] = [];

    /// The size the tabulated blocks are set at.
    const BODY: f64 = 11.0;

    #[test]
    fn every_language_labels_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 ruler panel sends each tabulation to a stop of its own, and a run
    /// wider than the gap to the next stop runs over what lands there. The
    /// headings are the widest thing in each column, so they are what has to
    /// fit.
    #[test]
    fn every_language_writes_headings_that_fit_between_the_stops() {
        let mut doc = Document::new();
        let text = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        let gaps = [
            RULER[0],
            RULER[1] - RULER[0],
            RULER[2] - RULER[1],
            RULER[2] - RULER[1],
        ];

        for (named, words) in WORDS {
            let code = named.code();
            for (heading, gap) in words.columns.iter().zip(gaps) {
                let measured = text.measure(heading, BODY);
                assert!(
                    measured < gap,
                    "the {code} page sets {heading:?} over {measured:.1} points, \
                     and the column it heads is {gap:.1} wide"
                );
            }
        }
    }

    /// The first panel's label spells out the share of a line one tabulation
    /// opens when a flow is told nothing. No language works it out from the
    /// page, so a library that stepped by another share would leave every one
    /// of them saying a number the panel no longer shows.
    #[test]
    fn the_first_panel_names_the_share_a_flow_takes_when_it_is_told_nothing() {
        let TabSize::Fraction(share) = TabSize::default() else {
            panic!("a flow told nothing steps by a share of the line, not by a distance")
        };
        assert_eq!(format!("{}%", share * 100.0), SHARE);
    }
}