write_first_page_first.rs

The Rust file of the “Showing page one before the file has arrived” example. The same document written twice, the ordinary way and with its first page moved to the head of the file, with how much of each must arrive before page one appears.

Rust 822 lines

What this example is for

Open the book below: the first page appears the instant you click it, as though the file carried a single page — and it carries 357. That is the whole of what this example is for, and it is worth more the longer the document gets: a catalogue, a manual, a report of two hundred pages behaves the same way.

What this example shows

  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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Lays a whole novel out, writes it twice — the ordinary way, then first page
//! first — and publishes the book written first page first, closed by a page
//! stating how much of each reading software must hold before it can show page
//! one.
//!
//! An ordinary PDF is read from the end: the table saying where every object
//! lives sits after every object, so reading software has to hold the whole
//! file before it can draw anything at all. A file written first page first
//! carries the first page, what that page draws with, and a table stating where
//! every other page begins, all at the head of the file — so page one appears
//! while the rest is still on its way, and page fifty is one stretch of bytes
//! to ask for.
//!
//! The document measured is a novel carried in full, laid out by the same code
//! as `write_english_book`. It is built once and written both ways, so the two
//! figures are two spellings of one document, and the file this leaves behind
//! is that same book: reading software that opens it shows page one while the
//! rest of the novel is still arriving.
//!
//! The closing page is added after the two figures are read, so what it states
//! is the book alone. The words on it are held in `Words`, once per language,
//! and `HQF_PDF_LANG` picks which set is drawn. The figures are not language:
//! they are read off the two files.
//!
//! A second path, if one is given, is where the book is written the ordinary
//! way, so that the two spellings of one document can be handed to reading
//! software side by side.
//!
//! Usage: `cargo run --example write_first_page_first -- tmp/first_page.pdf`
//!        `HQF_PDF_LANG=fr cargo run --example write_first_page_first --
//! tmp/premiere_page.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Page, TextFlow};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/book.rs"]
mod book;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// Where the committed fonts sit.
fn font_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
}

/// The chapter titles as English sets them.
///
/// The file writes them in capitals throughout, which English does not do. That
/// is undone here — nothing else is, and `check_the_titles_only_change_case`
/// holds this list to the file, letter for letter.
const TITLES: [&str; 47] = [
    "Playing Pilgrims",
    "A Merry Christmas",
    "The Laurence Boy",
    "Burdens",
    "Being Neighborly",
    "Beth Finds the Palace Beautiful",
    "Amy’s Valley of Humiliation",
    "Jo Meets Apollyon",
    "Meg Goes to Vanity Fair",
    "The P.C. and P.O.",
    "Experiments",
    "Camp Laurence",
    "Castles in the Air",
    "Secrets",
    "A Telegram",
    "Letters",
    "Little Faithful",
    "Dark Days",
    "Amy’s Will",
    "Confidential",
    "Laurie Makes Mischief, and Jo Makes Peace",
    "Pleasant Meadows",
    "Aunt March Settles the Question",
    "Gossip",
    "The First Wedding",
    "Artistic Attempts",
    "Literary Lessons",
    "Domestic Experiences",
    "Calls",
    "Consequences",
    "Our Foreign Correspondent",
    "Tender Troubles",
    "Jo’s Journal",
    "Friend",
    "Heartache",
    "Beth’s Secret",
    "New Impressions",
    "On the Shelf",
    "Lazy Laurence",
    "The Valley of the Shadow",
    "Learning to Forget",
    "All Alone",
    "Surprises",
    "My Lord and Lady",
    "Daisy and Demi",
    "Under the Umbrella",
    "Harvest Time",
];

/// The novel this lays out, carried in full. Its file opens a chapter on a line
/// that reads `CHAPTER I.`, and it holds forty-seven of them.
///
/// One book is drawn whatever language the closing page is written in: what is
/// being shown is the shape of the file, and the longer the book the plainer it
/// shows. The page that closes it names the book, so a reader of either
/// language is told what was measured.
const BOOK: book::Book = book::Book {
    title: "Little Women",
    author: "Louisa May Alcott",
    file: "littlewomen.txt",
    mark_before: "CHAPTER ",
    mark_after: ".",
    chapters: 47,
    contents_title: "Contents",
    titles: &TITLES,
    // English sets its marks tight against the word they close, and the file
    // already draws its dashes.
    typography: book::Typography {
        space_before: &[],
        space_after: &[],
        dash: None,
    },
};

