pdf-font 1.0.0-beta.3

PDF font handling: CFF/Type1 parsing, CMap parsing, and PostScript scanning.
Documentation
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
use crate::font::OutlineError;
use crate::font::argstack::ArgumentsStack;
use crate::font::type1::charstring_parser::CharStringParser;
use crate::font::type1::operator::{sb_operator, tb_operator};
use crate::font::type1::stream::Stream;
use crate::font::type1::{EncodingType, Parameters};
use crate::font::{Builder, OutlineBuilder, RectF};
use log::{debug, error, trace, warn};

const MAX_ARGUMENTS_STACK_LEN: usize = 48;
const STACK_LIMIT: u8 = 10;

struct CharStringParserContext<'a> {
    params: &'a Parameters,
    stems_len: u32,
    has_endchar: bool,
    has_seac: bool,
    width: Option<f32>,
    width_only: bool,
}

pub(crate) fn parse_char_string(
    data: &[u8],
    params: &Parameters,
    builder: &mut dyn OutlineBuilder,
) -> Result<(), OutlineError> {
    let mut ctx = CharStringParserContext {
        params,
        stems_len: 0,
        has_endchar: false,
        has_seac: false,
        width: None,
        width_only: false,
    };

    let mut inner_builder = Builder {
        builder,
        bbox: RectF::new(),
    };

    let stack = ArgumentsStack {
        data: &mut [0.0; MAX_ARGUMENTS_STACK_LEN],
        len: 0,
        max_len: MAX_ARGUMENTS_STACK_LEN,
    };

    let ps_stack = ArgumentsStack {
        data: &mut [0.0; MAX_ARGUMENTS_STACK_LEN],
        len: 0,
        max_len: MAX_ARGUMENTS_STACK_LEN,
    };

    let mut parser = CharStringParser {
        stack,
        builder: &mut inner_builder,
        x: 0.0,
        y: 0.0,
        sbx: 0.0,
        is_flexing: false,
        ps_stack,
    };
    _parse_char_string(&mut ctx, data, 0, &mut parser)?;

    if !ctx.has_endchar && !ctx.has_seac {
        return Err(OutlineError::MissingEndChar);
    }

    Ok(())
}

pub(crate) fn parse_char_string_width(
    data: &[u8],
    params: &Parameters,
) -> Result<f32, OutlineError> {
    let mut ctx = CharStringParserContext {
        params,
        stems_len: 0,
        has_endchar: false,
        has_seac: false,
        width: None,
        width_only: true,
    };

    let mut inner_builder = Builder {
        builder: &mut crate::font::DummyOutline,
        bbox: RectF::new(),
    };

    let stack = ArgumentsStack {
        data: &mut [0.0; MAX_ARGUMENTS_STACK_LEN],
        len: 0,
        max_len: MAX_ARGUMENTS_STACK_LEN,
    };

    let ps_stack = ArgumentsStack {
        data: &mut [0.0; MAX_ARGUMENTS_STACK_LEN],
        len: 0,
        max_len: MAX_ARGUMENTS_STACK_LEN,
    };

    let mut parser = CharStringParser {
        stack,
        builder: &mut inner_builder,
        x: 0.0,
        y: 0.0,
        sbx: 0.0,
        is_flexing: false,
        ps_stack,
    };
    _parse_char_string(&mut ctx, data, 0, &mut parser)?;

    if !ctx.has_endchar && !ctx.has_seac {
        return Err(OutlineError::MissingEndChar);
    }

    ctx.width.ok_or(OutlineError::InvalidArgumentsStackLength)
}

