write_self_showing_layers.rs

Die Rust-Datei des Beispiels „Ein Plan, der zeigt, was sich lesen lässt“. Ein Lageplan, dessen Ebenen selbst entscheiden, wann sie erscheinen. Ein breiter Name steht über dem Flurstück, solange der Plan als Ganzes betrachtet wird, die feinen Mauermaße kommen hinzu, sobald er auf das Doppelte vergrößert ist, und der Satz unter dem Plan steht in zwei Sprachen da, von denen die Anzeigesoftware die zeigt, auf die sie eingestellt ist.

Rust 647 Zeilen

Wofür dieses Beispiel da ist

Ein Grundstücksplan wird aus zwei Entfernungen gelesen. Über den Schreibtisch hinweg will jemand wissen, welches Grundstück es ist und wie breit, und das muss auf Armlänge lesbar sein. Am Bildschirm, vergrößert, will der Bauunternehmer die Zahl an jeder Wand — und diese Zahlen sind so klein, dass sie in normaler Größe ein grauer Fleck über der Zeichnung sind. Zeichnet man beides zugleich, ist der Plan im Ganzen überladen und vergrößert grob. Der Satz unter dem Plan hat dasselbe Problem noch einmal: Der Käufer liest Französisch, die Bank Englisch, und zwei Pläne nebeneinander zu führen heißt, zwei Pläne im Gleichklang zu halten.

Was dieses Beispiel zeigt

  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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Draws a land plan whose layers decide for themselves when to be shown.
//!
//! The plot and the house it holds are the page's own ink and are always there.
//! Three kinds of layer sit on top and nobody has to touch reading software's
//! panel for any of them: one wide label stands over the plot while the plan is
//! looked at whole, the fine figures come in once the plan is enlarged twice
//! over, and one layer per language carries the sentence under the plan, so
//! reading software set to French reads French.
//!
//! The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The table of words is also what the language layers are
//! built from: writing one more set of words gives the document one more layer,
//! without a line that draws being touched. The distances are not words — a
//! metre is a metre.
//!
//! The terminal also says that a pair of magnifications none falls between,
//! from the crossover down to nothing, is refused.
//!
//! Usage: `cargo run --example write_self_showing_layers -- tmp/plot.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_self_showing_layers`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Layer, LayerHandle, Magnifications, Page, Rgb};

#[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 page's text begins, in points from the left edge.
const LEFT: f64 = 80.0;

/// The baseline of the first language's sentence under the plan.
const CAPTION_TOP: f64 = 350.0;

/// How far each language's sentence stands under the one before it.
const CAPTION_STEP: f64 = 15.0;

/// The plot: where its lower left corner sits on the page, and how big it is.
const PLOT: (f64, f64, f64, f64) = (LEFT, 380.0, 435.0, 360.0);

/// The house inside the plot, as an inset from the plot's lower left corner and
/// a size of its own.
const HOUSE: (f64, f64, f64, f64) = (60.0, 90.0, 200.0, 170.0);

/// The magnification the wide label gives way to the fine figures at.
///
/// The label is shown below it and the figures from it, so exactly one of the
/// two stands at every magnification.
const CROSSOVER: f64 = 2.0;

/// How many layers watch the magnification.
const SCALED_COUNT: usize = 2;

/// How many lines say how to see all of it.
const SEEING_COUNT: usize = 3;

/// The distances the plan is measured at, each written inside the line it
/// stands for. None of them is language: a metre is a metre.
const PLOT_ALONG: &str = "24.30";
const PLOT_ACROSS: &str = "17.60";
const HOUSE_ALONG: &str = "11.20";
const HOUSE_ACROSS: &str = "8.40";
const SIDE_SETBACK: &str = "3.35";
const FOOT_SETBACK: &str = "5.10";

/// The two sides of the plot, written the way the wide label states them.
const OVERALL: &str = "24.30 m × 17.60 m";

