caj2pdf-core 0.8.1

Platform-neutral CAJ-family conversion core
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
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
// SPDX-License-Identifier: MIT

use super::*;
use crate::ErrorKind;
use crate::native::SeekableSource;
use crate::pdf::font::tests::{
    CALLSUBR, CffOptions as Options, ENDCHAR, RETURN, RLINETO, RMOVETO, Tables, build, charstrings,
    entry, get32, num, ops, otf, table, tables,
};
use crate::test_support::NEVER;
use std::io::Cursor;
use xberg_ttf_parser::{Face, GlyphId, OutlineBuilder};

#[derive(Default)]
struct Points(Vec<(i32, i32)>);

impl OutlineBuilder for Points {
    fn move_to(&mut self, x: f32, y: f32) {
        self.0.push((x as i32, y as i32));
    }
    fn line_to(&mut self, x: f32, y: f32) {
        self.0.push((x as i32, y as i32));
    }
    fn quad_to(&mut self, _: f32, _: f32, x: f32, y: f32) {
        self.0.push((x as i32, y as i32));
    }
    fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, x: f32, y: f32) {
        self.0.push((x as i32, y as i32));
    }
    fn close(&mut self) {}
}

fn outline(face: &Face<'_>, glyph: u16) -> Vec<(i32, i32)> {
    let mut points = Points::default();
    face.outline_glyph(GlyphId(glyph), &mut points);
    points.0
}

fn used(characters: &[char]) -> Vec<u8> {
    let mut bitmap = vec![0; 8192];
    for character in characters {
        super::super::mark_code(&mut bitmap, *character as usize);
    }
    bitmap
}

/// The CFF subset of `characters` and the source bytes read to build it.
fn plan(font: &[u8], characters: &[char]) -> Result<(CffSubset, u64)> {
    plan_within(font, characters, &Limits::default())
}

fn plan_within(font: &[u8], characters: &[char], limits: &Limits) -> Result<(CffSubset, u64)> {
    let mut source = SeekableSource::new(Cursor::new(font.to_vec())).unwrap();
    (|| {
        let mut font = OpenTypeFont::read(&mut source, 0, &Limits::default(), &NEVER)?;
        let cff = font.cff.clone().unwrap();
        let subset = font.plan_cff(
            &cff,
            crate::pdf::font::Characters::Unicode(&used(characters)),
            u64::MAX,
            limits,
            &NEVER,
        )?;
        Ok((subset, font.subset_bytes_read))
    })()
}

fn subset(font: &[u8], characters: &[char]) -> Result<Vec<u8>> {
    plan(font, characters).map(|(subset, _)| subset.parts().concat())
}

#[test]
fn mapped_cff_capacity_includes_notdef_and_checks_pair_allocation() {
    use crate::pdf::font::{Characters, GlyphCharacters};
    let limits = Limits::default();
    let mut source = SeekableSource::new(Cursor::new(otf(&Options::default()))).unwrap();
    let mut font = OpenTypeFont::read(&mut source, 0, &limits, &NEVER).unwrap();
    let cff = Rc::clone(font.cff.as_ref().unwrap());
    let entries = vec![
        GlyphCharacters {
            glyph: 'A',
            text: 'X'
        };
        usize::from(u16::MAX)
    ];
    let error = font
        .plan_cff(
            &cff,
            Characters::Mapped(&entries),
            u64::MAX,
            &limits,
            &NEVER,
        )
        .err()
        .unwrap();
    assert_eq!(
        error.reason,
        "CFF subset exceeds 65535 glyphs including .notdef"
    );
    let small = Limits {
        max_allocation_bytes: 1,
        ..Limits::default()
    };
    assert!(matches!(
        font.plan_cff(
            &cff,
            Characters::Mapped(&entries[..2]),
            u64::MAX,
            &small,
            &NEVER
        ),
        Err(Error {
            kind: ErrorKind::LimitExceeded { .. },
            ..
        })
    ));
    let plan = font
        .plan_cff(
            &cff,
            Characters::Mapped(&entries[..entries.len() - 1]),
            u64::MAX,
            &limits,
            &NEVER,
        )
        .unwrap();
    let (_, cids, _) = structure(&plan.parts().concat());
    assert_eq!(cids.len(), usize::from(u16::MAX) - 1);
    assert_eq!(cids.first(), Some(&1));
    assert_eq!(cids.last(), Some(&(u16::MAX - 1)));
}

