Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.2.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
105.5 KB
Downloads
24
Checksum
f438a48f6f2fc61d892f930eb4fb56fb5a8e302e733a8c3a6283d0ff7350cd08
Dependencies
rust/[email protected]
rust/[email protected]

font.rs

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
//! 書体の読み込み
//!
//! 寸法と字形は suki の読み取りをそのまま使う。ここで足すのは、PDF にフォントを
//! 埋め込むときに要るもの(元のファイル、PostScript の名前、字形を囲む箱、
//! 傾き、大文字の高さ)と、役ごとの割り当てである。
//!
//! 役は 7 つある。地の文、斜体、太字、太斜体、等幅、サンセリフ、和文。
//! 指定しなかった役は数式の書体で代える。

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};


/// 字形の持ち方
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outline {
    /// CFF。PDF では CIDFontType0 になる
    Cff,
    /// glyf。PDF では CIDFontType2 になる
    TrueType,
}


/// 書体 1 つ
#[derive(Debug, Clone)]
pub struct Face {
    /// フォントのファイルの中身。PDF に埋め込むのに要る
    pub data: Vec<u8>,
    /// 寸法と字形
    pub font: Font,
    /// PostScript の名前
    pub name: String,
    /// 字形の数
    pub count: usize,
    pub outline: Outline,
    /// 1em あたりの座標の単位
    pub units_per_em: f64,
    /// 字形を囲む箱。1000 分の 1 em で (左, 下, 右, 上)
    pub bbox: (f64, f64, f64, f64),
    /// 字の傾き(度)
    pub italic_angle: f64,
    /// ベースラインから上(1000 分の 1 em)
    pub ascent: f64,
    /// ベースラインから下(1000 分の 1 em、負)
    pub descent: f64,
    /// 大文字の高さ(1000 分の 1 em)
    pub cap_height: f64,
    /// 縦線の太さの見当(1000 分の 1 em)
    pub stem: f64,
    /// FontDescriptor の Flags
    pub flags: u32,
    /// すべての字が同じ幅か
    pub fixed: bool,
}


/// 役ごとに、どの書体を使うか。値は [`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,
}


/// 文書が使う書体一式
pub struct Library {
    pub face: Vec<Face>,
    pub role: Assignment,
    /// 化学式を組むための読み取り。lina は自前の型で持つ
    pub chem: lina::Font,
}


/// フォントのファイルを読み込む
pub fn load(path: &Path) -> Result<Face, Error> {
    let data = std::fs::read(path)
        .map_err(|reason| Error::new(format!("フォントを読めません: {}: {reason}", path.display()), 0))?;

    build(data)
}


/// 読み込んだファイルの中身から書体を組み立てる
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,
    })
}


/// 役ごとのファイルを読み込んで一式にする。指定しなかった役は数式の書体で代える
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!("フォントを読めません: {reason}"), 0))?;
    let chem = lina::load_font(data).map_err(|reason| Error::new(reason.to_string(), 0))?;

    Ok(Library {face, role, chem})
}


/// 指定がなければ代わりのファイルを使う
fn pick<'a>(given: Option<&'a Path>, fallback: &'a Path) -> &'a Path {
    given.unwrap_or(fallback)
}


/// 同じファイルは 1 度だけ読み込む
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)
}


/// 要るテーブルを引く
fn table(data: &[u8], tag: &str) -> Result<(usize, usize), Error> {
    read(opentype::require(data, tag))
}


/// suki の読み取りの誤りを、こちらの誤りに直す
fn read<T>(found: Result<T, suki::Error>) -> Result<T, Error> {
    found.map_err(|reason| Error::new(reason.to_string(), 0))
}


/// post テーブルから、字の傾きと、すべての字が同じ幅かを取る
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))
}


/// OS/2 と hhea から、上下の伸びと大文字の高さと太さを取る
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))
}


/// name テーブルから PostScript の名前を取る
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())
}


/// PostScript の名前がないときの代わり
fn font_family_name(data: &[u8]) -> String {
    match font::load(data.to_vec()) {
        Ok(font) => font::family(&font).replace(' ', ""),
        Err(_) => "Unknown".to_string(),
    }
}


/// 文字に当たる字形の番号
pub fn glyph(face: &Face, character: char) -> Option<u16> {
    font::glyph_of(&face.font, character)
}


/// 字送り(em)
pub fn advance(face: &Face, glyph: u16) -> f64 {
    font::advance(&face.font, glyph)
}


/// 字が占める高さと深さ(em)
pub fn extent(face: &Face, glyph: u16) -> (f64, f64) {
    font::extent(&face.font, glyph)
}


/// 装いに合う字形を選ぶ
///
/// 太字や斜体の書体が別にあればそれを使う。数式の書体しかないときは、
/// 数式用の英字(U+1D400 から)で代える
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),
    }
}


/// 英数字を、数式用の同じ字に置き換える
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,
    };

    // 斜体の h だけは、この並びに字が置かれていない
    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);
    }
}