GfxFont.cpp
1//========================================================================
2//
3// GfxFont.cpp
4//
5// Copyright 1996-2002 Glyph & Cog, LLC
6//
7//========================================================================
8
9#include <aconf.h>
10
11#ifdef USE_GCC_PRAGMAS
12#pragma implementation
13#endif
14
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <ctype.h>
19#include "gmem.h"
20#include "Error.h"
21#include "Object.h"
22#include "Dict.h"
23#include "GlobalParams.h"
24#include "CMap.h"
25#include "CharCodeToUnicode.h"
26#include "FontEncodingTables.h"
27#include "BuiltinFontTables.h"
28#include "FontFile.h"
29#include "GfxFont.h"
30
31//------------------------------------------------------------------------
32
33struct StdFontMapEntry {
34 const char *altName;
35 const char *properName;
36};
37
38static StdFontMapEntry stdFontMap[] = {
39 { "Arial", "Helvetica" },
40 { "Arial,Bold", "Helvetica-Bold" },
41 { "Arial,BoldItalic", "Helvetica-BoldOblique" },
42 { "Arial,Italic", "Helvetica-Oblique" },
43 { "Arial-Bold", "Helvetica-Bold" },
44 { "Arial-BoldItalic", "Helvetica-BoldOblique" },
45 { "Arial-BoldItalicMT", "Helvetica-BoldOblique" },
46 { "Arial-BoldMT", "Helvetica-Bold" },
47 { "Arial-Italic", "Helvetica-Oblique" },
48 { "Arial-ItalicMT", "Helvetica-Oblique" },
49 { "ArialMT", "Helvetica" },
50 { "Courier,Bold", "Courier-Bold" },
51 { "Courier,Italic", "Courier-Oblique" },
52 { "Courier,BoldItalic", "Courier-BoldOblique" },
53 { "CourierNew", "Courier" },
54 { "CourierNew,Bold", "Courier-Bold" },
55 { "CourierNew,BoldItalic", "Courier-BoldOblique" },
56 { "CourierNew,Italic", "Courier-Oblique" },
57 { "CourierNew-Bold", "Courier-Bold" },
58 { "CourierNew-BoldItalic", "Courier-BoldOblique" },
59 { "CourierNew-Italic", "Courier-Oblique" },
60 { "CourierNewPS-BoldItalicMT", "Courier-BoldOblique" },
61 { "CourierNewPS-BoldMT", "Courier-Bold" },
62 { "CourierNewPS-ItalicMT", "Courier-Oblique" },
63 { "CourierNewPSMT", "Courier" },
64 { "Helvetica,Bold", "Helvetica-Bold" },
65 { "Helvetica,BoldItalic", "Helvetica-BoldOblique" },
66 { "Helvetica,Italic", "Helvetica-Oblique" },
67 { "Helvetica-BoldItalic", "Helvetica-BoldOblique" },
68 { "Helvetica-Italic", "Helvetica-Oblique" },
69 { "TimesNewRoman", "Times-Roman" },
70 { "TimesNewRoman,Bold", "Times-Bold" },
71 { "TimesNewRoman,BoldItalic", "Times-BoldItalic" },
72 { "TimesNewRoman,Italic", "Times-Italic" },
73 { "TimesNewRoman-Bold", "Times-Bold" },
74 { "TimesNewRoman-BoldItalic", "Times-BoldItalic" },
75 { "TimesNewRoman-Italic", "Times-Italic" },
76 { "TimesNewRomanPS", "Times-Roman" },
77 { "TimesNewRomanPS-Bold", "Times-Bold" },
78 { "TimesNewRomanPS-BoldItalic", "Times-BoldItalic" },
79 { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
80 { "TimesNewRomanPS-BoldMT", "Times-Bold" },
81 { "TimesNewRomanPS-Italic", "Times-Italic" },
82 { "TimesNewRomanPS-ItalicMT", "Times-Italic" },
83 { "TimesNewRomanPSMT", "Times-Roman" }
84};
85
86//------------------------------------------------------------------------
87// GfxFont
88//------------------------------------------------------------------------
89
90GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
91 GString *nameA;
92 GfxFont *font;
93 Object obj1;
94
95 // get base font name
96 nameA = NULL;
97 fontDict->lookup("BaseFont", &obj1);
98 if (obj1.isName()) {
99 nameA = new GString(obj1.getName());
100 }
101 obj1.free();
102
103 // get font type
104 font = NULL;
105 fontDict->lookup("Subtype", &obj1);
106 if (obj1.isName("Type1") || obj1.isName("MMType1")) {
107 font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1, fontDict);
108 } else if (obj1.isName("Type1C")) {
109 font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType1C, fontDict);
110 } else if (obj1.isName("Type3")) {
111 font = new Gfx8BitFont(xref, tagA, idA, nameA, fontType3, fontDict);
112 } else if (obj1.isName("TrueType")) {
113 font = new Gfx8BitFont(xref, tagA, idA, nameA, fontTrueType, fontDict);
114 } else if (obj1.isName("Type0")) {
115 font = new GfxCIDFont(xref, tagA, idA, nameA, fontDict);
116 } else {
117 error(-1, "Unknown font type: '%s'",
118 obj1.isName() ? obj1.getName() : "???");
119 font = new Gfx8BitFont(xref, tagA, idA, nameA, fontUnknownType, fontDict);
120 }
121 obj1.free();
122
123 return font;
124}
125
126GfxFont::GfxFont(const char *tagA, Ref idA, GString *nameA) {
127 ok = gFalse;
128 tag = new GString(tagA);
129 id = idA;
130 name = nameA;
131 embFontName = NULL;
132 extFontFile = NULL;
133}
134
135GfxFont::~GfxFont() {
136 delete tag;
137 if (name) {
138 delete name;
139 }
140 if (embFontName) {
141 delete embFontName;
142 }
143 if (extFontFile) {
144 delete extFontFile;
145 }
146}
147
148void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
149 Object obj1, obj2, obj3, obj4;
150 double t;
151 int i;
152
153 // assume Times-Roman by default (for substitution purposes)
154 flags = fontSerif;
155
156 embFontID.num = -1;
157 embFontID.gen = -1;
158 missingWidth = 0;
159
160 if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
161
162 // get flags
163 if (obj1.dictLookup("Flags", &obj2)->isInt()) {
164 flags = obj2.getInt();
165 }
166 obj2.free();
167
168 // get name
169 obj1.dictLookup("FontName", &obj2);
170 if (obj2.isName()) {
171 embFontName = new GString(obj2.getName());
172 }
173 obj2.free();
174
175 // look for embedded font file
176 if (obj1.dictLookupNF("FontFile", &obj2)->isRef()) {
177 if (type == fontType1) {
178 embFontID = obj2.getRef();
179 } else {
180 error(-1, "Mismatch between font type and embedded font file");
181 }
182 }
183 obj2.free();
184 if (embFontID.num == -1 &&
185 obj1.dictLookupNF("FontFile2", &obj2)->isRef()) {
186 if (type == fontTrueType || type == fontCIDType2) {
187 embFontID = obj2.getRef();
188 } else {
189 error(-1, "Mismatch between font type and embedded font file");
190 }
191 }
192 obj2.free();
193 if (embFontID.num == -1 &&
194 obj1.dictLookupNF("FontFile3", &obj2)->isRef()) {
195 if (obj2.fetch(xref, &obj3)->isStream()) {
196 obj3.streamGetDict()->lookup("Subtype", &obj4);
197 if (obj4.isName("Type1")) {
198 if (type == fontType1) {
199 embFontID = obj2.getRef();
200 } else {
201 error(-1, "Mismatch between font type and embedded font file");
202 }
203 } else if (obj4.isName("Type1C")) {
204 if (type == fontType1) {
205 type = fontType1C;
206 embFontID = obj2.getRef();
207 } else if (type == fontType1C) {
208 embFontID = obj2.getRef();
209 } else {
210 error(-1, "Mismatch between font type and embedded font file");
211 }
212 } else if (obj4.isName("TrueType")) {
213 if (type == fontTrueType) {
214 embFontID = obj2.getRef();
215 } else {
216 error(-1, "Mismatch between font type and embedded font file");
217 }
218 } else if (obj4.isName("CIDFontType0C")) {
219 if (type == fontCIDType0) {
220 type = fontCIDType0C;
221 embFontID = obj2.getRef();
222 } else {
223 error(-1, "Mismatch between font type and embedded font file");
224 }
225 } else {
226 error(-1, "Unknown embedded font type '%s'",
227 obj4.isName() ? obj4.getName() : "???");
228 }
229 obj4.free();
230 }
231 obj3.free();
232 }
233 obj2.free();
234
235 // look for MissingWidth
236 obj1.dictLookup("MissingWidth", &obj2);
237 if (obj2.isNum()) {
238 missingWidth = obj2.getNum();
239 }
240 obj2.free();
241
242 // get Ascent and Descent
243 obj1.dictLookup("Ascent", &obj2);
244 if (obj2.isNum()) {
245 t = 0.001 * obj2.getNum();
246 // some broken font descriptors set ascent and descent to 0
247 if (t != 0) {
248 ascent = t;
249 }
250 }
251 obj2.free();
252 obj1.dictLookup("Descent", &obj2);
253 if (obj2.isNum()) {
254 t = 0.001 * obj2.getNum();
255 // some broken font descriptors set ascent and descent to 0
256 if (t != 0) {
257 descent = t;
258 }
259 }
260 obj2.free();
261
262 // font FontBBox
263 if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
264 for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
265 if (obj2.arrayGet(i, &obj3)->isNum()) {
266 fontBBox[i] = 0.001 * obj3.getNum();
267 }
268 obj3.free();
269 }
270 }
271 obj2.free();
272
273 }
274 obj1.free();
275}
276
277CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits) {
278 CharCodeToUnicode *ctu;
279 GString *buf;
280 Object obj1;
281 int c;
282
283 if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
284 obj1.free();
285 return NULL;
286 }
287 buf = new GString();
288 obj1.streamReset();
289 while ((c = obj1.streamGetChar()) != EOF) {
290 buf->append(c);
291 }
292 obj1.streamClose();
293 obj1.free();
294 ctu = CharCodeToUnicode::parseCMap(buf, nBits);
295 delete buf;
296 return ctu;
297}
298
299void GfxFont::findExtFontFile() {
300 if (name) {
301 if (type == fontType1) {
302 extFontFile = globalParams->findFontFile(name, ".pfa", ".pfb");
303 } else if (type == fontTrueType) {
304 extFontFile = globalParams->findFontFile(name, ".ttf", NULL);
305 }
306 }
307}
308
309char *GfxFont::readExtFontFile(int *len) {
310 FILE *f;
311 char *buf;
312
313 if (!(f = fopen(extFontFile->getCString(), "rb"))) {
314 error(-1, "External font file '%s' vanished", extFontFile->getCString());
315 return NULL;
316 }
317 fseek(f, 0, SEEK_END);
318 *len = (int)ftell(f);
319 fseek(f, 0, SEEK_SET);
320 buf = (char *)gmalloc(*len);
321 if ((int)fread(buf, 1, *len, f) != *len) {
322 error(-1, "Error reading external font file '%s'", extFontFile);
323 }
324 fclose(f);
325 return buf;
326}
327
328char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
329 char *buf;
330 Object obj1, obj2;
331 Stream *str;
332 int c;
333 int size, i;
334
335 obj1.initRef(embFontID.num, embFontID.gen);
336 obj1.fetch(xref, &obj2);
337 if (!obj2.isStream()) {
338 error(-1, "Embedded font file is not a stream");
339 obj2.free();
340 obj1.free();
341 embFontID.num = -1;
342 return NULL;
343 }
344 str = obj2.getStream();
345
346 buf = NULL;
347 i = size = 0;
348 str->reset();
349 while ((c = str->getChar()) != EOF) {
350 if (i == size) {
351 size += 4096;
352 buf = (char *)grealloc(buf, size);
353 }
354 buf[i++] = c;
355 }
356 *len = i;
357 str->close();
358
359 obj2.free();
360 obj1.free();
361
362 return buf;
363}
364
365//------------------------------------------------------------------------
366// Gfx8BitFont
367//------------------------------------------------------------------------
368
369Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
370 GfxFontType typeA, Dict *fontDict):
371 GfxFont(tagA, idA, nameA)
372{
373 BuiltinFont *builtinFont;
374 char **baseEnc;
375 GBool baseEncFromFontFile;
376 char *buf;
377 int len;
378 FontFile *fontFile;
379 int code, code2;
380 char *charName;
381 GBool missing, hex;
382 Unicode toUnicode[256];
383 double mul;
384 int firstChar, lastChar;
385 Gushort w;
386 Object obj1, obj2, obj3;
387 int n, i, a, b, m;
388
389 type = typeA;
390 ctu = NULL;
391
392 // Acrobat 4.0 and earlier substituted Base14-compatible fonts
393 // without providing Widths and a FontDescriptor, so we munge the
394 // names into the proper Base14 names. (This table is from
395 // implementation note 44 in the PDF 1.4 spec.)
396 if (name) {
397 a = 0;
398 b = sizeof(stdFontMap) / sizeof(StdFontMapEntry);
399 // invariant: stdFontMap[a].altName <= name < stdFontMap[b].altName
400 while (b - a > 1) {
401 m = (a + b) / 2;
402 if (name->cmp(stdFontMap[m].altName) >= 0) {
403 a = m;
404 } else {
405 b = m;
406 }
407 }
408 if (!name->cmp(stdFontMap[a].altName)) {
409 delete name;
410 name = new GString(stdFontMap[a].properName);
411 }
412 }
413
414 // is it a built-in font?
415 builtinFont = NULL;
416 if (name) {
417 for (i = 0; i < nBuiltinFonts; ++i) {
418 if (!name->cmp(builtinFonts[i].name)) {
419 builtinFont = &builtinFonts[i];
420 break;
421 }
422 }
423 }
424
425 // default ascent/descent values
426 if (builtinFont) {
427 ascent = 0.001 * builtinFont->ascent;
428 descent = 0.001 * builtinFont->descent;
429 fontBBox[0] = 0.001 * builtinFont->bbox[0];
430 fontBBox[1] = 0.001 * builtinFont->bbox[1];
431 fontBBox[2] = 0.001 * builtinFont->bbox[2];
432 fontBBox[3] = 0.001 * builtinFont->bbox[3];
433 } else {
434 ascent = 0.95;
435 descent = -0.35;
436 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
437 }
438
439 // get info from font descriptor
440 readFontDescriptor(xref, fontDict);
441
442 // look for an external font file
443 findExtFontFile();
444
445 // get font matrix
446 fontMat[0] = fontMat[3] = 1;
447 fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
448 if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
449 for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
450 if (obj1.arrayGet(i, &obj2)->isNum()) {
451 fontMat[i] = obj2.getNum();
452 }
453 obj2.free();
454 }
455 }
456 obj1.free();
457
458 // get Type 3 bounding box, font definition, and resources
459 if (type == fontType3) {
460 if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
461 for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
462 if (obj1.arrayGet(i, &obj2)->isNum()) {
463 fontBBox[i] = obj2.getNum();
464 }
465 obj2.free();
466 }
467 }
468 obj1.free();
469 if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
470 error(-1, "Missing or invalid CharProcs dictionary in Type 3 font");
471 charProcs.free();
472 }
473 if (!fontDict->lookup("Resources", &resources)->isDict()) {
474 resources.free();
475 }
476 }
477
478 //----- build the font encoding -----
479
480 // Encodings start with a base encoding, which can come from
481 // (in order of priority):
482 // 1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
483 // - MacRoman / MacExpert / WinAnsi / Standard
484 // 2. embedded or external font file
485 // 3. default:
486 // - builtin --> builtin encoding
487 // - TrueType --> MacRomanEncoding
488 // - others --> StandardEncoding
489 // and then add a list of differences (if any) from
490 // FontDict.Encoding.Differences.
491
492 // check FontDict for base encoding
493 hasEncoding = gFalse;
494 baseEnc = NULL;
495 baseEncFromFontFile = gFalse;
496 fontDict->lookup("Encoding", &obj1);
497 if (obj1.isDict()) {
498 obj1.dictLookup("BaseEncoding", &obj2);
499 if (obj2.isName("MacRomanEncoding")) {
500 hasEncoding = gTrue;
501 baseEnc = (char **)macRomanEncoding;
502 } else if (obj2.isName("MacExpertEncoding")) {
503 hasEncoding = gTrue;
504 baseEnc = (char **)macExpertEncoding;
505 } else if (obj2.isName("WinAnsiEncoding")) {
506 hasEncoding = gTrue;
507 baseEnc = (char **)winAnsiEncoding;
508 } else if (obj2.isName("StandardEncoding")) {
509 hasEncoding = gTrue;
510 baseEnc = (char **)standardEncoding;
511 }
512 obj2.free();
513 } else if (obj1.isName("MacRomanEncoding")) {
514 hasEncoding = gTrue;
515 baseEnc = (char **)macRomanEncoding;
516 } else if (obj1.isName("MacExpertEncoding")) {
517 hasEncoding = gTrue;
518 baseEnc = (char **)macExpertEncoding;
519 } else if (obj1.isName("WinAnsiEncoding")) {
520 hasEncoding = gTrue;
521 baseEnc = (char **)winAnsiEncoding;
522 } else if (obj1.isName("StandardEncoding")) {
523 hasEncoding = gTrue;
524 baseEnc = (char **)standardEncoding;
525 }
526
527 // check embedded or external font file for base encoding
528 // (only for Type 1 fonts - trying to get an encoding out of a
529 // TrueType font is a losing proposition)
530 fontFile = NULL;
531 buf = NULL;
532 if ((type == fontType1 || type == fontType1C) &&
533 (extFontFile || embFontID.num >= 0)) {
534 if (extFontFile) {
535 buf = readExtFontFile(&len);
536 } else {
537 buf = readEmbFontFile(xref, &len);
538 }
539 if (buf) {
540 if (type == fontType1C && !strncmp(buf, "%!", 2)) {
541 // various tools (including Adobe's) occasionally embed Type 1
542 // fonts but label them Type 1C
543 type = fontType1;
544 }
545 if (type == fontType1) {
546 fontFile = new Type1FontFile(buf, len);
547 } else {
548 fontFile = new Type1CFontFile(buf, len);
549 }
550 if (fontFile->getName()) {
551 if (embFontName) {
552 delete embFontName;
553 }
554 embFontName = new GString(fontFile->getName());
555 }
556 if (!baseEnc) {
557 baseEnc = fontFile->getEncoding();
558 baseEncFromFontFile = gTrue;
559 }
560 gfree(buf);
561 }
562 }
563
564 // get default base encoding
565 if (!baseEnc) {
566 if (builtinFont) {
567 baseEnc = (char **)builtinFont->defaultBaseEnc;
568 hasEncoding = gTrue;
569 } else if (type == fontTrueType) {
570 baseEnc = (char **)winAnsiEncoding;
571 } else {
572 baseEnc = (char **)standardEncoding;
573 }
574 }
575
576 // copy the base encoding
577 for (i = 0; i < 256; ++i) {
578 enc[i] = baseEnc[i];
579 if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
580 enc[i] = copyString(baseEnc[i]);
581 }
582 }
583
584 // merge differences into encoding
585 if (obj1.isDict()) {
586 obj1.dictLookup("Differences", &obj2);
587 if (obj2.isArray()) {
588 hasEncoding = gTrue;
589 code = 0;
590 for (i = 0; i < obj2.arrayGetLength(); ++i) {
591 obj2.arrayGet(i, &obj3);
592 if (obj3.isInt()) {
593 code = obj3.getInt();
594 } else if (obj3.isName()) {
595 if (code < 256) {
596 if (encFree[code]) {
597 gfree(enc[code]);
598 }
599 enc[code] = copyString(obj3.getName());
600 encFree[code] = gTrue;
601 }
602 ++code;
603 } else {
604 error(-1, "Wrong type in font encoding resource differences (%s)",
605 obj3.getTypeName());
606 }
607 obj3.free();
608 }
609 }
610 obj2.free();
611 }
612 obj1.free();
613 if (fontFile) {
614 delete fontFile;
615 }
616
617 //----- build the mapping to Unicode -----
618
619 // look for a ToUnicode CMap
620 if (!(ctu = readToUnicodeCMap(fontDict, 8))) {
621
622 // no ToUnicode CMap, so use the char names
623
624 // pass 1: use the name-to-Unicode mapping table
625 missing = hex = gFalse;
626 for (code = 0; code < 256; ++code) {
627 if ((charName = enc[code])) {
628 if (!(toUnicode[code] = globalParams->mapNameToUnicode(charName)) &&
629 strcmp(charName, ".notdef")) {
630 // if it wasn't in the name-to-Unicode table, check for a
631 // name that looks like 'Axx' or 'xx', where 'A' is any letter
632 // and 'xx' is two hex digits
633 if ((strlen(charName) == 3 &&
634 isalpha(charName[0]) &&
635 isxdigit(charName[1]) && isxdigit(charName[2]) &&
636 ((charName[1] >= 'a' && charName[1] <= 'f') ||
637 (charName[1] >= 'A' && charName[1] <= 'F') ||
638 (charName[2] >= 'a' && charName[2] <= 'f') ||
639 (charName[2] >= 'A' && charName[2] <= 'F'))) ||
640 (strlen(charName) == 2 &&
641 isxdigit(charName[0]) && isxdigit(charName[1]) &&
642 ((charName[0] >= 'a' && charName[0] <= 'f') ||
643 (charName[0] >= 'A' && charName[0] <= 'F') ||
644 (charName[1] >= 'a' && charName[1] <= 'f') ||
645 (charName[1] >= 'A' && charName[1] <= 'F')))) {
646 hex = gTrue;
647 }
648 missing = gTrue;
649 }
650 } else {
651 toUnicode[code] = 0;
652 }
653 }
654
655 // pass 2: try to fill in the missing chars, looking for names of
656 // the form 'Axx', 'xx', 'Ann', 'ABnn', or 'nn', where 'A' and 'B'
657 // are any letters, 'xx' is two hex digits, and 'nn' is 2-4
658 // decimal digits
659 if (missing && globalParams->getMapNumericCharNames()) {
660 for (code = 0; code < 256; ++code) {
661 if ((charName = enc[code]) && !toUnicode[code] &&
662 strcmp(charName, ".notdef")) {
663 n = strlen(charName);
664 code2 = -1;
665 if (hex && n == 3 && isalpha(charName[0]) &&
666 isxdigit(charName[1]) && isxdigit(charName[2])) {
667 unsigned int tmp;
668 sscanf(charName+1, "%x", &tmp);
669 code2 = tmp;
670 } else if (hex && n == 2 &&
671 isxdigit(charName[0]) && isxdigit(charName[1])) {
672 unsigned int tmp;
673 sscanf(charName, "%x", &tmp);
674 code2 = tmp;
675 } else if (!hex && n >= 2 && n <= 4 &&
676 isdigit(charName[0]) && isdigit(charName[1])) {
677 code2 = atoi(charName);
678 } else if (n >= 3 && n <= 5 &&
679 isdigit(charName[1]) && isdigit(charName[2])) {
680 code2 = atoi(charName+1);
681 } else if (n >= 4 && n <= 6 &&
682 isdigit(charName[2]) && isdigit(charName[3])) {
683 code2 = atoi(charName+2);
684 }
685 if (code2 >= 0 && code2 <= 0xff) {
686 toUnicode[code] = (Unicode)code2;
687 }
688 }
689 }
690 }
691
692 ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
693 }
694
695 //----- get the character widths -----
696
697 // initialize all widths
698 for (code = 0; code < 256; ++code) {
699 widths[code] = missingWidth * 0.001;
700 }
701
702 // use widths from font dict, if present
703 fontDict->lookup("FirstChar", &obj1);
704 firstChar = obj1.isInt() ? obj1.getInt() : 0;
705 obj1.free();
706 fontDict->lookup("LastChar", &obj1);
707 lastChar = obj1.isInt() ? obj1.getInt() : 255;
708 obj1.free();
709 mul = (type == fontType3) ? fontMat[0] : 0.001;
710 fontDict->lookup("Widths", &obj1);
711 if (obj1.isArray()) {
712 flags |= fontFixedWidth;
713 for (code = firstChar; code <= lastChar; ++code) {
714 obj1.arrayGet(code - firstChar, &obj2);
715 if (obj2.isNum()) {
716 widths[code] = obj2.getNum() * mul;
717 if (widths[code] != widths[firstChar]) {
718 flags &= ~fontFixedWidth;
719 }
720 }
721 obj2.free();
722 }
723
724 // use widths from built-in font
725 } else if (builtinFont) {
726 // this is a kludge for broken PDF files that encode char 32
727 // as .notdef
728 if (builtinFont->widths->getWidth("space", &w)) {
729 widths[32] = 0.001 * w;
730 }
731 for (code = 0; code < 256; ++code) {
732 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
733 widths[code] = 0.001 * w;
734 }
735 }
736
737 // couldn't find widths -- use defaults
738 } else {
739 // this is technically an error -- the Widths entry is required
740 // for all but the Base-14 fonts -- but certain PDF generators
741 // apparently don't include widths for Arial and TimesNewRoman
742 if (isFixedWidth()) {
743 i = 0;
744 } else if (isSerif()) {
745 i = 8;
746 } else {
747 i = 4;
748 }
749 if (isBold()) {
750 i += 2;
751 }
752 if (isItalic()) {
753 i += 1;
754 }
755 builtinFont = builtinFontSubst[i];
756 // this is a kludge for broken PDF files that encode char 32
757 // as .notdef
758 if (builtinFont->widths->getWidth("space", &w)) {
759 widths[32] = 0.001 * w;
760 }
761 for (code = 0; code < 256; ++code) {
762 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
763 widths[code] = 0.001 * w;
764 }
765 }
766 }
767 obj1.free();
768
769 ok = gTrue;
770}
771
772Gfx8BitFont::~Gfx8BitFont() {
773 int i;
774
775 for (i = 0; i < 256; ++i) {
776 if (encFree[i] && enc[i]) {
777 gfree(enc[i]);
778 }
779 }
780 ctu->decRefCnt();
781 if (charProcs.isDict()) {
782 charProcs.free();
783 }
784 if (resources.isDict()) {
785 resources.free();
786 }
787}
788
789int Gfx8BitFont::getNextChar(char *s, int /*len*/, CharCode *code,
790 Unicode *u, int uSize, int *uLen,
791 double *dx, double *dy, double *ox, double *oy) {
792 CharCode c;
793
794 *code = c = (CharCode)(*s & 0xff);
795 *uLen = ctu->mapToUnicode(c, u, uSize);
796 *dx = widths[c];
797 *dy = *ox = *oy = 0;
798 return 1;
799}
800
801CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
802 ctu->incRefCnt();
803 return ctu;
804}
805
806Dict *Gfx8BitFont::getCharProcs() {
807 return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
808}
809
810Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
811 if (charProcs.isDict()) {
812 charProcs.dictLookup(enc[code], proc);
813 } else {
814 proc->initNull();
815 }
816 return proc;
817}
818
819Dict *Gfx8BitFont::getResources() {
820 return resources.isDict() ? resources.getDict() : (Dict *)NULL;
821}
822
823//------------------------------------------------------------------------
824// GfxCIDFont
825//------------------------------------------------------------------------
826
827static int cmpWidthExcep(const void *w1, const void *w2) {
828 return ((GfxFontCIDWidthExcep *)w1)->first -
829 ((GfxFontCIDWidthExcep *)w2)->first;
830}
831
832static int cmpWidthExcepV(const void *w1, const void *w2) {
833 return ((GfxFontCIDWidthExcepV *)w1)->first -
834 ((GfxFontCIDWidthExcepV *)w2)->first;
835}
836
837GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
838 Dict *fontDict):
839 GfxFont(tagA, idA, nameA)
840{
841 Dict *desFontDict;
842 GString *collection, *cMapName;
843 Object desFontDictObj;
844 Object obj1, obj2, obj3, obj4, obj5, obj6;
845 int c1, c2;
846 int excepsSize, i, j, k;
847
848 ascent = 0.95;
849 descent = -0.35;
850 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
851 cMap = NULL;
852 ctu = NULL;
853 widths.defWidth = 1.0;
854 widths.defHeight = -1.0;
855 widths.defVY = 0.880;
856 widths.exceps = NULL;
857 widths.nExceps = 0;
858 widths.excepsV = NULL;
859 widths.nExcepsV = 0;
860 cidToGID = NULL;
861 cidToGIDLen = 0;
862
863 // get the descendant font
864 if (!fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
865 error(-1, "Missing DescendantFonts entry in Type 0 font");
866 obj1.free();
867 goto err1;
868 }
869 if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
870 error(-1, "Bad descendant font in Type 0 font");
871 goto err3;
872 }
873 obj1.free();
874 desFontDict = desFontDictObj.getDict();
875
876 // font type
877 if (!desFontDict->lookup("Subtype", &obj1)) {
878 error(-1, "Missing Subtype entry in Type 0 descendant font");
879 goto err3;
880 }
881 if (obj1.isName("CIDFontType0")) {
882 type = fontCIDType0;
883 } else if (obj1.isName("CIDFontType2")) {
884 type = fontCIDType2;
885 } else {
886 error(-1, "Unknown Type 0 descendant font type '%s'",
887 obj1.isName() ? obj1.getName() : "???");
888 goto err3;
889 }
890 obj1.free();
891
892 // get info from font descriptor
893 readFontDescriptor(xref, desFontDict);
894
895 // look for an external font file
896 findExtFontFile();
897
898 //----- encoding info -----
899
900 // char collection
901 if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
902 error(-1, "Missing CIDSystemInfo dictionary in Type 0 descendant font");
903 goto err3;
904 }
905 obj1.dictLookup("Registry", &obj2);
906 obj1.dictLookup("Ordering", &obj3);
907 if (!obj2.isString() || !obj3.isString()) {
908 error(-1, "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
909 goto err4;
910 }
911 collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
912 obj3.free();
913 obj2.free();
914 obj1.free();
915
916 // look for a ToUnicode CMap
917 if (!(ctu = readToUnicodeCMap(fontDict, 16))) {
918
919 // the "Adobe-Identity" and "Adobe-UCS" collections don't have
920 // cidToUnicode files
921 if (collection->cmp("Adobe-Identity") &&
922 collection->cmp("Adobe-UCS")) {
923
924 // look for a user-supplied .cidToUnicode file
925 if (!(ctu = globalParams->getCIDToUnicode(collection))) {
926 error(-1, "Unknown character collection '%s'",
927 collection->getCString());
928 delete collection;
929 goto err2;
930 }
931 }
932 }
933
934 // encoding (i.e., CMap)
935 //~ need to handle a CMap stream here
936 //~ also need to deal with the UseCMap entry in the stream dict
937 if (!fontDict->lookup("Encoding", &obj1)->isName()) {
938 error(-1, "Missing or invalid Encoding entry in Type 0 font");
939 delete collection;
940 goto err3;
941 }
942 cMapName = new GString(obj1.getName());
943 obj1.free();
944 if (!(cMap = globalParams->getCMap(collection, cMapName))) {
945 error(-1, "Unknown CMap '%s' for character collection '%s'",
946 cMapName->getCString(), collection->getCString());
947 delete collection;
948 delete cMapName;
949 goto err2;
950 }
951 delete collection;
952 delete cMapName;
953
954 // CIDToGIDMap (for embedded TrueType fonts)
955 if (type == fontCIDType2) {
956 fontDict->lookup("CIDToGIDMap", &obj1);
957 if (obj1.isStream()) {
958 cidToGIDLen = 0;
959 i = 64;
960 cidToGID = (Gushort *)gmalloc(i * sizeof(Gushort));
961 obj1.streamReset();
962 while ((c1 = obj1.streamGetChar()) != EOF &&
963 (c2 = obj1.streamGetChar()) != EOF) {
964 if (cidToGIDLen == i) {
965 i *= 2;
966 cidToGID = (Gushort *)grealloc(cidToGID, i * sizeof(Gushort));
967 }
968 cidToGID[cidToGIDLen++] = (Gushort)((c1 << 8) + c2);
969 }
970 } else if (!obj1.isName("Identity") && !obj1.isNull()) {
971 error(-1, "Invalid CIDToGIDMap entry in CID font");
972 }
973 obj1.free();
974 }
975
976 //----- character metrics -----
977
978 // default char width
979 if (desFontDict->lookup("DW", &obj1)->isInt()) {
980 widths.defWidth = obj1.getInt() * 0.001;
981 }
982 obj1.free();
983
984 // char width exceptions
985 if (desFontDict->lookup("W", &obj1)->isArray()) {
986 excepsSize = 0;
987 i = 0;
988 while (i + 1 < obj1.arrayGetLength()) {
989 obj1.arrayGet(i, &obj2);
990 obj1.arrayGet(i + 1, &obj3);
991 if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
992 if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
993 if (widths.nExceps == excepsSize) {
994 excepsSize += 16;
995 widths.exceps = (GfxFontCIDWidthExcep *)
996 grealloc(widths.exceps,
997 excepsSize * sizeof(GfxFontCIDWidthExcep));
998 }
999 widths.exceps[widths.nExceps].first = obj2.getInt();
1000 widths.exceps[widths.nExceps].last = obj3.getInt();
1001 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1002 ++widths.nExceps;
1003 } else {
1004 error(-1, "Bad widths array in Type 0 font");
1005 }
1006 obj4.free();
1007 i += 3;
1008 } else if (obj2.isInt() && obj3.isArray()) {
1009 if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
1010 excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
1011 widths.exceps = (GfxFontCIDWidthExcep *)
1012 grealloc(widths.exceps,
1013 excepsSize * sizeof(GfxFontCIDWidthExcep));
1014 }
1015 j = obj2.getInt();
1016 for (k = 0; k < obj3.arrayGetLength(); ++k) {
1017 if (obj3.arrayGet(k, &obj4)->isNum()) {
1018 widths.exceps[widths.nExceps].first = j;
1019 widths.exceps[widths.nExceps].last = j;
1020 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1021 ++j;
1022 ++widths.nExceps;
1023 } else {
1024 error(-1, "Bad widths array in Type 0 font");
1025 }
1026 obj4.free();
1027 }
1028 i += 2;
1029 } else {
1030 error(-1, "Bad widths array in Type 0 font");
1031 ++i;
1032 }
1033 obj3.free();
1034 obj2.free();
1035 }
1036 qsort(widths.exceps, widths.nExceps, sizeof(GfxFontCIDWidthExcep),
1037 &cmpWidthExcep);
1038 }
1039 obj1.free();
1040
1041 // default metrics for vertical font
1042 if (desFontDict->lookup("DW2", &obj1)->isArray() &&
1043 obj1.arrayGetLength() == 2) {
1044 if (obj1.arrayGet(0, &obj2)->isNum()) {
1045 widths.defVY = obj1.getNum() * 0.001;
1046 }
1047 obj2.free();
1048 if (obj1.arrayGet(1, &obj2)->isNum()) {
1049 widths.defHeight = obj1.getNum() * 0.001;
1050 }
1051 obj2.free();
1052 }
1053 obj1.free();
1054
1055 // char metric exceptions for vertical font
1056 if (desFontDict->lookup("W2", &obj1)->isArray()) {
1057 excepsSize = 0;
1058 i = 0;
1059 while (i + 1 < obj1.arrayGetLength()) {
1060 obj1.arrayGet(0, &obj2);
1061 obj2.arrayGet(0, &obj3);
1062 if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
1063 if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
1064 obj1.arrayGet(i + 3, &obj5)->isNum() &&
1065 obj1.arrayGet(i + 4, &obj6)->isNum()) {
1066 if (widths.nExcepsV == excepsSize) {
1067 excepsSize += 16;
1068 widths.excepsV = (GfxFontCIDWidthExcepV *)
1069 grealloc(widths.excepsV,
1070 excepsSize * sizeof(GfxFontCIDWidthExcepV));
1071 }
1072 widths.excepsV[widths.nExcepsV].first = obj2.getInt();
1073 widths.excepsV[widths.nExcepsV].last = obj3.getInt();
1074 widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
1075 widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
1076 widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
1077 ++widths.nExcepsV;
1078 } else {
1079 error(-1, "Bad widths (W2) array in Type 0 font");
1080 }
1081 obj6.free();
1082 obj5.free();
1083 obj4.free();
1084 i += 5;
1085 } else if (obj2.isInt() && obj3.isArray()) {
1086 if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
1087 excepsSize =
1088 (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
1089 widths.excepsV = (GfxFontCIDWidthExcepV *)
1090 grealloc(widths.excepsV,
1091 excepsSize * sizeof(GfxFontCIDWidthExcepV));
1092 }
1093 j = obj2.getInt();
1094 for (k = 0; k < obj3.arrayGetLength(); ++k) {
1095 if (obj3.arrayGet(k, &obj4)->isNum() &&
1096 obj3.arrayGet(k, &obj5)->isNum() &&
1097 obj3.arrayGet(k, &obj6)->isNum()) {
1098 widths.excepsV[widths.nExceps].first = j;
1099 widths.excepsV[widths.nExceps].last = j;
1100 widths.excepsV[widths.nExceps].height = obj4.getNum() * 0.001;
1101 widths.excepsV[widths.nExceps].vx = obj5.getNum() * 0.001;
1102 widths.excepsV[widths.nExceps].vy = obj6.getNum() * 0.001;
1103 ++j;
1104 ++widths.nExcepsV;
1105 } else {
1106 error(-1, "Bad widths (W2) array in Type 0 font");
1107 }
1108 obj6.free();
1109 obj5.free();
1110 obj4.free();
1111 }
1112 i += 2;
1113 } else {
1114 error(-1, "Bad widths (W2) array in Type 0 font");
1115 ++i;
1116 }
1117 obj3.free();
1118 obj2.free();
1119 }
1120 qsort(widths.excepsV, widths.nExcepsV, sizeof(GfxFontCIDWidthExcepV),
1121 &cmpWidthExcepV);
1122 }
1123 obj1.free();
1124
1125 desFontDictObj.free();
1126 ok = gTrue;
1127 return;
1128
1129 err4:
1130 obj3.free();
1131 obj2.free();
1132 err3:
1133 obj1.free();
1134 err2:
1135 desFontDictObj.free();
1136 err1:;
1137}
1138
1139GfxCIDFont::~GfxCIDFont() {
1140 if (cMap) {
1141 cMap->decRefCnt();
1142 }
1143 if (ctu) {
1144 ctu->decRefCnt();
1145 }
1146 gfree(widths.exceps);
1147 gfree(widths.excepsV);
1148 if (cidToGID) {
1149 gfree(cidToGID);
1150 }
1151}
1152
1153int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
1154 Unicode *u, int uSize, int *uLen,
1155 double *dx, double *dy, double *ox, double *oy) {
1156 CID cid;
1157 double w, h, vx, vy;
1158 int n, a, b, m;
1159
1160 if (!cMap) {
1161 *code = 0;
1162 *uLen = 0;
1163 *dx = *dy = 0;
1164 return 1;
1165 }
1166
1167 *code = (CharCode)(cid = cMap->getCID(s, len, &n));
1168 if (ctu) {
1169 *uLen = ctu->mapToUnicode(cid, u, uSize);
1170 } else {
1171 *uLen = 0;
1172 }
1173
1174 // horizontal
1175 if (cMap->getWMode() == 0) {
1176 w = widths.defWidth;
1177 h = vx = vy = 0;
1178 if (widths.nExceps > 0 && cid >= widths.exceps[0].first) {
1179 a = 0;
1180 b = widths.nExceps;
1181 // invariant: widths.exceps[a].first <= cid < widths.exceps[b].first
1182 while (b - a > 1) {
1183 m = (a + b) / 2;
1184 if (widths.exceps[m].first <= cid) {
1185 a = m;
1186 } else {
1187 b = m;
1188 }
1189 }
1190 if (cid <= widths.exceps[a].last) {
1191 w = widths.exceps[a].width;
1192 }
1193 }
1194
1195 // vertical
1196 } else {
1197 w = 0;
1198 h = widths.defHeight;
1199 vx = widths.defWidth / 2;
1200 vy = widths.defVY;
1201 if (widths.nExcepsV > 0 && cid >= widths.excepsV[0].first) {
1202 a = 0;
1203 b = widths.nExcepsV;
1204 // invariant: widths.excepsV[a].first <= cid < widths.excepsV[b].first
1205 while (b - a > 1) {
1206 m = (a + b) / 2;
1207 if (widths.excepsV[m].last <= cid) {
1208 a = m;
1209 } else {
1210 b = m;
1211 }
1212 }
1213 if (cid <= widths.excepsV[a].last) {
1214 h = widths.excepsV[a].height;
1215 vx = widths.excepsV[a].vx;
1216 vy = widths.excepsV[a].vy;
1217 }
1218 }
1219 }
1220
1221 *dx = w;
1222 *dy = h;
1223 *ox = vx;
1224 *oy = vy;
1225
1226 return n;
1227}
1228
1229int GfxCIDFont::getWMode() {
1230 return cMap ? cMap->getWMode() : 0;
1231}
1232
1233CharCodeToUnicode *GfxCIDFont::getToUnicode() {
1234 ctu->incRefCnt();
1235 return ctu;
1236}
1237
1238GString *GfxCIDFont::getCollection() {
1239 return cMap ? cMap->getCollection() : (GString *)NULL;
1240}
1241
1242//------------------------------------------------------------------------
1243// GfxFontDict
1244//------------------------------------------------------------------------
1245
1246GfxFontDict::GfxFontDict(XRef *xref, Dict *fontDict) {
1247 int i;
1248 Object obj1, obj2;
1249 Ref r;
1250
1251 numFonts = fontDict->getLength();
1252 fonts = (GfxFont **)gmalloc(numFonts * sizeof(GfxFont *));
1253 for (i = 0; i < numFonts; ++i) {
1254 fontDict->getValNF(i, &obj1);
1255 obj1.fetch(xref, &obj2);
1256 if (obj2.isDict()) {
1257 if (obj1.isRef()) {
1258 r = obj1.getRef();
1259 } else {
1260 // no indirect reference for this font, so invent a unique one
1261 // (legal generation numbers are five digits, so any 6-digit
1262 // number would be safe)
1263 r.num = i;
1264 r.gen = 999999;
1265 }
1266 fonts[i] = GfxFont::makeFont(xref, fontDict->getKey(i),
1267 r, obj2.getDict());
1268 if (fonts[i] && !fonts[i]->isOk()) {
1269 delete fonts[i];
1270 fonts[i] = NULL;
1271 }
1272 } else {
1273 error(-1, "font resource is not a dictionary");
1274 fonts[i] = NULL;
1275 }
1276 obj1.free();
1277 obj2.free();
1278 }
1279}
1280
1281GfxFontDict::~GfxFontDict() {
1282 int i;
1283
1284 for (i = 0; i < numFonts; ++i) {
1285 if (fonts[i]) {
1286 delete fonts[i];
1287 }
1288 }
1289 gfree(fonts);
1290}
1291
1292GfxFont *GfxFontDict::lookup(char *tag) {
1293 int i;
1294
1295 for (i = 0; i < numFonts; ++i) {
1296 if (fonts[i] && fonts[i]->matches(tag)) {
1297 return fonts[i];
1298 }
1299 }
1300 return NULL;
1301}