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 | //! Sets the same tabulated text under each of the three tab methods, then a
//! table of contents whose dots run out to a right-hand stop, twice — plain
//! dots, then spaced grey dots set on a grid — so what each method does to a
//! column can be read off the page.
//!
//! A second page sets the relative method told so, at twice the default step;
//! the ruler lining its prices up on a decimal comma; and the table of contents
//! three more times, its leader laid from the far edge inwards, stretched from
//! one end of the room to the other, and set smaller and raised off the
//! baseline.
//!
//! A grey rule is drawn at every stop the block was told to use, so the runs
//! can be seen landing on them. The relative method steps the pen on from
//! wherever it stands, so its columns never line up; the typewriter method
//! steps to the next multiple of the tab size, so they do; a ruler sends each
//! tabulation to a stop of its own and sets the run on it, centred over it, or
//! lined up on its decimal point.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is labelled in. The step the typewriter panel works in is
//! not one of them: its label is set around the very number the panel is given,
//! so no language can announce a grid the page does not land on.
//!
//! Usage: `cargo run --example write_tab_stops -- tmp/tab_stops.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_tab_stops --
//! tmp/tabulations.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::color::Rgb;
use hqf_pdf::content::Content;
use hqf_pdf::layout::{Leader, LeaderFit};
use hqf_pdf::{Document, Font, FontHandle, Page, TabAlign, TabMethod, TabSize, TextFlow};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
use language::Language;
/// The font the example draws with when none is given on the command line: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The left edge every panel is set from.
const X: f64 = 80.0;
/// The room every panel has to fill.
const COLUMN: f64 = 430.0;
/// The distance from a panel's heading down to the block below it.
const DROP: f64 = 20.0;
/// The reference, the quantity and the unit price of each row the first three
/// panels set. What each row is a category of is a word, and stands in
/// [`Words`] under the same order.
const ROWS: [[&str; 3]; 3] = [
["A-1180", "12", "18.50"],
["B-2050", "4", "7.05"],
["C-9004", "120", "1 250.00"],
];
/// The page each entry of the table of contents is on.
const PAGES: [&str; 5] = ["7", "18", "34", "61", "112"];
/// The step the typewriter panel works in, which is the grid its columns land
/// on and the number its label spells out.
const GRID: f64 = 96.0;
/// How much of a line one tabulation opens when a flow is told nothing, as the
/// first panel's label spells it out.
const SHARE: &str = "7.5%";
/// How much of a line one tabulation opens on the second page's relative panel.
const WIDE_SHARE: f64 = 0.15;
/// [`WIDE_SHARE`] as the panel's label spells it out.
const WIDE_SHARE_SAID: &str = "15%";
/// The stops the ruler panel sends its three tabulations to.
const RULER: [f64; 3] = [130.0, 260.0, 380.0];
/// The words the page is labelled in, one set per language.
#[derive(Debug)]
struct Words {
/// The label over the relative panel, set around the share of a line one
/// tabulation opens under the default.
relative: [&'static str; 2],
/// The label over the typewriter panel, set around the step it works in.
typewriter: [&'static str; 2],
/// The label over the ruler panel.
ruler: &'static str,
/// The label over the table of contents.
listing: &'static str,
/// The label over the table of contents whose leader is set on a grid.
grid_listing: &'static str,
/// The label over the second page's relative panel, set around the share of
/// a line one tabulation opens there.
relative_told: [&'static str; 2],
/// The label over the ruler panel whose prices line up on a comma.
comma: &'static str,
/// The label over the table of contents whose leader is laid from the far
/// edge.
from_edge: &'static str,
/// The label over the table of contents whose leader is stretched.
stretch: &'static str,
/// The label over the table of contents whose leader is set smaller and
/// raised.
from_text: &'static str,
/// What each of the four columns is called.
columns: [&'static str; 4],
/// What each row of [`ROWS`] is a category of.
categories: [&'static str; 3],
/// The entries of the table of contents, each set on the page [`PAGES`]
/// gives it.
contents: [&'static str; 5],
}
impl Words {
/// The words the page is labelled in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
/// The label over the relative panel, around the share it opens.
fn relative_label(&self) -> String {
format!("{}{SHARE}{}", self.relative[0], self.relative[1])
}
/// The label over the typewriter panel, around the step it works in.
fn typewriter_label(&self) -> String {
format!("{}{GRID}{}", self.typewriter[0], self.typewriter[1])
}
/// The label over the second page's relative panel, around the share it
/// opens.
fn relative_told_label(&self) -> String {
format!(
"{}{WIDE_SHARE_SAID}{}",
self.relative_told[0], self.relative_told[1]
)
}
/// The rows of [`rows`](Self::rows), their prices written with a decimal
/// comma.
fn comma_rows(&self) -> String {
self.rows().replace('.', ",")
}
/// The four columns the first three panels set, a tabulation between each
/// pair and a heading over them.
fn rows(&self) -> String {
let mut lines = vec![self.columns.join("\t")];
for (row, category) in ROWS.iter().zip(self.categories) {
lines.push(format!("{}\t{category}\t{}\t{}", row[0], row[1], row[2]));
}
lines.join("\n")
}
/// The table of contents, each entry with its page number behind a
/// tabulation.
fn contents(&self) -> String {
self.contents
.iter()
.zip(PAGES)
.map(|(entry, page)| format!("{entry}\t{page}"))
.collect::<Vec<_>>()
.join("\n")
}
}
/// The page in English.
const ENGLISH: Words = Words {
relative: [
"Relative, the default: each tabulation steps the pen on by ",
" of the column from where it stands, so the rows do not line up.",
],
typewriter: [
"Typewriter: each tabulation lands on the next multiple of ",
" points, so the rows line up on that grid.",
],
ruler: "Ruler: a stop of its own for each tabulation, the second centred on it and the third \
lined up on its decimal point, the heading, which carries none, ending on the stop.",
listing: "A ruler stop at the far edge, the run ending on it and the leader filling the room \
the tabulation opened.",
grid_listing: "The same stop, the leader a spaced dot in grey set on a grid, so its dots \
stand in the same columns on every line.",
relative_told: [
"Relative, told so, each tabulation stepping the pen on by ",
" of the column: steps twice as long, the rows still out of line.",
],
comma: "Ruler, its third stop lining the prices up on a decimal comma rather than on a \
full stop.",
from_edge: "The leader laid from the far edge inwards: the room its repeats do not fill \
is left against the words.",
stretch: "The leader stretched: as many whole dots as fit, spread from one end of the \
room to the other.",
from_text: "The leader laid from the words outwards, a dash in a smaller size raised off \
the baseline.",
columns: ["Reference", "Category", "Quantity", "Unit price"],
categories: ["Binding", "Cover", "Paper"],
contents: [
"Getting started",
"The page model",
"Fonts and the text engine",
"Tables and their columns",
"Digital signatures",
],
};
/// The page in French.
const FRENCH: Words = Words {
relative: [
"Relative, par défaut : chaque tabulation avance le texte de ",
" de la colonne à partir de sa position, si bien que les lignes ne s’alignent pas.",
],
typewriter: [
"Machine à écrire : chaque tabulation tombe sur le multiple suivant de ",
" points, donc les lignes s’alignent sur cette grille.",
],
ruler: "Règle : un taquet par tabulation, le deuxième centré dessus et le troisième \
aligné sur son séparateur décimal ; l’en-tête, qui n’en a pas, se termine sur \
le taquet.",
listing: "Un taquet de règle au bord droit, le texte s’y terminant et les points de \
conduite comblant l’espace ouvert par la tabulation.",
grid_listing: "Le même taquet, les points de conduite espacés, en gris et posés sur une \
grille, donc alignés d’une ligne à l’autre.",
relative_told: [
"Relative, demandée expressément, chaque tabulation avançant le texte de ",
" de la colonne : des pas deux fois plus longs, les lignes toujours décalées.",
],
comma: "Règle, son troisième taquet alignant les prix sur une virgule décimale plutôt \
que sur un point.",
from_edge: "Les points de conduite posés depuis le bord droit : l’espace qu’ils ne \
remplissent pas reste contre le texte.",
stretch: "Les points de conduite étirés : autant de points entiers qu’il en tient, \
répartis d’un bout à l’autre de l’espace.",
from_text: "Les points de conduite posés depuis le texte, un tiret plus petit et \
surélevé par rapport à la ligne de base.",
columns: ["Référence", "Catégorie", "Quantité", "Prix unitaire"],
categories: ["Reliure", "Couverture", "Papier"],
contents: [
"Pour commencer",
"Le modèle de page",
"Les polices et le moteur de texte",
"Les tableaux et leurs colonnes",
"Les signatures numériques",
],
};
/// The page in Dutch.
const DUTCH: Words = Words {
relative: [
"Relatief, de standaard: elke tab zet de pen",
" van de kolom verder vanaf waar hij staat, dus de rijen lijnen niet uit.",
],
typewriter: [
"Schrijfmachine: elke tab komt op het volgende veelvoud van",
" punten, dus de rijen lijnen uit op dat raster.",
],
ruler: "Liniaal: een eigen tabstop voor elke tab, de tweede erop gecentreerd en de derde uitgelijnd op het decimaalteken, en de kop, die er geen heeft, eindigt op de tabstop.",
listing: "Een liniaaltabstop aan de verre rand, de tekst eindigt erop en de opvulling vult de ruimte die de tab opende.",
grid_listing: "Dezelfde tabstop, de opvulling een gespatieerde grijze punt op een raster, dus de punten staan op elke regel in dezelfde kolommen.",
relative_told: [
"Relatief, uitdrukkelijk opgegeven: elke tab zet de pen",
" van de kolom verder: stappen twee keer zo lang, de rijen nog steeds niet uitgelijnd.",
],
comma: "Liniaal, de derde tabstop lijnt de prijzen uit op een decimale komma in plaats van een punt.",
from_edge: "De opvulling gelegd van de verre rand naar binnen: de ruimte die de herhalingen niet vullen, blijft bij de woorden.",
stretch: "De opvulling uitgerekt: zoveel hele punten als passen, verspreid van het ene eind van de ruimte naar het andere.",
from_text: "De opvulling gelegd van de woorden naar buiten, een streepje in een kleinere grootte boven de basislijn.",
columns: ["Referentie", "Categorie", "Aantal", "Stukprijs"],
categories: ["Bindwerk", "Omslag", "Papier"],
contents: [
"Aan de slag",
"Het paginamodel",
"Lettertypen en de tekstmotor",
"Tabellen en hun kolommen",
"Digitale handtekeningen",
],
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
relative: [
"Relativo, por omissão: cada tabulação avança a caneta",
" da coluna a partir de onde está, por isso as linhas não se alinham.",
],
typewriter: [
"Máquina de escrever: cada tabulação cai no múltiplo seguinte de",
" pontos, por isso as linhas alinham-se nessa grelha.",
],
ruler: "Régua: uma paragem própria para cada tabulação, a segunda centrada nela e a terceira alinhada pelo separador decimal, e o título, que não tem nenhum, a acabar na paragem.",
listing: "Uma paragem de régua na margem, o texto a acabar nela e o enchimento a preencher o espaço que a tabulação abriu.",
grid_listing: "A mesma paragem, o enchimento um ponto espaçado em cinzento numa grelha, por isso os seus pontos ficam nas mesmas colunas em cada linha.",
relative_told: [
"Relativo, dito explicitamente, cada tabulação a avançar a caneta",
" da coluna: passos duas vezes mais longos, as linhas ainda desalinhadas.",
],
comma: "Régua, a terceira paragem a alinhar os preços por uma vírgula decimal em vez de um ponto.",
from_edge: "O enchimento posto da margem para dentro: o espaço que as suas repetições não enchem fica junto às palavras.",
stretch: "O enchimento esticado: tantos pontos inteiros quantos cabem, espalhados de uma ponta à outra do espaço.",
from_text: "O enchimento posto das palavras para fora, um traço num corpo menor levantado da linha de base.",
columns: ["Referência", "Categoria", "Quantidade", "Preço unitário"],
categories: ["Encadernação", "Capa", "Papel"],
contents: [
"Primeiros passos",
"O modelo de página",
"Os tipos de letra e o motor de texto",
"As tabelas e as suas colunas",
"As assinaturas digitais",
],
};
/// The page in Italian.
const ITALIAN: Words = Words {
relative: [
"Relativo, predefinito: ogni tabulazione fa avanzare la penna di",
" della colonna da dove si trova, così le righe non si allineano.",
],
typewriter: [
"Macchina da scrivere: ogni tabulazione cade sul multiplo successivo di",
" punti, così le righe si allineano su quella griglia.",
],
ruler: "Righello: un fermo proprio per ogni tabulazione, il secondo centrato su di esso e il terzo allineato sul separatore decimale, e il titolo, che non ne ha, finisce sul fermo.",
listing: "Un fermo di righello sul bordo, il testo che finisce lì e il riempitivo che occupa lo spazio aperto dalla tabulazione.",
grid_listing: "Lo stesso fermo, il riempitivo un punto spaziato in grigio su una griglia, così i suoi punti stanno nelle stesse colonne su ogni riga.",
relative_told: [
"Relativo, detto esplicitamente, ogni tabulazione che fa avanzare la penna di",
" della colonna: passi lunghi il doppio, le righe ancora disallineate.",
],
comma: "Righello, il terzo fermo che allinea i prezzi su una virgola decimale anziché su un punto.",
from_edge: "Il riempitivo steso dal bordo verso l’interno: lo spazio che le sue ripetizioni non riempiono resta vicino alle parole.",
stretch: "Il riempitivo allungato: quanti punti interi ci stanno, distribuiti da un capo all’altro dello spazio.",
from_text: "Il riempitivo steso dalle parole verso l’esterno, un trattino in un corpo minore sollevato dalla linea di base.",
columns: ["Riferimento", "Categoria", "Quantità", "Prezzo unitario"],
categories: ["Rilegatura", "Copertina", "Carta"],
contents: [
"Per iniziare",
"Il modello di pagina",
"I font e il motore del testo",
"Le tabelle e le loro colonne",
"Le firme digitali",
],
};
/// The page in Spanish.
const SPANISH: Words = Words {
relative: [
"Relativo, por defecto: cada tabulación avanza la pluma",
" de la columna desde donde está, así que las filas no se alinean.",
],
typewriter: [
"Máquina de escribir: cada tabulación cae en el siguiente múltiplo de",
" puntos, así que las filas se alinean en esa rejilla.",
],
ruler: "Regla: un tope propio por tabulación, el segundo centrado en él y el tercero alineado en su separador decimal, y el título, que no lleva ninguno, acabando en el tope.",
listing: "Un tope de regla en el borde, el texto acabando en él y el relleno ocupando el hueco que abrió la tabulación.",
grid_listing: "El mismo tope, el relleno un punto espaciado en gris sobre una rejilla, así que sus puntos quedan en las mismas columnas en cada línea.",
relative_told: [
"Relativo, dicho expresamente, cada tabulación avanzando la pluma",
" de la columna: pasos el doble de largos, las filas aún desalineadas.",
],
comma: "Regla, su tercer tope alineando los precios en una coma decimal y no en un punto.",
from_edge: "El relleno puesto desde el borde hacia dentro: el hueco que no llenan sus repeticiones queda junto a las palabras.",
stretch: "El relleno estirado: tantos puntos enteros como caben, repartidos de un extremo al otro del hueco.",
from_text: "El relleno puesto desde las palabras hacia fuera, un guion en un cuerpo menor elevado sobre la línea base.",
columns: ["Referencia", "Categoría", "Cantidad", "Precio unitario"],
categories: ["Encuadernación", "Cubierta", "Papel"],
contents: [
"Primeros pasos",
"El modelo de página",
"Las fuentes y el motor de texto",
"Las tablas y sus columnas",
"Las firmas digitales",
],
};
/// The page in German.
const GERMAN: Words = Words {
relative: [
"Relativ, die Voreinstellung: Jeder Tabulator rückt den Stift um ",
" der Spalte von seiner Stelle aus weiter, also fluchten die Zeilen nicht.",
],
typewriter: [
"Schreibmaschine: Jeder Tabulator landet auf dem nächsten Vielfachen von ",
" Punkt, also fluchten die Zeilen auf diesem Raster.",
],
ruler: "Lineal: ein eigener Stopp für jeden Tabulator, der zweite darauf zentriert und der dritte am Dezimalpunkt ausgerichtet; die Kopfzeile, die keinen hat, endet am Stopp.",
listing: "Ein Linealstopp am äußeren Rand, der Text endet dort, und die Füllzeichen füllen den Raum, den der Tabulator öffnete.",
grid_listing: "Derselbe Stopp, die Füllzeichen ein gesperrter grauer Punkt auf einem Raster, also stehen seine Punkte in jeder Zeile in denselben Spalten.",
relative_told: [
"Relativ, ausdrücklich so eingestellt, jeder Tabulator rückt den Stift um ",
" der Spalte weiter: doppelt so lange Schritte, die Zeilen fluchten noch immer nicht.",
],
comma: "Lineal, sein dritter Stopp richtet die Preise an einem Dezimalkomma statt an einem Punkt aus.",
from_edge: "Füllzeichen vom äußeren Rand nach innen gelegt: Der Raum, den ihre Wiederholungen nicht füllen, bleibt an den Wörtern.",
stretch: "Füllzeichen gestreckt: so viele ganze Punkte, wie passen, von einem Ende des Raums zum anderen verteilt.",
from_text: "Füllzeichen von den Wörtern nach außen gelegt, ein kleinerer Strich über die Grundlinie gehoben.",
columns: ["Referenz", "Kategorie", "Menge", "Einzelpreis"],
categories: ["Bindung", "Umschlag", "Papier"],
contents: [
"Erste Schritte",
"Das Seitenmodell",
"Schriften und die Text-Engine",
"Tabellen und ihre Spalten",
"Digitale Signaturen",
],
};
/// 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),
];
/// Draws one panel: its heading, the tabulated block below it, and a grey rule
/// at every stop the block was told to use.
fn panel(
c: &mut Content,
handle: &FontHandle,
top: f64,
label: &str,
flow: &TextFlow<'_>,
text: &str,
stops: &[f64],
) -> Result<(), Box<dyn std::error::Error>> {
let heading = TextFlow::new(handle, 8.0);
let heading_lines = heading.break_lines(label, COLUMN);
c.begin_text();
heading.draw(c, &heading_lines, X, top, COLUMN)?;
c.end_text();
let text_top = top - DROP;
let lines = flow.break_lines(text, COLUMN);
let height = flow.height(&lines);
// The stops first, so the text is read over them rather than under them.
c.save_state();
c.set_stroke_rgb(0.78, 0.78, 0.82)?.set_line_width(0.5)?;
for stop in stops {
c.move_to(X + stop, text_top)?
.line_to(X + stop, text_top - height)?
.stroke();
}
c.restore_state();
c.begin_text();
flow.draw(c, &lines, X, text_top, COLUMN)?;
c.end_text();
Ok(())
}
/// The second page: the relative method told so at a wider step, the ruler on a
/// decimal comma, and the table of contents under three more leaders.
fn second_page(handle: &FontHandle, words: &Words) -> Result<Page, Box<dyn std::error::Error>> {
let mut c = Content::new();
let rows = words.rows();
// The method a flow takes when told nothing, told so, at a step of its own.
let relative = TextFlow::new(handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Relative)
.tab_size(TabSize::Fraction(WIDE_SHARE));
panel(
&mut c,
handle,
780.0,
&words.relative_told_label(),
&relative,
&rows,
&[],
)?;
let comma = TextFlow::new(handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Ruler)
.tab_ruler(RULER)
.tab_alignments([TabAlign::Left, TabAlign::Center, TabAlign::Decimal])
.tab_align_char(',');
panel(
&mut c,
handle,
660.0,
words.comma,
&comma,
&words.comma_rows(),
&RULER,
)?;
let listed = words.contents();
let leaders = [
(
540.0,
words.from_edge,
Leader::new(". ")
.color(Rgb::new(0.55, 0.55, 0.55))
.fit(LeaderFit::FromEdge),
),
(
400.0,
words.stretch,
Leader::new(".").fit(LeaderFit::Stretch),
),
(
260.0,
words.from_text,
Leader::new("\u{2013} ")
.font(handle, 7.0)
.rise(2.0)
.fit(LeaderFit::FromText),
),
];
for (top, label, leader) in leaders {
let flow = TextFlow::new(handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Ruler)
.tab_ruler([COLUMN])
.tab_alignments([TabAlign::Right])
.leader_with(leader);
panel(&mut c, handle, top, label, &flow, &listed, &[COLUMN])?;
}
let mut page = Page::a4();
page.content = c.into_bytes();
Ok(page)
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("tab_stops")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let font = Font::parse(fs::read(&font_path)?)?;
let mut doc = Document::new();
doc.set_license(licence::licensed());
let handle = doc.add_font(font);
let mut c = Content::new();
let rows = words.rows();
// Relative, which is what a flow does when it is told nothing: every
// tabulation steps the pen on by the tab size from wherever it stands, so a
// longer entry pushes the whole row along with it.
let relative = TextFlow::new(&handle, 11.0).leading(16.0);
panel(
&mut c,
&handle,
780.0,
&words.relative_label(),
&relative,
&rows,
&[],
)?;
// A typewriter's tab bar: every tabulation lands on the next multiple of
// the tab size, so the rows line up on a grid however wide their entries
// are.
let typewriter = TextFlow::new(&handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Typewriter)
.tab_size(TabSize::Points(GRID));
panel(
&mut c,
&handle,
660.0,
&words.typewriter_label(),
&typewriter,
&rows,
&[GRID, GRID * 2.0, GRID * 3.0, GRID * 4.0],
)?;
// A ruler names its stops, and each one says how the run it opens sits
// about it: the quantities are centred, the prices line up on their decimal
// point.
let ruler = TextFlow::new(&handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Ruler)
.tab_ruler(RULER)
.tab_alignments([TabAlign::Left, TabAlign::Center, TabAlign::Decimal]);
panel(&mut c, &handle, 540.0, words.ruler, &ruler, &rows, &RULER)?;
// The stop sits at the far edge and the run ends on it, so the numbers are
// flush right whatever they are worth, and the leader fills the room the
// tabulation opened.
let contents = TextFlow::new(&handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Ruler)
.tab_ruler([COLUMN])
.tab_alignments([TabAlign::Right])
.leader('.');
panel(
&mut c,
&handle,
420.0,
words.listing,
&contents,
&words.contents(),
&[COLUMN],
)?;
// The same listing, its leader a dot and a space in grey, laid on a grid of
// its own width counted from the left edge of the box.
let gridded = TextFlow::new(&handle, 11.0)
.leading(16.0)
.tab_method(TabMethod::Ruler)
.tab_ruler([COLUMN])
.tab_alignments([TabAlign::Right])
.leader_with(
Leader::new(". ")
.color(Rgb::new(0.55, 0.55, 0.55))
.fit(LeaderFit::Grid),
);
panel(
&mut c,
&handle,
280.0,
words.grid_listing,
&gridded,
&words.contents(),
&[COLUMN],
)?;
let mut page = Page::a4();
page.content = c.into_bytes();
doc.add_page(page)?;
doc.add_page(second_page(&handle, words)?)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&out).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out, &bytes)?;
println!("wrote {out}: {} bytes", bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::{Document, Font, TabSize};
use super::{RULER, SHARE, WIDE_SHARE, WIDE_SHARE_SAID, WORDS, default_font, language};
/// The lines two languages are allowed to write the same way. Every line in
/// `Words` is a label, a column heading, a category or a chapter title, and
/// two languages write one alike only where they spell it alike; the
/// references, the figures and the page numbers are not in `Words` at all.
const SPARED: [&str; 3] = [
// Written the same way in German.
r#""Papier""#,
// Written the same way in Portuguese.
r#""Categoria""#,
r#""Papel""#,
];
/// The size the tabulated blocks are set at.
const BODY: f64 = 11.0;
#[test]
fn every_language_labels_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 ruler panel sends each tabulation to a stop of its own, and a run
/// wider than the gap to the next stop runs over what lands there. The
/// headings are the widest thing in each column, so they are what has to
/// fit.
#[test]
fn every_language_writes_headings_that_fit_between_the_stops() {
let mut doc = Document::new();
let text = doc.add_font(
Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses"),
);
let gaps = [
RULER[0],
RULER[1] - RULER[0],
RULER[2] - RULER[1],
RULER[2] - RULER[1],
];
for (named, words) in WORDS {
let code = named.code();
for (heading, gap) in words.columns.iter().zip(gaps) {
let measured = text.measure(heading, BODY);
assert!(
measured < gap,
"the {code} page sets {heading:?} over {measured:.1} points, \
and the column it heads is {gap:.1} wide"
);
}
}
}
/// The first panel's label spells out the share of a line one tabulation
/// opens when a flow is told nothing. No language works it out from the
/// page, so a library that stepped by another share would leave every one
/// of them saying a number the panel no longer shows.
#[test]
fn the_first_panel_names_the_share_a_flow_takes_when_it_is_told_nothing() {
let TabSize::Fraction(share) = TabSize::default() else {
panic!("a flow told nothing steps by a share of the line, not by a distance")
};
assert_eq!(format!("{}%", share * 100.0), SHARE);
}
/// The second page's relative panel spells out the share it was given.
#[test]
fn the_second_relative_panel_names_the_share_it_steps_by() {
assert_eq!(format!("{}%", WIDE_SHARE * 100.0), WIDE_SHARE_SAID);
}
}
|