/// Wrap a subset CFF in the source's metadata so it can be outlined.
fn wrap(program: &[u8], source: &[u8]) -> Vec<u8> {
    let mut tables: Tables = tables(source)
        .into_iter()
        .filter(|(tag, _)| tag != b"CFF ")
        .collect();
    tables.push((*b"CFF ", program.to_vec()));
    let mut font = build(tables);
    font[..4].copy_from_slice(b"OTTO");
    font
}

/// Top DICT entries as operators with their operand values.
type TopDict = Vec<(u16, Vec<i64>)>;

/// Top DICT entries, charset CIDs and FDSelect of a subset program.
fn structure(program: &[u8]) -> (TopDict, Vec<u16>, Vec<u8>) {
    let mut source = SeekableSource::new(Cursor::new(program.to_vec())).unwrap();
    let limits = Limits::default();
    {
        let mut reader = Reader {
            source: &mut source,
            limits: &limits,
            cancellation: &NEVER,
            start: 0,
            end: program.len() as u64,
            read: 0,
        };
        let names = reader.index(4).unwrap();
        let tops = reader.index(names.end).unwrap();
        let top = reader.object_bytes(&tops, 0, MAX_DICT_BYTES).unwrap();
        let top: TopDict = dict(&top)
            .unwrap()
            .into_iter()
            .map(|entry| (entry.op, entry.values))
            .collect();
        let at = |op| top.iter().find(|(entry, _)| *entry == op).unwrap().1[0] as usize;
        let charstrings = reader.index(at(OP_CHARSTRINGS) as u64).unwrap();
        let count = charstrings.count as usize;
        let charset = program[at(15)..at(15) + 1 + 2 * (count - 1)].to_vec();
        assert_eq!(charset[0], 0);
        let cids = charset[1..]
            .chunks(2)
            .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
            .collect();
        let select = program[at(OP_FD_SELECT)..].to_vec();
        (top, cids, select)
    }
}

#[test]
fn name_keyed_fonts_become_desubroutinized_cid_subsets() {
    let options = Options::default();
    let font = otf(&options);
    let subset = subset(&font, &['中', 'B', 'A']).unwrap();
    let source = Face::parse(&font, 0).unwrap();
    let wrapped = wrap(&subset, &font);
    let face = Face::parse(&wrapped, 0).unwrap();
    // .notdef, then A, B and 中 in Unicode order.
    assert_eq!(face.number_of_glyphs(), 4);
    for (subset, original) in [(1, 1), (2, 3), (3, 2)] {
        assert_eq!(
            outline(&face, subset),
            outline(&source, original),
            "{subset}"
        );
        assert!(!outline(&face, subset).is_empty());
    }
    let (top, cids, select) = structure(&subset);
    assert_eq!(cids, [0x41, 0x42, 0x4e2d]);
    assert!(top.contains(&(OP_ROS, vec![391, 392, 0])));
    assert!(top.contains(&(1234, vec![0x4e2e])));
    // One font DICT for every glyph.
    assert_eq!(&select[..8], [3, 0, 1, 0, 0, 0, 0, 4]);
    // The subset is measured and tagged by its program bytes.
    let (planned, _) = plan(&font, &['中', 'B', 'A']).unwrap();
    let planned = super::super::subset::FontProgram::Cff(planned);
    assert_eq!(planned.length(), subset.len() as u64);
    assert_eq!(planned.name("Fixture").len(), 14);
}

