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
//! Loading typefaces
//!
//! Dimensions and glyphs come from suki's reader as they are. What this module adds is what is
//! needed to embed a font in a PDF (the original file, the PostScript name, the bounding box
//! of the glyphs, the slant, and the cap height) and the assignment of a typeface to each role.
//!
//! There are 7 roles: body text, italic, bold, bold italic, monospace, sans serif, and
//! Japanese text. A role that is not specified uses the math typeface instead.
use crate::error::Error;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use suki::font::{self, Font};
use suki::opentype::{self, read_i16, read_u16, read_u32};
/// How the glyphs are stored
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outline {
/// CFF. Becomes CIDFontType0 in the PDF
Cff,
/// glyf. Becomes CIDFontType2 in the PDF
TrueType,
}
/// One typeface
#[derive(Debug, Clone)]
pub struct Face {
/// The contents of the font file. Needed to embed the font in the PDF
pub data: Vec<u8>,
/// Dimensions and glyphs
pub font: Font,
/// The PostScript name
pub name: String,
/// The number of glyphs
pub count: usize,
pub outline: Outline,
/// The number of coordinate units per em
pub units_per_em: f64,
/// The bounding box of the glyphs, in 1/1000 em, as (left, bottom, right, top)
pub bbox: (f64, f64, f64, f64),
/// The slant of the letters, in degrees
pub italic_angle: f64,
/// The height above the baseline (1/1000 em)
pub ascent: f64,
/// The depth below the baseline (1/1000 em, negative)
pub descent: f64,
/// The cap height (1/1000 em)
pub cap_height: f64,
/// An estimate of the width of vertical stems (1/1000 em)
pub stem: f64,
/// The Flags of the FontDescriptor
pub flags: u32,
/// Whether all the letters have the same width
pub fixed: bool,
}
/// Which typeface to use for each role. Each value is the number of an entry in [`Library::face`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Assignment {
pub roman: usize,
pub italic: usize,
pub bold: usize,
pub bold_italic: usize,
pub mono: usize,
pub sans: usize,
pub japanese: usize,
pub math: usize,
}
/// The full set of typefaces that a document uses
pub struct Library {
pub face: Vec<Face>,
pub role: Assignment,
/// The font as read for laying out chemical structures. lina keeps it in its own type
pub chem: lina::Font,
}
/// Loads a font file
pub fn load(path: &Path) -> Result<Face, Error> {
let data = std::fs::read(path)
.map_err(|reason| Error::new(format!("cannot read the font {}: {reason}", path.display()), 0))?;
build(data)
}
/// Builds a typeface from the contents of a loaded file
pub fn build(data: Vec<u8>) -> Result<Face, Error> {
let font = font::load(data.clone()).map_err(|reason| Error::new(reason.to_string(), 0))?;
let units_per_em = font::units_per_em(&font);
let scale = 1000.0 / units_per_em;
let (head_at, _) = table(&data, "head")?;
let (maxp_at, _) = table(&data, "maxp")?;
let count = read(opentype::glyph_count(&data, maxp_at))?;
let bbox = (
read(read_i16(&data, head_at + 36))? as f64 * scale,
read(read_i16(&data, head_at + 38))? as f64 * scale,
read(read_i16(&data, head_at + 40))? as f64 * scale,
read(read_i16(&data, head_at + 42))? as f64 * scale,
);
let outline = if opentype::find(&data, "CFF ").ok().flatten().is_some() {
Outline::Cff
} else {
Outline::TrueType
};
let (italic_angle, fixed) = post_values(&data)?;
let (ascent, descent, cap_height, weight) = vertical_values(&data, head_at, scale)?;
let name = postscript_name(&data)?;
let stem = 50.0 + (weight as f64 / 65.0).powi(2);
let mut flags = 4;
if fixed {
flags |= 1;
}
if italic_angle != 0.0 {
flags |= 64;
}
Ok(Face {
data,
font,
name,
count,
outline,
units_per_em,
bbox,
italic_angle,
ascent,
descent,
cap_height,
stem,
flags,
fixed,
})
}
/// Loads the file for each role and makes a set of them. A role that is not specified uses the
/// math typeface instead
pub fn open(
math: &Path,
roman: Option<&Path>,
italic: Option<&Path>,
bold: Option<&Path>,
mono: Option<&Path>,
sans: Option<&Path>,
japanese: Option<&Path>,
) -> Result<Library, Error> {
let mut face = Vec::new();
let mut known: HashMap<PathBuf, usize> = HashMap::new();
let math_index = place(&mut face, &mut known, math)?;
let roman_index = place(&mut face, &mut known, pick(roman, math))?;
let role = Assignment {
roman: roman_index,
italic: place(&mut face, &mut known, pick(italic, math))?,
bold: place(&mut face, &mut known, pick(bold, math))?,
bold_italic: place(&mut face, &mut known, pick(italic.or(bold), math))?,
mono: place(&mut face, &mut known, pick(mono, math))?,
sans: place(&mut face, &mut known, pick(sans, math))?,
japanese: place(&mut face, &mut known, pick(japanese, math))?,
math: math_index,
};
let data = std::fs::read(math)
.map_err(|reason| Error::new(format!("cannot read the font: {reason}"), 0))?;
let chem = lina::load_font(data).map_err(|reason| Error::new(reason.to_string(), 0))?;
Ok(Library {face, role, chem})
}
/// Makes a set of typefaces from the contents of font files, for where files cannot be read.
/// Every role but Japanese text uses the math typeface
pub fn open_bytes(math: Vec<u8>, japanese: Option<Vec<u8>>) -> Result<Library, Error> {
let chem = lina::load_font(math.clone()).map_err(|reason| Error::new(reason.to_string(), 0))?;
let mut face = vec![build(math)?];
if let Some(data) = japanese {
face.push(build(data)?);
}
let role = Assignment {
roman: 0,
italic: 0,
bold: 0,
bold_italic: 0,
mono: 0,
sans: 0,
japanese: face.len() - 1,
math: 0,
};
Ok(Library {face, role, chem})
}
/// Uses the fallback file if none is specified
fn pick<'a>(given: Option<&'a Path>, fallback: &'a Path) -> &'a Path {
given.unwrap_or(fallback)
}
/// Loads the same file only once
fn place(
face: &mut Vec<Face>,
known: &mut HashMap<PathBuf, usize>,
path: &Path,
) -> Result<usize, Error> {
let key = path.to_path_buf();
if let Some(found) = known.get(&key) {
return Ok(*found);
}
face.push(load(path)?);
let index = face.len() - 1;
known.insert(key, index);
Ok(index)
}
/// Looks up a table that must be present
fn table(data: &[u8], tag: &str) -> Result<(usize, usize), Error> {
read(opentype::require(data, tag))
}
/// Turns an error from suki's reader into an error of this crate
fn read<T>(found: Result<T, suki::Error>) -> Result<T, Error> {
found.map_err(|reason| Error::new(reason.to_string(), 0))
}
/// From the post table, gets the slant and whether all the letters have the same width
fn post_values(data: &[u8]) -> Result<(f64, bool), Error> {
let at = match opentype::find(data, "post").ok().flatten() {
Some((at, _)) => at,
None => return Ok((0.0, false)),
};
let raw = read(read_u32(data, at + 4))? as i32;
let angle = raw as f64 / 65536.0;
let fixed = read(read_u32(data, at + 12))? != 0;
Ok((angle, fixed))
}
/// From OS/2 and hhea, gets the ascent and descent, the cap height, and the weight
fn vertical_values(
data: &[u8],
head_at: usize,
scale: f64,
) -> Result<(f64, f64, f64, u16), Error> {
let top = read(read_i16(data, head_at + 42))? as f64 * scale;
let bottom = read(read_i16(data, head_at + 38))? as f64 * scale;
let os2 = match opentype::find(data, "OS/2").ok().flatten() {
Some((at, _)) => at,
None => return Ok((top, bottom, top * 0.7, 400)),
};
let version = read(read_u16(data, os2))?;
let weight = read(read_u16(data, os2 + 4))?;
let ascent = read(read_i16(data, os2 + 68))? as f64 * scale;
let descent = read(read_i16(data, os2 + 70))? as f64 * scale;
let cap_height = if version >= 2 {
read(read_i16(data, os2 + 88))? as f64 * scale
} else {
top * 0.7
};
let ascent = if ascent > 0.0 {ascent} else {top};
let descent = if descent < 0.0 {descent} else {bottom};
let cap_height = if cap_height > 0.0 {cap_height} else {top * 0.7};
Ok((ascent, descent, cap_height, weight))
}
/// Gets the PostScript name from the name table
fn postscript_name(data: &[u8]) -> Result<String, Error> {
let (at, _) = table(data, "name")?;
let count = read(read_u16(data, at + 2))? as usize;
let storage = at + read(read_u16(data, at + 4))? as usize;
let mut found = String::new();
for index in 0..count {
let record = at + 6 + index * 12;
let platform = read(read_u16(data, record))?;
let name_id = read(read_u16(data, record + 6))?;
if name_id != 6 {
continue;
}
let length = read(read_u16(data, record + 8))? as usize;
let offset = storage + read(read_u16(data, record + 10))? as usize;
let slice = match data.get(offset..offset + length) {
Some(slice) => slice,
None => continue,
};
let text = if platform == 3 {
let mut out = String::new();
for pair in slice.chunks(2) {
if pair.len() == 2 {
let unit = u16::from_be_bytes([pair[0], pair[1]]);
if let Some(character) = char::from_u32(unit as u32) {
out.push(character);
}
}
}
out
} else {
slice.iter().map(|byte| *byte as char).collect()
};
if !text.is_empty() {
found = text;
if platform == 3 {
break;
}
}
}
if found.is_empty() {
found = font_family_name(data);
}
Ok(found.chars().filter(|character| character.is_ascii_graphic()).collect())
}
/// What to use instead when there is no PostScript name
fn font_family_name(data: &[u8]) -> String {
match font::load(data.to_vec()) {
Ok(font) => font::family(&font).replace(' ', ""),
Err(_) => "Unknown".to_string(),
}
}
/// The glyph ID for a character
pub fn glyph(face: &Face, character: char) -> Option<u16> {
font::glyph_of(&face.font, character)
}
/// The advance (em)
pub fn advance(face: &Face, glyph: u16) -> f64 {
font::advance(&face.font, glyph)
}
/// The height and depth that a glyph takes up (em)
pub fn extent(face: &Face, glyph: u16) -> (f64, f64) {
font::extent(&face.font, glyph)
}
/// Chooses the glyph that matches the style
///
/// If there is a separate bold or italic typeface, that is used. When there is only the math
/// typeface, the Latin letters for math (from U+1D400) are used instead
pub fn styled(face: &Face, character: char, bold: bool, italic: bool) -> Option<u16> {
if (!bold && !italic) || !font::has_math(&face.font) {
return glyph(face, character);
}
match alphabet(character, bold, italic).and_then(|other| glyph(face, other)) {
Some(found) => Some(found),
None => glyph(face, character),
}
}
/// Replaces a Latin letter or digit with the same character for math
fn alphabet(character: char, bold: bool, italic: bool) -> Option<char> {
let base = match (bold, italic) {
(true, true) => (0x1d468, 0x1d482, 0x1d7ce),
(true, false) => (0x1d400, 0x1d41a, 0x1d7ce),
(false, true) => (0x1d434, 0x1d44e, 0x30),
(false, false) => return None,
};
let code = character as u32;
let shifted = match character {
'A'..='Z' => base.0 + (code - 0x41),
'a'..='z' => base.1 + (code - 0x61),
'0'..='9' => base.2 + (code - 0x30),
_ => return None,
};
// Only the italic h has no character in this sequence
if shifted == 0x1d455 {
return char::from_u32(0x210e);
}
char::from_u32(shifted)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Face {
let data = std::fs::read("../suki/font/latinmodern-math.otf").expect("見本のフォント");
build(data).unwrap()
}
#[test]
fn a_face_knows_what_the_pdf_needs() {
let face = sample();
assert_eq!(face.outline, Outline::Cff);
assert!(face.count > 1000);
assert!(face.units_per_em > 0.0);
assert!(face.bbox.2 > face.bbox.0);
assert!(face.ascent > 0.0);
assert!(face.descent < 0.0);
assert!(face.cap_height > 0.0);
assert!(!face.name.is_empty());
assert!(!face.name.contains(' '));
}
#[test]
fn letters_have_glyphs() {
let face = sample();
assert!(glyph(&face, 'a').is_some());
assert!(advance(&face, glyph(&face, 'a').unwrap()) > 0.0);
}
#[test]
fn a_math_font_stands_in_for_bold_and_italic() {
let face = sample();
let plain = glyph(&face, 'a').unwrap();
let bold = styled(&face, 'a', true, false).unwrap();
let italic = styled(&face, 'a', false, true).unwrap();
assert_ne!(plain, bold);
assert_ne!(plain, italic);
assert_ne!(bold, italic);
}
#[test]
fn a_set_can_be_made_from_bytes() {
let data = std::fs::read("../suki/font/latinmodern-math.otf").expect("見本のフォント");
let library = open_bytes(data, None).unwrap();
assert_eq!(library.face.len(), 1);
assert_eq!(library.role.japanese, library.role.math);
}
}