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 | //! Sets four short samples twice each — once as the font is read straight off
//! its `cmap`, once with one typographic feature turned on — so the difference
//! each feature makes can be seen side by side.
//!
//! The four are the ligatures a font offers, small capitals, old-style figures,
//! and kerning. Nothing is on unless it is asked for, so the two settings of a
//! sample differ in exactly one thing.
//!
//! The font here is Spectral, which offers all four.
//!
//! The closing lines are measured off the fonts themselves rather than written
//! down: how many glyphs the ligature sample takes each way, and how much
//! narrower kerning draws its own.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn.
//!
//! Usage: `cargo run --example write_typography -- tmp/typography.pdf`
//! `HQF_PDF_LANG=fr cargo run --example write_typography --
//! tmp/typographie.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font, FontHandle, Page, TextFlow};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
use language::Language;
/// Where the committed fonts sit.
fn font_dir() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
}
/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
/// The line across the top of the page.
title: &'static str,
/// What the page shows, in two sentences.
why: &'static str,
/// The heading over each of the four samples.
headings: [&'static str; 4],
/// What each feature does, one line each.
explanations: [&'static str; 4],
/// The four samples, each set twice.
samples: [&'static str; 4],
/// What is written beside the setting with nothing turned on.
off: &'static str,
/// What is written beside the setting with the feature turned on.
on: &'static str,
/// The line about the ligature sample, cut where the two counts go into it.
glyphs_before: &'static str,
glyphs_between: &'static str,
glyphs_after: &'static str,
/// The line about the kerning sample, cut where the width goes into it.
kerned_before: &'static str,
kerned_after: &'static str,
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
/// The line about the ligature sample, with the two counts in it.
fn glyph_line(&self, apart: usize, joined: usize) -> String {
format!(
"{}{apart}{}{joined}{}",
self.glyphs_before, self.glyphs_between, self.glyphs_after
)
}
/// The line about the kerning sample, with the width it saves in it.
fn kerned_line(&self, saved: f64) -> String {
format!("{}{saved:.1}{}", self.kerned_before, self.kerned_after)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Four things a font knows about its own letters",
why: "A font file carries more than one glyph per character. It says which \
letters are drawn joined, which figures hang below the line, which \
letters have a small capital of their own, and how far apart each \
pair of glyphs should stand.\n\
None of it is used unless it is asked for, so a document written \
before these settings existed comes out byte for byte as it did. Each \
sample below is set twice, and only the setting differs.",
headings: [
"Ligatures",
"Small capitals",
"Old-style figures",
"Kerning",
],
explanations: [
"Letters that meet are drawn as one glyph the font designer cut for them.",
"Lowercase letters drawn as capitals no taller than an x.",
"Figures that rise and fall around the x-height instead of standing at cap height.",
"Each pair of glyphs moved as far apart as the font asks.",
],
samples: [
"office filing affidavit",
"reprinted quarterly",
"1 234 567 890",
"Wavy TAXI Today",
],
off: "off",
on: "on",
glyphs_before: "The first sample takes ",
glyphs_between: " glyphs as it stands and ",
glyphs_after: " with the ligatures on: the pairs the font joins are one glyph each.",
kerned_before: "The last sample is drawn ",
kerned_after: " points narrower with kerning on, and it is measured that way \
too, so the line is as wide as it looks.",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Quatre choses qu'une police sait de ses propres lettres",
why: "Un fichier de police porte plus d'un dessin par caractère. Il dit \
quelles lettres se dessinent liées, quels chiffres descendent sous la \
ligne, quelles lettres ont une petite capitale à elles, et à quelle \
distance chaque paire de dessins doit se tenir.\n\
Rien de tout cela ne sert tant qu'on ne le demande pas : un document \
écrit avant que ces réglages existent sort octet pour octet comme \
avant. Chaque échantillon ci-dessous est composé deux fois, et seul le \
réglage change.",
headings: [
"Lettres liées",
"Petites capitales",
"Chiffres elzéviriens",
"Approche de paire",
],
explanations: [
"Deux lettres qui se touchent sont dessinées d'un seul trait, prévu par le dessinateur.",
"Des minuscules dessinées en capitales pas plus hautes qu'un x.",
"Des chiffres qui montent et descendent autour du x au lieu de se tenir à hauteur de capitale.",
"Chaque paire de dessins écartée d'autant que la police le demande.",
],
samples: [
"affiche officielle du greffe",
"réédition trimestrielle",
"1 234 567 890",
"Wagon TAXI Toiture",
],
off: "sans",
on: "avec",
glyphs_before: "Le premier échantillon prend ",
glyphs_between: " dessins tel quel et ",
glyphs_after: " une fois les lettres liées : chaque paire liée ne fait plus qu'un dessin.",
kerned_before: "Le dernier échantillon est dessiné ",
kerned_after: " points plus étroit avec l'approche, et il est mesuré ainsi \
aussi, donc la ligne fait la largeur qu'elle paraît faire.",
};
/// 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); 2] =
[(Language::English, &ENGLISH), (Language::French, &FRENCH)];
/// The left edge of everything on the page.
const X: f64 = 60.0;
/// The width every block is broken to.
const ROOM: f64 = 475.0;
/// The baseline the title sits on.
const TITLE_TOP: f64 = 780.0;
/// The top of the block that says what the page shows.
const WHY_TOP: f64 = 748.0;
/// The top of each of the four samples, in the order they are drawn.
const TOPS: [f64; 4] = [640.0, 515.0, 390.0, 265.0];
/// How far the line that explains a feature sits below its heading.
const EXPLAIN_DROP: f64 = 16.0;
/// How far the setting with nothing turned on sits below the heading.
const OFF_DROP: f64 = 42.0;
/// How far the setting with the feature turned on sits below the heading.
const ON_DROP: f64 = 68.0;
/// Where the word beside a setting is written, and where the sample begins.
const LABEL_X: f64 = X;
const SAMPLE_X: f64 = X + 46.0;
/// The size the samples are set in.
const SAMPLE_SIZE: f64 = 18.0;
/// The size the headings are set in.
const HEADING_SIZE: f64 = 12.0;
/// The size everything that is not a heading or a sample is set in.
const SMALL: f64 = 9.0;
/// The top of the two closing lines.
const CLOSING_TOP: f64 = 150.0;
/// How far the second closing line sits below the first.
const CLOSING_DROP: f64 = 30.0;
/// Draws one line of text at `size`, left-aligned at `x`, with its baseline
/// under `top`.
fn line(
c: &mut Content,
handle: &FontHandle,
text: &str,
size: f64,
x: f64,
top: f64,
) -> hqf_pdf::Result<()> {
let flow = TextFlow::new(handle, size);
let lines = flow.break_lines(text, ROOM);
c.begin_text();
flow.draw(c, &lines, x, top, ROOM)?;
c.end_text();
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let out = env::args()
.nth(1)
.unwrap_or_else(|| language.file_name(&out::default_path("typography")));
let bytes = fs::read(font_dir().join("Spectral-Regular.ttf"))?;
let mut doc = Document::new();
doc.set_license(licence::licensed());
let plain = doc.add_font(Font::parse(bytes)?);
// One handle per feature, each turned on alone: the two settings of a
// sample then differ in exactly one thing.
let with: [FontHandle; 4] = [
plain.clone().with_ligatures(),
plain.clone().with_small_capitals(),
plain.clone().with_oldstyle_figures(),
plain.clone().with_kerning(),
];
let mut c = Content::new();
line(&mut c, &plain, words.title, 18.0, X, TITLE_TOP)?;
let why = TextFlow::new(&plain, 10.0).leading(14.0);
let why_lines = why.break_lines(words.why, ROOM);
c.begin_text();
why.draw(&mut c, &why_lines, X, WHY_TOP, ROOM)?;
c.end_text();
for (index, top) in TOPS.iter().enumerate() {
line(&mut c, &plain, words.headings[index], HEADING_SIZE, X, *top)?;
line(
&mut c,
&plain,
words.explanations[index],
SMALL,
X,
top - EXPLAIN_DROP,
)?;
for (drop, label, handle) in [
(OFF_DROP, words.off, &plain),
(ON_DROP, words.on, &with[index]),
] {
line(&mut c, &plain, label, SMALL, LABEL_X, top - drop)?;
line(
&mut c,
handle,
words.samples[index],
SAMPLE_SIZE,
SAMPLE_X,
top - drop,
)?;
}
}
// Both closing lines are read off the fonts, not written down.
let apart = plain
.runs(words.samples[0])
.iter()
.map(|run| run.glyphs().len())
.sum();
let joined = with[0]
.runs(words.samples[0])
.iter()
.map(|run| run.glyphs().len())
.sum();
let saved = plain.measure(words.samples[3], SAMPLE_SIZE)
- with[3].measure(words.samples[3], SAMPLE_SIZE);
let closing = TextFlow::new(&plain, 10.0).leading(14.0);
for (drop, text) in [
(0.0, words.glyph_line(apart, joined)),
(CLOSING_DROP, words.kerned_line(saved)),
] {
let lines = closing.break_lines(&text, ROOM);
c.begin_text();
closing.draw(&mut c, &lines, X, CLOSING_TOP - drop, ROOM)?;
c.end_text();
}
let mut page = Page::a4();
page.content = c.into_bytes();
doc.add_page(page)?;
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 super::{
CLOSING_DROP, CLOSING_TOP, HEADING_SIZE, ON_DROP, ROOM, SAMPLE_SIZE, SAMPLE_X, SMALL, TOPS,
WORDS, X, language,
};
use hqf_pdf::{Document, Font, FontHandle, TextFlow};
/// The lines two languages are allowed to write the same way: the figures
/// are figures in both.
const SPARED: [&str; 1] = ["\"1 234 567 890\""];
/// The room a sample has, from where it begins to the edge of the block.
const SAMPLE_ROOM: f64 = ROOM - SAMPLE_X + X;
/// The committed font, added to a document of its own.
fn font() -> (Document, FontHandle) {
let bytes = std::fs::read(super::font_dir().join("Spectral-Regular.ttf"))
.expect("the font is committed");
let mut doc = Document::new();
let handle = doc.add_font(Font::parse(bytes).expect("the font parses"));
(doc, handle)
}
#[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 page rests on the font joining letters in the first sample and
/// kerning pairs in the last: a page whose two settings drew the same thing
/// would show nothing at all.
#[test]
fn every_language_gives_the_two_settings_something_to_differ_about() {
let (_doc, plain) = font();
let joined = plain.clone().with_ligatures();
let kerned = plain.clone().with_kerning();
for (code, words) in WORDS {
let ligature_sample = words.samples[0];
assert!(
joined.runs(ligature_sample)[0].glyphs().len()
< plain.runs(ligature_sample)[0].glyphs().len(),
"{code:?} writes a first sample the font joins nothing in"
);
let kerning_sample = words.samples[3];
assert!(
kerned.measure(kerning_sample, SAMPLE_SIZE)
< plain.measure(kerning_sample, SAMPLE_SIZE),
"{code:?} writes a last sample the font kerns nothing in"
);
let figures = words.samples[2];
assert_ne!(
plain.clone().with_oldstyle_figures().runs(figures)[0].glyphs(),
plain.runs(figures)[0].glyphs(),
"{code:?} writes a sample of figures the font hangs none of"
);
}
}
/// The second sample rests on the font having a small capital for the
/// letters it holds, and on the capitals being left where they stand.
#[test]
fn the_small_capitals_sample_is_drawn_with_small_capitals() {
let (_doc, plain) = font();
let asked = plain.clone().with_small_capitals();
for (code, words) in WORDS {
let sample = words.samples[1];
assert_ne!(
asked.runs(sample)[0].glyphs(),
plain.runs(sample)[0].glyphs(),
"{code:?} writes a second sample the font has no small capital for"
);
assert!(
sample.chars().all(|ch| !ch.is_uppercase()),
"{code:?} writes a capital into the sample, which the setting leaves alone"
);
}
}
/// Nothing the page draws runs off the paper.
#[test]
fn every_language_writes_blocks_no_wider_than_the_room_they_have() {
let (_doc, plain) = font();
for (code, words) in WORDS {
for (text, size, room) in [
(words.title, 18.0, ROOM),
(words.off, SMALL, ROOM),
(words.on, SMALL, ROOM),
] {
let width = plain.measure(text, size);
assert!(
width <= room,
"{code:?} writes {width} points in {room}: {text}"
);
}
for index in 0..4 {
let heading = plain.measure(words.headings[index], HEADING_SIZE);
assert!(heading <= ROOM, "{code:?} writes a heading of {heading}");
let explanation = plain.measure(words.explanations[index], SMALL);
assert!(
explanation <= ROOM,
"{code:?} writes an explanation of {explanation} points"
);
let sample = plain.measure(words.samples[index], SAMPLE_SIZE);
assert!(
sample <= SAMPLE_ROOM,
"{code:?} writes a sample of {sample} points in {SAMPLE_ROOM}"
);
}
}
}
/// The samples stand clear of one another, and the last stands clear of the
/// closing lines.
#[test]
fn nothing_the_page_draws_lands_on_what_comes_after_it() {
let (_doc, plain) = font();
let flow = TextFlow::new(&plain, SAMPLE_SIZE);
for (code, words) in WORDS {
for (index, top) in TOPS.iter().enumerate() {
let lines = flow.break_lines(words.samples[index], ROOM);
let bottom = top - ON_DROP - flow.height(&lines);
let next = TOPS.get(index + 1).copied().unwrap_or(CLOSING_TOP);
assert!(
bottom > next,
"{code:?} sets its sample {index} down to {bottom}, over {next}"
);
}
let closing = TextFlow::new(&plain, 10.0).leading(14.0);
let lines = closing.break_lines(&words.kerned_line(9.9), ROOM);
let bottom = CLOSING_TOP - CLOSING_DROP - closing.height(&lines);
assert!(bottom > 0.0, "{code:?} writes off the bottom of the paper");
}
}
}
|