#[test]
fn cid_keyed_fonts_keep_used_font_dicts_and_matrices() {
    for select_format in [0, 3] {
        let options = Options {
            cid: true,
            select_format,
            ..Options::default()
        };
        let font = otf(&options);
        let source = Face::parse(&font, 0).unwrap();
        // Only FD 1 is used: 中 and B. .notdef uses FD 0.
        let subset = subset(&font, &['中', 'B']).unwrap();
        let wrapped = wrap(&subset, &font);
        let face = Face::parse(&wrapped, 0).unwrap();
        assert_eq!(outline(&face, 1), outline(&source, 3));
        assert_eq!(outline(&face, 2), outline(&source, 2));
        let (top, cids, select) = structure(&subset);
        assert_eq!(cids, [0x42, 0x4e2d]);
        assert!(top.iter().any(|(op, _)| *op == OP_FONT_MATRIX));
        assert_eq!(&select[..11], [3, 0, 2, 0, 0, 0, 0, 1, 1, 0, 3]);
    }
    // An empty subset keeps only .notdef.
    let font = otf(&Options {
        cid: true,
        ..Options::default()
    });
    let (_, cids, _) = structure(&subset(&font, &[]).unwrap());
    assert!(cids.is_empty());
}

fn reason(result: Result<Vec<u8>>) -> &'static str {
    match result {
        Err(Error {
            kind: ErrorKind::Malformed,
            reason,
            ..
        }) => reason,
        Err(Error {
            kind: ErrorKind::LimitExceeded { resource, .. },
            ..
        }) => resource,
        Err(other) => panic!("unexpected {other:?}"),
        Ok(_) => "ok",
    }
}

#[test]
fn malformed_charstrings_fail_closed() {
    let a = |glyph: Vec<u8>| {
        let mut charstrings = charstrings();
        charstrings[1] = glyph;
        Options {
            charstrings,
            ..Options::default()
        }
    };
    let deep = Options {
        local: vec![ops(&[&[-107, CALLSUBR as i32], &[RETURN as i32]])],
        ..a(ops(&[&[-107, CALLSUBR as i32], &[ENDCHAR as i32]]))
    };
    let big = Options {
        local: vec![[ops(&[&[1, 1, RLINETO as i32]]).repeat(3000), vec![RETURN]].concat()],
        ..a([ops(&[&[-107, CALLSUBR as i32]]).repeat(40), vec![ENDCHAR]].concat())
    };
    // Subroutine `i` calls subroutine `i + 1` six times: about 6^9 calls
    // from a few hundred bytes.
    let mut nested: Vec<Vec<u8>> = (1..10)
        .map(|next| {
            [
                ops(&[&[next - 107, CALLSUBR as i32]]).repeat(6),
                vec![RETURN],
            ]
            .concat()
        })
        .collect();
    nested.push(vec![RETURN]);
    let amplified = Options {
        local: nested,
        ..a(ops(&[&[-107, CALLSUBR as i32], &[ENDCHAR as i32]]))
    };
    let cases = [
        (
            a(ops(&[&[0, 0, RMOVETO as i32]])),
            "CFF charstring ends without endchar or return",
        ),
        (a(vec![255, 0, 1]), "CFF charstring is truncated"),
        (
            a(ops(&[&[RETURN as i32]])),
            "CFF charstring returns outside a subroutine",
        ),
        (
            a(ops(&[&[0, 0, 0, 0, ENDCHAR as i32]])),
            "CFF accented-character endchar is not supported",
        ),
        (
            a(ops(&[&[CALLSUBR as i32]])),
            "CFF subroutine call has no number",
        ),
        (
            a(vec![255, 0, 0, 0, 0, CALLSUBR]),
            "CFF subroutine number is not an integer",
        ),
        (
            a(ops(&[&[-1000, CALLSUBR as i32]])),
            "CFF subroutine number is out of range",
        ),
        (
            a(ops(&[&[100, CALLSUBR as i32]])),
            "CFF INDEX object is out of range",
        ),
        (
            a(ops(&[&[2000, CALLSUBR as i32]])),
            "CFF INDEX object is out of range",
        ),
        (a(ops(&[&[1210]])), "unsupported CFF charstring operator"),
        (a(ops(&[&[0]])), "invalid CFF charstring operator"),
        (
            a([num(1).repeat(49), vec![ENDCHAR]].concat()),
            "CFF charstring argument stack overflows",
        ),
        (deep, "CFF subroutines nest too deeply"),
        (big, "CFF charstring bytes"),
        (amplified, "CFF charstring bytes"),
        (
            Options {
                subrs: false,
                ..Options::default()
            },
            "CFF charstring calls missing subroutines",
        ),
    ];
    for (index, (options, expected)) in cases.into_iter().enumerate() {
        let font = otf(&options);
        assert_eq!(reason(subset(&font, &['A'])), expected, "case {index}");
    }
}