fn _parse_char_string(
    ctx: &mut CharStringParserContext<'_>,
    char_string: &[u8],
    depth: u8,
    p: &mut CharStringParser<'_>,
) -> Result<(), OutlineError> {
    macro_rules! trace_op {
        ($name:literal) => {
            debug!("{} ({})", $name, &p.stack.dump());
        };
    }

    let mut s = Stream::new(char_string);
    while !s.at_end() {
        let op = s.read_byte().ok_or(OutlineError::ReadOutOfBounds)?;
        match op {
            sb_operator::HORIZONTAL_STEM | sb_operator::VERTICAL_STEM => {
                trace_op!("HORIZONTAL_STEM | VERTICAL_STEM");
                let len = p.stack.len();

                ctx.stems_len += len as u32 >> 1;

                p.stack.clear();
            }
            sb_operator::VERTICAL_MOVE_TO => {
                trace_op!("VERTICAL_MOVE_TO");

                p.parse_vertical_move_to()?;
            }
            sb_operator::LINE_TO => {
                trace_op!("LINE_TO");

                p.parse_line_to()?;
            }
            sb_operator::HORIZONTAL_LINE_TO => {
                trace_op!("HORIZONTAL_LINE_TO");

                p.parse_horizontal_line_to()?;
            }
            sb_operator::VERTICAL_LINE_TO => {
                trace_op!("VERTICAL_LINE_TO");

                p.parse_vertical_line_to()?;
            }
            sb_operator::CURVE_TO => {
                trace_op!("CURVE_TO");

                p.parse_curve_to()?;
            }
            sb_operator::CLOSE_PATH => {
                trace_op!("CLOSE_PATH");

                p.parse_close_path()?;
            }
            sb_operator::CALL_SUBR => {
                trace_op!("CALL_SUBR");

                if p.stack.is_empty() {
                    return Err(OutlineError::InvalidArgumentsStackLength);
                }

                if depth == STACK_LIMIT {
                    return Err(OutlineError::NestingLimitReached);
                }

                let index = p.stack.pop() as u32;

                if let Some(subr) = ctx.params.subroutines.get(&index) {
                    _parse_char_string(ctx, subr, depth + 1, p)?;
                } else {
                    return Err(OutlineError::NoLocalSubroutines);
                }
            }
            sb_operator::RETURN => {
                trace_op!("RETURN");

                break;
            }
            sb_operator::ESCAPE => {
                let op = s.read_byte().ok_or(OutlineError::ReadOutOfBounds)?;

                match op {
                    tb_operator::DOTSECTION => {
                        trace_op!("DOTSECTION");

                        p.stack.clear();
                    }
                    tb_operator::VSTEM3 => {
                        trace_op!("VSTEM3");

                        p.stack.clear();
                    }
                    tb_operator::HSTEM3 => {
                        trace_op!("HSTEM3");

                        p.stack.clear();
                    }
                    tb_operator::SEAC => {
                        trace_op!("SEAC");

                        if p.stack.len != 5 {
                            return Err(OutlineError::InvalidArgumentsStackLength);
                        }

                        let accent_char = EncodingType::Standard.encode(p.stack.pop() as u8);
                        let base_char = EncodingType::Standard.encode(p.stack.pop() as u8);
                        let dy = p.stack.pop();
                        let dx = p.stack.pop();
                        let asb = p.stack.pop();

                        ctx.has_seac = true;

                        if depth == STACK_LIMIT {
                            return Err(OutlineError::NestingLimitReached);
                        }

                        let base_char_string = ctx
                            .params
                            .charstrings
                            .get(base_char.ok_or(OutlineError::InvalidSeacCode)?)
                            .ok_or(OutlineError::InvalidSeacCode)?;
                        if ctx.width_only {
                            if ctx.width.is_none() {
                                _parse_char_string(ctx, base_char_string, depth + 1, p)?;
                            }
                            break;
                        }

                        _parse_char_string(ctx, base_char_string, depth + 1, p)?;
                        p.x = dx + p.sbx - asb;
                        p.y = dy;

                        let accent_char_string = ctx
                            .params
                            .charstrings
                            .get(accent_char.ok_or(OutlineError::InvalidSeacCode)?)
                            .ok_or(OutlineError::InvalidSeacCode)?;
                        _parse_char_string(ctx, accent_char_string, depth + 1, p)?;
                        break;
                    }
                    tb_operator::SBW => {
                        trace_op!("SBW");
                        if ctx.width_only && ctx.width.is_none() {
                            ctx.width = Some(p.stack.at(2));
                        }
                        p.x = p.stack.at(0);
                        p.y = p.stack.at(1);
                        p.sbx = p.x;

                        p.stack.clear();
                    }
                    tb_operator::DIV => {
                        trace_op!("DIV");
                        let num2 = p.stack.pop();
                        let num1 = p.stack.pop();

                        p.stack.push(num1 / num2)?;
                    }
                    tb_operator::CALL_OTHER_SUBR => {
                        trace_op!("CALL_OTHER_SUBR");

                        let subr_index = p.stack.pop() as i32;
                        let n_args = p.stack.pop() as i32;

                        if subr_index == 1 && n_args == 0 {
                            p.is_flexing = true;
                        } else if subr_index == 0 && n_args == 3 {
                            p.parse_flex()?;
                            p.is_flexing = false;
                        } else if (14..=17).contains(&subr_index)
                            && let Some(wv) = &ctx.params.weight_vector
                            && wv.len() > 1
                        {
                            // Note: Following code (as well as any code related to
                            // MM fonts) was AI-generated based on FreeType code,
                            // haven't double-checked.

                            // MultipleMaster interpolation (base + delta form).
                            //
                            // Stack layout: [base0, ..., baseN, d0_m1, d0_m2, ..., d(N-1)_m(M-1)]
                            // where N = num_points, M = num_designs.
                            //
                            // result_i = base_i + sum(delta_i_j * w_j) for j = 1..M-1
                            let n_results = (subr_index - 13) as usize;
                            let stack_base = p.stack.len() - n_args as usize;
                            let mut delta_idx = stack_base + n_results;

                            // Compute blended results.
                            let mut results = [0.0_f32; 4];
                            for (i, result) in results[..n_results].iter_mut().enumerate() {
                                let mut tmp = p.stack.at(stack_base + i);
                                for w in &wv[1..] {
                                    tmp += p.stack.at(delta_idx) * w;
                                    delta_idx += 1;
                                }
                                *result = tmp;
                            }

                            // Remove consumed args from charstring stack.
                            for _ in 0..n_args {
                                p.stack.pop();
                            }

                            // Push results to ps_stack in reverse order
                            // so that POP retrieves result[0] first.
                            p.ps_stack.clear();
                            for i in (0..n_results).rev() {
                                p.ps_stack.push(results[i])?;
                            }
                        } else {
                            trace!("ignoring call_other_subr with {subr_index}, {n_args}");

                            p.ps_stack.clear();
                            for _ in 0..n_args {
                                if p.stack.is_empty() {
                                    break;
                                }
                                let val = p.stack.pop();
                                p.ps_stack.push(val)?;
                            }
                        }
                    }
                    tb_operator::POP => {
                        trace_op!("POP");

                        if !p.ps_stack.is_empty() {
                            let val = p.ps_stack.pop();
                            p.stack.push(val)?;
                        }
                    }
                    tb_operator::SET_CURRENT_POINT => {
                        trace_op!("SET_CURRENT_POINT");
                        p.x = p.stack.at(0);
                        p.y = p.stack.at(1);

                        p.stack.clear();
                    }
                    _ => error!("unknown two-byte operator {op}"),
                }
            }
            sb_operator::HSBW => {
                trace_op!("HSBW");
                if ctx.width_only && ctx.width.is_none() {
                    ctx.width = Some(p.stack.at(1));
                }

                p.x += p.stack.at(0);
                p.sbx = p.x;

                p.stack.clear();
            }
            sb_operator::ENDCHAR => {
                trace_op!("ENDCHAR");
                ctx.has_endchar = true;

                break;
            }
            sb_operator::MOVE_TO => {
                trace_op!("MOVE_TO");

                p.parse_move_to()?;
            }
            sb_operator::HORIZONTAL_MOVE_TO => {
                trace_op!("HORIZONTAL_MOVE_TO");

                p.parse_horizontal_move_to()?;
            }
            sb_operator::VH_CURVE_TO => {
                trace_op!("VH_CURVE_TO");

                p.parse_vh_curve_to()?;
            }
            sb_operator::HV_CURVE_TO => {
                trace_op!("HV_CURVE_TO");

                p.parse_hv_curve_to()?;
            }
            32..=246 => {
                p.parse_int1(op)?;
            }
            247..=250 => {
                p.parse_int2(op, &mut s)?;
            }
            251..=254 => {
                p.parse_int3(op, &mut s)?;
            }
            255 => p.parse_int4(&mut s)?,
            _ => {
                warn!("unrecognized charstring op: {op}");
            }
        }
    }

    Ok(())
}