write_paragraphs.rs

Die Rust-Datei des Beispiels „Absatzeinzüge und -abstände“. Dieselben zwei Absätze auf sechs Arten: wie sie kommen, eine eingerückte erste Zeile, eine herausgerückte erste Zeile, der Raum darüber und darunter, ein Blocksatzblock, dessen letzte Zeile zentriert ist, und wo die erste und die letzte Zeile in ihrem Rechteck sitzen. Eine zweite Seite setzt sie auf vier weitere Arten: zwei andere Regeln für die erste und letzte Zeile, nur umrandete Buchstaben und durch eine Linie darum verstärkte Buchstaben.

Rust 584 Zeilen

Wofür dieses Beispiel da ist

Was eine professionell wirkende Seite von einer anderen unterscheidet, ist selten die Schrift. Es ist der Raum um die Absätze: wie weit die erste Zeile eingerückt ist, wie viel Luft zwischen zwei Blöcken liegt, ob der linke Rand einer Liste hängt oder bündig steht. Dieselben zwei Absätze sind hier zehnmal gesetzt, über zwei Seiten, sodass sich die Wirkung jeder dieser Zahlen einzeln sehen lässt.

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
//! Sets the same two paragraphs six ways, one shape to a block: indents, the
//! room around a paragraph, the alignment of its last line, and where its first
//! baseline sits. Under them, one sentence is placed three times in a box
//! taller than it: against the box's top, centred in it, and against its
//! bottom, where [`TextFlow::top_for`] says the block starts.
//!
//! A second page sets the same paragraphs four more ways: the first baseline an
//! ascender down and the block ending on its last baseline, both baselines at
//! distances of their own, the letters outlined and left hollow, and the
//! letters filled and outlined over to thicken them.
//!
//! The paragraphs and the heading over each block are written in the language
//! `HQF_PDF_LANG` names: what a shape does to a paragraph is only visible on a
//! paragraph somebody can read.
//!
//! Usage: `cargo run --example write_paragraphs -- tmp/paragraphs.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_paragraphs`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{Align, FirstBaseline, LastBaseline, VAlign};
use hqf_pdf::{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 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 width of a block, and the gap between the two columns of them.
const COLUMN: f64 = 225.0;
/// The left edge of the two columns.
const LEFT: [f64; 2] = [60.0, 310.0];
/// The top of the first block of each column.
const TOP: f64 = 780.0;
/// How far apart the blocks of a column are stacked.
const STEP: f64 = 190.0;

/// The body size every block is set at, and the leading it is set on.
const SIZE: f64 = 10.0;
const LEADING: f64 = 13.0;

/// The size a block's heading is set at, and the leading it is set on.
const HEADING: f64 = 7.5;
const HEADING_LEADING: f64 = 9.5;

/// How far under its heading the text of a block starts.
const HEADING_GAP: f64 = 8.0;

/// The top of the three boxes a sentence is placed in, their width, the gap
/// between two of them, and their height.
const PLACED_TOP: f64 = 200.0;
const PLACED_WIDTH: f64 = 145.0;
const PLACED_GAP: f64 = 20.0;
const PLACED_HEIGHT: f64 = 90.0;

/// Where the sentence sits in each of the three boxes, from the left.
const PLACES: [VAlign; 3] = [VAlign::Top, VAlign::Middle, VAlign::Bottom];

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// Two paragraphs, so that every block shows both what happens inside one
    /// and what happens between two.
    text: &'static str,
    /// What each block is headed by, in the order they are set.
    headings: [&'static str; 6],
    /// What each block of the second page is headed by, in the order they are
    /// set.
    more_headings: [&'static str; 4],
    /// The sentence placed in the three boxes.
    placed: &'static str,
    /// What each of the three boxes is headed by, from the left.
    places: [&'static str; 3],
}

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 {
    text: "The deposit is held on the account named overleaf and is returned \
within thirty days of the keys being handed back.\nDeductions are itemised in \
writing, and anything not itemised is not deducted.",
    headings: [
        "Nothing set: the shape a flow has by default.",
        "First line indented; the paragraphs are told apart by that alone.",
        "First line hung out to the left of the block.",
        "Room left above and below each paragraph.",
        "Justified, with the last line of each paragraph centred.",
        "First baseline on the top of the capitals, last line clear of its \
         descenders.",
    ],
    more_headings: [
        "First baseline one ascender down; the block ends on its last baseline.",
        "First baseline 18 points down, and 9 points kept under the last.",
        "Letters outlined in a hairline and left hollow.",
        "Letters filled, and outlined over to thicken them.",
    ],
    placed: "Keys are handed back at the office, against a signed receipt.",
    places: [
        "Against the top of its box.",
        "Centred in its box.",
        "Against the bottom of its box.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    text: "Le dépôt de garantie est conservé sur le compte indiqué au verso et restitué \
dans les trente jours qui suivent la remise des clés.\nToute retenue est \
détaillée par écrit, et ce qui n’est pas détaillé n’est pas retenu.",
    headings: [
        "Rien de réglé : la forme qu’un bloc prend par défaut.",
        "Première ligne en retrait ; c’est le seul signe qui sépare les paragraphes.",
        "Première ligne débordant à gauche du bloc.",
        "De l’air laissé au-dessus et au-dessous de chaque paragraphe.",
        "Justifié, la dernière ligne de chaque paragraphe centrée.",
        "Première ligne de base sur le haut des capitales, dernière ligne \
         dégagée de ses jambages.",
    ],
    more_headings: [
        "Première ligne de base à une hauteur d’ascendante du haut ; le bloc finit sur \
sa dernière ligne de base.",
        "Première ligne de base à 18 points du haut, et 9 points gardés sous la \
         dernière.",
        "Lettres tracées d’un filet fin et laissées creuses.",
        "Lettres pleines, cernées d’un trait qui les épaissit.",
    ],
    placed: "Les clés sont rendues à l’agence, contre un reçu signé.",
    places: [
        "Contre le haut de sa boîte.",
        "Centré dans sa boîte.",
        "Contre le bas de sa boîte.",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    text: "De borg staat op de rekening op de achterzijde en wordt binnen dertig dagen na teruggave van de sleutels terugbetaald.\nInhoudingen worden schriftelijk gespecificeerd, en wat niet gespecificeerd is, wordt niet ingehouden.",
    headings: [
        "Niets ingesteld: de vorm die een tekst standaard heeft.",
        "Eerste regel ingesprongen; de alinea’s zijn alleen daaraan te onderscheiden.",
        "Eerste regel links buiten het blok hangend.",
        "Ruimte boven en onder elke alinea.",
        "Uitgevuld, met de laatste regel van elke alinea gecentreerd.",
        "Eerste basislijn tegen de bovenkant van de hoofdletters, laatste regel vrij van zijn onderstokken.",
    ],
    more_headings: [
        "Eerste basislijn één stok omlaag; het blok eindigt op zijn laatste basislijn.",
        "Eerste basislijn 18 punten omlaag, en 9 punten vrijgehouden onder de laatste.",
        "Letters omlijnd met een haarlijn en hol gelaten.",
        "Letters gevuld, en erover omlijnd om ze dikker te maken.",
    ],
    placed: "Sleutels worden op kantoor teruggegeven, tegen een getekend ontvangstbewijs.",
    places: [
        "Tegen de bovenkant van zijn kader.",
        "Gecentreerd in zijn kader.",
        "Tegen de onderkant van zijn kader.",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    text: "A caução fica na conta indicada no verso e é devolvida nos trinta dias seguintes à entrega das chaves.\nAs deduções são discriminadas por escrito, e o que não for discriminado não é deduzido.",
    headings: [
        "Nada definido: a forma que um texto tem por omissão.",
        "Primeira linha avançada; os parágrafos distinguem-se só por isso.",
        "Primeira linha pendurada à esquerda do bloco.",
        "Espaço acima e abaixo de cada parágrafo.",
        "Justificado, com a última linha de cada parágrafo centrada.",
        "Primeira linha de base no topo das maiúsculas, última linha livre das descendentes.",
    ],
    more_headings: [
        "Primeira linha de base um ascendente abaixo; o bloco acaba na sua última linha de base.",
        "Primeira linha de base 18 pontos abaixo, e 9 pontos guardados sob a última.",
        "Letras contornadas por um filete e deixadas ocas.",
        "Letras preenchidas, e contornadas por cima para as engrossar.",
    ],
    placed: "As chaves entregam-se no escritório, contra recibo assinado.",
    places: [
        "Encostado ao topo da sua caixa.",
        "Centrado na sua caixa.",
        "Encostado ao fundo da sua caixa.",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    text: "Il deposito cauzionale è tenuto sul conto indicato sul retro ed è restituito entro trenta giorni dalla riconsegna delle chiavi.\nLe detrazioni sono elencate per iscritto, e ciò che non è elencato non è detratto.",
    headings: [
        "Nessuna impostazione: la forma predefinita di un testo.",
        "Prima riga rientrata; i paragrafi si distinguono solo per questo.",
        "Prima riga sporgente a sinistra del blocco.",
        "Spazio sopra e sotto ogni paragrafo.",
        "Giustificato, con l’ultima riga di ogni paragrafo centrata.",
        "Prima linea di base in cima alle maiuscole, ultima riga libera dai discendenti.",
    ],
    more_headings: [
        "Prima linea di base un ascendente più in basso; il blocco finisce sulla sua ultima linea di base.",
        "Prima linea di base 18 punti più in basso, e 9 punti tenuti sotto l’ultima.",
        "Lettere contornate da un filetto e lasciate vuote.",
        "Lettere piene, e contornate sopra per ispessirle.",
    ],
    placed: "Le chiavi si riconsegnano in ufficio, contro ricevuta firmata.",
    places: [
        "Contro il bordo superiore del suo riquadro.",
        "Centrato nel suo riquadro.",
        "Contro il bordo inferiore del suo riquadro.",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    text: "La fianza se guarda en la cuenta indicada al dorso y se devuelve en los treinta días siguientes a la entrega de las llaves.\nLas deducciones se detallan por escrito, y lo que no se detalla no se deduce.",
    headings: [
        "Nada ajustado: la forma que tiene un texto por defecto.",
        "Primera línea sangrada; los párrafos se distinguen solo por eso.",
        "Primera línea colgada a la izquierda del bloque.",
        "Espacio encima y debajo de cada párrafo.",
        "Justificado, con la última línea de cada párrafo centrada.",
        "Primera línea base en lo alto de las mayúsculas, última línea libre de sus descendentes.",
    ],
    more_headings: [
        "Primera línea base un ascendente más abajo; el bloque acaba en su última línea base.",
        "Primera línea base 18 puntos más abajo, y 9 puntos guardados bajo la última.",
        "Letras contorneadas con un filete y dejadas huecas.",
        "Letras rellenas, y contorneadas encima para engrosarlas.",
    ],
    placed: "Las llaves se devuelven en la oficina, contra un recibo firmado.",
    places: [
        "Contra el borde superior de su caja.",
        "Centrado en su caja.",
        "Contra el borde inferior de su caja.",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    text: "Die Kaution liegt auf dem umseitig genannten Konto und wird binnen dreißig Tagen nach Rückgabe der Schlüssel erstattet.\nAbzüge werden schriftlich einzeln aufgeführt, und was nicht aufgeführt ist, wird nicht abgezogen.",
    headings: [
        "Nichts eingestellt: die Form, die ein Textfluss standardmäßig hat.",
        "Erste Zeile eingerückt; allein daran unterscheiden sich die Absätze.",
        "Erste Zeile links aus dem Block herausgehängt.",
        "Raum über und unter jedem Absatz.",
        "Blocksatz, die letzte Zeile jedes Absatzes zentriert.",
        "Erste Grundlinie auf Versalhöhe, letzte Zeile frei von ihren Unterlängen.",
    ],
    more_headings: [
        "Erste Grundlinie eine Oberlänge tiefer; der Block endet auf seiner letzten Grundlinie.",
        "Erste Grundlinie 18 Punkt tiefer, und 9 Punkt unter der letzten freigehalten.",
        "Buchstaben mit Haarlinie umrandet und hohl gelassen.",
        "Buchstaben gefüllt und darüber umrandet, um sie zu verstärken.",
    ],
    placed: "Schlüssel werden im Büro gegen Quittung zurückgegeben.",
    places: [
        "An der Oberkante seines Rahmens.",
        "In seinem Rahmen zentriert.",
        "An der Unterkante seines Rahmens.",
    ],
};

/// 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 six blocks: what each is headed by, and the shape it sets the two
/// paragraphs in.
fn blocks<'a>(handle: &'a FontHandle, words: &'static Words) -> [(&'static str, TextFlow<'a>); 6] {
    let plain = TextFlow::new(handle, SIZE).leading(LEADING);
    [
        (words.headings[0], plain.clone()),
        (words.headings[1], plain.clone().first_line_indent(18.0)),
        (
            words.headings[2],
            plain.clone().left_indent(24.0).first_line_indent(-24.0),
        ),
        (
            words.headings[3],
            plain.clone().space_before(4.0).space_after(8.0),
        ),
        (
            words.headings[4],
            plain
                .clone()
                .align(Align::Justify)
                .last_align(Align::Center)
                .right_indent(12.0),
        ),
        (
            words.headings[5],
            plain
                .clone()
                .first_baseline(FirstBaseline::CapHeight)
                .last_baseline(LastBaseline::Descender),
        ),
    ]
}

/// The four blocks of the second page: what each is headed by, and the shape it
/// sets the two paragraphs in.
fn more_blocks<'a>(
    handle: &'a FontHandle,
    words: &'static Words,
) -> [(&'static str, TextFlow<'a>); 4] {
    let plain = TextFlow::new(handle, SIZE).leading(LEADING);
    [
        (
            words.more_headings[0],
            plain
                .clone()
                .first_baseline(FirstBaseline::Ascender)
                .last_baseline(LastBaseline::None),
        ),
        (
            words.more_headings[1],
            plain
                .clone()
                .first_baseline(FirstBaseline::Points(18.0))
                .last_baseline(LastBaseline::Points(9.0)),
        ),
        (
            words.more_headings[2],
            plain.clone().outline(0.4, Rgb::new(0.0, 0.25, 0.55)),
        ),
        (
            words.more_headings[3],
            plain.filled_outline(0.5, Rgb::gray(0.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 out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("paragraphs")));
    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();
    for (index, (label, flow)) in blocks(&handle, words).iter().enumerate() {
        let x = LEFT[index / 3];
        let top = STEP.mul_add(-count(index % 3), TOP);
        block(&mut c, &handle, flow, x, top, label, words.text)?;
    }
    for (index, (label, align)) in words.places.iter().zip(PLACES).enumerate() {
        let x = (PLACED_WIDTH + PLACED_GAP).mul_add(count(index), LEFT[0]);
        placed(&mut c, &handle, x, label, align, words.placed)?;
    }

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

    let mut c = Content::new();
    for (index, (label, flow)) in more_blocks(&handle, words).iter().enumerate() {
        let x = LEFT[index / 2];
        let top = STEP.mul_add(-count(index % 2), TOP);
        block(&mut c, &handle, flow, x, top, label, words.text)?;
    }
    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(())
}

/// Converts a block count to a float. Six blocks never approach the point where
/// a `usize` loses precision as an `f64`.
#[expect(
    clippy::cast_precision_loss,
    reason = "a block index is far below f64's exact-integer range"
)]
const fn count(n: usize) -> f64 {
    n as f64
}

/// Sets one block: its heading, the text under it, and the box the flow says it
/// fills.
fn block(
    c: &mut Content,
    handle: &FontHandle,
    flow: &TextFlow<'_>,
    x: f64,
    top: f64,
    label: &str,
    text: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let heading = TextFlow::new(handle, HEADING)
        .leading(HEADING_LEADING)
        .color(Rgb::gray(0.35));
    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 - heading.height(&heading_lines) - HEADING_GAP;
    let lines = flow.break_lines(text, COLUMN);
    c.begin_text();
    flow.draw(c, &lines, x, text_top, COLUMN)?;
    c.end_text();

    // The box the flow reports filling, so that the room it keeps around a
    // paragraph is visible and not merely stated.
    let height = flow.height(&lines);
    c.save_state();
    c.set_stroke_rgb(0.8, 0.8, 0.8)?
        .set_line_width(0.5)?
        .rect(x, text_top - height, COLUMN, height)?
        .stroke();
    c.restore_state();
    Ok(())
}

/// Sets one of the three boxes: its heading, its outline, and the sentence
/// placed in it as `align` says.
fn placed(
    c: &mut Content,
    handle: &FontHandle,
    x: f64,
    label: &str,
    align: VAlign,
    text: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let heading = TextFlow::new(handle, HEADING)
        .leading(HEADING_LEADING)
        .color(Rgb::gray(0.35));
    let heading_lines = heading.break_lines(label, PLACED_WIDTH);
    c.begin_text();
    heading.draw(c, &heading_lines, x, PLACED_TOP, PLACED_WIDTH)?;
    c.end_text();

    let box_top = PLACED_TOP - heading.height(&heading_lines) - HEADING_GAP;
    c.save_state();
    c.set_stroke_rgb(0.8, 0.8, 0.8)?
        .set_line_width(0.5)?
        .rect(x, box_top - PLACED_HEIGHT, PLACED_WIDTH, PLACED_HEIGHT)?
        .stroke();
    c.restore_state();

    let flow = TextFlow::new(handle, SIZE).leading(LEADING);
    let lines = flow.break_lines(text, PLACED_WIDTH);
    let top = flow.top_for(&lines, box_top, PLACED_HEIGHT, align);
    c.begin_text();
    flow.draw(c, &lines, x, top, PLACED_WIDTH)?;
    c.end_text();
    Ok(())
}

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

    use super::{
        COLUMN, HEADING, HEADING_GAP, HEADING_LEADING, LEADING, PLACED_HEIGHT, PLACED_WIDTH, SIZE,
        STEP, WORDS, blocks, default_font, language, more_blocks,
    };

    /// The lines two languages are allowed to write the same way. There are
    /// none: the two paragraphs and all six headings are words a person reads.
    const SPARED: [&str; 0] = [];

    #[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 blocks are stacked a fixed step apart, and nothing stops a block
    /// from running into the one below it: a language whose paragraphs take one
    /// line more would set the two on top of each other, and the page would
    /// show what a shape does to a paragraph over the top of another paragraph.
    #[test]
    fn no_block_reaches_the_one_stacked_under_it() {
        let mut doc = Document::new();
        let handle = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            let heading = TextFlow::new(&handle, HEADING)
                .leading(HEADING_LEADING)
                .color(Rgb::gray(0.35));

            let every = blocks(&handle, words)
                .into_iter()
                .chain(more_blocks(&handle, words));
            for (label, flow) in every {
                let heading_lines = heading.break_lines(label, COLUMN);
                let lines = flow.break_lines(words.text, COLUMN);
                let height = heading.height(&heading_lines) + HEADING_GAP + flow.height(&lines);

                assert!(
                    height <= STEP,
                    "the {} block headed {label:?} runs {height:.1} points, \
                     and the blocks are stacked {STEP:.1} apart",
                    named.code()
                );
            }
        }
    }

    /// A sentence as tall as its box, or taller, is left against the top
    /// whatever it is asked, and the three boxes would then show one place
    /// three times: the sentence has to leave room in its box, in every
    /// language.
    #[test]
    fn the_placed_sentence_leaves_room_in_its_box() {
        let mut doc = Document::new();
        let handle = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );
        let flow = TextFlow::new(&handle, SIZE).leading(LEADING);

        for (named, words) in WORDS {
            let height = flow.height(&flow.break_lines(words.placed, PLACED_WIDTH));

            assert!(
                height < PLACED_HEIGHT / 2.0,
                "the {} sentence runs {height:.1} points in a box {PLACED_HEIGHT:.1} tall",
                named.code()
            );
        }
    }
}