/// The words the closing page is written in, one set per language.
///
/// What is not language stays out of it: the three figures and the page count
/// are read off the files themselves.
#[derive(Debug)]
struct Words {
    /// The line across the top of the page.
    title: &'static str,
    /// What writing a file first page first does, in two paragraphs.
    why: &'static str,
    /// The heading over the three figures.
    figures: &'static str,
    /// What was measured, cut where the page count goes in. The name of the
    /// book stands in the first half.
    subject_before: &'static str,
    subject_after: &'static str,
    /// The label on what reading software waits for in the ordinary file.
    ordinary: &'static str,
    /// The label on what it waits for in the file written first page first.
    reordered: &'static str,
    /// The label on the difference between the two.
    held_back: &'static str,
    /// What a figure is counted in.
    unit: &'static str,
    /// The closing note, cut where the share goes into it.
    note_before: &'static str,
    note_after: &'static str,
    /// The line saying what this very file is.
    itself: &'static str,
}

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

    /// What was measured, over `pages` pages.
    fn subject(&self, pages: usize) -> String {
        format!("{}{pages}{}", self.subject_before, self.subject_after)
    }

    /// The closing note, with the share reading software waits for in it.
    fn note(&self, share: usize) -> String {
        format!("{}{share}{}", self.note_before, self.note_after)
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "What reading software waits for before page one",
    why: "An ordinary PDF is read from the end. The table saying where every \
          object lives is written after every object, so reading software has \
          to hold the whole file before it can show a single page — however \
          few of them it means to look at.\n\
          Written first page first, the same document carries page one, what \
          page one draws with, and a table stating where every other page \
          begins and ends, all at the head of the file. Page one appears while \
          the rest is still arriving, and page fifty is one stretch of bytes to \
          ask for rather than a whole document to fetch.",
    figures: "The same book, measured twice",
    subject_before: "The book measured here is Little Women, by Louisa May \
                     Alcott, carried in full over ",
    subject_after: " pages, each of them headed, numbered and reached from a \
                    contents a reader can click. This closing page is the only \
                    thing added to it, and the figures below are the book \
                    without it.",
    ordinary: "Written the ordinary way",
    reordered: "Written first page first",
    held_back: "No longer waited for",
    unit: "bytes",
    note_before: "Reading software given this file shows page one after ",
    note_after: " per cent of it has arrived, and reads the first chapter while \
                 the last one is still on its way. The book is the same one \
                 either way: reading software that knows nothing of any of \
                 this opens the file as it opens every other.",
    itself: "The pages before this one are that book, written first page first. \
             A reader who has read them has read one of the two documents \
             being measured.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce que le logiciel de lecture attend avant la page un",
    why: "Un PDF ordinaire se lit par la fin. La table qui dit où vit chaque \
          objet est écrite après tous les objets : le logiciel de lecture doit \
          donc tenir le fichier entier avant de pouvoir afficher une seule \
          page — même s'il n'a l'intention d'en regarder qu'une.\n\
          Écrit première page en tête, le même document porte la page un, ce \
          que la page un dessine, et une table qui dit où commence et où finit \
          chacune des autres pages, le tout au début du fichier. La page un \
          paraît pendant que le reste arrive, et la page cinquante est une \
          tranche d'octets à demander plutôt qu'un document entier à \
          rapatrier.",
    figures: "Le même livre, mesuré deux fois",
    subject_before: "Le livre mesuré ici est Little Women, de Louisa May \
                     Alcott, porté en entier sur ",
    subject_after: " pages, chacune coiffée, numérotée et atteinte depuis une \
                    table des matières où le lecteur peut cliquer. Cette page \
                    de fin est la seule chose qui lui ait été ajoutée, et les \
                    chiffres ci-dessous sont ceux du livre sans elle.",
    ordinary: "Écrit à l'ordinaire",
    reordered: "Écrit première page en tête",
    held_back: "Plus attendu",
    unit: "octets",
    note_before: "Sur ce fichier, le logiciel de lecture affiche la page un dès que ",
    note_after: " pour cent est arrivé, et lit le premier chapitre pendant que \
                 le dernier arrive encore. Le livre est le même des deux \
                 côtés : un logiciel de lecture qui ne sait rien de tout cela l'ouvre \
                 comme il ouvre les autres.",
    itself: "Les pages qui précèdent celle-ci sont ce livre, écrit première \
             page en tête. Un lecteur qui les a lues a donc lu l'un des deux \
             documents mesurés.",
};