#[test]
fn each_subroutine_is_read_once_per_subset() {
    // A calls local subroutine 1 two hundred times; 中 calls it through a
    // global subroutine as well.
    let mut charstrings = charstrings();
    charstrings[1] = [
        ops(&[&[0, 0, RMOVETO as i32]]),
        ops(&[&[-106, CALLSUBR as i32]]).repeat(200),
        vec![ENDCHAR],
    ]
    .concat();
    let font = otf(&Options {
        charstrings,
        ..Options::default()
    });
    let (subset, read) = plan(&font, &['A', '中']).unwrap();
    assert!(subset.length() > 200 * 4);
    assert!(read < font.len() as u64, "{read}");
    // Charstrings and cached subroutines count toward the allocation limit.
    let limits = Limits {
        max_allocation_bytes: 600,
        ..Limits::default()
    };
    assert!(matches!(
        plan_within(&font, &['A', '中'], &limits),
        Err(Error {
            kind: ErrorKind::LimitExceeded {
                resource: "allocation bytes",
                ..
            },
            ..
        })
    ));
}

fn top_edit(edit: impl Fn(&mut Options)) -> Vec<u8> {
    let mut options = Options::default();
    edit(&mut options);
    otf(&options)
}

#[test]
fn malformed_structures_fail_when_the_font_is_read() {
    let read = |font: Vec<u8>| -> &'static str {
        let mut source = SeekableSource::new(Cursor::new(font)).unwrap();
        match OpenTypeFont::read(&mut source, 0, &Limits::default(), &NEVER) {
            Err(Error {
                kind: ErrorKind::Malformed,
                reason,
                ..
            }) => reason,
            Err(Error {
                kind: ErrorKind::LimitExceeded { resource, .. },
                ..
            }) => resource,
            Err(other) => panic!("unexpected {other:?}"),
            Ok(_) => "ok",
        }
    };
    let patched = |edit: fn(&mut [u8])| {
        let mut font = otf(&Options::default());
        let at = get32(&font, entry(&font, b"CFF ") + 8) as usize;
        edit(&mut font[at..]);
        font
    };
    assert_eq!(read(otf(&Options::default())), "ok");
    assert_eq!(read(patched(|cff| cff[0] = 2)), "unsupported CFF header");
    assert_eq!(
        read(patched(|cff| cff[6] = 5)),
        "invalid CFF INDEX offset size"
    );
    assert_eq!(read(patched(|cff| cff[7] = 0)), "invalid CFF INDEX offsets");
    assert_eq!(
        read(top_edit(|options| options.top_extra = vec![139, 139, 17])),
        "CFF DICT operator has the wrong operands"
    );
    assert_eq!(
        read(top_edit(
            |options| options.top_extra = [num(1), vec![12, 6]].concat()
        )),
        "only Type 2 CFF charstrings are supported"
    );
    let mut fewer = tables(&otf(&Options::default()));
    table(&mut fewer, b"maxp")[4..6].copy_from_slice(&3_u16.to_be_bytes());
    let mut fewer = build(fewer);
    fewer[..4].copy_from_slice(b"OTTO");
    assert_eq!(
        read(fewer),
        "CFF CharStrings count differs from the glyph count"
    );
    assert_eq!(
        read(top_edit(|options| options.top_extra = vec![22])),
        "invalid CFF DICT byte"
    );
    assert_eq!(
        read(top_edit(|options| options.top_extra = vec![139; 49])),
        "CFF DICT has too many operands"
    );
    assert_eq!(
        read(top_edit(
            |options| options.top_extra = [num(-1), vec![15]].concat()
        )),
        "ok"
    );
    assert_eq!(
        read(patched(|cff| cff[17] = 0)),
        "a CFF table must hold exactly one font"
    );
    assert_eq!(
        read(top_edit(
            |options| options.top_extra = vec![29, 0, 2, 0, 0, 139, 18]
        )),
        "CFF structure bytes"
    );
    assert_eq!(
        read(top_edit(
            |options| options.top_extra = vec![29, 0, 0x10, 0, 0, 17]
        )),
        "CFF structure is outside its table"
    );
    assert_eq!(
        read(top_edit(
            |options| options.top_extra = [&num(391)[..], &num(392), &num(0), &[12, 30]].concat()
        )),
        "CID-keyed CFF needs an FDArray and FDSelect"
    );
    // Private DICT entries other than Subrs are kept.
    assert_eq!(
        read(top_edit(
            |options| options.private_extra = [num(1), vec![10]].concat()
        )),
        "ok"
    );
    let select = |select: &[u8]| {
        otf(&Options {
            cid: true,
            select: Some(select.to_vec()),
            ..Options::default()
        })
    };
    assert_eq!(read(select(&[0, 0, 0, 1, 1])), "ok");
    assert_eq!(read(select(&[3, 0, 1, 0, 0, 0, 0, 4])), "ok");
    for bad in [
        &[0, 0, 0, 1, 2][..],
        &[3, 0, 0, 0, 4],
        &[3, 0, 1, 0, 1, 0, 0, 4],
        &[3, 0, 2, 0, 0, 0, 0, 0, 1, 0, 4],
        &[3, 0, 1, 0, 0, 2, 0, 4],
        &[3, 0, 1, 0, 0, 0, 0, 3],
    ] {
        assert_eq!(read(select(bad)), "invalid CFF FDSelect", "{bad:?}");
    }
    assert_eq!(read(select(&[1])), "unsupported CFF FDSelect format");
}

