Montrer la page un sans attendre le reste

Le même document écrit deux fois, à l'ordinaire puis avec sa première page portée en tête du fichier, avec ce qu'il faut avoir reçu de chacun pour voir la page un.

Cette page est le programme entier, pour celui qui écrit vos logiciels. Il n'y a rien d'autre à y lire. Revenir au document qu'il écrit.

Rust write_first_page_first.rs 634 lignes
  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
//! Writes one document twice — the ordinary way, then first page first — and
//! draws a page stating how much of each a reader 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 a reader 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 being measured is built here and written both ways. The page
//! that reports the two figures is itself written first page first, so the file
//! this leaves behind is one of the two things it is talking about.
//!
//! The words 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 document that was measured is
//! written the ordinary way, so that the two spellings of one document can be
//! handed to a reader 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::metadata::xmp::Metadata;
use hqf_pdf::{Bookmark, Document, Font, Page, TextFlow};

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

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

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

use language::Language;

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

/// How many pages the document being measured holds.
///
/// The figure a reader waits for is the whole file in the ordinary case, so the
/// longer the document, the further apart the two figures are: a document of
/// one page would show almost nothing.
const MEASURED_PAGES: usize = 200;

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: the three figures 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 the document being measured is, cut where the page count goes in.
    subject_before: &'static str,
    subject_after: &'static str,
    /// The label on what a reader 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 the document being measured is.
    fn subject(&self) -> String {
        format!(
            "{}{MEASURED_PAGES}{}",
            self.subject_before, self.subject_after
        )
    }

    /// The closing note, with the share a reader 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 a reader 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 a reader has to hold \
          the whole file before it can draw 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 document, measured twice",
    subject_before: "The document measured here holds ",
    subject_after: " pages, each under a heading of its own, with a list of \
                    those headings a reader can jump from.",
    ordinary: "Written the ordinary way",
    reordered: "Written first page first",
    held_back: "No longer waited for",
    unit: "bytes",
    note_before: "A reader shown the second file draws page one after ",
    note_after: " per cent of it has arrived. The document is the same one \
                 either way: a reader that knows nothing of any of this opens \
                 the file as it opens every other.",
    itself: "This very file is written first page first, so a reader that \
             opened it has read one of the two documents being measured.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Ce que le lecteur 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 lecteur doit donc tenir \
          le fichier entier avant de pouvoir dessiner 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 document, mesuré deux fois",
    subject_before: "Le document mesuré ici tient en ",
    subject_after: " pages, chacune sous son propre titre, avec la liste de ces \
                    titres d'où le lecteur peut sauter.",
    ordinary: "Écrit à l'ordinaire",
    reordered: "Écrit première page en tête",
    held_back: "Plus attendu",
    unit: "octets",
    note_before: "Sur le second fichier, le lecteur dessine la page un dès que ",
    note_after: " pour cent est arrivé. Le document est le même des deux côtés : \
                 un lecteur qui ne sait rien de tout cela l'ouvre comme il \
                 ouvre les autres.",
    itself: "Ce fichier-ci est écrit première page en tête : un lecteur qui l'a \
             ouvert 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;

/// 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 = 560.0;

/// The top of the first of the three figures.
const FIRST_FIGURE_TOP: f64 = 534.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 = 446.0;

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

/// The document whose two figures the page reports: pages of prose, each under
/// a heading of its own, with a list of those headings to jump from.
fn measured(font: &Font) -> Result<Document, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_metadata(Metadata {
        title: Some("A document measured from both ends".to_owned()),
        author: Some("HQF Development".to_owned()),
        ..Metadata::default()
    });
    let handle = doc.add_font(font.clone());

    for number in 1..=MEASURED_PAGES {
        let mut c = Content::new();

        let heading = TextFlow::new(&handle, 16.0);
        let title = format!("Chapter {number}");
        c.begin_text();
        heading.draw(&mut c, &heading.break_lines(&title, ROOM), X, 760.0, ROOM)?;
        c.end_text();

        let body = TextFlow::new(&handle, 11.0).leading(15.0);
        let prose = format!(
            "This is page {number} of a document written twice over, so that \
             what a reader waits for can be measured rather than claimed."
        );
        c.begin_text();
        body.draw(&mut c, &body.break_lines(&prose, ROOM), X, 720.0, ROOM)?;
        c.end_text();

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

        doc.add_bookmark(Bookmark::new(format!("Chapter {number}"), number - 1));
    }
    Ok(doc)
}

/// How many bytes of `bytes` a reader 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 a reader 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 a reader 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 reports the two figures.
fn report(
    handle: &hqf_pdf::FontHandle,
    words: &Words,
    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(14.0);
    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(14.0);
    c.begin_text();
    subject.draw(
        &mut c,
        &subject.break_lines(&words.subject(), 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(14.0);
    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(14.0);
    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() -> 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"))?)?;

    let the_ordinary_way = measured(&font)?.to_bytes()?;
    let mut reordered_document = measured(&font)?;
    reordered_document.set_linearized(true);
    let reordered = reordered_document.to_bytes()?;

    let ordinary = waited_for(&the_ordinary_way);
    let first_page = waited_for(&reordered);

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

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_linearized(true);
    let handle = doc.add_font(font);

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

    let bytes = doc.to_bytes()?;
    written(&out, &bytes)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        FIGURE_DROP, FIRST_FIGURE_TOP, ITSELF_TOP, MEASURED_PAGES, NOTE_TOP, ROOM, WORDS, counted,
        font_dir, language, measured, share_waited_for, waited_for,
    };
    use hqf_pdf::{Document, Font, TextFlow};

    /// 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 document measured, written both ways.
    fn both_ways() -> (Vec<u8>, Vec<u8>) {
        let font = Font::parse(std::fs::read(font_dir().join("DejaVuSans.ttf")).expect("the font"))
            .expect("the font parses");
        let ordinary = measured(&font)
            .expect("the document builds")
            .to_bytes()
            .expect("the document is written");
        let mut reordered = measured(&font).expect("the document builds");
        reordered.set_linearized(true);
        (
            ordinary,
            reordered.to_bytes().expect("the document 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 page has something to report: a reader 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 (ordinary, reordered) = both_ways();
        let waited = waited_for(&reordered);

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

    /// What the reordered 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 (_, reordered) = both_ways();
        let waited = waited_for(&reordered);

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

    /// The document measured holds the pages and the rows the page names.
    #[test]
    fn the_document_measured_holds_what_the_page_says_it_holds() {
        let (_, reordered) = both_ways();

        let reader = hqf_pdf::read::Reader::new(reordered).expect("the document reads");
        assert_eq!(
            reader.pages().expect("the document has pages").len(),
            MEASURED_PAGES
        );
        assert_eq!(
            reader
                .bookmarks()
                .expect("the document has an outline")
                .len(),
            MEASURED_PAGES
        );
    }

    /// 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(), &words.note(4)] {
                let flow = TextFlow::new(&handle, 10.0).leading(14.0);
                for line in &flow.break_lines(text, ROOM) {
                    assert!(
                        line.natural_width() <= ROOM,
                        "{language:?} sets a line wider than {ROOM}"
                    );
                }
            }
        }
    }

    /// 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(14.0);
            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}"
            );
        }
    }
}