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