#[test]
fn index_lengths_match_written_indexes() {
    for lengths in [&[][..], &[0, 0], &[255], &[300], &[0x1_0000], &[0x100_0000]] {
        let items: Vec<Vec<u8>> = lengths.iter().map(|length| vec![0; *length]).collect();
        let items: Vec<&[u8]> = items.iter().map(|item| &item[..]).collect();
        let mut written = Vec::new();
        index(&mut written, &items);
        assert_eq!(index_length(lengths), written.len(), "{lengths:?}");
    }
}

#[test]
fn dict_parsing_handles_every_operand_form() {
    let bytes = [
        &num(5)[..],
        &num(500),
        &num(-500),
        &num(30_000),
        &[29, 0, 1, 0, 0],
        &[30, 0x1a, 0x5f],
        &[12, 7],
        &[17],
    ]
    .concat();
    let entries = dict(&bytes).unwrap();
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0].op, OP_FONT_MATRIX);
    assert_eq!(entries[0].values, [5, 500, -500, 30_000, 65536, 0]);
    assert_eq!(entries[1].op, OP_CHARSTRINGS);
    assert!(matches!(
        dict(&[30, 0x11]),
        Err(Error {
            kind: ErrorKind::Malformed,
            reason: "CFF real number is truncated",
            ..
        })
    ));
    for bad in [&[28, 0][..], &[29][..], &[247][..], &[12][..], &[139][..]] {
        assert!(dict(bad).is_err(), "{bad:?}");
    }
    let entry = &dict(&[&num(-1)[..], &[17]].concat()).unwrap()[0];
    assert!(operands::<1>(entry).is_err());
    assert_eq!([bias(0), bias(1240), bias(33900)], [107, 1131, 32768]);
}