/// 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 left edge of everything on the page.
const X: f64 = 60.0;

/// The width every block is broken to.
const ROOM: f64 = 475.0;

/// How far apart two lines of a block sit, which is also the least room a block
/// leaves between its last line and whatever stands under it.
const BLOCK_LEADING: f64 = 14.0;

/// The baseline the title sits on.
const TITLE_TOP: f64 = 780.0;

/// The top of the block that says what writing a file first page first does.
const WHY_TOP: f64 = 748.0;

/// The top of the line naming what was measured.
const SUBJECT_TOP: f64 = 606.0;

/// The top of the heading over the three figures.
const FIGURES_TOP: f64 = 520.0;

/// The top of the first of the three figures.
const FIRST_FIGURE_TOP: f64 = 494.0;

/// How far apart two figures sit.
const FIGURE_DROP: f64 = 20.0;

/// Where the number of a figure begins, its label sitting at [`X`].
const NUMBER_X: f64 = X + 190.0;

/// The top of the closing note.
const NOTE_TOP: f64 = 406.0;

/// The top of the line saying what this file is.
const ITSELF_TOP: f64 = 320.0;

/// The book, laid out whole, and the handle its text is drawn through.
fn laid_out(font: &Font) -> Result<(Document, FontHandle), Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let handle = doc.add_font(font.clone());

    let text = fs::read_to_string(BOOK.path())?;
    book::lay_out(&mut doc, &handle, &BOOK, &text)?;
    Ok((doc, handle))
}

/// One book, written every way this example writes it.
#[derive(Debug)]
struct Writings {
    /// The book written the ordinary way, table of offsets last.
    the_ordinary_way: Vec<u8>,
    /// The book written first page first, closed by the page that reports the
    /// figures. This is the file the example publishes.
    published: Vec<u8>,
}

/// The book written both ways, then again with the page that reports the two
/// figures.
///
/// The figures are read off the book before that page is added, so what the
/// page states is the book and not the file the page is in.
fn writings(font: &Font, words: &'static Words) -> Result<Writings, Box<dyn std::error::Error>> {
    let (mut doc, handle) = laid_out(font)?;

    let the_ordinary_way = doc.to_bytes()?;
    doc.set_linearized(true);
    let reordered = doc.to_bytes()?;

    let ordinary = waited_for(&the_ordinary_way);
    let first_page = waited_for(&reordered);
    let pages = doc.page_count();

    let mut page = Page::a4();
    page.content = report(&handle, words, pages, ordinary, first_page)?;
    doc.add_page(page)?;

    Ok(Writings {
        the_ordinary_way,
        published: doc.to_bytes()?,
    })
}

/// How many bytes of `bytes` reading software holds before it can draw page
/// one.
///
/// A file written first page first says so itself: the `/E` entry of its
/// parameter dictionary is the offset of the end of the first page, and
/// everything before it is what reading software needs. A file written the
/// ordinary way states no such thing, and the answer for it is the whole file.
fn waited_for(bytes: &[u8]) -> usize {
    let head = &bytes[..1024.min(bytes.len())];
    let Some(at) = head.windows(3).position(|window| window == b"/E ") else {
        return bytes.len();
    };
    let mut at = at + 3;
    while head.get(at) == Some(&b' ') {
        at += 1;
    }
    let mut value = 0;
    while let Some(digit) = head.get(at).filter(|byte| byte.is_ascii_digit()) {
        value = value * 10 + usize::from(digit - b'0');
        at += 1;
    }
    value
}

/// A count of bytes, its thousands held apart by a space.
fn counted(value: usize) -> String {
    let digits = value.to_string();
    let mut grouped = String::new();
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            grouped.push(' ');
        }
        grouped.push(digit);
    }
    grouped
}

/// The share of a file reading software holds before page one appears, in whole
/// per cent.
///
/// Whole numbers throughout: a share written as a fraction would be spelled by
/// whatever language drew it, and the two twins must write the same bytes.
const fn share_waited_for(ordinary: usize, reordered: usize) -> usize {
    if ordinary == 0 {
        return 0;
    }
    reordered * 100 / ordinary
}