/// The words the page is written in, one set per language.
///
/// The name of the language and the sentence under the plan are the language
/// layer's own: reading software's panel shows the one and the page shows the
/// other, and both stay in their language whatever language the rest of the
/// page is in. Everything else follows the page.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// What stands under it, saying what the page is about.
    intro: &'static str,
    /// What this language is called, which is the name its layer carries in
    /// reading software's panel.
    tongue: &'static str,
    /// The sentence this language's layer carries under the plan.
    caption: &'static str,
    /// What the two layers that watch the magnification are called.
    scaled: [&'static str; SCALED_COUNT],
    /// What the legend says each of them holds.
    holdings: [&'static str; SCALED_COUNT],
    /// The wide label the plot carries while the plan is looked at whole.
    whole: &'static str,
    /// What the legend says about the layers that carry the wording.
    wording: &'static str,
    /// The lines under the legend saying how to see all of it.
    seeing: [&'static str; SEEING_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 {
    title: "A plan that shows what can be read",
    intro: "Every layer here decides for itself, by the magnification and by the language.",
    tongue: "English",
    caption: "Plot 12, Mill Lane — sold with the barn and the well.",
    scaled: ["Whole plot", "Fine figures"],
    holdings: [
        "stands over the plan while it is looked at whole",
        "comes in once the plan is enlarged twice over",
    ],
    whole: "PLOT 12",
    wording: "one layer a language, shown when reading software is set to it",
    seeing: [
        "Enlarge the plan past two hundred per cent: the figures on the walls come in as the",
        "wide label steps back. Set reading software to another language and the sentence",
        "follows.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Un plan qui montre ce qui se lit",
    intro: "Ici, chaque calque décide seul de son affichage, selon l’agrandissement et la langue.",
    tongue: "Français",
    caption: "Parcelle 12, chemin du Moulin — vendue avec la grange et le puits.",
    scaled: ["Parcelle entière", "Cotes fines"],
    holdings: [
        "s’affiche sur le plan tant qu’on le voit en entier",
        "apparaissent dès que le plan est agrandi deux fois",
    ],
    whole: "PARCELLE 12",
    wording: "un calque par langue, affiché quand le logiciel de lecture y est réglé",
    seeing: [
        "Agrandissez le plan au-delà de deux cents pour cent : les cotes apparaissent et",
        "le grand titre s’efface. Réglez le logiciel de lecture sur une autre langue : la phrase",
        "suit.",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Een plattegrond die toont wat leesbaar is",
    intro: "Elke laag beslist hier zelf, naar de vergroting en naar de taal.",
    tongue: "Nederlands",
    caption: "Perceel 12, Mill Lane — verkocht met de schuur en de put.",
    scaled: ["Heel perceel", "Fijne maten"],
    holdings: [
        "staat over de plattegrond zolang die geheel in beeld is",
        "komt tevoorschijn zodra de plattegrond twee keer vergroot is",
    ],
    whole: "PERCEEL 12",
    wording: "één laag per taal, getoond als de leessoftware op die taal staat",
    seeing: [
        "Vergroot de plattegrond voorbij 200\u{a0}%: de maten op de muren komen tevoorschijn",
        "terwijl het brede label wijkt. Zet de leessoftware op een andere taal en de zin",
        "volgt.",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Uma planta que mostra o que se pode ler",
    intro: "Cada camada decide aqui por si, pela ampliação e pela língua.",
    tongue: "Português",
    caption: "Lote 12, Mill Lane — vendido com o celeiro e o poço.",
    scaled: ["Lote inteiro", "Cotas finas"],
    holdings: [
        "fica sobre a planta enquanto é vista inteira",
        "aparece quando a planta é ampliada para o dobro",
    ],
    whole: "LOTE 12",
    wording: "uma camada por língua, visível quando o programa de leitura está nessa língua",
    seeing: [
        "Amplie a planta para lá dos 200\u{a0}%: as cotas nas paredes aparecem enquanto",
        "a etiqueta larga se retira. Ponha o programa de leitura noutra língua e a frase",
        "acompanha.",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Una pianta che mostra ciò che si può leggere",
    intro: "Ogni livello decide qui da sé, secondo l’ingrandimento e secondo la lingua.",
    tongue: "Italiano",
    caption: "Lotto 12, Mill Lane — venduto con il fienile e il pozzo.",
    scaled: ["Lotto intero", "Quote fini"],
    holdings: [
        "sta sopra la pianta mentre la si guarda intera",
        "compare quando la pianta è ingrandita due volte",
    ],
    whole: "LOTTO 12",
    wording: "un livello per lingua, visibile quando il programma di lettura è impostato su di essa",
    seeing: [
        "Ingrandite la pianta oltre il duecento per cento: le quote sui muri compaiono mentre",
        "l’etichetta larga si ritira. Impostate il programma di lettura su un’altra lingua e la frase",
        "segue.",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Un plano que muestra lo que se puede leer",
    intro: "Cada capa decide aquí por sí misma, según el aumento y según el idioma.",
    tongue: "Español",
    caption: "Parcela 12, Mill Lane — se vende con el granero y el pozo.",
    scaled: ["Parcela entera", "Cotas finas"],
    holdings: [
        "está sobre el plano mientras se mira entero",
        "aparece cuando el plano se amplía al doble",
    ],
    whole: "PARCELA 12",
    wording: "una capa por idioma, visible cuando el programa de lectura está en ese idioma",
    seeing: [
        "Amplíe el plano por encima del 200\u{a0}%: las cotas de los muros aparecen cuando",
        "la etiqueta ancha se retira. Ponga el programa de lectura en otro idioma y la frase",
        "le sigue.",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Ein Plan, der zeigt, was sich lesen lässt",
    intro: "Jede Ebene hier entscheidet selbst, nach Vergrößerung und nach Sprache.",
    tongue: "Deutsch",
    caption: "Flurstück 12, Mill Lane — mit Scheune und Brunnen verkauft.",
    scaled: ["Ganzes Flurstück", "Feine Maße"],
    holdings: [
        "steht über dem Plan, solange er als Ganzes betrachtet wird",
        "erscheint, sobald der Plan auf das Doppelte vergrößert ist",
    ],
    whole: "FLURSTÜCK 12",
    wording: "eine Ebene je Sprache, gezeigt, wenn die Lesesoftware darauf eingestellt ist",
    seeing: [
        "Den Plan über 200 Prozent vergrößern: Die Maße an den Wänden erscheinen, und die",
        "breite Beschriftung tritt zurück. Die Lesesoftware auf eine andere Sprache stellen,",
        "und der Satz folgt.",
    ],
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here, and the document gains its layer.
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),
];

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

/// The house, as a place and a size on the page.
const fn house() -> (f64, f64, f64, f64) {
    let (x, y, _, _) = PLOT;
    let (inset_x, inset_y, width, height) = HOUSE;
    (x + inset_x, y + inset_y, width, height)
}

/// Draws the ink the plan always carries: the plot's boundary and the house
/// standing in it.
fn ground(content: &mut Content) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let (hx, hy, hw, hh) = house();
    content.save_state();
    content.set_stroke(Rgb::gray(0.2))?;
    content.set_line_width(1.6)?;
    content.rect(x, y, width, height)?.stroke();
    content.set_fill(Rgb::new(0.9, 0.91, 0.94))?;
    content.set_line_width(1.2)?;
    content.rect(hx, hy, hw, hh)?.fill();
    content.rect(hx, hy, hw, hh)?.stroke();
    content.restore_state();
    Ok(())
}

/// Draws the wide label: what the plot is called and how big it is, in type
/// that reads from across a desk.
fn wide_label(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let middle = x + width / 2.0;
    content.save_state();
    content.set_fill(Rgb::new(0.35, 0.42, 0.55))?;
    let name = font.measure(words.whole, 26.0);
    text(
        content,
        font,
        26.0,
        middle - name / 2.0,
        y + height - 54.0,
        words.whole,
    )?;
    let sizes = font.measure(OVERALL, 12.0);
    text(
        content,
        font,
        12.0,
        middle - sizes / 2.0,
        y + height - 76.0,
        OVERALL,
    )?;
    content.restore_state();
    Ok(())
}

/// Draws the fine figures: the distance each wall and each setback stands for,
/// in type too small to read until the plan is enlarged.
fn fine_figures(content: &mut Content, font: &FontHandle) -> Result<(), hqf_pdf::Error> {
    let (x, y, width, height) = PLOT;
    let (hx, hy, hw, hh) = house();
    let figures = [
        (x + width / 2.0, y + 5.0, PLOT_ALONG),
        (x + 14.0, y + height / 2.0, PLOT_ACROSS),
        (hx + hw / 2.0, hy + 5.0, HOUSE_ALONG),
        (hx + 14.0, hy + hh / 2.0, HOUSE_ACROSS),
        (f64::midpoint(x, hx), hy + hh / 2.0, SIDE_SETBACK),
        (hx + hw / 2.0, f64::midpoint(y, hy), FOOT_SETBACK),
    ];
    content.save_state();
    content.set_fill(Rgb::new(0.2, 0.45, 0.35))?;
    for (at, up, figure) in figures {
        text(
            content,
            font,
            4.5,
            at - font.measure(figure, 4.5) / 2.0,
            up,
            figure,
        )?;
    }
    content.restore_state();
    Ok(())
}

/// Draws the legend under the plan: what each layer holds and when it stands.
fn legend(
    content: &mut Content,
    font: &FontHandle,
    words: &'static Words,
) -> Result<(), hqf_pdf::Error> {
    // The legend starts under the last language's sentence, however many
    // languages there are.
    #[expect(
        clippy::cast_precision_loss,
        reason = "the languages of the examples are counted on one hand"
    )]
    let mut baseline = (WORDS.len() as f64).mul_add(-CAPTION_STEP, CAPTION_TOP) - 10.0;
    for (name, what) in words.scaled.into_iter().zip(words.holdings) {
        text(content, font, 10.0, LEFT, baseline, name)?;
        content.save_state();
        content.set_fill(Rgb::gray(0.35))?;
        text(content, font, 10.0, LEFT + 110.0, baseline, what)?;
        content.restore_state();
        baseline -= 18.0;
    }

    let tongues: Vec<&str> = WORDS.iter().map(|(_, words)| words.tongue).collect();
    text(content, font, 10.0, LEFT, baseline, &tongues.join(" · "))?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(content, font, 10.0, LEFT, baseline - 14.0, words.wording)?;
    for (rank, line) in words.seeing.into_iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "three lines are counted, and three is exact in an f64"
        )]
        let step = rank as f64 * 14.0;
        text(content, font, 10.0, LEFT, baseline - 46.0 - step, line)?;
    }
    content.restore_state();
    Ok(())
}

/// Draws `body` inside `layer`, so reading software shows and hides all of it
/// at once.
fn on_layer<F>(content: &mut Content, layer: &LayerHandle, body: F) -> Result<(), hqf_pdf::Error>
where
    F: FnOnce(&mut Content) -> Result<(), hqf_pdf::Error>,
{
    content.begin_layer(layer);
    body(content)?;
    content.end_marked();
    Ok(())
}

/// The document the example writes, in `words`, drawn with the font at
/// `font_path`.
///
/// # Errors
///
/// Returns whatever reading the font, adding a layer or drawing hands back.
fn build(
    language: Language,
    words: &'static Words,
    font_path: &Path,
) -> Result<Document, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(font_path)?)?);

    let wide = doc.add_layer(Layer::new(words.scaled[0]).zoom(0.0, CROSSOVER))?;
    // The pair is judged here, before the layer is built on it.
    let enlarged = Magnifications::new(CROSSOVER, f64::INFINITY)?;
    let fine = doc.add_layer(Layer::new(words.scaled[1]).zoom(enlarged.min(), enlarged.max()))?;
    // One layer a language, built from the same table the page is written from.
    // The one the page itself is in is the one reading software falls back on
    // when is set to a language no layer states.
    let mut spoken = Vec::with_capacity(WORDS.len());
    for (named, said) in WORDS {
        let layer = Layer::new(said.tongue);
        let layer = if named == language {
            layer.preferred_language(named.code())
        } else {
            layer.language(named.code())
        };
        spoken.push((doc.add_layer(layer)?, said));
    }

    let mut content = Content::new();
    text(&mut content, &font, 15.0, LEFT, 790.0, words.title)?;
    content.save_state();
    content.set_fill(Rgb::gray(0.35))?;
    text(&mut content, &font, 10.0, LEFT, 770.0, words.intro)?;
    content.restore_state();

    ground(&mut content)?;
    on_layer(&mut content, &wide, |content| {
        wide_label(content, &font, words)
    })?;
    on_layer(&mut content, &fine, |content| fine_figures(content, &font))?;
    // Every language's sentence stands on a line of its own, so reading
    // software that states no language of its own reads them one under the
    // other rather than one over the other.
    for (rank, (layer, said)) in spoken.iter().enumerate() {
        #[expect(
            clippy::cast_precision_loss,
            reason = "the languages of the examples are counted on one hand"
        )]
        let step = rank as f64 * CAPTION_STEP;
        on_layer(&mut content, layer, |content| {
            text(content, &font, 10.0, LEFT, CAPTION_TOP - step, said.caption)
        })?;
    }
    legend(&mut content, &font, words)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;
    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("plot")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let doc = build(language, words, &font_path)?;
    let layers = SCALED_COUNT + WORDS.len();

    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, {layers} layers", bytes.len());
    let refused = Magnifications::new(CROSSOVER, 0.0).is_err();
    println!(
        "a layer shown from {CROSSOVER:.1} and below 0.0 is refused: {}",
        if refused { "yes" } else { "no" }
    );
    Ok(())
}

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

    use super::{LEFT, WORDS, Words, build, default_font, language};

    /// The room a line of the legend has: the page less the margin either side.
    const ROOM: f64 = 595.0 - 2.0 * LEFT;

    /// The test font, added to a document so that lines can be measured 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)
    }

    /// The lines two languages are allowed to write the same way.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""Cotas finas""#,
    ];

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

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

    /// Every line the page sets on one line stays on one line: one that wrapped
    /// would run off the right edge, since nothing here is flowed.
    #[test]
    fn every_line_of_the_page_fits_the_page() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, 10.0);

        for (named, words) in WORDS {
            let Words {
                intro,
                caption,
                wording,
                seeing,
                ..
            } = words;
            let mut lines = vec![*intro, *caption, *wording];
            lines.extend(seeing);
            for line in lines {
                assert_eq!(
                    flow.break_lines(line, ROOM).len(),
                    1,
                    "the {} line {line:?} does not fit the page",
                    named.code()
                );
            }
        }
    }

    /// What the legend says a layer holds stands in the column beside the
    /// layer's name, and the two must not run into each other.
    #[test]
    fn every_holding_fits_the_column_it_stands_in() {
        let (_doc, handle) = handle();
        let flow = TextFlow::new(&handle, 10.0);
        let room = ROOM - 110.0;

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

    /// The point of the page: the two layers that watch the magnification meet
    /// without overlapping, and every language of the table has a layer of its
    /// own that reading software is told the language of.
    #[test]
    fn every_layer_states_when_it_shows_itself() {
        for (named, words) in WORDS {
            let mut doc = build(named, words, &default_font()).expect("the document builds");
            doc.set_compression(false);
            let pdf =
                String::from_utf8_lossy(&doc.to_bytes().expect("the document writes")).into_owned();

            assert!(pdf.contains("/max 2"), "the wide label gives way at two");
            assert!(pdf.contains("/min 2"), "the fine figures come in at two");
            for (spoken, _) in WORDS {
                assert!(
                    pdf.contains(&format!("({})", spoken.code())),
                    "no layer states {}",
                    spoken.code()
                );
            }
            assert_eq!(
                pdf.matches("/Preferred /ON").count(),
                1,
                "one language is fallen back on, and one only"
            );
            // Reading software settles all of it by itself, so every one of the
            // four stands under the viewing event of the configuration.
            assert!(pdf.contains("/AS ["), "the configuration lists the events");
        }
    }
}