write_filled_in_place.rs

Le fichier Rust de l’exemple « Un formulaire rempli après sa création ». Un formulaire créé avec ses champs vides, puis rempli comme un programme remplit un formulaire reçu, dans une section ajoutée à la fin du fichier : le numéro de client occupe une case par caractère, et le code secret s’affiche en points, ses chiffres n’étant conservés que dans la valeur du champ.

Rust 377 lignes

À quoi sert cet exemple

Quand un programme reçoit un formulaire et y répond, comme une banque qui ouvre un compte ou un assureur qui complète une déclaration de sinistre, il ne doit pas réécrire le fichier reçu : une signature déjà présente en couvre les octets, et une copie archivée doit rester identique. Les réponses sont ajoutées dans une section placée à la fin du fichier, et tout ce qui était déjà écrit reste en place.

Ce que montre cet exemple

  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
//! Writes a small form, then fills it in as a section added to the file, the
//! way a program answers a form it received: the name, the customer number set
//! a character to each box of its comb, and the PIN, drawn as dots.
//!
//! The form is written first, its three fields empty. It is then read back and
//! answered in place: the answers and their appearances are appended to the
//! file as a section of its own, and the bytes written before stay as they
//! were. The fields are set in Helvetica, one of the fonts every reader
//! carries, so each answer is drawn into the file and shows in a reader that
//! draws nothing itself. The PIN is drawn as one dot for each of its digits;
//! the digits are kept in the field's value alone.
//!
//! The title, the sentence and the labels are held in `Words`, once per
//! language, and `HQF_PDF_LANG` picks which set is drawn. The fields' names
//! and the answers are what a program reads and writes, and stand the same in
//! every language.
//!
//! Usage: `cargo run --example write_filled_in_place -- tmp/filled_in_place.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_filled_in_place --
//! tmp/rempli_en_place.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    Document, FieldBorder, FillBaking, Font, FontHandle, IncrementalUpdate, Page, Rgb,
    StandardFont, TextField, 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 example draws its words 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 page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title at the head of the page.
    title: &'static str,
    /// The sentence under the title, saying how the answers came in.
    about: &'static str,
    /// The label beside the name field.
    name: &'static str,
    /// The label beside the customer number field.
    customer: &'static str,
    /// The label beside the PIN field.
    pin: &'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: "Account opening",
    about: "The three answers below were filled in after the form was written, as a section \
            added to the file. The PIN is drawn as dots; its digits are kept in the field's \
            value alone.",
    name: "Full name",
    customer: "Customer number",
    pin: "PIN",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ouverture de compte",
    about: "Le formulaire a d’abord été créé, puis les trois réponses ci-dessous ont été \
            inscrites dans une section ajoutée à la fin du fichier. Le code secret s’affiche \
            sous forme de points\u{a0}; ses chiffres ne figurent que dans la valeur du champ.",
    name: "Nom complet",
    customer: "Numéro de client",
    pin: "Code secret",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Kontoeröffnung",
    about: "Die drei Antworten unten wurden nach dem Schreiben des Formulars eingetragen, \
            in einem an die Datei angehängten Abschnitt. Die PIN erscheint als Punkte; ihre \
            Ziffern stehen nur im Wert des Feldes.",
    name: "Vollständiger Name",
    customer: "Kundennummer",
    pin: "PIN",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Apertura de cuenta",
    about: "Las tres respuestas de abajo se rellenaron después de escribir el formulario, en \
            una sección añadida al archivo. El PIN se muestra como puntos; sus cifras solo \
            constan en el valor del campo.",
    name: "Nombre completo",
    customer: "Número de cliente",
    pin: "PIN",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Apertura del conto",
    about: "Le tre risposte qui sotto sono state compilate dopo la scrittura del modulo, in \
            una sezione aggiunta al file. Il PIN appare come punti; le sue cifre si trovano \
            solo nel valore del campo.",
    name: "Nome e cognome",
    customer: "Numero cliente",
    pin: "Codice PIN",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Abertura de conta",
    about: "As três respostas abaixo foram preenchidas depois de o formulário ter sido \
            escrito, numa secção acrescentada ao ficheiro. O PIN aparece em pontos; os seus \
            algarismos ficam apenas no valor do campo.",
    name: "Nome completo",
    customer: "Número de cliente",
    pin: "Código PIN",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Rekening openen",
    about: "De drie antwoorden hieronder zijn ingevuld nadat het formulier was geschreven, \
            in een sectie die aan het bestand is toegevoegd. De pincode verschijnt als \
            puntjes; de cijfers staan alleen in de waarde van het veld.",
    name: "Volledige naam",
    customer: "Klantnummer",
    pin: "Pincode",
};

/// 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); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// The answers given to the form, by field name, in the order they are given.
const ANSWERS: [(&str, &str); 3] = [
    ("Name", "Ada Lovelace"),
    ("Customer", "HQF-0917"),
    ("Pin", "4271"),
];

/// How many boxes the customer number's comb is divided into: one to each
/// character of the number.
const CUSTOMER_BOXES: u32 = 8;

/// What the PIN is drawn as, once for each of its digits.
const MASK: char = '\u{2022}';

/// The size the words and the answers are set at, in points.
const SIZE: f64 = 11.0;

