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 | //! Prints two orders of unequal length side by side in frames of one height,
//! and ends both of them on the same bottom edge.
//!
//! A pad of pre-printed stationery has the frame already on the paper: a box
//! for the lines, a rule under it, and the total below that rule. What goes in
//! the box is a different length every time. Left alone, an order of four lines
//! leaves a hand's breadth of white above the rule and an order of seven fills
//! it, and the pad looks like two different documents.
//!
//! So the box is filled instead. The rows of the order share whatever room the
//! frame has left, in equal parts, once they have all been measured, and the
//! last of them ends on the bottom edge. The headings and the total are left
//! exactly where the stationery puts them.
//!
//! The notes at the foot of the page do the same for words rather than rows:
//! the lines of each note are moved apart until they reach the bottom of their
//! box, so two notes of unequal length end on one line. A limit is given with
//! the box, and a note far too short for it keeps the spacing it came with
//! rather than being stretched into a ladder.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The amounts are the same in both.
//!
//! Usage: `cargo run --example write_filled_frame -- [out.pdf] [face.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_filled_frame`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::layout::{
Cell, ColumnWidth, Columns, FirstBaseline, LastBaseline, Padding, Row, Rule, Stroke, Table,
TableFrame, VAlign,
};
use hqf_pdf::{Align, Document, Font, FontHandle, Page, Rgb, TextFlow};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
use language::Language;
/// The font the page is set in when none is given on the command line: the one
/// committed for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// How many lines the shorter order bills.
const SHORT_COUNT: usize = 4;
/// How many lines the longer order bills.
const LONG_COUNT: usize = 7;
/// What the shorter order's lines cost, in euros.
const SHORT_AMOUNTS: [f64; SHORT_COUNT] = [420.0, 96.0, 158.0, 240.0];
/// What the longer order's lines cost, in euros.
const LONG_AMOUNTS: [f64; LONG_COUNT] = [180.0, 64.0, 112.0, 45.0, 320.0, 88.0, 150.0];
/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
/// The page's title.
title: &'static str,
/// What the page is about.
lead: &'static str,
/// The label over the two orders.
orders: &'static str,
/// What each order is called, over its own frame.
short_order: &'static str,
long_order: &'static str,
/// The two column headings of an order.
item: &'static str,
amount: &'static str,
/// What the shorter order bills.
short_items: [&'static str; SHORT_COUNT],
/// What the longer order bills.
long_items: [&'static str; LONG_COUNT],
/// The label on the last row of an order.
total: &'static str,
/// The label over the two notes.
notes: &'static str,
/// What each note says.
short_note: &'static str,
long_note: &'static str,
/// What the page leaves the reader with.
caveat: &'static str,
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Two orders, one frame, one bottom edge",
lead: "The two frames below are the same height, and the orders in them are \
not the same length. Each frame is filled: whatever room the lines \
leave is shared out among them in equal parts, once they have all been \
measured, so the last line of an order of four ends where the last line \
of an order of seven ends. The headings and the total stay where the \
stationery puts them, and only the billed lines grow.",
orders: "Four lines and seven, ending together",
short_order: "Order 4412",
long_order: "Order 4413",
item: "Item",
amount: "Amount",
short_items: [
"Site survey",
"Cable, 40 m",
"Wall boxes",
"Fitting, one day",
],
long_items: [
"Site survey",
"Cable, 15 m",
"Wall boxes",
"Junction box",
"Fitting, two days",
"Cover plates",
"Test and report",
],
total: "Total",
notes: "Two notes of unequal length, ending together",
short_note: "Goods stay ours until they are paid for in full. Anything found \
broken is to be written on the driver's sheet before it is \
signed, and told to us the same week. A pallet left with a \
neighbour is left at the buyer's own risk.",
long_note: "Payment is due thirty days from the date of issue, by transfer to \
the account named at the foot of the invoice. A line queried in \
writing suspends nothing but the line itself, and the rest of the \
invoice falls due on the day it always did. Work already booked \
is held for a fortnight after that day and released afterwards.",
caveat: "The lines of a note are moved apart, and nothing else: the room kept \
around a paragraph, the drop under the last line and the height of \
the words themselves stand where they are. A limit is given along \
with the box, so two lines in a tall box keep the spacing they came \
with rather than being stretched into a ladder.",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Deux commandes, un seul cadre, un même bord inférieur",
lead: "Les deux cadres ci-dessous ont la même hauteur, mais les commandes qu’ils \
contiennent n’ont pas la même longueur. Chaque cadre est rempli : la place que \
laissent les lignes est répartie entre elles à parts égales, une fois toutes \
mesurées, si bien que la dernière ligne d’une commande de quatre lignes finit \
au même niveau que celle d’une commande de sept. Les en-têtes et le total \
restent là où le modèle les place ; seules les lignes facturées \
s’agrandissent.",
orders: "Quatre lignes et sept, qui finissent ensemble",
short_order: "Commande 4412",
long_order: "Commande 4413",
item: "Poste",
amount: "Montant",
short_items: [
"Visite des lieux",
"Câble, 40 m",
"Boîtiers muraux",
"Pose, une journée",
],
long_items: [
"Visite des lieux",
"Câble, 15 m",
"Boîtiers muraux",
"Boîte de dérivation",
"Pose, deux journées",
"Plaques de finition",
"Essais et rapport",
],
total: "Total",
notes: "Deux mentions de longueurs différentes, qui finissent ensemble",
short_note: "La marchandise reste notre propriété jusqu’au paiement intégral. Tout élément \
trouvé cassé doit être inscrit sur la feuille du chauffeur avant signature, et \
nous être signalé dans la semaine. Une palette laissée chez un voisin l’est \
aux risques de l’acheteur.",
long_note: "Le paiement est dû trente jours après la date d’émission, par virement au \
compte indiqué au bas de la facture. Une ligne contestée par écrit ne suspend \
que cette ligne ; le reste de la facture demeure exigible à la date prévue. \
Les travaux déjà planifiés restent réservés quinze jours après cette date, \
puis sont libérés.",
caveat: "Seules les lignes d’une mention sont écartées : l’espace réservé autour d’un \
paragraphe, celui sous la dernière ligne et la hauteur des mots eux-mêmes ne \
bougent pas. Le cadre est donné avec une limite : deux lignes dans un grand \
cadre gardent ainsi leur interligne d’origine au lieu de s’étirer en échelle.",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Twee bestellingen, één kader, één onderrand",
lead: "De twee kaders hieronder zijn even hoog, en de bestellingen erin zijn niet even lang. Elk kader wordt gevuld: de ruimte die de regels overlaten wordt in gelijke delen over de regels verdeeld, nadat ze allemaal gemeten zijn, dus de laatste regel van een bestelling van vier eindigt waar de laatste regel van een bestelling van zeven eindigt. De koppen en het totaal blijven waar het briefpapier ze zet, en alleen de gefactureerde regels groeien.",
orders: "Vier regels en zeven, die samen eindigen",
short_order: "Bestelling 4412",
long_order: "Bestelling 4413",
item: "Artikel",
amount: "Bedrag",
short_items: [
"Opname ter plaatse",
"Kabel, 40 m",
"Wanddozen",
"Montage, één dag",
],
long_items: [
"Opname ter plaatse",
"Kabel, 15 m",
"Wanddozen",
"Aansluitdoos",
"Montage, twee dagen",
"Afdekplaten",
"Test en rapport",
],
total: "Totaal",
notes: "Twee notities van ongelijke lengte, die samen eindigen",
short_note: "Goederen blijven van ons tot ze volledig betaald zijn. Wat kapot aankomt, wordt op het blad van de chauffeur genoteerd voordat het getekend wordt, en ons dezelfde week gemeld. Een pallet die bij de buren wordt achtergelaten, is voor risico van de koper.",
long_note: "Betaling vervalt dertig dagen na de uitgiftedatum, per overschrijving naar de rekening onderaan de factuur. Een schriftelijk betwiste regel schort alleen die regel op, en de rest van de factuur vervalt op de gewone dag. Al geboekt werk blijft na die dag twee weken gereserveerd en komt daarna vrij.",
caveat: "De regels van een notitie worden uit elkaar gezet, en verder niets: de ruimte rond een alinea, de ruimte onder de laatste regel en de hoogte van de woorden zelf blijven waar ze zijn. Samen met het kader wordt een grens gegeven, dus twee regels in een hoog kader houden hun regelafstand in plaats van tot een ladder uitgerekt te worden.",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Duas encomendas, uma moldura, uma mesma margem inferior",
lead: "As duas molduras abaixo têm a mesma altura, e as encomendas que contêm não têm o mesmo comprimento. Cada moldura é preenchida: o espaço que as linhas deixam reparte-se entre elas em partes iguais, depois de todas medidas, por isso a última linha de uma encomenda de quatro acaba onde acaba a última de uma encomenda de sete. Os títulos e o total ficam onde os põe o papel timbrado, e só crescem as linhas faturadas.",
orders: "Quatro linhas e sete, a acabar juntas",
short_order: "Encomenda 4412",
long_order: "Encomenda 4413",
item: "Artigo",
amount: "Montante",
short_items: [
"Visita técnica",
"Cabo, 40 m",
"Caixas de parede",
"Montagem, um dia",
],
long_items: [
"Visita técnica",
"Cabo, 15 m",
"Caixas de parede",
"Caixa de derivação",
"Montagem, dois dias",
"Espelhos",
"Ensaio e relatório",
],
total: "Total",
notes: "Duas notas de comprimento desigual, a acabar juntas",
short_note: "A mercadoria é nossa até ser paga por inteiro. O que chegar partido anota-se na folha do motorista antes de assinar e comunica-se-nos na mesma semana. Uma palete deixada a um vizinho fica por conta e risco do comprador.",
long_note: "O pagamento vence a trinta dias da data de emissão, por transferência para a conta indicada no rodapé da fatura. Uma linha contestada por escrito só suspende essa linha, e o resto da fatura vence na data prevista. O trabalho já agendado é mantido até quinze dias após essa data e, depois, libertado.",
caveat: "As linhas de uma nota afastam-se, e nada mais: o espaço à volta de um parágrafo, a queda sob a última linha e a altura das próprias palavras ficam onde estão. Com a caixa dá-se um limite, por isso duas linhas numa caixa alta mantêm o entrelinhamento em vez de se esticarem em escada.",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Due ordini, una cornice, un solo bordo inferiore",
lead: "Le due cornici qui sotto hanno la stessa altezza, e gli ordini che contengono non hanno la stessa lunghezza. Ogni cornice è riempita: lo spazio lasciato dalle righe si ripartisce tra loro in parti uguali, una volta misurate tutte, così l’ultima riga di un ordine di quattro finisce dove finisce l’ultima di un ordine di sette. I titoli e il totale restano dove li mette la carta intestata, e crescono solo le righe fatturate.",
orders: "Quattro righe e sette, che finiscono insieme",
short_order: "Ordine 4412",
long_order: "Ordine 4413",
item: "Voce",
amount: "Importo",
short_items: [
"Sopralluogo",
"Cavo, 40 m",
"Scatole a muro",
"Posa, un giorno",
],
long_items: [
"Sopralluogo",
"Cavo, 15 m",
"Scatole a muro",
"Scatola di derivazione",
"Posa, due giorni",
"Placche",
"Collaudo e rapporto",
],
total: "Totale",
notes: "Due note di lunghezza diversa, che finiscono insieme",
short_note: "La merce resta nostra finché non è pagata per intero. Ciò che arriva rotto va scritto sul foglio dell’autista prima di firmarlo e comunicato a noi nella stessa settimana. Un bancale lasciato a un vicino resta a rischio dell’acquirente.",
long_note: "Il pagamento scade a trenta giorni dalla data di emissione, con bonifico sul conto indicato a piè di fattura. Una riga contestata per iscritto sospende solo quella riga, e il resto della fattura scade il giorno di sempre. Il lavoro già prenotato è tenuto quindici giorni dopo quel giorno e poi liberato.",
caveat: "Le righe di una nota si allontanano, e nient’altro: lo spazio intorno a un paragrafo, la caduta sotto l’ultima riga e l’altezza delle parole stesse restano dove sono. Con la cornice si dà un limite, così due righe in una cornice alta tengono la loro interlinea anziché sparpagliarsi per tutta l’altezza.",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Dos pedidos, un marco, un mismo borde inferior",
lead: "Los dos marcos de abajo tienen la misma altura, y los pedidos que contienen no tienen la misma longitud. Cada marco se llena: el sitio que dejan las líneas se reparte entre ellas a partes iguales, una vez medidas todas, así que la última línea de un pedido de cuatro acaba donde acaba la última de un pedido de siete. Los títulos y el total se quedan donde los pone el papel, y solo crecen las líneas facturadas.",
orders: "Cuatro líneas y siete, acabando juntas",
short_order: "Pedido 4412",
long_order: "Pedido 4413",
item: "Artículo",
amount: "Importe",
short_items: [
"Visita técnica",
"Cable, 40 m",
"Cajas de pared",
"Montaje, un día",
],
long_items: [
"Visita técnica",
"Cable, 15 m",
"Cajas de pared",
"Caja de empalmes",
"Montaje, dos días",
"Tapas",
"Prueba e informe",
],
total: "Total",
notes: "Dos notas de distinta longitud, acabando juntas",
short_note: "La mercancía es nuestra hasta que se paga por completo. Lo que llegue roto se anota en la hoja del conductor antes de firmarla y se nos comunica la misma semana. Un palé dejado a un vecino queda a riesgo del comprador.",
long_note: "El pago vence a treinta días de la fecha de emisión, por transferencia a la cuenta indicada al pie de la factura. Una línea impugnada por escrito solo suspende esa línea, y el resto de la factura vence en la fecha prevista. El trabajo ya reservado se mantiene quince días después de ese día y luego se libera.",
caveat: "Las líneas de una nota se separan, y nada más: el espacio alrededor de un párrafo, el espacio bajo la última línea y la altura de las propias palabras se quedan como están. La caja fija un límite, así que dos líneas en una caja alta conservan su interlineado en vez de estirarse en escalera.",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Zwei Bestellungen, ein Rahmen, eine Unterkante",
lead: "Die beiden Rahmen unten sind gleich hoch, und die Bestellungen darin sind nicht gleich lang. Jeder Rahmen wird gefüllt: Der Platz, den die Zeilen übrig lassen, wird zu gleichen Teilen unter ihnen verteilt, sobald alle gemessen sind, sodass die letzte Zeile einer Bestellung mit vier Posten dort endet, wo die letzte Zeile einer Bestellung mit sieben endet. Die Überschriften und die Summe bleiben, wo das Briefpapier sie vorsieht, und nur die berechneten Zeilen wachsen.",
orders: "Vier Zeilen und sieben, die zusammen enden",
short_order: "Bestellung 4412",
long_order: "Bestellung 4413",
item: "Posten",
amount: "Betrag",
short_items: [
"Ortsbesichtigung",
"Kabel, 40 m",
"Wanddosen",
"Montage, ein Tag",
],
long_items: [
"Ortsbesichtigung",
"Kabel, 15 m",
"Wanddosen",
"Abzweigdose",
"Montage, zwei Tage",
"Abdeckplatten",
"Prüfung und Bericht",
],
total: "Summe",
notes: "Zwei ungleich lange Hinweise, die zusammen enden",
short_note: "Die Ware bleibt unser Eigentum, bis sie vollständig bezahlt ist. Was beschädigt ankommt, ist auf dem Blatt des Fahrers zu vermerken, bevor es unterschrieben wird, und uns in derselben Woche mitzuteilen. Eine bei einem Nachbarn abgegebene Palette bleibt auf eigene Gefahr des Käufers dort.",
long_note: "Die Zahlung ist dreißig Tage nach dem Ausstellungsdatum fällig, per Überweisung auf das im Fuß der Rechnung genannte Konto. Eine schriftlich beanstandete Zeile hält nur diese Zeile an, und der Rest der Rechnung wird an dem Tag fällig, an dem er ohnehin fällig geworden wäre. Bereits gebuchte Arbeit wird nach diesem Tag vierzehn Tage lang vorgehalten und danach freigegeben.",
caveat: "Die Zeilen eines Hinweises werden auseinandergerückt, und sonst nichts: Der Raum um einen Absatz, der Abstand unter der letzten Zeile und die Höhe der Wörter selbst bleiben, wie sie sind. Mit dem Rahmen wird eine Grenze angegeben, sodass zwei Zeilen in einem hohen Rahmen ihren Abstand behalten, statt zu einer Leiter gestreckt zu werden.",
};
/// 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 LEFT: f64 = 72.0;
/// How wide a block of text is, and how wide the two frames are together.
const WIDTH: f64 = 451.0;
/// How wide one frame is.
const FRAME_WIDTH: f64 = 216.0;
/// How far apart the two frames stand.
const FRAME_GAP: f64 = WIDTH - 2.0 * FRAME_WIDTH;
/// How tall each of the two order frames is.
const FRAME_HEIGHT: f64 = 200.0;
/// How tall each of the two note boxes is.
const NOTE_HEIGHT: f64 = 110.0;
/// The size a note is set at.
const NOTE_SIZE: f64 = 8.5;
/// The furthest apart the lines of a note are ever moved.
const NOTE_LIMIT: f64 = 26.0;
/// The size an order is set at.
const ORDER_SIZE: f64 = 8.5;
/// The least tall a billed line is before the frame is shared out.
const ROW_HEIGHT: f64 = 16.0;
/// The grey the page draws its second-rank words in.
const GREY: Rgb = Rgb::gray(0.42);
/// The grey a note's box is outlined in.
const OUTLINE: Rgb = Rgb::gray(0.72);
/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
c: &mut Content,
flow: &TextFlow,
x: f64,
top: f64,
width: f64,
text: &str,
) -> Result<f64, Box<dyn std::error::Error>> {
let lines = flow.break_lines(text, width);
c.begin_text();
flow.draw(c, &lines, x, top, width)?;
c.end_text();
Ok(top - flow.height(&lines))
}
/// An amount, as an order writes it: "1 158.00".
fn amount(value: f64) -> String {
let fixed = format!("{value:.2}");
let (units, hundredths) = fixed.split_once('.').unwrap_or((fixed.as_str(), "00"));
let mut grouped = String::new();
for (index, digit) in units.chars().enumerate() {
if index > 0 && (units.len() - index) % 3 == 0 {
grouped.push('\u{00A0}');
}
grouped.push(digit);
}
format!("{grouped}.{hundredths}")
}
/// One of the two orders: a heading row, the billed lines, and the total.
fn order<'a>(
handle: &'a FontHandle,
words: &'static Words,
items: &'static [&'static str],
amounts: &'static [f64],
) -> Result<Table<'a>, hqf_pdf::Error> {
let columns = Columns::new(
vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(62.0)],
FRAME_WIDTH,
)?;
let mut table = Table::new(columns);
table.header(1);
table.footer(1);
// Every box the table is fitted into is filled to its bottom edge.
table.fill_frame(true);
table
.rule(Rule::Frame, Stroke::black(0.7))
.rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.78)))
.rule(Rule::Horizontal(1), Stroke::black(0.7))
.rule(Rule::HorizontalFromEnd(1), Stroke::black(0.7));
let pad = Padding::symmetric(5.0, 4.0);
table.push(
Row::new()
.cell(
Cell::new(handle, ORDER_SIZE, words.item)
.padding(pad)
.fill(Rgb::gray(0.9))
.valign(VAlign::Middle),
)
.cell(
Cell::new(handle, ORDER_SIZE, words.amount)
.padding(pad)
.align(Align::Right)
.fill(Rgb::gray(0.9))
.valign(VAlign::Middle),
)
.min_height(18.0),
);
let mut total = 0.0;
for (label, value) in items.iter().zip(amounts) {
total += value;
table.push(
Row::new()
.cell(
Cell::new(handle, ORDER_SIZE, *label)
.padding(pad)
.valign(VAlign::Middle),
)
.cell(
Cell::new(handle, ORDER_SIZE, amount(*value))
.padding(pad)
.align(Align::Right)
.valign(VAlign::Middle),
)
.min_height(ROW_HEIGHT),
);
}
table.push(
Row::new()
.cell(
Cell::new(handle, ORDER_SIZE, words.total)
.padding(pad)
.valign(VAlign::Middle),
)
.cell(
Cell::new(handle, ORDER_SIZE, amount(total))
.padding(pad)
.align(Align::Right)
.valign(VAlign::Middle),
)
.min_height(18.0),
);
Ok(table)
}
/// Draws one note in a box `NOTE_HEIGHT` points tall, its lines moved apart
/// until the last of them reaches the bottom.
fn note(
c: &mut Content,
handle: &FontHandle,
x: f64,
top: f64,
text: &str,
) -> Result<(), Box<dyn std::error::Error>> {
c.set_stroke(OUTLINE)?;
c.set_line_width(0.4)?;
c.rect(x, top - NOTE_HEIGHT, FRAME_WIDTH, NOTE_HEIGHT)?;
c.stroke();
// The box is filled from the top of the letters to the foot of them, so the
// block the spread is measured against is the block a reader sees.
let flow = TextFlow::new(handle, NOTE_SIZE)
.first_baseline(FirstBaseline::Ascender)
.last_baseline(LastBaseline::Descender);
let lines = flow.break_lines(text, FRAME_WIDTH - 12.0);
let spread = flow
.clone()
.leading(flow.fill_leading(&lines, NOTE_HEIGHT, NOTE_LIMIT));
c.begin_text();
spread.draw(c, &lines, x + 6.0, top, FRAME_WIDTH - 12.0)?;
c.end_text();
Ok(())
}
/// Draws the whole page.
fn build(words: &'static Words, font: Font) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut doc = Document::new();
doc.set_license(licence::licensed());
let handle = doc.add_font(font);
let title = TextFlow::new(&handle, 18.0);
let lead = TextFlow::new(&handle, 10.0);
let label = TextFlow::new(&handle, 12.0);
let small = TextFlow::new(&handle, 8.5).color(GREY);
let mut c = Content::new();
let mut top = 790.0;
top = block(&mut c, &title, LEFT, top, WIDTH, words.title)? - 12.0;
top = block(&mut c, &lead, LEFT, top, WIDTH, words.lead)? - 22.0;
top = block(&mut c, &label, LEFT, top, WIDTH, words.orders)? - 12.0;
let right = LEFT + FRAME_WIDTH + FRAME_GAP;
block(&mut c, &small, LEFT, top, FRAME_WIDTH, words.short_order)?;
top = block(&mut c, &small, right, top, FRAME_WIDTH, words.long_order)? - 6.0;
for (x, items, amounts) in [
(LEFT, words.short_items.as_slice(), SHORT_AMOUNTS.as_slice()),
(right, words.long_items.as_slice(), LONG_AMOUNTS.as_slice()),
] {
let table = order(&handle, words, items, amounts)?;
let placed = table.fit(TableFrame::new(x, top, FRAME_HEIGHT), 0)?;
placed.draw(&mut c)?;
}
top -= FRAME_HEIGHT + 26.0;
top = block(&mut c, &label, LEFT, top, WIDTH, words.notes)? - 14.0;
note(&mut c, &handle, LEFT, top, words.short_note)?;
note(&mut c, &handle, right, top, words.long_note)?;
top -= NOTE_HEIGHT + 24.0;
let closing = TextFlow::new(&handle, 9.0).color(GREY);
block(&mut c, &closing, LEFT, top, WIDTH, words.caveat)?;
let mut page = Page::a4();
page.content = c.into_bytes();
doc.add_page(page)?;
Ok(doc.to_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 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("filled_frame")));
let face = args.next().map_or_else(default_font, PathBuf::from);
let font = Font::parse(fs::read(&face)?)?;
let drawn = build(words, font)?;
if let Some(parent) = Path::new(&out).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out, &drawn)?;
println!("wrote {out}: {} bytes", drawn.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::layout::{FirstBaseline, LastBaseline, TableFrame};
use hqf_pdf::{Document, Font, TextFlow};
use super::{
FRAME_HEIGHT, FRAME_WIDTH, LONG_AMOUNTS, LONG_COUNT, NOTE_HEIGHT, NOTE_LIMIT, NOTE_SIZE,
SHORT_AMOUNTS, SHORT_COUNT, WORDS, Words, amount, default_font, language, order,
};
/// The lines two languages are allowed to write the same way: an order is
/// named by its number, and a total is a total in both.
const SPARED: [&str; 8] = [
"short_order: \"Order 4412\"",
"long_order: \"Order 4413\"",
"total: \"Total\"",
// Written the same way in Spanish.
r#""Cable, 15 m""#,
r#""Cable, 40 m""#,
// Written the same way in Portuguese.
r#""Visita técnica""#,
// Written the same way in Dutch.
r#""Kabel, 15 m""#,
r#""Kabel, 40 m""#,
];
/// The committed font, parsed.
fn fixture() -> Font {
Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses")
}
#[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 whole point of the page: two orders of unequal length, fitted into
/// frames of one height, place the same number of rows and both reach the
/// bottom edge.
#[test]
fn both_orders_fill_the_frame_they_are_given() {
let mut doc = Document::new();
let handle = doc.add_font(fixture());
for (named, words) in WORDS {
for (items, amounts, count) in [
(
words.short_items.as_slice(),
SHORT_AMOUNTS.as_slice(),
SHORT_COUNT,
),
(
words.long_items.as_slice(),
LONG_AMOUNTS.as_slice(),
LONG_COUNT,
),
] {
let table = order(&handle, words, items, amounts).expect("the order lays out");
let placed = table
.fit(TableFrame::new(0.0, FRAME_HEIGHT, FRAME_HEIGHT), 0)
.expect("the order fits its frame");
assert_eq!(
placed.row_count(),
count + 2,
"the {} order of {count} lines placed {} rows of {}",
named.code(),
placed.row_count(),
count + 2
);
assert!(
(placed.height() - FRAME_HEIGHT).abs() < 1e-6,
"the {} order of {count} lines reaches {:.3} of {FRAME_HEIGHT:.3}",
named.code(),
placed.height()
);
}
}
}
/// The two notes are what makes the second half worth drawing: they are of
/// unequal length, and the spread brings both to the bottom of the box
/// without ever passing the limit.
#[test]
fn both_notes_reach_the_bottom_of_their_box_within_the_limit() {
let mut doc = Document::new();
let handle = doc.add_font(fixture());
let flow = TextFlow::new(&handle, NOTE_SIZE)
.first_baseline(FirstBaseline::Ascender)
.last_baseline(LastBaseline::Descender);
for (named, words) in WORDS {
let mut counts = Vec::new();
for text in [words.short_note, words.long_note] {
let lines = flow.break_lines(text, FRAME_WIDTH - 12.0);
counts.push(lines.len());
let leading = flow.fill_leading(&lines, NOTE_HEIGHT, NOTE_LIMIT);
assert!(
leading <= NOTE_LIMIT,
"the {} note is spread to {leading:.2}, over the limit of {NOTE_LIMIT:.2}",
named.code()
);
let spread = flow.clone().leading(leading);
assert!(
(spread.height(&lines) - NOTE_HEIGHT).abs() < 1e-6,
"the {} note reaches {:.3} of {NOTE_HEIGHT:.3}",
named.code(),
spread.height(&lines)
);
}
assert_ne!(
counts[0],
counts[1],
"the two {} notes are the same length, and the page says they are not",
named.code()
);
}
}
/// The two orders have to differ, or the frames prove nothing.
#[test]
fn the_two_orders_bill_a_different_number_of_lines() {
assert_ne!(SHORT_COUNT, LONG_COUNT);
assert_eq!(SHORT_AMOUNTS.len(), SHORT_COUNT);
assert_eq!(LONG_AMOUNTS.len(), LONG_COUNT);
}
#[test]
fn an_amount_is_written_with_a_space_between_its_thousands() {
assert_eq!(amount(96.0), "96.00");
assert_eq!(amount(1158.5), "1\u{00A0}158.50");
}
/// The words are read through a reference of the same life as the tables
/// built from them, which is what `order` asks for.
#[test]
fn the_words_of_a_language_outlive_the_order_they_bill() {
let words: &'static Words = language::pick(&WORDS, language::Language::English);
assert_eq!(words.short_items.len(), SHORT_COUNT);
}
}
|