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 | //! Prints a sheet of conference badges whose boxes are all one size and whose
//! names are not, letting each name find the size at which it fits.
//!
//! A badge is a rectangle a printer cut before anyone knew who would wear it.
//! The name that goes in it is whatever the register holds: two short words for
//! one guest, a double-barrelled surname for the next. Asking for a size that
//! suits the longest name would leave the short ones lost in their boxes, and
//! asking for one that suits the short names would push the long ones out of
//! theirs.
//!
//! Each name here is therefore handed its box and asked what size it fits at.
//! The sizes step down by a quarter of a point until the whole of the name
//! stays inside the box on both counts, and the badge is set at the first size
//! that holds. The size each one settled on is printed under its badge, so the
//! sheet says what it did.
//!
//! A floor stops the shrinking, and the last panel shows what happens at it: a
//! name too long for a luggage tag comes back at the floor whether it fits
//! there or not, the tag is drawn clipped to its own edges, and the caller
//! decides what to do about it.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The guests' names are the same in both.
//!
//! Usage: `cargo run --example write_shrink_to_fit -- [out.pdf] [face.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_shrink_to_fit`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
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 sheet 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 badges the sheet carries.
const BADGE_COUNT: usize = 8;
/// The guests the sheet is printed for, in the order the badges are laid out.
///
/// A name is a name in every language, so these stay out of `Words`. They run
/// from two short words to a double-barrelled surname longer than the box.
const GUESTS: [&str; BADGE_COUNT] = [
"Ana Ruiz",
"Wei Chen",
"Marguerite Vandenbossche",
"Jean-Baptiste Delaunay",
"Konstantinos Papadopoulos",
"Aleksandra Wiśniewska-Kowalczyk",
"Åsa Lindqvist",
"Mohammed Al-Rashid ibn Saleh",
];
/// The name on the luggage tag, which no size fits.
const TAGGED: &str = "Bartholomew Christopher Fitzwilliam-Harrington";
/// The words the sheet is written in, one set per language.
#[derive(Debug)]
struct Words {
/// The sheet's title.
title: &'static str,
/// What the sheet is about.
lead: &'static str,
/// The label over the eight badges.
sheet: &'static str,
/// What each guest is at the conference, in the order `GUESTS` names them.
roles: [&'static str; BADGE_COUNT],
/// The line under a badge saying what size its name came out at.
settled: &'static str,
/// The label over the luggage tag.
floor: &'static str,
/// What the floor does.
floored: &'static str,
/// The line under the luggage tag.
clipped: &'static str,
/// What the sheet leaves the reader with.
caveat: &'static str,
}
impl Words {
/// The words the sheet is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The sheet in English.
const ENGLISH: Words = Words {
title: "Badges of one size, names of every length",
lead: "The eight boxes below are the same box, cut before anyone knew who \
would wear it. Each name is handed the box it has to fit and asked \
what size it fits at: the sizes step down by a quarter of a point, \
each one broken to the width of the box and weighed against its \
height, and the name is set at the first size that holds. Nothing \
here is measured by hand, and no name is shortened.",
sheet: "One box, eight names",
roles: [
"Speaker",
"Attendee",
"Session chair",
"Press",
"Workshop host",
"Organiser",
"Volunteer",
"Exhibitor",
],
settled: "Set at %size% points",
floor: "Where the shrinking stops",
floored: "A floor is given along with the box, and the size never goes \
under it: a name shrunk until it disappears is worse than a name \
that runs over. The luggage tag below is far too small for the \
name it carries, so the floor is what comes back, and the tag is \
drawn at the floor and clipped to its own edges. What to do about \
a box no size fills is the caller's to decide: draw it clipped, as \
here, print the name on a second line, or hand the register back \
a name it has to shorten.",
clipped: "At the floor, clipped to the tag",
caveat: "The size that comes back is never larger than the one asked for, \
so a short name is set at the size the design chose and only a long \
one comes out smaller. Every badge on this sheet went through the \
same call, and the size printed under each is the one it handed \
back.",
};
/// The sheet in French.
const FRENCH: Words = Words {
title: "Des badges d’une seule taille, des noms de toutes les longueurs",
lead: "Les huit cadres ci-dessous sont un seul et même cadre, découpé avant qu’on \
sache à qui il irait. Chaque nom reçoit le cadre qu’il doit remplir, et on \
cherche la taille à laquelle il y tient : les tailles descendent d’un quart de \
point, le nom est coupé en lignes à la largeur du cadre puis comparé à sa \
hauteur, et il est composé à la première taille qui convient. Rien ici n’est \
mesuré à la main, et aucun nom n’est raccourci.",
sheet: "Un cadre, huit noms",
roles: [
"Conférencière",
"Participant",
"Présidente de séance",
"Presse",
"Animateur d’atelier",
"Organisatrice",
"Bénévole",
"Exposant",
],
settled: "Composé à %size% points",
floor: "Là où la réduction s’arrête",
floored: "Un plancher est donné avec le cadre, et la taille ne descend jamais en \
dessous : un nom réduit jusqu’à disparaître vaut moins qu’un nom qui déborde. \
L’étiquette de bagage ci-dessous est bien trop petite pour le nom qu’elle doit \
recevoir : c’est donc le plancher qui revient, et l’étiquette est composée au \
plancher puis rognée à ses propres bords. Que faire d’un cadre qu’aucune \
taille ne remplit, c’est à l’appelant d’en décider : le composer rogné, comme \
ici, reporter le nom sur une seconde ligne, ou renvoyer au registre un nom à \
abréger.",
clipped: "Au plancher, rogné à l’étiquette",
caveat: "La taille rendue n’est jamais plus grande que celle demandée : un nom court \
est composé à la taille choisie par la maquette, et seul un nom long sort plus \
petit. Chaque badge de cette planche est passé par le même appel, et la taille \
imprimée sous chacun est celle que l’appel a rendue.",
};
/// The sheet in Dutch.
const DUTCH: Words = Words {
title: "Badges van één formaat, namen van elke lengte",
lead: "De acht kaders hieronder zijn hetzelfde kader, gesneden voordat iemand wist wie het zou dragen. Elke naam krijgt het kader waarin hij moet passen en er wordt gevraagd op welke grootte hij past: de groottes zakken per kwart punt, elk afgebroken op de breedte van het kader en afgewogen tegen zijn hoogte, en de naam wordt gezet op de eerste grootte die past. Niets hier is met de hand gemeten, en geen naam is ingekort.",
sheet: "Eén kader, acht namen",
roles: [
"Spreker",
"Deelnemer",
"Voorzitter",
"Pers",
"Workshopleider",
"Organisator",
"Vrijwilliger",
"Exposant",
],
settled: "Gezet op %size% punten",
floor: "Waar het verkleinen ophoudt",
floored: "Samen met het kader wordt een ondergrens gegeven, en de grootte zakt er nooit onder: een naam die krimpt tot hij verdwijnt, is erger dan een naam die overloopt. Het bagagelabel hieronder is veel te klein voor de naam die erop staat, dus komt de ondergrens terug, en het label wordt op die grootte getekend en tot zijn eigen randen bijgesneden. Wat te doen met een kader dat geen grootte vult, beslist de aanroeper: bijgesneden tekenen, zoals hier, de naam op een tweede regel zetten, of de registratie een naam teruggeven die ingekort moet worden.",
clipped: "Op de ondergrens, bijgesneden tot het label",
caveat: "De grootte die terugkomt, is nooit groter dan de gevraagde, dus een korte naam wordt gezet op de grootte die het ontwerp koos en alleen een lange komt kleiner uit. Elke badge op dit blad ging door dezelfde aanroep, en de grootte onder elke badge is degene die hij teruggaf.",
};
/// The sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Crachás de um só tamanho, nomes de todos os comprimentos",
lead: "As oito caixas abaixo são a mesma caixa, cortada antes de se saber quem a usaria. A cada nome dá-se a caixa em que tem de caber e pergunta-se a que tamanho cabe: os tamanhos descem um quarto de ponto de cada vez, cada um partido à largura da caixa e comparado com a sua altura, e o nome é composto ao primeiro tamanho que cabe. Nada aqui é medido à mão, e nenhum nome é encurtado.",
sheet: "Uma caixa, oito nomes",
roles: [
"Orador",
"Participante",
"Moderador",
"Imprensa",
"Anfitrião da oficina",
"Organizador",
"Voluntário",
"Expositor",
],
settled: "Composto a %size% pontos",
floor: "Onde para a redução",
floored: "Com a caixa dá-se um mínimo, e o tamanho nunca desce abaixo dele: um nome reduzido até desaparecer é pior do que um nome que transborda. A etiqueta de bagagem abaixo é pequena demais para o nome que leva, por isso volta o mínimo, e a etiqueta é desenhada nesse tamanho e recortada pelas suas margens. O que fazer com uma caixa que nenhum tamanho preenche decide-o o programa que chama a biblioteca: desenhá-la recortada, como aqui, imprimir o nome numa segunda linha, ou devolver ao registo um nome que tem de encurtar.",
clipped: "No mínimo, recortado à etiqueta",
caveat: "O tamanho devolvido nunca é maior do que o pedido, por isso um nome curto é composto ao tamanho que o design escolheu e só um longo sai mais pequeno. Cada crachá desta folha passou pela mesma chamada, e o tamanho impresso por baixo de cada um é o que ela devolveu.",
};
/// The sheet in Italian.
const ITALIAN: Words = Words {
title: "Badge di una sola misura, nomi di ogni lunghezza",
lead: "Gli otto riquadri qui sotto sono lo stesso riquadro, tagliato prima che si sapesse chi l’avrebbe portato. A ogni nome si dà il riquadro in cui deve stare e gli si chiede a quale corpo ci sta: i corpi scendono di un quarto di punto, ciascuno spezzato alla larghezza del riquadro e confrontato con la sua altezza, e il nome è composto al primo corpo che ci sta. Niente è misurato a mano, e nessun nome è accorciato.",
sheet: "Un riquadro, otto nomi",
roles: [
"Relatore",
"Partecipante",
"Moderatore",
"Stampa",
"Conduttore del laboratorio",
"Organizzatore",
"Volontario",
"Espositore",
],
settled: "Composto a %size% punti",
floor: "Dove si ferma la riduzione",
floored: "Con il riquadro si dà un minimo, e il corpo non scende mai sotto: un nome ridotto fino a sparire è peggio di un nome che sborda. L’etichetta bagaglio qui sotto è troppo piccola per il nome che porta, così torna il minimo, e l’etichetta è disegnata a quel corpo e ritagliata ai propri bordi. Cosa fare di un riquadro che nessun corpo riempie lo decide chi chiama: disegnarlo ritagliato, come qui, stampare il nome su una seconda riga, o restituire al registro un nome da accorciare.",
clipped: "Al minimo, ritagliato all’etichetta",
caveat: "Il corpo restituito non è mai più grande di quello chiesto, così un nome corto è composto al corpo scelto dal progetto e solo uno lungo esce più piccolo. Ogni badge di questo foglio è passato per la stessa chiamata, e il corpo stampato sotto ciascuno è quello che ha restituito.",
};
/// The sheet in Spanish.
const SPANISH: Words = Words {
title: "Acreditaciones de un tamaño, nombres de todas las longitudes",
lead: "Las ocho cajas de abajo son la misma caja, cortada antes de que nadie supiera quién la llevaría. A cada nombre se le da la caja en que debe caber y se le pregunta a qué tamaño cabe: los tamaños bajan de cuarto en cuarto de punto, cada uno cortado al ancho de la caja y comparado con su altura, y el nombre se compone al primer tamaño que cabe. Nada se mide a mano y ningún nombre se acorta.",
sheet: "Una caja, ocho nombres",
roles: [
"Ponente",
"Asistente",
"Moderador",
"Prensa",
"Anfitrión del taller",
"Organizador",
"Voluntario",
"Expositor",
],
settled: "Compuesto a %size% puntos",
floor: "Dónde para la reducción",
floored: "Con la caja se da un mínimo, y el tamaño nunca baja de él: un nombre reducido hasta desaparecer es peor que un nombre que se sale. La etiqueta de equipaje de abajo es demasiado pequeña para el nombre que lleva, así que vuelve el mínimo, y la etiqueta se dibuja a ese tamaño recortada a sus propios bordes. Qué hacer con una caja que ningún tamaño llena lo decide el programa que pide el tamaño: dibujarla recortada, como aquí, imprimir el nombre en una segunda línea o devolver al registro un nombre que tiene que acortar.",
clipped: "Al mínimo, recortado a la etiqueta",
caveat: "El tamaño que vuelve nunca es mayor que el pedido, así que un nombre corto se compone al tamaño que eligió el diseño y solo uno largo sale más pequeño. Cada acreditación de esta hoja pasó por la misma llamada, y el tamaño impreso debajo de cada una es el que devolvió.",
};
/// The sheet in German.
const GERMAN: Words = Words {
title: "Namensschilder einer Größe, Namen jeder Länge",
lead: "Die acht Rahmen unten sind derselbe Rahmen, zugeschnitten, bevor jemand wusste, wer ihn tragen würde. Jedem Namen wird der Rahmen übergeben, in den er passen muss, und er wird gefragt, in welcher Größe er passt: Die Größen sinken um je einen Viertelpunkt, jede wird auf die Breite des Rahmens umbrochen und gegen seine Höhe gewogen, und der Name wird in der ersten Größe gesetzt, die passt. Nichts hier ist von Hand gemessen, und kein Name wird gekürzt.",
sheet: "Ein Rahmen, acht Namen",
roles: [
"Vortrag",
"Teilnahme",
"Sitzungsleitung",
"Presse",
"Workshopleitung",
"Organisation",
"Helferteam",
"Ausstellung",
],
settled: "Gesetzt in %size% Punkt",
floor: "Wo das Verkleinern aufhört",
floored: "Mit dem Rahmen wird eine Untergrenze angegeben, und die Größe fällt nie darunter: Ein bis zum Verschwinden verkleinerter Name ist schlimmer als einer, der überläuft. Der Kofferanhänger unten ist viel zu klein für seinen Namen, also kommt die Untergrenze zurück, und der Anhänger wird in dieser Größe gezeichnet und an seinen eigenen Rändern beschnitten. Was mit einem Rahmen geschieht, den keine Größe füllt, entscheidet der Aufrufer: beschnitten zeichnen wie hier, den Namen auf eine zweite Zeile setzen oder der Anmeldung einen Namen zurückgeben, den sie kürzen muss.",
clipped: "An der Untergrenze, auf den Anhänger beschnitten",
caveat: "Die zurückgegebene Größe ist nie größer als die verlangte, also wird ein kurzer Name in der Größe gesetzt, die das Design gewählt hat, und nur ein langer kommt kleiner heraus. Jedes Schild auf diesem Bogen lief durch denselben Aufruf, und die darunter gedruckte Größe ist die, die er zurückgab.",
};
/// 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 columns of badges are
/// together.
const WIDTH: f64 = 451.0;
/// How wide one badge is.
const BADGE_WIDTH: f64 = 216.0;
/// How tall one badge is.
const BADGE_HEIGHT: f64 = 58.0;
/// How far apart the two columns of badges stand.
const BADGE_GAP: f64 = WIDTH - 2.0 * BADGE_WIDTH;
/// How far a badge's contents sit inside its edges.
const INSET: f64 = 10.0;
/// How wide a badge's contents are, between its two insets.
const INNER_WIDTH: f64 = BADGE_WIDTH - INSET - INSET;
/// The box a name is fitted into, inside the badge.
const NAME_HEIGHT: f64 = 27.0;
/// The size a name is asked for before it is asked to fit.
const NAME_SIZE: f64 = 22.0;
/// The size a name is never set below.
const FLOOR: f64 = 8.0;
/// How wide the luggage tag is.
const TAG_WIDTH: f64 = 100.0;
/// How tall the luggage tag is.
const TAG_HEIGHT: f64 = 20.0;
/// The grey the sheet draws its second-rank words in.
const GREY: Rgb = Rgb::gray(0.42);
/// The grey the badges are outlined in.
const OUTLINE: Rgb = Rgb::gray(0.55);
/// 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))
}
/// The size the name of guest `index` is set at, inside a badge.
fn badge_size(handle: &FontHandle, index: usize) -> f64 {
TextFlow::new(handle, NAME_SIZE)
.align(Align::Center)
.fit_size(GUESTS[index], INNER_WIDTH, NAME_HEIGHT, FLOOR)
}
/// Draws one badge, its box at `(x, top)`, and hands back the ordinate its
/// caption ends at.
fn badge(
c: &mut Content,
handle: &FontHandle,
words: &Words,
index: usize,
x: f64,
top: f64,
) -> Result<f64, Box<dyn std::error::Error>> {
c.set_stroke(OUTLINE)?;
c.set_line_width(0.5)?;
c.rect(x, top - BADGE_HEIGHT, BADGE_WIDTH, BADGE_HEIGHT)?;
c.stroke();
let size = badge_size(handle, index);
let name = TextFlow::new(handle, NAME_SIZE)
.align(Align::Center)
.resized(size);
block(c, &name, x + INSET, top - INSET, INNER_WIDTH, GUESTS[index])?;
let role = TextFlow::new(handle, 9.0).align(Align::Center).color(GREY);
block(
c,
&role,
x + INSET,
top - INSET - NAME_HEIGHT,
INNER_WIDTH,
words.roles[index],
)?;
let caption = TextFlow::new(handle, 8.0).align(Align::Center).color(GREY);
let said = words.settled.replace("%size%", &points(size));
block(c, &caption, x, top - BADGE_HEIGHT - 4.0, BADGE_WIDTH, &said)
}
/// Draws the luggage tag no size fits, its box at `(x, top)`, and hands back
/// the ordinate its caption ends at.
fn tag(
c: &mut Content,
handle: &FontHandle,
words: &Words,
x: f64,
top: f64,
) -> Result<f64, Box<dyn std::error::Error>> {
// The floor is one the library has nothing to say about: a floor under six
// points would come back with a warning beside the size.
let (size, said) = TextFlow::new(handle, NAME_SIZE)
.align(Align::Center)
.fit_size_reporting(TAGGED, TAG_WIDTH - 2.0, TAG_HEIGHT, FLOOR);
if let Some(warning) = said {
eprintln!("{warning}");
}
c.save_state();
c.rect(x, top - TAG_HEIGHT, TAG_WIDTH, TAG_HEIGHT)?;
c.clip().end_path();
let name = TextFlow::new(handle, size).align(Align::Center);
block(c, &name, x + 1.0, top, TAG_WIDTH - 2.0, TAGGED)?;
c.restore_state();
c.set_stroke(OUTLINE)?;
c.set_line_width(0.5)?;
c.rect(x, top - TAG_HEIGHT, TAG_WIDTH, TAG_HEIGHT)?;
c.stroke();
let caption = TextFlow::new(handle, 8.0).color(GREY);
block(
c,
&caption,
x + TAG_WIDTH + 12.0,
top - 4.0,
WIDTH - TAG_WIDTH - 12.0,
words.clipped,
)
}
/// Draws the whole sheet.
fn build(words: &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 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.sheet)? - 14.0;
for pair in 0..BADGE_COUNT / 2 {
let mut lowest = top;
for column in 0..2 {
let x = (BADGE_WIDTH + BADGE_GAP).mul_add(f64::from(column), LEFT);
let index = pair * 2 + usize::try_from(column).unwrap_or(0);
lowest = badge(&mut c, &handle, words, index, x, top)?.min(lowest);
}
top = lowest - 12.0;
}
top -= 10.0;
top = block(&mut c, &label, LEFT, top, WIDTH, words.floor)? - 12.0;
top = block(&mut c, &lead, LEFT, top, WIDTH, words.floored)? - 20.0;
top = tag(&mut c, &handle, words, LEFT, top)? - 22.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()?)
}
/// A size in points, as the sheet prints it: two decimals, so the quarter-point
/// step the sizes come in is visible.
fn points(size: f64) -> String {
format!("{size:.2}")
}
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("shrink_to_fit")));
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::{Align, Document, Font, TextFlow};
use super::{
BADGE_COUNT, FLOOR, GUESTS, INNER_WIDTH, NAME_HEIGHT, NAME_SIZE, TAG_HEIGHT, TAG_WIDTH,
TAGGED, WORDS, badge_size, default_font, language, points,
};
/// The lines two languages are allowed to write the same way, where two
/// languages spell a word alike. Every word is a word of the language it is
/// written in.
const SPARED: [&str; 5] = [
// Written the same way in German.
r#""Presse""#,
// Written the same way in Portuguese.
r#""Expositor""#,
r#""Moderador""#,
r#""Organizador""#,
// Written the same way in Dutch.
r#""Exposant""#,
];
/// 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_sheet_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the sheet says these in more than one language: {untranslated:?}"
);
}
/// The size a badge settles on holds the whole of the name: every line
/// stays inside the width, and the block ends above the bottom.
#[test]
fn every_name_stays_inside_the_badge_at_the_size_it_settled_on() {
let mut doc = Document::new();
let handle = doc.add_font(fixture());
for (index, guest) in GUESTS.iter().enumerate() {
let size = badge_size(&handle, index);
let flow = TextFlow::new(&handle, size).align(Align::Center);
let lines = flow.break_lines(guest, INNER_WIDTH);
assert!(
flow.height(&lines) <= NAME_HEIGHT,
"{guest} is {:.2} points tall at {size:.2}, and the badge has {NAME_HEIGHT:.2}",
flow.height(&lines)
);
for line in &lines {
assert!(
line.natural_width() <= INNER_WIDTH,
"{guest} draws a line {:.2} points wide at {size:.2}, and the badge \
has {INNER_WIDTH:.2}",
line.natural_width()
);
}
}
}
/// The sheet is only worth printing if the boxes really do disagree: a
/// short name keeps the size the design asked for, and a long one comes
/// back smaller.
#[test]
fn the_shortest_name_keeps_the_size_asked_for_and_the_longest_does_not() {
let mut doc = Document::new();
let handle = doc.add_font(fixture());
let sizes: Vec<f64> = (0..BADGE_COUNT).map(|i| badge_size(&handle, i)).collect();
assert!(
(sizes[0] - NAME_SIZE).abs() < f64::EPSILON,
"{} came back at {:.2}, and it fits at {NAME_SIZE:.2}",
GUESTS[0],
sizes[0]
);
let longest = sizes.last().copied().expect("the sheet carries badges");
assert!(
longest < NAME_SIZE && longest > FLOOR,
"{} came back at {longest:.2}, which is neither shrunk nor floored",
GUESTS[BADGE_COUNT - 1]
);
}
/// The luggage tag is the box no size fills, which is what makes the last
/// panel worth drawing.
#[test]
fn the_name_on_the_luggage_tag_comes_back_at_the_floor() {
let mut doc = Document::new();
let handle = doc.add_font(fixture());
let size = TextFlow::new(&handle, NAME_SIZE)
.align(Align::Center)
.fit_size(TAGGED, TAG_WIDTH - 2.0, TAG_HEIGHT, FLOOR);
assert!(
(size - FLOOR).abs() < f64::EPSILON,
"the tag came back at {size:.2}, and no size fits it"
);
}
#[test]
fn a_size_is_printed_with_the_quarter_point_it_came_in() {
assert_eq!(points(22.0), "22.00");
assert_eq!(points(10.25), "10.25");
assert_eq!(points(8.5), "8.50");
}
}
|