/// The size of the title, in points.
const TITLE_SIZE: f64 = 18.0;

/// The left edge of the words and of the labels.
const X: f64 = 72.0;

/// The left edge of every field.
const FIELD_X: f64 = 200.0;

/// The width the sentence under the title is broken to.
const TEXT_WIDTH: f64 = 450.0;

/// The colour every field's border is stroked in.
const BORDER: Rgb = Rgb::gray(0.6);

/// The width every field's border is stroked at, in points.
const BORDER_WIDTH: f64 = 0.75;

/// The baseline of the title.
const TITLE_TOP: f64 = 760.0;

/// The top of the sentence under the title.
const ABOUT_TOP: f64 = 735.0;

/// The baseline of the first label; each one after it stands `ROW` lower.
const FIRST_ROW: f64 = 650.0;

/// The room between two labels.
const ROW: f64 = 36.0;

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 path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("filled_in_place")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    let helvetica = doc.add_standard_font(StandardFont::Helvetica);
    doc.add_page(form_page(&font, &helvetica, words)?)?;
    let written = doc.to_bytes()?;

    // The form read back and answered in place: the answers and the appearances
    // drawn for them are appended to the file as a section of their own.
    let mut update = IncrementalUpdate::new(written.clone())?;
    update.set_license(licence::licensed());
    update.set_baking(FillBaking::new().password_mask(MASK));
    let bytes = update.to_filled_bytes(&ANSWERS)?;

    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;
    println!(
        "wrote {path}: {} bytes, the form's own {} and {} added by the answers",
        bytes.len(),
        written.len(),
        bytes.len() - written.len()
    );
    Ok(())
}

/// The form: a title, the sentence under it, and three labelled fields, empty.
fn form_page(
    font: &FontHandle,
    helvetica: &FontHandle,
    words: &Words,
) -> Result<Page, hqf_pdf::Error> {
    let mut content = Content::new();
    let mut page = Page::a4();

    draw(&mut content, font, TITLE_SIZE, TITLE_TOP, words.title)?;
    let about = TextFlow::new(font, SIZE).leading(SIZE * 1.4);
    let lines = about.break_lines(words.about, TEXT_WIDTH);
    content.begin_text();
    about.draw(&mut content, &lines, X, ABOUT_TOP, TEXT_WIDTH)?;
    content.end_text();

    let field = |name: &str, row: f64, width: f64| {
        TextField::new(
            name,
            FIELD_X,
            row - 4.0,
            width,
            SIZE + 8.0,
            helvetica.name(),
            SIZE,
        )
        .border(FieldBorder::solid(BORDER, BORDER_WIDTH))
    };

    let name_row = FIRST_ROW;
    draw(&mut content, font, SIZE, name_row, words.name)?;
    page.fields
        .push(field("Name", name_row, 240.0).tooltip(words.name).into());

    let customer_row = FIRST_ROW - ROW;
    draw(&mut content, font, SIZE, customer_row, words.customer)?;
    page.fields.push(
        field("Customer", customer_row, 160.0)
            .comb(CUSTOMER_BOXES)
            .tooltip(words.customer)
            .into(),
    );

    let pin_row = 2.0f64.mul_add(-ROW, FIRST_ROW);
    draw(&mut content, font, SIZE, pin_row, words.pin)?;
    page.fields.push(
        field("Pin", pin_row, 80.0)
            .password()
            .tooltip(words.pin)
            .into(),
    );

    page.content = content.into_bytes();
    Ok(page)
}

/// Draws `text` on one line at `size`, its baseline at `y`, from the left edge
/// of the words.
fn draw(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    y: f64,
    text: &str,
) -> Result<(), hqf_pdf::Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(X, y)?;
    content.show_glyphs(&font.glyphs(text));
    content.end_text();
    Ok(())
}

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

    use super::{ABOUT_TOP, ANSWERS, CUSTOMER_BOXES, FIRST_ROW, SIZE, TEXT_WIDTH, WORDS};
    use super::{default_font, language};

    /// The lines two languages are allowed to write the same way: "PIN" is the
    /// word for it in English, German and Spanish, and Spanish and Portuguese
    /// name a customer number alike.
    const SPARED: [&str; 2] = ["pin: \"PIN\"", "customer: \"Número de cliente\""];

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

    #[test]
    fn the_sentence_ends_above_the_first_label_in_every_language() {
        let mut doc = Document::new();
        let font = doc.add_font(Font::parse(std::fs::read(default_font()).unwrap()).unwrap());
        let about = TextFlow::new(&font, SIZE).leading(SIZE * 1.4);

        let low: Vec<_> = WORDS
            .iter()
            .map(|(language, words)| {
                let lines = about.break_lines(words.about, TEXT_WIDTH);
                (language, ABOUT_TOP - about.height(&lines))
            })
            .filter(|(_, bottom)| *bottom < 2.0f64.mul_add(SIZE, FIRST_ROW))
            .collect();

        assert!(low.is_empty(), "the sentence runs into the labels: {low:?}");
    }

    #[test]
    fn the_customer_number_fills_its_comb_a_character_to_a_box() {
        let (_, number) = ANSWERS[1];

        assert_eq!(number.chars().count(), CUSTOMER_BOXES as usize);
    }
}