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