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 | //! Sets text down the page, in columns: three signs painted on narrow boards,
//! the letters of each word stacked one under the next.
//!
//! Each board is a box of its own, and each sets its columns a different way:
//! from the top and right to left, the order Japanese and Chinese are set in,
//! broken between any two letters, a hyphen ending each column a cut inside a
//! word closes; from the bottom and left to right, broken only at a space; and
//! centred down the board, in a colour of its own and a wider leading. Only the
//! columns that fit the board's width are drawn.
//!
//! Under each board, lines say how many of its columns fit and how many it
//! broke into, how tall the tallest runs, how many end a paragraph, what the
//! first one holds, and how tall the whole text would stand in one column. A
//! grey outline marks the box every drawn column covers.
//!
//! The font is added to run down the page, which is what a flow down the page
//! is refused without. The words are held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which set the page is written in.
//!
//! Usage: `cargo run --example write_vertical_text -- tmp/vertical_text.pdf
//! [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_vertical_text --
//! tmp/vertical_text_fr.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::{
ColumnAlign, ColumnOrder, Guides, Overlong, TextColumn, TextFlow, VerticalFlow,
};
use hqf_pdf::{Document, Font, FontHandle, Page};
#[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 writes with when none is given on the command line.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// How far in from the left edge of the sheet the heading starts, in points.
const MARGIN: f64 = 72.0;
/// Where the baseline of the heading sits, in points up from the foot of the
/// sheet.
const HEAD_TOP: f64 = 790.0;
/// The size the heading is set at, in points.
const HEADING: f64 = 16.0;
/// The size the lines under the heading and under the boards are set at, in
/// points.
const BODY: f64 = 9.0;
/// How far below one of those lines the next one sits, in points.
const LINE_STEP: f64 = 12.0;
/// The left edges of the three boards, in points.
const BOARDS: [f64; 3] = [72.0, 247.0, 422.0];
/// How wide a board is, in points.
const BOARD_WIDTH: f64 = 110.0;
/// How wide the label over a board and the lines under it may run, in points.
const LABEL_WIDTH: f64 = 150.0;
/// Where the top of every board sits, in points up from the foot of the sheet.
const BOARD_TOP: f64 = 720.0;
/// How tall a board is, in points.
const BOARD_HEIGHT: f64 = 280.0;
/// The room kept between a board's edge and its outermost column, in points.
const INSET: f64 = 6.0;
/// The size the signs are set at, in points.
const SIGN: f64 = 18.0;
/// Every word the page says, in one language.
#[derive(Debug)]
struct Words {
/// The heading, and what the file says of itself.
title: &'static str,
/// What the page says under its heading.
intro: [&'static str; 2],
/// What each board is labelled, left to right.
labels: [&'static str; 3],
/// What each board says, left to right; a newline starts a paragraph.
signs: [&'static str; 3],
/// How many columns fit and how many there are; `{shown}` and `{count}`
/// stand for them.
shown: &'static str,
/// How tall the tallest column runs; `{tall}` stands for it.
tallest: &'static str,
/// How many columns end a paragraph; `{ends}` stands for it.
ends: &'static str,
/// What the first column holds; `{first}` stands for it.
first: &'static str,
/// How tall the whole text would stand in one column; `{long}` stands for
/// it.
long: &'static str,
/// How far across the drawn columns reach; `{across}` stands for it.
across: &'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: "Text set down the page",
intro: [
"Three signs on narrow boards, each word's letters stacked one under the next,",
"each board setting its columns another way. Under each, what its columns measure.",
],
labels: [
"From the top, right to left, a hyphen at each cut",
"From the bottom, left to right",
"Centred, in blue, wider apart",
],
signs: [
"HARBOUR VIEW HOTEL\nROOMS FREE\nBREAKFAST SERVED\nPARKING\nWIFI",
"OPEN\nALL YEAR",
"FERRY\nTO THE\nISLANDS",
],
shown: "{shown} of {count} columns fit",
tallest: "tallest: {tall} pt",
ends: "{ends} end a paragraph",
first: "first: {first}",
long: "in one column: {long} pt",
across: "across: {across} pt",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Du texte composé de haut en bas",
intro: [
"Trois enseignes sur des planches étroites, les lettres de chaque mot empilées,",
"chaque planche posant ses colonnes autrement. Dessous, ce que mesurent ses colonnes.",
],
labels: [
"Du haut, de droite à gauche, un trait d’union à chaque coupure",
"Du bas, de gauche à droite",
"Centré, en bleu, plus espacé",
],
signs: [
"HÔTEL DE LA MARINE\nCHAMBRES LIBRES\nPETIT DÉJEUNER\nPARKING\nWIFI",
"OUVERT\nTOUTE L’ANNÉE",
"BAC\nPOUR\nLES ÎLES",
],
shown: "{shown} colonnes sur {count} tiennent",
tallest: "la plus haute : {tall} pt",
ends: "{ends} finissent un paragraphe",
first: "la première : {first}",
long: "en une colonne : {long} pt",
across: "en largeur : {across} pt",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Tekst gezet langs de pagina omlaag",
intro: [
"Drie borden op smalle planken, de letters van elk woord onder elkaar gestapeld;",
"elk bord zet zijn kolommen op een andere manier. Eronder wat de kolommen meten.",
],
labels: [
"Van boven, van rechts naar links, een streepje bij elke breuk",
"Van onder, van links naar rechts",
"Gecentreerd, in blauw, verder uit elkaar",
],
signs: [
"HOTEL HAVENZICHT\nKAMERS VRIJ\nONTBIJT\nPARKEREN\nWIFI",
"OPEN\nHET HELE JAAR",
"VEERBOOT\nNAAR DE\nEILANDEN",
],
shown: "{shown} van {count} kolommen passen",
tallest: "hoogste: {tall} pt",
ends: "{ends} sluiten een alinea af",
first: "eerste: {first}",
long: "in één kolom: {long} pt",
across: "in de breedte: {across} pt",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Texto composto para baixo",
intro: [
"Três letreiros em tábuas estreitas, as letras de cada palavra empilhadas umas sob as outras,",
"e cada tábua compõe as suas colunas de outra forma. Por baixo de cada uma, o que medem as colunas.",
],
labels: [
"Da direita para a esquerda, um hífen em cada corte",
"De baixo, da esquerda para a direita",
"Centrado, a azul, mais espaçado",
],
signs: [
"HOTEL VISTA DO PORTO\nQUARTOS LIVRES\nPEQUENO-ALMOÇO\nESTACIONAMENTO\nWIFI",
"ABERTO\nO ANO TODO",
"FERRY\nPARA AS\nILHAS",
],
shown: "cabem {shown} de {count} colunas",
tallest: "a mais alta: {tall} pt",
ends: "{ends} acabam um parágrafo",
first: "primeira: {first}",
long: "numa coluna: {long} pt",
across: "na largura: {across} pt",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Testo composto verso il basso",
intro: [
"Tre insegne su assi strette, le lettere di ogni parola impilate l’una sotto l’altra,",
"e ogni asse compone le sue colonne in un altro modo. Sotto ciascuna, cosa misurano le sue colonne.",
],
labels: [
"Dall’alto, da destra a sinistra, un trattino a ogni taglio",
"Dal basso, da sinistra a destra",
"Centrato, in blu, più spaziato",
],
signs: [
"HOTEL VISTA PORTO\nCAMERE LIBERE\nCOLAZIONE\nPARCHEGGIO\nWIFI",
"APERTO\nTUTTO L’ANNO",
"TRAGHETTO\nPER LE\nISOLE",
],
shown: "ci stanno {shown} colonne su {count}",
tallest: "la più alta: {tall} pt",
ends: "{ends} chiudono un paragrafo",
first: "prima: {first}",
long: "in una colonna: {long} pt",
across: "in larghezza: {across} pt",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Texto compuesto hacia abajo",
intro: [
"Tres carteles en tablas estrechas, las letras de cada palabra apiladas una bajo otra,",
"y cada tabla compone sus columnas de otra forma. Debajo de cada una, lo que miden sus columnas.",
],
labels: [
"De derecha a izquierda, un guion en cada corte",
"Desde abajo, de izquierda a derecha",
"Centrado, en azul, más espaciado",
],
signs: [
"HOTEL VISTA AL PUERTO\nHABITACIONES LIBRES\nDESAYUNO\nAPARCAMIENTO\nWIFI",
"ABIERTO\nTODO EL AÑO",
"FERRY\nA LAS\nISLAS",
],
shown: "caben {shown} de {count} columnas",
tallest: "la más alta: {tall} pt",
ends: "{ends} acaban un párrafo",
first: "primera: {first}",
long: "en una columna: {long} pt",
across: "a lo ancho: {across} pt",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Senkrecht gesetzter Text",
intro: [
"Drei Schilder auf schmalen Brettern, die Buchstaben jedes Worts untereinander gestapelt,",
"jedes Brett setzt seine Spalten anders. Darunter, was seine Spalten messen.",
],
labels: [
"Von oben, rechts nach links, Bindestrich bei Umbruch",
"Von unten, von links nach rechts",
"Zentriert, in Blau, weiter auseinander",
],
signs: [
"HOTEL HAFENBLICK\nZIMMER FREI\nFRÜHSTÜCK\nPARKPLATZ\nWLAN",
"GANZJÄHRIG\nGEÖFFNET",
"FÄHRE\nZU DEN\nINSELN",
],
shown: "{shown} von {count} Spalten passen",
tallest: "am höchsten: {tall} pt",
ends: "{ends} beenden einen Absatz",
first: "erste: {first}",
long: "in einer Spalte: {long} pt",
across: "quer: {across} pt",
};
/// 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),
];
/// `line` set across the page at `(x, y)` in `font` at `size` points.
fn line_at(
content: &mut Content,
font: &FontHandle,
size: f64,
(x, y): (f64, f64),
line: &str,
) -> Result<(), hqf_pdf::Error> {
content.begin_text();
content.set_font(font, size)?;
content.text_origin(x, y)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
Ok(())
}
/// The three ways the boards set their columns, left to right.
fn flows(upright: &FontHandle) -> Result<[VerticalFlow<'_>; 3], hqf_pdf::Error> {
Ok([
VerticalFlow::new(upright, SIGN)?
.align(ColumnAlign::Top)
.order(ColumnOrder::RightToLeft)
.overlong(Overlong::Break)
.cut_mark(Some('-')),
VerticalFlow::new(upright, SIGN)?
.align(ColumnAlign::Bottom)
.order(ColumnOrder::LeftToRight)
.overlong(Overlong::Overflow),
VerticalFlow::new(upright, SIGN)?
.align(ColumnAlign::Center)
.leading(SIGN * 1.6)
.color(Rgb::new(0.0, 0.3, 0.65)),
])
}
/// What the board holding `columns` says of them under it, `fitting` of them
/// drawn and `text` their whole text.
fn said(
flow: &VerticalFlow<'_>,
columns: &[TextColumn],
fitting: usize,
text: &str,
words: &Words,
) -> [String; 6] {
let height = columns.iter().map(TextColumn::height).fold(0.0, f64::max);
let closing = columns
.iter()
.filter(|column| column.last_of_paragraph())
.count();
let opening = columns
.iter()
.find(|column| !column.is_empty())
.map_or("", TextColumn::text);
let whole = text.replace('\n', " ");
[
words
.shown
.replace("{shown}", &fitting.to_string())
.replace("{count}", &columns.len().to_string()),
words.tallest.replace("{tall}", &format!("{height:.0}")),
words.ends.replace("{ends}", &closing.to_string()),
words.first.replace("{first}", opening),
words
.long
.replace("{long}", &format!("{:.0}", flow.measure(&whole))),
words.across.replace(
"{across}",
&format!("{:.0}", flow.width(&columns[..fitting])),
),
]
}
/// The page: the heading, then each board with its label over it, its columns
/// that fit, the outline of the box each covers, and what it says of them under
/// it.
fn page(
font: &FontHandle,
upright: &FontHandle,
words: &Words,
) -> Result<Page, Box<dyn std::error::Error>> {
let mut content = Content::new();
content.set_fill_rgb(0.0, 0.0, 0.0)?;
line_at(&mut content, font, HEADING, (MARGIN, HEAD_TOP), words.title)?;
let mut y = HEAD_TOP - 22.0;
for line in words.intro {
line_at(&mut content, font, BODY, (MARGIN, y), line)?;
y -= LINE_STEP;
}
let label = TextFlow::new(font, BODY).leading(LINE_STEP);
let outlines = Guides::hairline(Rgb::gray(0.6));
for (index, flow) in flows(upright)?.iter().enumerate() {
let left = BOARDS[index];
let labelled = label.break_lines(words.labels[index], LABEL_WIDTH);
content.begin_text();
label.draw(&mut content, &labelled, left, BOARD_TOP + 30.0, LABEL_WIDTH)?;
content.end_text();
content.save_state();
content
.set_stroke_rgb(0.2, 0.2, 0.2)?
.set_line_width(0.8)?
.rect(left, BOARD_TOP - BOARD_HEIGHT, BOARD_WIDTH, BOARD_HEIGHT)?
.stroke();
content.restore_state();
let text = words.signs[index];
let room = BOARD_HEIGHT - INSET - INSET;
let columns = flow.break_columns(text, room);
let shown = flow.fit(&columns, BOARD_WIDTH - INSET - INSET, 0);
let drawn = &columns[..shown];
// A column hangs from its middle: the first sits half an em in from the
// edge the order starts from.
let x = if index == 1 {
left + INSET + SIGN / 2.0
} else {
left + BOARD_WIDTH - INSET - SIGN / 2.0
};
let top = BOARD_TOP - INSET;
content.begin_text();
flow.draw(&mut content, drawn, x, top, room)?;
content.end_text();
outlines.outline_all(&mut content, &flow.column_boxes(drawn, x, top, room))?;
let mut baseline = BOARD_TOP - BOARD_HEIGHT - 14.0;
content.set_fill_rgb(0.0, 0.0, 0.0)?;
for line in said(flow, &columns, shown, text, words) {
line_at(&mut content, font, BODY, (left, baseline), &line)?;
baseline -= LINE_STEP;
}
}
let mut page = Page::a4();
page.content = content.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 path = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("vertical_text")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_info(hqf_pdf::cos::Name::new("Title"), words.title);
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
let upright = doc.add_vertical_font(Font::parse(fs::read(&font_path)?)?);
doc.add_page(page(&font, &upright, words)?)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &bytes)?;
println!("wrote {} ({} bytes)", path, bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::layout::TextFlow;
use hqf_pdf::{Document, Font};
use super::{BODY, LABEL_WIDTH, LINE_STEP, WORDS, default_font, language};
/// The lines two languages are allowed to write the same way. There are
/// none: a sign shares a word or two across languages, never the whole of
/// what it says.
const SPARED: [&str; 0] = [];
#[test]
fn every_language_writes_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:?}"
);
}
/// A label is set over its board in the room two lines leave; a third line
/// would run into the board. The lines under a board are not broken, and
/// run no wider than the label may, their numbers the widest the page gives
/// them.
#[test]
fn every_language_labels_and_describes_a_board_in_the_room_it_has() {
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 flow = TextFlow::new(&text, BODY).leading(LINE_STEP);
for (named, words) in WORDS {
let code = named.code();
for label in words.labels {
let lines = flow.break_lines(label, LABEL_WIDTH).len();
assert!(
lines <= 2,
"the {code} page labels a board {label:?} on {lines} lines"
);
}
let under = [
words.shown.replace("{shown}", "5").replace("{count}", "7"),
words.tallest.replace("{tall}", "252"),
words.ends.replace("{ends}", "5"),
words.first.replace("{first}", "HÔTEL DE LA M-"),
words.long.replace("{long}", "1000"),
words.across.replace("{across}", "100"),
];
for line in under {
let measured = text.measure(&line, BODY);
assert!(
measured <= LABEL_WIDTH,
"the {code} page sets {line:?} over {measured:.1} points, and \
it has {LABEL_WIDTH:.1}"
);
}
}
}
}
|