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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909 | //! 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 indique où se trouve chaque \
objet est écrite après tous les objets : le logiciel de lecture doit donc \
recevoir le fichier entier avant de pouvoir afficher une seule page — même \
s’il ne compte en regarder qu’une.\nÉcrit première page en tête, le même \
document contient, dès le début du fichier, la page un, ce dont elle a besoin \
pour s’afficher, et une table qui indique où commence et où finit chacune des \
autres pages. La page un s’affiche pendant que le reste arrive, et la page \
cinquante n’est qu’une plage d’octets à demander, et non 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, reproduit en \
entier sur ",
subject_after: " pages, chacune dotée d’un titre courant, numérotée et accessible depuis une \
table des matières cliquable. Cette page de fin est le seul ajout, et les \
chiffres ci-dessous concernent le livre sans elle.",
ordinary: "Écrit de la façon habituelle",
reordered: "Écrit première page en tête",
held_back: "Attente supprimée",
unit: "octets",
note_before: "Avec ce fichier, le logiciel de lecture affiche la page un dès que ",
note_after: " pour cent du fichier est arrivé, et affiche le premier chapitre pendant que le \
dernier est encore en route. Dans les deux cas, le livre est le même : un \
logiciel de lecture qui ignore tout cela l’ouvre comme n’importe quel autre \
fichier.",
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.",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Waar leessoftware op wacht vóór pagina één",
why: "Een gewone pdf wordt vanaf het einde gelezen. De tabel die zegt waar elk object staat, wordt na alle objecten geschreven, dus leessoftware moet het hele bestand hebben voordat ze één pagina kan tonen, hoe weinig ze er ook wil zien.\nWordt de eerste pagina eerst geschreven, dan staan pagina één, alles waarmee pagina één getekend wordt en een tabel die zegt waar elke andere pagina begint en eindigt, allemaal aan het begin van het bestand. Pagina één verschijnt terwijl de rest nog binnenkomt, en pagina vijftig is één reeks bytes om op te vragen in plaats van een heel document om op te halen.",
figures: "Hetzelfde boek, twee keer gemeten",
subject_before: "Het hier gemeten boek is Little Women (Onder moeders vleugels) van Louisa May Alcott, volledig, op",
subject_after: " pagina’s, elk met een kop, genummerd en bereikbaar via een klikbare inhoudsopgave. Deze slotpagina is het enige wat is toegevoegd, en de cijfers hieronder gelden voor het boek zonder deze pagina.",
ordinary: "Op de gewone manier geschreven",
reordered: "Met pagina één voorop geschreven",
held_back: "Niet meer op gewacht",
unit: "bytes",
note_before: "Leessoftware die dit bestand krijgt, toont pagina één zodra",
note_after: " procent ervan binnen is, en leest het eerste hoofdstuk terwijl het laatste nog onderweg is. Het boek is in beide gevallen hetzelfde: leessoftware die hier niets van weet, opent het bestand zoals elk ander.",
itself: "De pagina’s vóór deze zijn dat boek, met de eerste pagina eerst geschreven. Wie ze gelezen heeft, heeft een van de twee gemeten documenten gelezen.",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "O que um leitor de PDF espera antes da página 1",
why: "Um PDF normal lê-se a partir do fim. A tabela que diz onde vive cada objeto é escrita depois de todos os objetos, por isso o programa de leitura tem de ter o ficheiro inteiro antes de mostrar uma só página, por poucas que queira ver.\nEscrito com a primeira página primeiro, o mesmo documento leva a página um, aquilo com que ela se desenha e uma tabela que diz onde começa e acaba cada uma das outras páginas, tudo no início do ficheiro. A página um aparece enquanto o resto ainda chega, e a página cinquenta é um troço de bytes a pedir e não um documento inteiro a descarregar.",
figures: "O mesmo livro, medido duas vezes",
subject_before: "O livro medido aqui é Little Women (Mulherzinhas), de Louisa May Alcott, completo em",
subject_after: " páginas, cada uma com cabeçalho, numerada e acessível a partir de um índice clicável. Esta página final é a única coisa acrescentada, e os números abaixo são o livro sem ela.",
ordinary: "Escrito da forma normal",
reordered: "Escrito com a página um à frente",
held_back: "Já não se espera",
unit: "bytes",
note_before: "Um programa de leitura mostra a página um deste ficheiro quando chegaram",
note_after: " por cento dele, e lê o primeiro capítulo enquanto o último ainda vem a caminho. O livro é o mesmo nos dois casos: um programa de leitura que não sabe nada disto abre o ficheiro como qualquer outro.",
itself: "As páginas antes desta são esse livro, escrito com a primeira página primeiro. Quem as leu, leu um dos dois documentos medidos.",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Cosa aspetta un lettore PDF prima della pagina 1",
why: "Un PDF normale si legge dalla fine. La tabella che dice dove vive ogni oggetto è scritta dopo tutti gli oggetti, così il programma di lettura deve avere l’intero file prima di mostrare una sola pagina, per quanto poche ne voglia guardare.\nScritto con la prima pagina in testa, lo stesso documento porta la pagina uno, ciò con cui essa si disegna e una tabella che dice dove inizia e finisce ogni altra pagina, tutto all’inizio del file. La pagina uno appare mentre il resto sta ancora arrivando, e la pagina cinquanta è un tratto di byte da chiedere e non un documento intero da scaricare.",
figures: "Lo stesso libro, misurato due volte",
subject_before: "Il libro misurato qui è Little Women (Piccole donne), di Louisa May Alcott, completo su",
subject_after: " pagine, ciascuna con intestazione, numerata e raggiungibile da un indice cliccabile. Questa pagina finale è l’unica aggiunta, e le cifre qui sotto sono il libro senza di essa.",
ordinary: "Scritto nel modo normale",
reordered: "Scritto con la prima pagina in testa",
held_back: "Non più atteso",
unit: "byte",
note_before: "Un programma di lettura mostra la pagina uno di questo file quando ne è arrivato il",
note_after: " per cento, e legge il primo capitolo mentre l’ultimo è ancora in viaggio. Il libro è lo stesso nei due casi: un programma di lettura che non sa nulla di tutto questo apre il file come ogni altro.",
itself: "Le pagine prima di questa sono quel libro, scritto con la prima pagina in testa. Chi le ha lette ha letto uno dei due documenti misurati.",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Qué espera un lector de PDF antes de la página 1",
why: "Un PDF normal se lee desde el final. La tabla que dice dónde está cada objeto se escribe después de todos los objetos, así que el programa de lectura tiene que tener el archivo entero antes de mostrar una sola página, por pocas que quiera mirar.\nEscrito con la primera página primero, el mismo documento lleva la página uno, lo que ella usa para dibujarse y una tabla que dice dónde empieza y acaba cada una de las demás páginas, todo al principio del archivo. La página uno aparece mientras llega el resto, y la página cincuenta es un tramo de bytes que pedir y no un documento entero que descargar.",
figures: "El mismo libro, medido dos veces",
subject_before: "El libro medido aquí es Little Women (Mujercitas), de Louisa May Alcott, completo en ",
subject_after: " páginas, cada una con cabecera, numerada y accesible desde un índice en el que se puede hacer clic. Esta página final es lo único añadido, y las cifras de abajo son el libro sin ella.",
ordinary: "Escrito de la forma normal",
reordered: "Escrito con la primera página primero",
held_back: "Ya no se espera",
unit: "bytes",
note_before: "Un programa de lectura muestra la página uno de este archivo cuando ha llegado el ",
note_after: " por ciento, y lee el primer capítulo mientras el último aún está en camino. El libro es el mismo en los dos casos: un programa de lectura que no sabe nada de esto abre el archivo como cualquier otro.",
itself: "Las páginas anteriores son ese libro, escrito con la primera página primero. Quien las haya leído ha leído uno de los dos documentos medidos.",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Worauf eine Lesesoftware vor Seite eins wartet",
why: "Ein gewöhnliches PDF wird vom Ende her gelesen. Die Tabelle, die sagt, wo jedes Objekt liegt, steht hinter allen Objekten, also muss eine Lesesoftware die ganze Datei haben, bevor sie eine einzige Seite zeigen kann — wie wenige Seiten man auch ansehen will.\nMit der ersten Seite zuerst geschrieben, trägt dasselbe Dokument Seite eins, was Seite eins zur Anzeige braucht, und eine Tabelle, die sagt, wo jede andere Seite beginnt und endet, alles am Anfang der Datei. Seite eins erscheint, während der Rest noch eintrifft, und Seite fünfzig ist ein Byte-Bereich, den man anfordert, statt eines ganzen Dokuments, das man holen muss.",
figures: "Dasselbe Buch, zweimal gemessen",
subject_before: "Das hier gemessene Buch ist Little Women von Louisa May Alcott, vollständig auf ",
subject_after: " Seiten, jede mit Kopfzeile und Nummer und über ein anklickbares Inhaltsverzeichnis erreichbar. Diese Schlussseite ist das Einzige, was hinzugefügt wurde, und die Zahlen unten gelten für das Buch ohne sie.",
ordinary: "Gewöhnlich geschrieben",
reordered: "Erste Seite zuerst",
held_back: "Nicht mehr abzuwarten",
unit: "Bytes",
note_before: "Eine Lesesoftware, die diese Datei erhält, zeigt Seite eins, sobald ",
note_after: " Prozent davon eingetroffen sind, und liest das erste Kapitel, während das letzte noch unterwegs ist. Das Buch ist in beiden Fällen dasselbe: Eine Lesesoftware, die von alldem nichts weiß, öffnet die Datei wie jede andere.",
itself: "Die Seiten vor dieser sind dieses Buch, mit der ersten Seite zuerst geschrieben. Wer sie gelesen hat, hat eines der beiden gemessenen Dokumente gelesen.",
};
/// 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 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).is_multiple_of(3) {
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(¬e, 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, where two
/// languages spell a word alike.
const SPARED: [&str; 1] = [
// Written the same way in Spanish.
r#"unit: "bytes""#,
];
/// 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(¬e, ROOM));
assert!(
bottom > ITSELF_TOP,
"{language:?} sets its note down to {bottom}, over a line at {ITSELF_TOP}"
);
}
}
}
|