/// Converts a row number to a float. A page holds far too few rows for a
/// `usize` to lose precision as an `f64`.
#[expect(
    clippy::cast_precision_loss,
    reason = "a row number on a page is a very small whole number"
)]
const fn count_f64(n: usize) -> f64 {
    n as f64
}

/// Writes `bytes` to `path`, making the directory it goes in if it is not
/// there, and says what was written.
fn written(path: &str, bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(parent) = Path::new(path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(path, bytes)?;
    println!("wrote {path}: {} bytes", bytes.len());
    Ok(())
}

/// Draws the page that closes the book and reports the two figures.
fn report(
    handle: &FontHandle,
    words: &Words,
    pages: usize,
    ordinary: usize,
    reordered: usize,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut c = Content::new();

    let title = TextFlow::new(handle, 18.0);
    c.begin_text();
    title.draw(
        &mut c,
        &title.break_lines(words.title, ROOM),
        X,
        TITLE_TOP,
        ROOM,
    )?;
    c.end_text();

    let why = TextFlow::new(handle, 10.0).leading(BLOCK_LEADING);
    c.begin_text();
    why.draw(&mut c, &why.break_lines(words.why, ROOM), X, WHY_TOP, ROOM)?;
    c.end_text();

    let subject = TextFlow::new(handle, 10.0).leading(BLOCK_LEADING);
    c.begin_text();
    subject.draw(
        &mut c,
        &subject.break_lines(&words.subject(pages), ROOM),
        X,
        SUBJECT_TOP,
        ROOM,
    )?;
    c.end_text();

    let heading = TextFlow::new(handle, 11.0);
    c.begin_text();
    heading.draw(
        &mut c,
        &heading.break_lines(words.figures, ROOM),
        X,
        FIGURES_TOP,
        ROOM,
    )?;
    c.end_text();

    let rows = [
        (words.ordinary, ordinary),
        (words.reordered, reordered),
        (words.held_back, ordinary - reordered),
    ];
    for (index, (label, figure)) in rows.iter().enumerate() {
        let top = FIGURE_DROP.mul_add(-count_f64(index), FIRST_FIGURE_TOP);
        let line = TextFlow::new(handle, 10.0);
        c.begin_text();
        line.draw(&mut c, &line.break_lines(label, ROOM), X, top, ROOM)?;
        c.end_text();

        let stated = format!("{} {}", counted(*figure), words.unit);
        let number = TextFlow::new(handle, 10.0);
        c.begin_text();
        number.draw(
            &mut c,
            &number.break_lines(&stated, ROOM),
            NUMBER_X,
            top,
            ROOM,
        )?;
        c.end_text();
    }

    let note = words.note(share_waited_for(ordinary, reordered));
    let closing = TextFlow::new(handle, 10.0).leading(BLOCK_LEADING);
    c.begin_text();
    closing.draw(&mut c, &closing.break_lines(&note, ROOM), X, NOTE_TOP, ROOM)?;
    c.end_text();

    let itself = TextFlow::new(handle, 10.0).leading(BLOCK_LEADING);
    c.begin_text();
    itself.draw(
        &mut c,
        &itself.break_lines(words.itself, ROOM),
        X,
        ITSELF_TOP,
        ROOM,
    )?;
    c.end_text();

    Ok(c.into_bytes())
}

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 out = env::args()
        .nth(1)
        .unwrap_or_else(|| language.file_name(&out::default_path("first_page_first")));

    let font = Font::parse(fs::read(font_dir().join("DejaVuSans.ttf"))?)?;

    // One book, written twice: the two figures are two spellings of it, not two
    // documents that happen to hold the same thing.
    let writings = writings(&font, words)?;

    if let Some(beside) = env::args().nth(2) {
        written(&beside, &writings.the_ordinary_way)?;
    }

    written(&out, &writings.published)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        BLOCK_LEADING, BOOK, FIGURE_DROP, FIGURES_TOP, FIRST_FIGURE_TOP, ITSELF_TOP, NOTE_TOP,
        ROOM, SUBJECT_TOP, WORDS, Words, Writings, book, counted, font_dir, language,
        share_waited_for, waited_for, writings,
    };
    use hqf_pdf::{Document, Font, TextFlow};
    use language::Language;
    use std::sync::OnceLock;

    /// The lines two languages are allowed to write the same way. There are
    /// none.
    const SPARED: [&str; 0] = [];

    /// The committed font, added to a document of its own.
    fn a_font() -> (Document, hqf_pdf::FontHandle) {
        let mut doc = Document::new();
        let handle = doc.add_font(
            Font::parse(std::fs::read(font_dir().join("DejaVuSans.ttf")).expect("the font"))
                .expect("the font parses"),
        );
        (doc, handle)
    }

    /// The book written every way, in English.
    ///
    /// Laid out once and held afterwards: the tests below read the same files,
    /// and laying a whole novel out is the slowest thing here.
    fn written_ways() -> &'static Writings {
        static WRITTEN: OnceLock<Writings> = OnceLock::new();

        WRITTEN.get_or_init(|| {
            let font =
                Font::parse(std::fs::read(font_dir().join("DejaVuSans.ttf")).expect("the font"))
                    .expect("the font parses");
            writings(&font, Words::of(Language::English)).expect("the book is written")
        })
    }

    #[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 file published is the book itself, and it is written first page
    /// first: reading software shows page one long before the novel has
    /// arrived.
    #[test]
    fn the_file_published_is_the_book_written_first_page_first() {
        let published = &written_ways().published;
        let reader = hqf_pdf::read::Reader::new(published.clone()).expect("the file reads");
        let pages = reader.pages().expect("the file has pages").len();

        assert!(
            pages > 50,
            "the file published holds {pages} pages, which is no book"
        );
        let waited = waited_for(published);
        assert!(
            waited * 4 < published.len(),
            "reading software waits for {waited} bytes of {}, which is not a quarter",
            published.len()
        );
    }

    /// The closing page states the page count of the book it closes, which is
    /// every page of the file but itself.
    #[test]
    fn the_closing_page_is_the_only_page_added_to_the_book() {
        let ways = written_ways();
        let book = hqf_pdf::read::Reader::new(ways.the_ordinary_way.clone())
            .expect("the book reads")
            .pages()
            .expect("the book has pages")
            .len();
        let published = hqf_pdf::read::Reader::new(ways.published.clone())
            .expect("the file reads")
            .pages()
            .expect("the file has pages")
            .len();

        assert_eq!(
            published,
            book + 1,
            "the file published holds {published} pages against the book's {book}"
        );
    }

    #[test]
    fn every_chapter_of_the_novel_is_headed_and_carries_prose() {
        book::check_every_chapter_is_headed(&BOOK);
    }

    #[test]
    fn no_chapter_is_headed_in_capitals_throughout() {
        book::check_no_title_is_set_in_capitals(&BOOK);
    }

    #[test]
    fn the_titles_drawn_are_the_ones_the_file_carries() {
        book::check_the_titles_only_change_case(&BOOK);
    }

    #[test]
    fn the_marks_are_spaced_the_way_this_book_sets_them() {
        book::check_the_marks_are_spaced_the_way_the_book_sets_them(&BOOK);
    }

    #[test]
    fn the_contents_points_at_every_chapter() {
        let (_doc, handle) = a_font();

        book::check_the_contents_points_at_every_chapter(&handle, &BOOK);
    }

    #[test]
    fn the_running_heads_stay_on_one_line() {
        let (_doc, handle) = a_font();

        book::check_the_running_heads_stay_on_one_line(&BOOK, &handle);
    }

    /// Every language names the book it measured, so a reader of either is told
    /// what the figures are about.
    #[test]
    fn every_language_names_the_book_it_measured() {
        for (language, words) in WORDS {
            assert!(
                words.subject_before.contains(BOOK.title),
                "{language:?} does not name the book it measured"
            );
        }
    }

    /// The page has something to report: reading software waits for a great
    /// deal less of the reordered file than of the ordinary one.
    #[test]
    fn the_reordered_file_shows_its_first_page_far_sooner() {
        let ways = written_ways();
        let ordinary = waited_for(&ways.the_ordinary_way);
        let first_page = waited_for(&ways.published);

        assert_eq!(
            ordinary,
            ways.the_ordinary_way.len(),
            "the ordinary file states nothing, so reading software waits for all of it"
        );
        assert!(
            first_page * 4 < ordinary,
            "reading software waits for {first_page} bytes of {ordinary}, which is not a quarter"
        );
        assert!(
            share_waited_for(ordinary, first_page) >= 1,
            "the share reading software waits for rounds down to nothing"
        );
    }

    /// What the published file says about its first page is where its second
    /// page begins, which is what makes the figure the page reports honest.
    #[test]
    fn what_the_file_says_about_its_first_page_is_where_the_next_one_starts() {
        let published = &written_ways().published;
        let waited = waited_for(published);

        let at = published[waited..]
            .iter()
            .position(|byte| !byte.is_ascii_whitespace())
            .expect("something follows the first page");
        assert_eq!(
            &published[waited + at..waited + at + 6],
            b"1 0 ob",
            "the second page opens the numbering, and it starts where /E ends"
        );
    }

    /// A count of bytes holds its thousands apart, in every language.
    #[test]
    fn a_count_of_bytes_holds_its_thousands_apart() {
        for (value, written) in [
            (0_usize, "0"),
            (999, "999"),
            (1_000, "1 000"),
            (50_177, "50 177"),
            (1_234_567, "1 234 567"),
        ] {
            assert_eq!(counted(value), written);
        }
    }

    /// Nothing the page draws runs off the paper.
    #[test]
    fn every_language_writes_blocks_no_wider_than_the_room_they_have() {
        let (_doc, handle) = a_font();

        for (language, words) in WORDS {
            for (text, size) in [
                (words.title, 18.0),
                (words.figures, 11.0),
                (words.ordinary, 10.0),
                (words.reordered, 10.0),
                (words.held_back, 10.0),
            ] {
                let width = handle.measure(text, size);
                assert!(
                    width <= ROOM,
                    "{language:?} writes {width} points in {ROOM}: {text}"
                );
            }

            for text in [words.why, words.itself, &words.subject(355), &words.note(4)] {
                let flow = TextFlow::new(&handle, 10.0).leading(BLOCK_LEADING);
                for line in &flow.break_lines(text, ROOM) {
                    assert!(
                        line.natural_width() <= ROOM,
                        "{language:?} sets a line wider than {ROOM}"
                    );
                }
            }
        }
    }

    /// The line naming what was measured keeps a line of leading between itself
    /// and the heading over the figures.
    ///
    /// It is the block that grows when the book being measured changes, and the
    /// heading under it does not move.
    #[test]
    fn what_was_measured_leaves_the_heading_under_it_its_room() {
        let (_doc, handle) = a_font();

        for (language, words) in WORDS {
            let flow = TextFlow::new(&handle, 10.0).leading(BLOCK_LEADING);
            let bottom = SUBJECT_TOP - flow.height(&flow.break_lines(&words.subject(355), ROOM));
            assert!(
                bottom - FIGURES_TOP >= BLOCK_LEADING,
                "{language:?} sets what it measured down to {bottom}, \
                 over a heading at {FIGURES_TOP}"
            );
        }
    }

    /// A label and the figure beside it never touch.
    #[test]
    fn a_label_leaves_room_for_the_figure_beside_it() {
        let (_doc, handle) = a_font();
        let room = super::NUMBER_X - super::X;

        for (language, words) in WORDS {
            for label in [words.ordinary, words.reordered, words.held_back] {
                let width = handle.measure(label, 10.0);
                assert!(
                    width <= room,
                    "{language:?} writes {width} points in {room}: {label}"
                );
            }
        }
    }

    /// Nothing the page draws lands on what comes after it.
    #[test]
    fn nothing_the_page_draws_lands_on_what_comes_after_it() {
        let (_doc, handle) = a_font();

        let lowest = FIGURE_DROP.mul_add(-2.0, FIRST_FIGURE_TOP);
        assert!(
            lowest > NOTE_TOP,
            "the last figure sits at {lowest}, over a note at {NOTE_TOP}"
        );

        for (language, words) in WORDS {
            let flow = TextFlow::new(&handle, 10.0).leading(BLOCK_LEADING);
            let note = words.note(4);
            let bottom = NOTE_TOP - flow.height(&flow.break_lines(&note, ROOM));
            assert!(
                bottom > ITSELF_TOP,
                "{language:?} sets its note down to {bottom}, over a line at {ITSELF_TOP}"
            );
        }
    }
}