fix getsup (HH)
[luatex.git] / source / libs / poppler / poppler-src / poppler / GfxFont.cc
blobea23e03a534cbfd4ee55927fb4a13c382ca5e513
1 //========================================================================
2 //
3 // GfxFont.cc
4 //
5 // Copyright 1996-2003 Glyph & Cog, LLC
6 //
7 //========================================================================
9 //========================================================================
11 // Modified under the Poppler project - http://poppler.freedesktop.org
13 // All changes made under the Poppler project to this file are licensed
14 // under GPL version 2 or later
16 // Copyright (C) 2005, 2006, 2008-2010, 2012, 2014, 2015 Albert Astals Cid <aacid@kde.org>
17 // Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
18 // Copyright (C) 2006 Takashi Iwai <tiwai@suse.de>
19 // Copyright (C) 2007 Julien Rebetez <julienr@svn.gnome.org>
20 // Copyright (C) 2007 Jeff Muizelaar <jeff@infidigm.net>
21 // Copyright (C) 2007 Koji Otani <sho@bbr.jp>
22 // Copyright (C) 2007 Ed Catmur <ed@catmur.co.uk>
23 // Copyright (C) 2008 Jonathan Kew <jonathan_kew@sil.org>
24 // Copyright (C) 2008 Ed Avis <eda@waniasset.com>
25 // Copyright (C) 2008, 2010 Hib Eris <hib@hiberis.nl>
26 // Copyright (C) 2009 Peter Kerzum <kerzum@yandex-team.ru>
27 // Copyright (C) 2009, 2010 David Benjamin <davidben@mit.edu>
28 // Copyright (C) 2011 Axel Strübing <axel.struebing@freenet.de>
29 // Copyright (C) 2011, 2012, 2014 Adrian Johnson <ajohnson@redneon.com>
30 // Copyright (C) 2012 Yi Yang <ahyangyi@gmail.com>
31 // Copyright (C) 2012 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
32 // Copyright (C) 2012 Thomas Freitag <Thomas.Freitag@alfa.de>
33 // Copyright (C) 2013-2016 Jason Crain <jason@aquaticape.us>
34 // Copyright (C) 2014 Olly Betts <olly@survex.com>
36 // To see a description of the changes please see the Changelog file that
37 // came with your tarball or type make ChangeLog if you are building from git
39 //========================================================================
41 #include <config.h>
43 #ifdef USE_GCC_PRAGMAS
44 #pragma implementation
45 #endif
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <ctype.h>
51 #include <math.h>
52 #include <limits.h>
53 #include <algorithm>
54 #include "goo/gmem.h"
55 #include "Error.h"
56 #include "Object.h"
57 #include "Dict.h"
58 #include "GlobalParams.h"
59 #include "CMap.h"
60 #include "CharCodeToUnicode.h"
61 #include "FontEncodingTables.h"
62 #include "BuiltinFontTables.h"
63 #include "UnicodeTypeTable.h"
64 #include <fofi/FoFiIdentifier.h>
65 #include <fofi/FoFiType1.h>
66 #include <fofi/FoFiType1C.h>
67 #include <fofi/FoFiTrueType.h>
68 #include "GfxFont.h"
69 #include "PSOutputDev.h"
71 //------------------------------------------------------------------------
73 struct Base14FontMapEntry {
74 const char *altName;
75 const char *base14Name;
78 static const Base14FontMapEntry base14FontMap[] = {
79 { "Arial", "Helvetica" },
80 { "Arial,Bold", "Helvetica-Bold" },
81 { "Arial,BoldItalic", "Helvetica-BoldOblique" },
82 { "Arial,Italic", "Helvetica-Oblique" },
83 { "Arial-Bold", "Helvetica-Bold" },
84 { "Arial-BoldItalic", "Helvetica-BoldOblique" },
85 { "Arial-BoldItalicMT", "Helvetica-BoldOblique" },
86 { "Arial-BoldMT", "Helvetica-Bold" },
87 { "Arial-Italic", "Helvetica-Oblique" },
88 { "Arial-ItalicMT", "Helvetica-Oblique" },
89 { "ArialMT", "Helvetica" },
90 { "Courier", "Courier" },
91 { "Courier,Bold", "Courier-Bold" },
92 { "Courier,BoldItalic", "Courier-BoldOblique" },
93 { "Courier,Italic", "Courier-Oblique" },
94 { "Courier-Bold", "Courier-Bold" },
95 { "Courier-BoldOblique", "Courier-BoldOblique" },
96 { "Courier-Oblique", "Courier-Oblique" },
97 { "CourierNew", "Courier" },
98 { "CourierNew,Bold", "Courier-Bold" },
99 { "CourierNew,BoldItalic", "Courier-BoldOblique" },
100 { "CourierNew,Italic", "Courier-Oblique" },
101 { "CourierNew-Bold", "Courier-Bold" },
102 { "CourierNew-BoldItalic", "Courier-BoldOblique" },
103 { "CourierNew-Italic", "Courier-Oblique" },
104 { "CourierNewPS-BoldItalicMT", "Courier-BoldOblique" },
105 { "CourierNewPS-BoldMT", "Courier-Bold" },
106 { "CourierNewPS-ItalicMT", "Courier-Oblique" },
107 { "CourierNewPSMT", "Courier" },
108 { "Helvetica", "Helvetica" },
109 { "Helvetica,Bold", "Helvetica-Bold" },
110 { "Helvetica,BoldItalic", "Helvetica-BoldOblique" },
111 { "Helvetica,Italic", "Helvetica-Oblique" },
112 { "Helvetica-Bold", "Helvetica-Bold" },
113 { "Helvetica-BoldItalic", "Helvetica-BoldOblique" },
114 { "Helvetica-BoldOblique", "Helvetica-BoldOblique" },
115 { "Helvetica-Italic", "Helvetica-Oblique" },
116 { "Helvetica-Oblique", "Helvetica-Oblique" },
117 { "Symbol", "Symbol" },
118 { "Symbol,Bold", "Symbol" },
119 { "Symbol,BoldItalic", "Symbol" },
120 { "Symbol,Italic", "Symbol" },
121 { "SymbolMT", "Symbol" },
122 { "SymbolMT,Bold", "Symbol" },
123 { "SymbolMT,BoldItalic", "Symbol" },
124 { "SymbolMT,Italic", "Symbol" },
125 { "Times-Bold", "Times-Bold" },
126 { "Times-BoldItalic", "Times-BoldItalic" },
127 { "Times-Italic", "Times-Italic" },
128 { "Times-Roman", "Times-Roman" },
129 { "TimesNewRoman", "Times-Roman" },
130 { "TimesNewRoman,Bold", "Times-Bold" },
131 { "TimesNewRoman,BoldItalic", "Times-BoldItalic" },
132 { "TimesNewRoman,Italic", "Times-Italic" },
133 { "TimesNewRoman-Bold", "Times-Bold" },
134 { "TimesNewRoman-BoldItalic", "Times-BoldItalic" },
135 { "TimesNewRoman-Italic", "Times-Italic" },
136 { "TimesNewRomanPS", "Times-Roman" },
137 { "TimesNewRomanPS-Bold", "Times-Bold" },
138 { "TimesNewRomanPS-BoldItalic", "Times-BoldItalic" },
139 { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
140 { "TimesNewRomanPS-BoldMT", "Times-Bold" },
141 { "TimesNewRomanPS-Italic", "Times-Italic" },
142 { "TimesNewRomanPS-ItalicMT", "Times-Italic" },
143 { "TimesNewRomanPSMT", "Times-Roman" },
144 { "TimesNewRomanPSMT,Bold", "Times-Bold" },
145 { "TimesNewRomanPSMT,BoldItalic", "Times-BoldItalic" },
146 { "TimesNewRomanPSMT,Italic", "Times-Italic" },
147 { "ZapfDingbats", "ZapfDingbats" }
150 //------------------------------------------------------------------------
152 // index: {fixed:0, sans-serif:4, serif:8} + bold*2 + italic
153 // NB: must be in same order as psSubstFonts in PSOutputDev.cc
154 static const char *base14SubstFonts[14] = {
155 "Courier",
156 "Courier-Oblique",
157 "Courier-Bold",
158 "Courier-BoldOblique",
159 "Helvetica",
160 "Helvetica-Oblique",
161 "Helvetica-Bold",
162 "Helvetica-BoldOblique",
163 "Times-Roman",
164 "Times-Italic",
165 "Times-Bold",
166 "Times-BoldItalic",
167 // the last two are never used for substitution
168 "Symbol",
169 "ZapfDingbats"
172 //------------------------------------------------------------------------
174 static int parseCharName(char *charName, Unicode *uBuf, int uLen,
175 GBool names, GBool ligatures,
176 GBool numeric, GBool hex, GBool variants);
178 //------------------------------------------------------------------------
180 static int readFromStream(void *data) {
181 return ((Stream *)data)->getChar();
184 //------------------------------------------------------------------------
185 // GfxFontLoc
186 //------------------------------------------------------------------------
188 GfxFontLoc::GfxFontLoc() {
189 path = NULL;
190 fontNum = 0;
191 encoding = NULL;
192 substIdx = -1;
195 GfxFontLoc::~GfxFontLoc() {
196 if (path) {
197 delete path;
199 if (encoding) {
200 delete encoding;
204 //------------------------------------------------------------------------
205 // GfxFont
206 //------------------------------------------------------------------------
208 GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
209 GooString *nameA;
210 Ref embFontIDA;
211 GfxFontType typeA;
212 GfxFont *font;
213 Object obj1;
215 // get base font name
216 nameA = NULL;
217 fontDict->lookup("BaseFont", &obj1);
218 if (obj1.isName()) {
219 nameA = new GooString(obj1.getName());
221 obj1.free();
223 // get embedded font ID and font type
224 typeA = getFontType(xref, fontDict, &embFontIDA);
226 // create the font object
227 font = NULL;
228 if (typeA < fontCIDType0) {
229 font = new Gfx8BitFont(xref, tagA, idA, nameA, typeA, embFontIDA,
230 fontDict);
231 } else {
232 font = new GfxCIDFont(xref, tagA, idA, nameA, typeA, embFontIDA,
233 fontDict);
236 return font;
239 GfxFont::GfxFont(const char *tagA, Ref idA, GooString *nameA,
240 GfxFontType typeA, Ref embFontIDA) {
241 ok = gFalse;
242 tag = new GooString(tagA);
243 id = idA;
244 name = nameA;
245 type = typeA;
246 embFontID = embFontIDA;
247 embFontName = NULL;
248 family = NULL;
249 stretch = StretchNotDefined;
250 weight = WeightNotDefined;
251 refCnt = 1;
252 encodingName = new GooString("");
253 hasToUnicode = gFalse;
256 GfxFont::~GfxFont() {
257 delete tag;
258 delete family;
259 if (name) {
260 delete name;
262 if (embFontName) {
263 delete embFontName;
265 if (encodingName) {
266 delete encodingName;
270 void GfxFont::incRefCnt() {
271 refCnt++;
274 void GfxFont::decRefCnt() {
275 if (--refCnt == 0)
276 delete this;
279 // This function extracts three pieces of information:
280 // 1. the "expected" font type, i.e., the font type implied by
281 // Font.Subtype, DescendantFont.Subtype, and
282 // FontDescriptor.FontFile3.Subtype
283 // 2. the embedded font object ID
284 // 3. the actual font type - determined by examining the embedded font
285 // if there is one, otherwise equal to the expected font type
286 // If the expected and actual font types don't match, a warning
287 // message is printed. The expected font type is not used for
288 // anything else.
289 GfxFontType GfxFont::getFontType(XRef *xref, Dict *fontDict, Ref *embID) {
290 GfxFontType t, expectedType;
291 FoFiIdentifierType fft;
292 Dict *fontDict2;
293 Object subtype, fontDesc, obj1, obj2, obj3, obj4;
294 GBool isType0, err;
296 t = fontUnknownType;
297 embID->num = embID->gen = -1;
298 err = gFalse;
300 fontDict->lookup("Subtype", &subtype);
301 expectedType = fontUnknownType;
302 isType0 = gFalse;
303 if (subtype.isName("Type1") || subtype.isName("MMType1")) {
304 expectedType = fontType1;
305 } else if (subtype.isName("Type1C")) {
306 expectedType = fontType1C;
307 } else if (subtype.isName("Type3")) {
308 expectedType = fontType3;
309 } else if (subtype.isName("TrueType")) {
310 expectedType = fontTrueType;
311 } else if (subtype.isName("Type0")) {
312 isType0 = gTrue;
313 } else {
314 error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
315 subtype.isName() ? subtype.getName() : "???");
317 subtype.free();
319 fontDict2 = fontDict;
320 if (fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
321 if (obj1.arrayGetLength() == 0) {
322 error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
323 obj2.initNull();
324 } else if (obj1.arrayGet(0, &obj2)->isDict()) {
325 if (!isType0) {
326 error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
328 fontDict2 = obj2.getDict();
329 fontDict2->lookup("Subtype", &subtype);
330 if (subtype.isName("CIDFontType0")) {
331 if (isType0) {
332 expectedType = fontCIDType0;
334 } else if (subtype.isName("CIDFontType2")) {
335 if (isType0) {
336 expectedType = fontCIDType2;
339 subtype.free();
341 } else {
342 obj2.initNull();
345 if (fontDict2->lookup("FontDescriptor", &fontDesc)->isDict()) {
346 if (fontDesc.dictLookupNF("FontFile", &obj3)->isRef()) {
347 *embID = obj3.getRef();
348 if (expectedType != fontType1) {
349 err = gTrue;
352 obj3.free();
353 if (embID->num == -1 &&
354 fontDesc.dictLookupNF("FontFile2", &obj3)->isRef()) {
355 *embID = obj3.getRef();
356 if (isType0) {
357 expectedType = fontCIDType2;
358 } else if (expectedType != fontTrueType) {
359 err = gTrue;
362 obj3.free();
363 if (embID->num == -1 &&
364 fontDesc.dictLookupNF("FontFile3", &obj3)->isRef()) {
365 *embID = obj3.getRef();
366 if (obj3.fetch(xref, &obj4)->isStream()) {
367 obj4.streamGetDict()->lookup("Subtype", &subtype);
368 if (subtype.isName("Type1")) {
369 if (expectedType != fontType1) {
370 err = gTrue;
371 expectedType = isType0 ? fontCIDType0 : fontType1;
373 } else if (subtype.isName("Type1C")) {
374 if (expectedType == fontType1) {
375 expectedType = fontType1C;
376 } else if (expectedType != fontType1C) {
377 err = gTrue;
378 expectedType = isType0 ? fontCIDType0C : fontType1C;
380 } else if (subtype.isName("TrueType")) {
381 if (expectedType != fontTrueType) {
382 err = gTrue;
383 expectedType = isType0 ? fontCIDType2 : fontTrueType;
385 } else if (subtype.isName("CIDFontType0C")) {
386 if (expectedType == fontCIDType0) {
387 expectedType = fontCIDType0C;
388 } else {
389 err = gTrue;
390 expectedType = isType0 ? fontCIDType0C : fontType1C;
392 } else if (subtype.isName("OpenType")) {
393 if (expectedType == fontTrueType) {
394 expectedType = fontTrueTypeOT;
395 } else if (expectedType == fontType1) {
396 expectedType = fontType1COT;
397 } else if (expectedType == fontCIDType0) {
398 expectedType = fontCIDType0COT;
399 } else if (expectedType == fontCIDType2) {
400 expectedType = fontCIDType2OT;
401 } else {
402 err = gTrue;
404 } else {
405 error(errSyntaxError, -1, "Unknown font type '{0:s}'",
406 subtype.isName() ? subtype.getName() : "???");
408 subtype.free();
410 obj4.free();
412 obj3.free();
414 fontDesc.free();
416 t = fontUnknownType;
417 if (embID->num >= 0) {
418 obj3.initRef(embID->num, embID->gen);
419 obj3.fetch(xref, &obj4);
420 if (obj4.isStream()) {
421 obj4.streamReset();
422 fft = FoFiIdentifier::identifyStream(&readFromStream, obj4.getStream());
423 obj4.streamClose();
424 switch (fft) {
425 case fofiIdType1PFA:
426 case fofiIdType1PFB:
427 t = fontType1;
428 break;
429 case fofiIdCFF8Bit:
430 t = isType0 ? fontCIDType0C : fontType1C;
431 break;
432 case fofiIdCFFCID:
433 t = fontCIDType0C;
434 break;
435 case fofiIdTrueType:
436 case fofiIdTrueTypeCollection:
437 t = isType0 ? fontCIDType2 : fontTrueType;
438 break;
439 case fofiIdOpenTypeCFF8Bit:
440 t = expectedType; // hack: open type always == expected type? s. bug-poppler20605.pdf
441 break;
442 case fofiIdOpenTypeCFFCID:
443 t = fontCIDType0COT;
444 break;
445 default:
446 error(errSyntaxError, -1, "Embedded font file may be invalid");
447 break;
450 obj4.free();
451 obj3.free();
454 if (t == fontUnknownType) {
455 t = expectedType;
458 if (t != expectedType) {
459 err = gTrue;
462 if (err) {
463 error(errSyntaxWarning, -1,
464 "Mismatch between font type and embedded font file");
467 obj2.free();
468 obj1.free();
470 return t;
473 void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
474 Object obj1, obj2, obj3, obj4;
475 double t;
476 int i;
478 // assume Times-Roman by default (for substitution purposes)
479 flags = fontSerif;
481 missingWidth = 0;
483 if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
485 // get flags
486 if (obj1.dictLookup("Flags", &obj2)->isInt()) {
487 flags = obj2.getInt();
489 obj2.free();
491 // get name
492 obj1.dictLookup("FontName", &obj2);
493 if (obj2.isName()) {
494 embFontName = new GooString(obj2.getName());
496 obj2.free();
497 if (embFontName == NULL) {
498 // get name with typo
499 obj1.dictLookup("Fontname", &obj2);
500 if (obj2.isName()) {
501 embFontName = new GooString(obj2.getName());
502 error(errSyntaxWarning, -1, "The file uses Fontname instead of FontName please notify the creator that the file is broken");
504 obj2.free();
507 // get family
508 obj1.dictLookup("FontFamily", &obj2);
509 if (obj2.isString()) family = new GooString(obj2.getString());
510 obj2.free();
512 // get stretch
513 obj1.dictLookup("FontStretch", &obj2);
514 if (obj2.isName()) {
515 if (strcmp(obj2.getName(), "UltraCondensed") == 0) stretch = UltraCondensed;
516 else if (strcmp(obj2.getName(), "ExtraCondensed") == 0) stretch = ExtraCondensed;
517 else if (strcmp(obj2.getName(), "Condensed") == 0) stretch = Condensed;
518 else if (strcmp(obj2.getName(), "SemiCondensed") == 0) stretch = SemiCondensed;
519 else if (strcmp(obj2.getName(), "Normal") == 0) stretch = Normal;
520 else if (strcmp(obj2.getName(), "SemiExpanded") == 0) stretch = SemiExpanded;
521 else if (strcmp(obj2.getName(), "Expanded") == 0) stretch = Expanded;
522 else if (strcmp(obj2.getName(), "ExtraExpanded") == 0) stretch = ExtraExpanded;
523 else if (strcmp(obj2.getName(), "UltraExpanded") == 0) stretch = UltraExpanded;
524 else error(errSyntaxWarning, -1, "Invalid Font Stretch");
526 obj2.free();
528 // get weight
529 obj1.dictLookup("FontWeight", &obj2);
530 if (obj2.isNum()) {
531 if (obj2.getNum() == 100) weight = W100;
532 else if (obj2.getNum() == 200) weight = W200;
533 else if (obj2.getNum() == 300) weight = W300;
534 else if (obj2.getNum() == 400) weight = W400;
535 else if (obj2.getNum() == 500) weight = W500;
536 else if (obj2.getNum() == 600) weight = W600;
537 else if (obj2.getNum() == 700) weight = W700;
538 else if (obj2.getNum() == 800) weight = W800;
539 else if (obj2.getNum() == 900) weight = W900;
540 else error(errSyntaxWarning, -1, "Invalid Font Weight");
542 obj2.free();
544 // look for MissingWidth
545 obj1.dictLookup("MissingWidth", &obj2);
546 if (obj2.isNum()) {
547 missingWidth = obj2.getNum();
549 obj2.free();
551 // get Ascent and Descent
552 obj1.dictLookup("Ascent", &obj2);
553 if (obj2.isNum()) {
554 t = 0.001 * obj2.getNum();
555 // some broken font descriptors specify a negative ascent
556 if (t < 0) {
557 t = -t;
559 // some broken font descriptors set ascent and descent to 0;
560 // others set it to ridiculous values (e.g., 32768)
561 if (t != 0 && t < 3) {
562 ascent = t;
565 obj2.free();
566 obj1.dictLookup("Descent", &obj2);
567 if (obj2.isNum()) {
568 t = 0.001 * obj2.getNum();
569 // some broken font descriptors specify a positive descent
570 if (t > 0) {
571 t = -t;
573 // some broken font descriptors set ascent and descent to 0
574 if (t != 0 && t > -3) {
575 descent = t;
578 obj2.free();
580 // font FontBBox
581 if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
582 for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
583 if (obj2.arrayGet(i, &obj3)->isNum()) {
584 fontBBox[i] = 0.001 * obj3.getNum();
586 obj3.free();
589 obj2.free();
592 obj1.free();
595 CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits,
596 CharCodeToUnicode *ctu) {
597 GooString *buf;
598 Object obj1;
600 if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
601 obj1.free();
602 return NULL;
604 buf = new GooString();
605 obj1.getStream()->fillGooString(buf);
606 obj1.streamClose();
607 obj1.free();
608 if (ctu) {
609 ctu->mergeCMap(buf, nBits);
610 } else {
611 ctu = CharCodeToUnicode::parseCMap(buf, nBits);
613 hasToUnicode = gTrue;
614 delete buf;
615 return ctu;
618 GfxFontLoc *GfxFont::locateFont(XRef *xref, PSOutputDev *ps) {
619 GfxFontLoc *fontLoc;
620 SysFontType sysFontType;
621 GooString *path, *base14Name, *substName;
622 PSFontParam16 *psFont16;
623 Object refObj, embFontObj;
624 int substIdx, fontNum;
625 GBool embed;
627 if (type == fontType3) {
628 return NULL;
631 //----- embedded font
632 if (embFontID.num >= 0) {
633 embed = gTrue;
634 refObj.initRef(embFontID.num, embFontID.gen);
635 refObj.fetch(xref, &embFontObj);
636 if (!embFontObj.isStream()) {
637 error(errSyntaxError, -1, "Embedded font object is wrong type");
638 embed = gFalse;
640 embFontObj.free();
641 refObj.free();
642 if (embed) {
643 if (ps) {
644 switch (type) {
645 case fontType1:
646 case fontType1C:
647 case fontType1COT:
648 embed = ps->getEmbedType1();
649 break;
650 case fontTrueType:
651 case fontTrueTypeOT:
652 embed = ps->getEmbedTrueType();
653 break;
654 case fontCIDType0C:
655 case fontCIDType0COT:
656 embed = ps->getEmbedCIDPostScript();
657 break;
658 case fontCIDType2:
659 case fontCIDType2OT:
660 embed = ps->getEmbedCIDTrueType();
661 break;
662 default:
663 break;
666 if (embed) {
667 fontLoc = new GfxFontLoc();
668 fontLoc->locType = gfxFontLocEmbedded;
669 fontLoc->fontType = type;
670 fontLoc->embFontID = embFontID;
671 return fontLoc;
676 //----- PS passthrough
677 if (ps && !isCIDFont() && ps->getFontPassthrough()) {
678 fontLoc = new GfxFontLoc();
679 fontLoc->locType = gfxFontLocResident;
680 fontLoc->fontType = fontType1;
681 fontLoc->path = name->copy();
682 return fontLoc;
685 //----- PS resident Base-14 font
686 if (ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
687 fontLoc = new GfxFontLoc();
688 fontLoc->locType = gfxFontLocResident;
689 fontLoc->fontType = fontType1;
690 fontLoc->path = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
691 return fontLoc;
694 //----- external font file (fontFile, fontDir)
695 if (name && (path = globalParams->findFontFile(name))) {
696 if ((fontLoc = getExternalFont(path, isCIDFont()))) {
697 return fontLoc;
701 //----- external font file for Base-14 font
702 if (!ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
703 base14Name = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
704 if ((path = globalParams->findBase14FontFile(base14Name, this))) {
705 if ((fontLoc = getExternalFont(path, gFalse))) {
706 delete base14Name;
707 return fontLoc;
710 delete base14Name;
713 //----- system font
714 if ((path = globalParams->findSystemFontFile(this, &sysFontType,
715 &fontNum))) {
716 if (isCIDFont()) {
717 if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
718 fontLoc = new GfxFontLoc();
719 fontLoc->locType = gfxFontLocExternal;
720 fontLoc->fontType = fontCIDType2;
721 fontLoc->path = path;
722 fontLoc->fontNum = fontNum;
723 return fontLoc;
725 } else {
726 if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
727 fontLoc = new GfxFontLoc();
728 fontLoc->locType = gfxFontLocExternal;
729 fontLoc->fontType = fontTrueType;
730 fontLoc->path = path;
731 return fontLoc;
732 } else if (sysFontType == sysFontPFA || sysFontType == sysFontPFB) {
733 fontLoc = new GfxFontLoc();
734 fontLoc->locType = gfxFontLocExternal;
735 fontLoc->fontType = fontType1;
736 fontLoc->path = path;
737 fontLoc->fontNum = fontNum;
738 return fontLoc;
741 delete path;
744 if (!isCIDFont()) {
746 //----- 8-bit PS resident font
747 if (name && ps) {
748 if ((path = globalParams->getPSResidentFont(name))) {
749 fontLoc = new GfxFontLoc();
750 fontLoc->locType = gfxFontLocResident;
751 fontLoc->fontType = fontType1;
752 fontLoc->path = path;
753 return fontLoc;
757 //----- 8-bit font substitution
758 if (flags & fontFixedWidth) {
759 substIdx = 0;
760 } else if (flags & fontSerif) {
761 substIdx = 8;
762 } else {
763 substIdx = 4;
765 if (isBold()) {
766 substIdx += 2;
768 if (isItalic()) {
769 substIdx += 1;
771 substName = new GooString(base14SubstFonts[substIdx]);
772 if (ps) {
773 error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
774 base14SubstFonts[substIdx], name ? name->getCString() : "null");
775 fontLoc = new GfxFontLoc();
776 fontLoc->locType = gfxFontLocResident;
777 fontLoc->fontType = fontType1;
778 fontLoc->path = substName;
779 fontLoc->substIdx = substIdx;
780 return fontLoc;
781 } else {
782 path = globalParams->findFontFile(substName);
783 delete substName;
784 if (path) {
785 if ((fontLoc = getExternalFont(path, gFalse))) {
786 error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
787 base14SubstFonts[substIdx], name ? name->getCString() : "");
788 name = new GooString(base14SubstFonts[substIdx]);
789 fontLoc->substIdx = substIdx;
790 return fontLoc;
795 // failed to find a substitute font
796 return NULL;
799 //----- 16-bit PS resident font
800 if (ps && ((psFont16 = globalParams->getPSResidentFont16(
801 name,
802 ((GfxCIDFont *)this)->getWMode())))) {
803 fontLoc = new GfxFontLoc();
804 fontLoc->locType = gfxFontLocResident;
805 fontLoc->fontType = fontCIDType0; // this is not used
806 fontLoc->path = psFont16->psFontName->copy();
807 fontLoc->encoding = psFont16->encoding->copy();
808 fontLoc->wMode = psFont16->wMode;
809 return fontLoc;
811 if (ps && ((psFont16 = globalParams->getPSResidentFontCC(
812 ((GfxCIDFont *)this)->getCollection(),
813 ((GfxCIDFont *)this)->getWMode())))) {
814 error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
815 psFont16->psFontName, name);
816 fontLoc = new GfxFontLoc();
817 fontLoc->locType = gfxFontLocResident;
818 fontLoc->fontType = fontCIDType0; // this is not used
819 fontLoc->path = psFont16->psFontName->copy();
820 fontLoc->encoding = psFont16->encoding->copy();
821 fontLoc->wMode = psFont16->wMode;
822 return fontLoc;
825 //----- CID font substitution
826 if ((path = globalParams->findCCFontFile(
827 ((GfxCIDFont *)this)->getCollection()))) {
828 if ((fontLoc = getExternalFont(path, gTrue))) {
829 error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
830 fontLoc->path, name);
831 return fontLoc;
835 // failed to find a substitute font
836 return NULL;
839 GfxFontLoc *GfxFont::locateBase14Font(GooString *base14Name) {
840 GooString *path;
842 path = globalParams->findFontFile(base14Name);
843 if (!path) {
844 return NULL;
846 return getExternalFont(path, gFalse);
849 GfxFontLoc *GfxFont::getExternalFont(GooString *path, GBool cid) {
850 FoFiIdentifierType fft;
851 GfxFontType fontType;
852 GfxFontLoc *fontLoc;
854 fft = FoFiIdentifier::identifyFile(path->getCString());
855 switch (fft) {
856 case fofiIdType1PFA:
857 case fofiIdType1PFB:
858 fontType = fontType1;
859 break;
860 case fofiIdCFF8Bit:
861 fontType = fontType1C;
862 break;
863 case fofiIdCFFCID:
864 fontType = fontCIDType0C;
865 break;
866 case fofiIdTrueType:
867 case fofiIdTrueTypeCollection:
868 fontType = cid ? fontCIDType2 : fontTrueType;
869 break;
870 case fofiIdOpenTypeCFF8Bit:
871 fontType = fontType1COT;
872 break;
873 case fofiIdOpenTypeCFFCID:
874 fontType = fontCIDType0COT;
875 break;
876 case fofiIdUnknown:
877 case fofiIdError:
878 default:
879 fontType = fontUnknownType;
880 break;
882 if (fontType == fontUnknownType ||
883 (cid ? (fontType < fontCIDType0)
884 : (fontType >= fontCIDType0))) {
885 delete path;
886 return NULL;
888 fontLoc = new GfxFontLoc();
889 fontLoc->locType = gfxFontLocExternal;
890 fontLoc->fontType = fontType;
891 fontLoc->path = path;
892 return fontLoc;
895 char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
896 char *buf;
897 Object obj1, obj2;
898 Stream *str;
900 obj1.initRef(embFontID.num, embFontID.gen);
901 obj1.fetch(xref, &obj2);
902 if (!obj2.isStream()) {
903 error(errSyntaxError, -1, "Embedded font file is not a stream");
904 obj2.free();
905 obj1.free();
906 embFontID.num = -1;
907 *len = 0;
908 return NULL;
910 str = obj2.getStream();
912 buf = (char*)str->toUnsignedChars(len);
913 str->close();
915 obj2.free();
916 obj1.free();
918 return buf;
922 struct AlternateNameMap {
923 const char *name;
924 const char *alt;
927 static const AlternateNameMap alternateNameMap[] =
929 { "fi", "f_i" },
930 { "fl", "f_l" },
931 { "ff", "f_f" },
932 { "ffi", "f_f_i" },
933 { "ffl", "f_f_l" },
934 { 0, 0 }
937 const char *GfxFont::getAlternateName(const char *name) {
938 const AlternateNameMap *map = alternateNameMap;
939 while (map->name) {
940 if (strcmp(name, map->name) == 0) {
941 return map->alt;
943 map++;
945 return 0;
948 //------------------------------------------------------------------------
949 // Gfx8BitFont
950 //------------------------------------------------------------------------
952 // Parse character names of the form 'Axx', 'xx', 'Ann', 'ABnn', or
953 // 'nn', where 'A' and 'B' are any letters, 'xx' is two hex digits,
954 // and 'nn' is decimal digits.
955 static GBool parseNumericName(char *s, GBool hex, unsigned int *u) {
956 char *endptr;
958 // Strip leading alpha characters.
959 if (hex) {
960 int n = 0;
962 // Get string length while ignoring junk at end.
963 while (isalnum(s[n]))
964 ++n;
966 // Only 2 hex characters with optional leading alpha is allowed.
967 if (n == 3 && isalpha(*s)) {
968 ++s;
969 } else if (n != 2) {
970 return gFalse;
972 } else {
973 // Strip up to two alpha characters.
974 for (int i = 0; i < 2 && isalpha(*s); ++i)
975 ++s;
978 int v = strtol(s, &endptr, hex ? 16 : 10);
980 if (endptr == s)
981 return gFalse;
983 // Skip trailing junk characters.
984 while (*endptr != '\0' && !isalnum(*endptr))
985 ++endptr;
987 if (*endptr == '\0') {
988 if (u)
989 *u = v;
990 return gTrue;
992 return gFalse;
995 // Returns gTrue if the font has character names like xx or Axx which
996 // should be parsed for hex or decimal values.
997 static GBool testForNumericNames(Dict *fontDict, GBool hex) {
998 Object enc, diff, obj;
999 GBool numeric = gTrue;
1001 fontDict->lookup("Encoding", &enc);
1002 if (!enc.isDict()) {
1003 enc.free();
1004 return gFalse;
1007 enc.dictLookup("Differences", &diff);
1008 enc.free();
1009 if (!diff.isArray()) {
1010 diff.free();
1011 return gFalse;
1014 for (int i = 0; i < diff.arrayGetLength() && numeric; ++i) {
1015 diff.arrayGet(i, &obj);
1016 if (obj.isInt()) {
1017 // All sequences must start between character codes 0 and 5.
1018 if (obj.getInt() > 5)
1019 numeric = gFalse;
1020 } else if (obj.isName()) {
1021 // All character names must sucessfully parse.
1022 if (!parseNumericName(obj.getName(), hex, NULL))
1023 numeric = gFalse;
1024 } else {
1025 numeric = gFalse;
1027 obj.free();
1030 diff.free();
1031 return numeric;
1034 Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GooString *nameA,
1035 GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
1036 GfxFont(tagA, idA, nameA, typeA, embFontIDA) {
1037 GooString *name2;
1038 BuiltinFont *builtinFont;
1039 const char **baseEnc;
1040 GBool baseEncFromFontFile;
1041 char *buf;
1042 int len;
1043 FoFiType1 *ffT1;
1044 FoFiType1C *ffT1C;
1045 int code;
1046 char *charName;
1047 GBool missing, hex;
1048 GBool numeric;
1049 Unicode toUnicode[256];
1050 CharCodeToUnicode *utu, *ctu2;
1051 Unicode uBuf[8];
1052 double mul;
1053 int firstChar, lastChar;
1054 Gushort w;
1055 Object obj1, obj2, obj3;
1056 int n, i, a, b, m;
1058 refCnt = 1;
1059 ctu = NULL;
1061 // do font name substitution for various aliases of the Base 14 font
1062 // names
1063 base14 = NULL;
1064 if (name) {
1065 name2 = name->copy();
1066 i = 0;
1067 while (i < name2->getLength()) {
1068 if (name2->getChar(i) == ' ') {
1069 name2->del(i);
1070 } else {
1071 ++i;
1074 a = 0;
1075 b = sizeof(base14FontMap) / sizeof(Base14FontMapEntry);
1076 // invariant: base14FontMap[a].altName <= name2 < base14FontMap[b].altName
1077 while (b - a > 1) {
1078 m = (a + b) / 2;
1079 if (name2->cmp(base14FontMap[m].altName) >= 0) {
1080 a = m;
1081 } else {
1082 b = m;
1085 if (!name2->cmp(base14FontMap[a].altName)) {
1086 base14 = &base14FontMap[a];
1088 delete name2;
1091 // is it a built-in font?
1092 builtinFont = NULL;
1093 if (base14) {
1094 for (i = 0; i < nBuiltinFonts; ++i) {
1095 if (!strcmp(base14->base14Name, builtinFonts[i].name)) {
1096 builtinFont = &builtinFonts[i];
1097 break;
1102 // default ascent/descent values
1103 if (builtinFont) {
1104 ascent = 0.001 * builtinFont->ascent;
1105 descent = 0.001 * builtinFont->descent;
1106 fontBBox[0] = 0.001 * builtinFont->bbox[0];
1107 fontBBox[1] = 0.001 * builtinFont->bbox[1];
1108 fontBBox[2] = 0.001 * builtinFont->bbox[2];
1109 fontBBox[3] = 0.001 * builtinFont->bbox[3];
1110 } else {
1111 ascent = 0.95;
1112 descent = -0.35;
1113 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1116 // get info from font descriptor
1117 readFontDescriptor(xref, fontDict);
1119 // for non-embedded fonts, don't trust the ascent/descent/bbox
1120 // values from the font descriptor
1121 if (builtinFont && embFontID.num < 0) {
1122 ascent = 0.001 * builtinFont->ascent;
1123 descent = 0.001 * builtinFont->descent;
1124 fontBBox[0] = 0.001 * builtinFont->bbox[0];
1125 fontBBox[1] = 0.001 * builtinFont->bbox[1];
1126 fontBBox[2] = 0.001 * builtinFont->bbox[2];
1127 fontBBox[3] = 0.001 * builtinFont->bbox[3];
1130 // get font matrix
1131 fontMat[0] = fontMat[3] = 1;
1132 fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
1133 if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
1134 for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
1135 if (obj1.arrayGet(i, &obj2)->isNum()) {
1136 fontMat[i] = obj2.getNum();
1138 obj2.free();
1141 obj1.free();
1143 // get Type 3 bounding box, font definition, and resources
1144 if (type == fontType3) {
1145 if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
1146 for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
1147 if (obj1.arrayGet(i, &obj2)->isNum()) {
1148 fontBBox[i] = obj2.getNum();
1150 obj2.free();
1153 obj1.free();
1154 if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
1155 error(errSyntaxError, -1,
1156 "Missing or invalid CharProcs dictionary in Type 3 font");
1157 charProcs.free();
1159 if (!fontDict->lookup("Resources", &resources)->isDict()) {
1160 resources.free();
1164 //----- build the font encoding -----
1166 // Encodings start with a base encoding, which can come from
1167 // (in order of priority):
1168 // 1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
1169 // - MacRoman / MacExpert / WinAnsi / Standard
1170 // 2. embedded or external font file
1171 // 3. default:
1172 // - builtin --> builtin encoding
1173 // - TrueType --> WinAnsiEncoding
1174 // - others --> StandardEncoding
1175 // and then add a list of differences (if any) from
1176 // FontDict.Encoding.Differences.
1178 // check FontDict for base encoding
1179 hasEncoding = gFalse;
1180 usesMacRomanEnc = gFalse;
1181 baseEnc = NULL;
1182 baseEncFromFontFile = gFalse;
1183 fontDict->lookup("Encoding", &obj1);
1184 if (obj1.isDict()) {
1185 obj1.dictLookup("BaseEncoding", &obj2);
1186 if (obj2.isName("MacRomanEncoding")) {
1187 hasEncoding = gTrue;
1188 usesMacRomanEnc = gTrue;
1189 baseEnc = macRomanEncoding;
1190 } else if (obj2.isName("MacExpertEncoding")) {
1191 hasEncoding = gTrue;
1192 baseEnc = macExpertEncoding;
1193 } else if (obj2.isName("WinAnsiEncoding")) {
1194 hasEncoding = gTrue;
1195 baseEnc = winAnsiEncoding;
1197 obj2.free();
1198 } else if (obj1.isName("MacRomanEncoding")) {
1199 hasEncoding = gTrue;
1200 usesMacRomanEnc = gTrue;
1201 baseEnc = macRomanEncoding;
1202 } else if (obj1.isName("MacExpertEncoding")) {
1203 hasEncoding = gTrue;
1204 baseEnc = macExpertEncoding;
1205 } else if (obj1.isName("WinAnsiEncoding")) {
1206 hasEncoding = gTrue;
1207 baseEnc = winAnsiEncoding;
1210 // check embedded font file for base encoding
1211 // (only for Type 1 fonts - trying to get an encoding out of a
1212 // TrueType font is a losing proposition)
1213 ffT1 = NULL;
1214 ffT1C = NULL;
1215 buf = NULL;
1216 if (type == fontType1 && embFontID.num >= 0) {
1217 if ((buf = readEmbFontFile(xref, &len))) {
1218 if ((ffT1 = FoFiType1::make(buf, len))) {
1219 if (ffT1->getName()) {
1220 if (embFontName) {
1221 delete embFontName;
1223 embFontName = new GooString(ffT1->getName());
1225 if (!baseEnc) {
1226 baseEnc = (const char **)ffT1->getEncoding();
1227 baseEncFromFontFile = gTrue;
1230 gfree(buf);
1232 } else if (type == fontType1C && embFontID.num >= 0) {
1233 if ((buf = readEmbFontFile(xref, &len))) {
1234 if ((ffT1C = FoFiType1C::make(buf, len))) {
1235 if (ffT1C->getName()) {
1236 if (embFontName) {
1237 delete embFontName;
1239 embFontName = new GooString(ffT1C->getName());
1241 if (!baseEnc) {
1242 baseEnc = (const char **)ffT1C->getEncoding();
1243 baseEncFromFontFile = gTrue;
1246 gfree(buf);
1250 // get default base encoding
1251 if (!baseEnc) {
1252 if (builtinFont && embFontID.num < 0) {
1253 baseEnc = builtinFont->defaultBaseEnc;
1254 hasEncoding = gTrue;
1255 } else if (type == fontTrueType) {
1256 baseEnc = winAnsiEncoding;
1257 } else {
1258 baseEnc = standardEncoding;
1262 if (baseEncFromFontFile) {
1263 encodingName->Set("Builtin");
1264 } else if (baseEnc == winAnsiEncoding) {
1265 encodingName->Set("WinAnsi");
1266 } else if (baseEnc == macRomanEncoding) {
1267 encodingName->Set("MacRoman");
1268 } else if (baseEnc == macExpertEncoding) {
1269 encodingName->Set("MacExpert");
1270 } else if (baseEnc == symbolEncoding) {
1271 encodingName->Set("Symbol");
1272 } else if (baseEnc == zapfDingbatsEncoding) {
1273 encodingName->Set("ZapfDingbats");
1274 } else {
1275 encodingName->Set("Standard");
1278 // copy the base encoding
1279 for (i = 0; i < 256; ++i) {
1280 enc[i] = (char *)baseEnc[i];
1281 if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
1282 enc[i] = copyString(baseEnc[i]);
1286 // some Type 1C font files have empty encodings, which can break the
1287 // T1C->T1 conversion (since the 'seac' operator depends on having
1288 // the accents in the encoding), so we fill in any gaps from
1289 // StandardEncoding
1290 if (type == fontType1C && embFontID.num >= 0 && baseEncFromFontFile) {
1291 for (i = 0; i < 256; ++i) {
1292 if (!enc[i] && standardEncoding[i]) {
1293 enc[i] = (char *)standardEncoding[i];
1294 encFree[i] = gFalse;
1299 // merge differences into encoding
1300 if (obj1.isDict()) {
1301 obj1.dictLookup("Differences", &obj2);
1302 if (obj2.isArray()) {
1303 encodingName->Set("Custom");
1304 hasEncoding = gTrue;
1305 code = 0;
1306 for (i = 0; i < obj2.arrayGetLength(); ++i) {
1307 obj2.arrayGet(i, &obj3);
1308 if (obj3.isInt()) {
1309 code = obj3.getInt();
1310 } else if (obj3.isName()) {
1311 if (code >= 0 && code < 256) {
1312 if (encFree[code]) {
1313 gfree(enc[code]);
1315 enc[code] = copyString(obj3.getName());
1316 encFree[code] = gTrue;
1318 ++code;
1319 } else {
1320 error(errSyntaxError, -1,
1321 "Wrong type in font encoding resource differences ({0:s})",
1322 obj3.getTypeName());
1324 obj3.free();
1327 obj2.free();
1329 obj1.free();
1330 if (ffT1) {
1331 delete ffT1;
1333 if (ffT1C) {
1334 delete ffT1C;
1337 //----- build the mapping to Unicode -----
1339 // pass 1: use the name-to-Unicode mapping table
1340 missing = hex = gFalse;
1341 GBool isZapfDingbats = name && name->endsWith("ZapfDingbats");
1342 for (code = 0; code < 256; ++code) {
1343 if ((charName = enc[code])) {
1344 if (isZapfDingbats) {
1345 // include ZapfDingbats names
1346 toUnicode[code] = globalParams->mapNameToUnicodeAll(charName);
1347 } else {
1348 toUnicode[code] = globalParams->mapNameToUnicodeText(charName);
1350 if (!toUnicode[code] && strcmp(charName, ".notdef")) {
1351 // if it wasn't in the name-to-Unicode table, check for a
1352 // name that looks like 'Axx' or 'xx', where 'A' is any letter
1353 // and 'xx' is two hex digits
1354 if ((strlen(charName) == 3 &&
1355 isalpha(charName[0]) &&
1356 isxdigit(charName[1]) && isxdigit(charName[2]) &&
1357 ((charName[1] >= 'a' && charName[1] <= 'f') ||
1358 (charName[1] >= 'A' && charName[1] <= 'F') ||
1359 (charName[2] >= 'a' && charName[2] <= 'f') ||
1360 (charName[2] >= 'A' && charName[2] <= 'F'))) ||
1361 (strlen(charName) == 2 &&
1362 isxdigit(charName[0]) && isxdigit(charName[1]) &&
1363 // Only check idx 1 to avoid misidentifying a decimal
1364 // number like a0
1365 ((charName[1] >= 'a' && charName[1] <= 'f') ||
1366 (charName[1] >= 'A' && charName[1] <= 'F')))) {
1367 hex = gTrue;
1369 missing = gTrue;
1371 } else {
1372 toUnicode[code] = 0;
1376 numeric = testForNumericNames(fontDict, hex);
1378 // construct the char code -> Unicode mapping object
1379 ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1381 // pass 1a: Expand ligatures in the Alphabetic Presentation Form
1382 // block (eg "fi", "ffi") to normal form
1383 for (code = 0; code < 256; ++code) {
1384 if (unicodeIsAlphabeticPresentationForm(toUnicode[code])) {
1385 Unicode *normalized = unicodeNormalizeNFKC(&toUnicode[code], 1, &len, NULL);
1386 if (len > 1)
1387 ctu->setMapping((CharCode)code, normalized, len);
1388 gfree(normalized);
1392 // pass 2: try to fill in the missing chars, looking for ligatures, numeric
1393 // references and variants
1394 if (missing) {
1395 for (code = 0; code < 256; ++code) {
1396 if (!toUnicode[code]) {
1397 if ((charName = enc[code]) && strcmp(charName, ".notdef")
1398 && (n = parseCharName(charName, uBuf, sizeof(uBuf)/sizeof(*uBuf),
1399 gFalse, // don't check simple names (pass 1)
1400 gTrue, // do check ligatures
1401 numeric,
1402 hex,
1403 gTrue))) { // do check variants
1404 ctu->setMapping((CharCode)code, uBuf, n);
1405 continue;
1408 // if the 'mapUnknownCharNames' flag is set, do a simple pass-through
1409 // mapping for unknown character names
1410 if (globalParams->getMapUnknownCharNames()) {
1411 uBuf[0] = code;
1412 ctu->setMapping((CharCode)code, uBuf, 1);
1418 // merge in a ToUnicode CMap, if there is one -- this overwrites
1419 // existing entries in ctu, i.e., the ToUnicode CMap takes
1420 // precedence, but the other encoding info is allowed to fill in any
1421 // holes
1422 readToUnicodeCMap(fontDict, 16, ctu);
1424 // look for a Unicode-to-Unicode mapping
1425 if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1426 Unicode *uAux;
1427 for (i = 0; i < 256; ++i) {
1428 toUnicode[i] = 0;
1430 ctu2 = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1431 for (i = 0; i < 256; ++i) {
1432 n = ctu->mapToUnicode((CharCode)i, &uAux);
1433 if (n >= 1) {
1434 n = utu->mapToUnicode((CharCode)uAux[0], &uAux);
1435 if (n >= 1) {
1436 ctu2->setMapping((CharCode)i, uAux, n);
1440 utu->decRefCnt();
1441 delete ctu;
1442 ctu = ctu2;
1445 //----- get the character widths -----
1447 // initialize all widths
1448 for (code = 0; code < 256; ++code) {
1449 widths[code] = missingWidth * 0.001;
1452 // use widths from font dict, if present
1453 fontDict->lookup("FirstChar", &obj1);
1454 firstChar = obj1.isInt() ? obj1.getInt() : 0;
1455 obj1.free();
1456 if (firstChar < 0 || firstChar > 255) {
1457 firstChar = 0;
1459 fontDict->lookup("LastChar", &obj1);
1460 lastChar = obj1.isInt() ? obj1.getInt() : 255;
1461 obj1.free();
1462 if (lastChar < 0 || lastChar > 255) {
1463 lastChar = 255;
1465 mul = (type == fontType3) ? fontMat[0] : 0.001;
1466 fontDict->lookup("Widths", &obj1);
1467 if (obj1.isArray()) {
1468 flags |= fontFixedWidth;
1469 if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
1470 lastChar = firstChar + obj1.arrayGetLength() - 1;
1472 for (code = firstChar; code <= lastChar; ++code) {
1473 obj1.arrayGet(code - firstChar, &obj2);
1474 if (obj2.isNum()) {
1475 widths[code] = obj2.getNum() * mul;
1476 if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
1477 flags &= ~fontFixedWidth;
1480 obj2.free();
1483 // use widths from built-in font
1484 } else if (builtinFont) {
1485 // this is a kludge for broken PDF files that encode char 32
1486 // as .notdef
1487 if (builtinFont->widths->getWidth("space", &w)) {
1488 widths[32] = 0.001 * w;
1490 for (code = 0; code < 256; ++code) {
1491 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1492 widths[code] = 0.001 * w;
1496 // couldn't find widths -- use defaults
1497 } else {
1498 // this is technically an error -- the Widths entry is required
1499 // for all but the Base-14 fonts -- but certain PDF generators
1500 // apparently don't include widths for Arial and TimesNewRoman
1501 if (isFixedWidth()) {
1502 i = 0;
1503 } else if (isSerif()) {
1504 i = 8;
1505 } else {
1506 i = 4;
1508 if (isBold()) {
1509 i += 2;
1511 if (isItalic()) {
1512 i += 1;
1514 builtinFont = builtinFontSubst[i];
1515 // this is a kludge for broken PDF files that encode char 32
1516 // as .notdef
1517 if (builtinFont->widths->getWidth("space", &w)) {
1518 widths[32] = 0.001 * w;
1520 for (code = 0; code < 256; ++code) {
1521 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1522 widths[code] = 0.001 * w;
1526 obj1.free();
1528 ok = gTrue;
1531 Gfx8BitFont::~Gfx8BitFont() {
1532 int i;
1534 for (i = 0; i < 256; ++i) {
1535 if (encFree[i] && enc[i]) {
1536 gfree(enc[i]);
1539 ctu->decRefCnt();
1540 if (charProcs.isDict()) {
1541 charProcs.free();
1543 if (resources.isDict()) {
1544 resources.free();
1548 // This function is in part a derived work of the Adobe Glyph Mapping
1549 // Convention: http://www.adobe.com/devnet/opentype/archives/glyph.html
1550 // Algorithmic comments are excerpted from that document to aid
1551 // maintainability.
1552 static int parseCharName(char *charName, Unicode *uBuf, int uLen,
1553 GBool names, GBool ligatures,
1554 GBool numeric, GBool hex, GBool variants)
1556 if (uLen <= 0) {
1557 error(errInternal, -1, "Zero-length output buffer (recursion overflow?) in "
1558 "parseCharName, component \"{0:s}\"", charName);
1559 return 0;
1561 // Step 1: drop all the characters from the glyph name starting with the
1562 // first occurrence of a period (U+002E FULL STOP), if any.
1563 if (variants) {
1564 char *var_part = strchr(charName, '.');
1565 if (var_part == charName) {
1566 return 0; // .notdef or similar
1567 } else if (var_part != NULL) {
1568 // parse names of the form 7.oldstyle, P.swash, s.sc, etc.
1569 char *main_part = gstrndup(charName, var_part - charName);
1570 GBool namesRecurse = gTrue, variantsRecurse = gFalse;
1571 int n = parseCharName(main_part, uBuf, uLen, namesRecurse, ligatures,
1572 numeric, hex, variantsRecurse);
1573 gfree(main_part);
1574 return n;
1577 // Step 2: split the remaining string into a sequence of components, using
1578 // underscore (U+005F LOW LINE) as the delimiter.
1579 if (ligatures && strchr(charName, '_')) {
1580 // parse names of the form A_a (e.g. f_i, T_h, l_quotesingle)
1581 char *lig_part, *lig_end, *lig_copy;
1582 int n = 0, m;
1583 lig_part = lig_copy = copyString(charName);
1584 do {
1585 if ((lig_end = strchr(lig_part, '_')))
1586 *lig_end = '\0';
1587 if (lig_part[0] != '\0') {
1588 GBool namesRecurse = gTrue, ligaturesRecurse = gFalse;
1589 if ((m = parseCharName(lig_part, uBuf + n, uLen - n, namesRecurse,
1590 ligaturesRecurse, numeric, hex, variants)))
1591 n += m;
1592 else
1593 error(errSyntaxWarning, -1, "Could not parse ligature component \"{0:s}\" of \"{1:s}\" in "
1594 "parseCharName", lig_part, charName);
1596 lig_part = lig_end + 1;
1597 } while (lig_end && n < uLen);
1598 gfree(lig_copy);
1599 return n;
1601 // Step 3: map each component to a character string according to the
1602 // procedure below, and concatenate those strings; the result is the
1603 // character string to which the glyph name is mapped.
1604 // 3.1. if the font is Zapf Dingbats (PostScript FontName ZapfDingbats), and
1605 // the component is in the ZapfDingbats list, then map it to the
1606 // corresponding character in that list.
1607 // 3.2. otherwise, if the component is in the Adobe Glyph List, then map it
1608 // to the corresponding character in that list.
1609 if (names && (uBuf[0] = globalParams->mapNameToUnicodeText(charName))) {
1610 return 1;
1612 if (globalParams->getMapNumericCharNames()) {
1613 unsigned int n = strlen(charName);
1614 // 3.3. otherwise, if the component is of the form "uni" (U+0075 U+006E
1615 // U+0069) followed by a sequence of uppercase hexadecimal digits (0 .. 9,
1616 // A .. F, i.e. U+0030 .. U+0039, U+0041 .. U+0046), the length of that
1617 // sequence is a multiple of four, and each group of four digits represents
1618 // a number in the set {0x0000 .. 0xD7FF, 0xE000 .. 0xFFFF}, then interpret
1619 // each such number as a Unicode scalar value and map the component to the
1620 // string made of those scalar values. Note that the range and digit length
1621 // restrictions mean that the "uni" prefix can be used only with Unicode
1622 // values from the Basic Multilingual Plane (BMP).
1623 if (n >= 7 && (n % 4) == 3 && !strncmp(charName, "uni", 3)) {
1624 int i;
1625 unsigned int m;
1626 for (i = 0, m = 3; i < uLen && m < n; m += 4) {
1627 if (isxdigit(charName[m]) && isxdigit(charName[m + 1]) &&
1628 isxdigit(charName[m + 2]) && isxdigit(charName[m + 3])) {
1629 unsigned int u;
1630 sscanf(charName + m, "%4x", &u);
1631 if (u <= 0xD7FF || (0xE000 <= u && u <= 0xFFFF)) {
1632 uBuf[i++] = u;
1636 return i;
1638 // 3.4. otherwise, if the component is of the form "u" (U+0075) followed by
1639 // a sequence of four to six uppercase hexadecimal digits {0 .. 9, A .. F}
1640 // (U+0030 .. U+0039, U+0041 .. U+0046), and those digits represent a
1641 // number in {0x0000 .. 0xD7FF, 0xE000 .. 0x10FFFF}, then interpret this
1642 // number as a Unicode scalar value and map the component to the string
1643 // made of this scalar value.
1644 if (n >= 5 && n <= 7 && charName[0] == 'u' && isxdigit(charName[1]) &&
1645 isxdigit(charName[2]) && isxdigit(charName[3]) && isxdigit(charName[4])
1646 && (n <= 5 || isxdigit(charName[5]))
1647 && (n <= 6 || isxdigit(charName[6]))) {
1648 unsigned int u;
1649 sscanf(charName + 1, "%x", &u);
1650 if (u <= 0xD7FF || (0xE000 <= u && u <= 0x10FFFF)) {
1651 uBuf[0] = u;
1652 return 1;
1655 // Not in Adobe Glyph Mapping convention: look for names like xx
1656 // or Axx and parse for hex or decimal values.
1657 if (numeric && parseNumericName(charName, hex, uBuf))
1658 return 1;
1660 // 3.5. otherwise, map the component to the empty string
1661 return 0;
1664 int Gfx8BitFont::getNextChar(char *s, int len, CharCode *code,
1665 Unicode **u, int *uLen,
1666 double *dx, double *dy, double *ox, double *oy) {
1667 CharCode c;
1669 *code = c = (CharCode)(*s & 0xff);
1670 *uLen = ctu->mapToUnicode(c, u);
1671 *dx = widths[c];
1672 *dy = *ox = *oy = 0;
1673 return 1;
1676 CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
1677 ctu->incRefCnt();
1678 return ctu;
1681 int *Gfx8BitFont::getCodeToGIDMap(FoFiTrueType *ff) {
1682 int *map;
1683 int cmapPlatform, cmapEncoding;
1684 int unicodeCmap, macRomanCmap, msSymbolCmap, cmap;
1685 GBool useMacRoman, useUnicode;
1686 char *charName;
1687 Unicode u;
1688 int code, i, n;
1690 map = (int *)gmallocn(256, sizeof(int));
1691 for (i = 0; i < 256; ++i) {
1692 map[i] = 0;
1695 // To match up with the Adobe-defined behaviour, we choose a cmap
1696 // like this:
1697 // 1. If the PDF font has an encoding:
1698 // 1a. If the PDF font specified MacRomanEncoding and the
1699 // TrueType font has a Macintosh Roman cmap, use it, and
1700 // reverse map the char names through MacRomanEncoding to
1701 // get char codes.
1702 // 1b. If the PDF font is not symbolic or the PDF font is not
1703 // embedded, and the TrueType font has a Microsoft Unicode
1704 // cmap or a non-Microsoft Unicode cmap, use it, and use the
1705 // Unicode indexes, not the char codes.
1706 // 1c. If the PDF font is symbolic and the TrueType font has a
1707 // Microsoft Symbol cmap, use it, and use char codes
1708 // directly (possibly with an offset of 0xf000).
1709 // 1d. If the TrueType font has a Macintosh Roman cmap, use it,
1710 // as in case 1a.
1711 // 2. If the PDF font does not have an encoding or the PDF font is
1712 // symbolic:
1713 // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
1714 // and use char codes directly (possibly with an offset of
1715 // 0xf000).
1716 // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
1717 // and use char codes directly (possible with an offset of
1718 // 0xf000).
1719 // 3. If none of these rules apply, use the first cmap and hope for
1720 // the best (this shouldn't happen).
1721 unicodeCmap = macRomanCmap = msSymbolCmap = -1;
1722 for (i = 0; i < ff->getNumCmaps(); ++i) {
1723 cmapPlatform = ff->getCmapPlatform(i);
1724 cmapEncoding = ff->getCmapEncoding(i);
1725 if ((cmapPlatform == 3 && cmapEncoding == 1) ||
1726 cmapPlatform == 0) {
1727 unicodeCmap = i;
1728 } else if (cmapPlatform == 1 && cmapEncoding == 0) {
1729 macRomanCmap = i;
1730 } else if (cmapPlatform == 3 && cmapEncoding == 0) {
1731 msSymbolCmap = i;
1734 cmap = 0;
1735 useMacRoman = gFalse;
1736 useUnicode = gFalse;
1737 if (hasEncoding || type == fontType1) {
1738 if (usesMacRomanEnc && macRomanCmap >= 0) {
1739 cmap = macRomanCmap;
1740 useMacRoman = gTrue;
1741 } else if ((!(flags & fontSymbolic) || embFontID.num < 0) &&
1742 unicodeCmap >= 0) {
1743 cmap = unicodeCmap;
1744 useUnicode = gTrue;
1745 } else if ((flags & fontSymbolic) && msSymbolCmap >= 0) {
1746 cmap = msSymbolCmap;
1747 } else if ((flags & fontSymbolic) && macRomanCmap >= 0) {
1748 cmap = macRomanCmap;
1749 } else if (macRomanCmap >= 0) {
1750 cmap = macRomanCmap;
1751 useMacRoman = gTrue;
1753 } else {
1754 if (msSymbolCmap >= 0) {
1755 cmap = msSymbolCmap;
1756 } else if (macRomanCmap >= 0) {
1757 cmap = macRomanCmap;
1761 // reverse map the char names through MacRomanEncoding, then map the
1762 // char codes through the cmap
1763 if (useMacRoman) {
1764 for (i = 0; i < 256; ++i) {
1765 if ((charName = enc[i])) {
1766 if ((code = globalParams->getMacRomanCharCode(charName))) {
1767 map[i] = ff->mapCodeToGID(cmap, code);
1769 } else {
1770 map[i] = -1;
1774 // map Unicode through the cmap
1775 } else if (useUnicode) {
1776 Unicode *uAux;
1777 for (i = 0; i < 256; ++i) {
1778 if (((charName = enc[i]) && (u = globalParams->mapNameToUnicodeAll(charName))))
1779 map[i] = ff->mapCodeToGID(cmap, u);
1780 else
1782 n = ctu->mapToUnicode((CharCode)i, &uAux);
1783 if (n > 0) map[i] = ff->mapCodeToGID(cmap, uAux[0]);
1784 else map[i] = -1;
1788 // map the char codes through the cmap, possibly with an offset of
1789 // 0xf000
1790 } else {
1791 for (i = 0; i < 256; ++i) {
1792 if (!(map[i] = ff->mapCodeToGID(cmap, i))) {
1793 map[i] = ff->mapCodeToGID(cmap, 0xf000 + i);
1798 // try the TrueType 'post' table to handle any unmapped characters
1799 for (i = 0; i < 256; ++i) {
1800 if (map[i] <= 0 && (charName = enc[i])) {
1801 map[i] = ff->mapNameToGID(charName);
1805 return map;
1808 Dict *Gfx8BitFont::getCharProcs() {
1809 return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
1812 Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
1813 if (enc[code] && charProcs.isDict()) {
1814 charProcs.dictLookup(enc[code], proc);
1815 } else {
1816 proc->initNull();
1818 return proc;
1821 Dict *Gfx8BitFont::getResources() {
1822 return resources.isDict() ? resources.getDict() : (Dict *)NULL;
1825 //------------------------------------------------------------------------
1826 // GfxCIDFont
1827 //------------------------------------------------------------------------
1829 struct cmpWidthExcepFunctor {
1830 bool operator()(const GfxFontCIDWidthExcep &w1,
1831 const GfxFontCIDWidthExcep &w2) {
1832 return w1.first < w2.first;
1836 struct cmpWidthExcepVFunctor {
1837 bool operator()(const GfxFontCIDWidthExcepV &w1,
1838 const GfxFontCIDWidthExcepV &w2) {
1839 return w1.first < w2.first;
1843 GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GooString *nameA,
1844 GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
1845 GfxFont(tagA, idA, nameA, typeA, embFontIDA)
1847 Dict *desFontDict;
1848 Object desFontDictObj;
1849 Object obj1, obj2, obj3, obj4, obj5, obj6;
1850 CharCodeToUnicode *utu;
1851 CharCode c;
1852 Unicode *uBuf;
1853 int c1, c2;
1854 int excepsSize, i, j, k, n;
1856 refCnt = 1;
1857 ascent = 0.95;
1858 descent = -0.35;
1859 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1860 collection = NULL;
1861 cMap = NULL;
1862 ctu = NULL;
1863 ctuUsesCharCode = gTrue;
1864 widths.defWidth = 1.0;
1865 widths.defHeight = -1.0;
1866 widths.defVY = 0.880;
1867 widths.exceps = NULL;
1868 widths.nExceps = 0;
1869 widths.excepsV = NULL;
1870 widths.nExcepsV = 0;
1871 cidToGID = NULL;
1872 cidToGIDLen = 0;
1874 // get the descendant font
1875 if (!fontDict->lookup("DescendantFonts", &obj1)->isArray() ||
1876 obj1.arrayGetLength() == 0) {
1877 error(errSyntaxError, -1, "Missing or empty DescendantFonts entry in Type 0 font");
1878 obj1.free();
1879 goto err1;
1881 if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
1882 error(errSyntaxError, -1, "Bad descendant font in Type 0 font");
1883 goto err3;
1885 obj1.free();
1886 desFontDict = desFontDictObj.getDict();
1888 // get info from font descriptor
1889 readFontDescriptor(xref, desFontDict);
1891 //----- encoding info -----
1893 // char collection
1894 if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
1895 error(errSyntaxError, -1, "Missing CIDSystemInfo dictionary in Type 0 descendant font");
1896 goto err3;
1898 obj1.dictLookup("Registry", &obj2);
1899 obj1.dictLookup("Ordering", &obj3);
1900 if (!obj2.isString() || !obj3.isString()) {
1901 error(errSyntaxError, -1, "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
1902 goto err3;
1904 collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
1905 obj3.free();
1906 obj2.free();
1907 obj1.free();
1909 // look for a ToUnicode CMap
1910 if (!(ctu = readToUnicodeCMap(fontDict, 16, NULL))) {
1911 ctuUsesCharCode = gFalse;
1913 // use an identity mapping for the "Adobe-Identity" and
1914 // "Adobe-UCS" collections
1915 if (!collection->cmp("Adobe-Identity") ||
1916 !collection->cmp("Adobe-UCS")) {
1917 ctu = CharCodeToUnicode::makeIdentityMapping();
1918 } else {
1919 // look for a user-supplied .cidToUnicode file
1920 if (!(ctu = globalParams->getCIDToUnicode(collection))) {
1921 // I'm not completely sure that this is the best thing to do
1922 // but it seems to produce better results when the .cidToUnicode
1923 // files from the poppler-data package are missing. At least
1924 // we know that assuming the Identity mapping is definitely wrong.
1925 // -- jrmuizel
1926 static const char * knownCollections [] = {
1927 "Adobe-CNS1",
1928 "Adobe-GB1",
1929 "Adobe-Japan1",
1930 "Adobe-Japan2",
1931 "Adobe-Korea1",
1933 for (size_t i = 0; i < sizeof(knownCollections)/sizeof(knownCollections[0]); i++) {
1934 if (collection->cmp(knownCollections[i]) == 0) {
1935 error(errSyntaxError, -1, "Missing language pack for '{0:t}' mapping", collection);
1936 goto err2;
1939 error(errSyntaxError, -1, "Unknown character collection '{0:t}'",
1940 collection);
1941 // fall-through, assuming the Identity mapping -- this appears
1942 // to match Adobe's behavior
1947 // look for a Unicode-to-Unicode mapping
1948 if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1949 if (ctu) {
1950 for (c = 0; c < ctu->getLength(); ++c) {
1951 n = ctu->mapToUnicode(c, &uBuf);
1952 if (n >= 1) {
1953 n = utu->mapToUnicode((CharCode)uBuf[0], &uBuf);
1954 if (n >= 1) {
1955 ctu->setMapping(c, uBuf, n);
1959 utu->decRefCnt();
1960 } else {
1961 ctu = utu;
1965 // encoding (i.e., CMap)
1966 if (fontDict->lookup("Encoding", &obj1)->isNull()) {
1967 error(errSyntaxError, -1, "Missing Encoding entry in Type 0 font");
1968 goto err2;
1970 if (!(cMap = CMap::parse(NULL, collection, &obj1))) {
1971 goto err2;
1973 obj1.free();
1974 if (cMap->getCMapName()) {
1975 encodingName->Set(cMap->getCMapName()->getCString());
1976 } else {
1977 encodingName->Set("Custom");
1980 // CIDToGIDMap (for embedded TrueType fonts)
1981 if (type == fontCIDType2 || type == fontCIDType2OT) {
1982 desFontDict->lookup("CIDToGIDMap", &obj1);
1983 if (obj1.isStream()) {
1984 cidToGIDLen = 0;
1985 i = 64;
1986 cidToGID = (int *)gmallocn(i, sizeof(int));
1987 obj1.streamReset();
1988 while ((c1 = obj1.streamGetChar()) != EOF &&
1989 (c2 = obj1.streamGetChar()) != EOF) {
1990 if (cidToGIDLen == i) {
1991 i *= 2;
1992 cidToGID = (int *)greallocn(cidToGID, i, sizeof(int));
1994 cidToGID[cidToGIDLen++] = (c1 << 8) + c2;
1996 } else if (!obj1.isName("Identity") && !obj1.isNull()) {
1997 error(errSyntaxError, -1, "Invalid CIDToGIDMap entry in CID font");
1999 obj1.free();
2002 //----- character metrics -----
2004 // default char width
2005 if (desFontDict->lookup("DW", &obj1)->isInt()) {
2006 widths.defWidth = obj1.getInt() * 0.001;
2008 obj1.free();
2010 // char width exceptions
2011 if (desFontDict->lookup("W", &obj1)->isArray()) {
2012 excepsSize = 0;
2013 i = 0;
2014 while (i + 1 < obj1.arrayGetLength()) {
2015 obj1.arrayGet(i, &obj2);
2016 obj1.arrayGet(i + 1, &obj3);
2017 if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
2018 if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
2019 if (widths.nExceps == excepsSize) {
2020 excepsSize += 16;
2021 widths.exceps = (GfxFontCIDWidthExcep *)
2022 greallocn(widths.exceps,
2023 excepsSize, sizeof(GfxFontCIDWidthExcep));
2025 widths.exceps[widths.nExceps].first = obj2.getInt();
2026 widths.exceps[widths.nExceps].last = obj3.getInt();
2027 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
2028 ++widths.nExceps;
2029 } else {
2030 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2032 obj4.free();
2033 i += 3;
2034 } else if (obj2.isInt() && obj3.isArray()) {
2035 if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
2036 excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
2037 widths.exceps = (GfxFontCIDWidthExcep *)
2038 greallocn(widths.exceps,
2039 excepsSize, sizeof(GfxFontCIDWidthExcep));
2041 j = obj2.getInt();
2042 for (k = 0; k < obj3.arrayGetLength(); ++k) {
2043 if (obj3.arrayGet(k, &obj4)->isNum()) {
2044 widths.exceps[widths.nExceps].first = j;
2045 widths.exceps[widths.nExceps].last = j;
2046 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
2047 ++j;
2048 ++widths.nExceps;
2049 } else {
2050 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2052 obj4.free();
2054 i += 2;
2055 } else {
2056 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2057 ++i;
2059 obj3.free();
2060 obj2.free();
2062 std::sort(widths.exceps, widths.exceps + widths.nExceps,
2063 cmpWidthExcepFunctor());
2065 obj1.free();
2067 // default metrics for vertical font
2068 if (desFontDict->lookup("DW2", &obj1)->isArray() &&
2069 obj1.arrayGetLength() == 2) {
2070 if (obj1.arrayGet(0, &obj2)->isNum()) {
2071 widths.defVY = obj2.getNum() * 0.001;
2073 obj2.free();
2074 if (obj1.arrayGet(1, &obj2)->isNum()) {
2075 widths.defHeight = obj2.getNum() * 0.001;
2077 obj2.free();
2079 obj1.free();
2081 // char metric exceptions for vertical font
2082 if (desFontDict->lookup("W2", &obj1)->isArray()) {
2083 excepsSize = 0;
2084 i = 0;
2085 while (i + 1 < obj1.arrayGetLength()) {
2086 obj1.arrayGet(i, &obj2);
2087 obj1.arrayGet(i+ 1, &obj3);
2088 if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
2089 if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
2090 obj1.arrayGet(i + 3, &obj5)->isNum() &&
2091 obj1.arrayGet(i + 4, &obj6)->isNum()) {
2092 if (widths.nExcepsV == excepsSize) {
2093 excepsSize += 16;
2094 widths.excepsV = (GfxFontCIDWidthExcepV *)
2095 greallocn(widths.excepsV,
2096 excepsSize, sizeof(GfxFontCIDWidthExcepV));
2098 widths.excepsV[widths.nExcepsV].first = obj2.getInt();
2099 widths.excepsV[widths.nExcepsV].last = obj3.getInt();
2100 widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2101 widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2102 widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2103 ++widths.nExcepsV;
2104 } else {
2105 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2107 obj6.free();
2108 obj5.free();
2109 obj4.free();
2110 i += 5;
2111 } else if (obj2.isInt() && obj3.isArray()) {
2112 if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
2113 excepsSize =
2114 (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
2115 widths.excepsV = (GfxFontCIDWidthExcepV *)
2116 greallocn(widths.excepsV,
2117 excepsSize, sizeof(GfxFontCIDWidthExcepV));
2119 j = obj2.getInt();
2120 for (k = 0; k < obj3.arrayGetLength(); k += 3) {
2121 if (obj3.arrayGet(k, &obj4)->isNum() &&
2122 obj3.arrayGet(k+1, &obj5)->isNum() &&
2123 obj3.arrayGet(k+2, &obj6)->isNum()) {
2124 widths.excepsV[widths.nExcepsV].first = j;
2125 widths.excepsV[widths.nExcepsV].last = j;
2126 widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2127 widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2128 widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2129 ++j;
2130 ++widths.nExcepsV;
2131 } else {
2132 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2134 obj6.free();
2135 obj5.free();
2136 obj4.free();
2138 i += 2;
2139 } else {
2140 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2141 ++i;
2143 obj3.free();
2144 obj2.free();
2146 std::sort(widths.excepsV, widths.excepsV + widths.nExcepsV,
2147 cmpWidthExcepVFunctor());
2149 obj1.free();
2151 desFontDictObj.free();
2152 ok = gTrue;
2153 return;
2155 err3:
2156 obj3.free();
2157 obj2.free();
2158 err2:
2159 obj1.free();
2160 desFontDictObj.free();
2161 err1:;
2164 GfxCIDFont::~GfxCIDFont() {
2165 if (collection) {
2166 delete collection;
2168 if (cMap) {
2169 cMap->decRefCnt();
2171 if (ctu) {
2172 ctu->decRefCnt();
2174 gfree(widths.exceps);
2175 gfree(widths.excepsV);
2176 if (cidToGID) {
2177 gfree(cidToGID);
2181 int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
2182 Unicode **u, int *uLen,
2183 double *dx, double *dy, double *ox, double *oy) {
2184 CID cid;
2185 CharCode c;
2186 double w, h, vx, vy;
2187 int n, a, b, m;
2189 if (!cMap) {
2190 *code = 0;
2191 *uLen = 0;
2192 *dx = *dy = 0;
2193 return 1;
2196 *code = (CharCode)(cid = cMap->getCID(s, len, &c, &n));
2197 if (ctu) {
2198 if (hasToUnicode) {
2199 int i = 0, c = 0;
2200 while (i < n) {
2201 c = (c << 8 ) + (s[i] & 0xff);
2202 ++i;
2204 *uLen = ctu->mapToUnicode(c, u);
2205 } else {
2206 *uLen = ctu->mapToUnicode(cid, u);
2208 } else {
2209 *uLen = 0;
2212 // horizontal
2213 if (cMap->getWMode() == 0) {
2214 w = getWidth(cid);
2215 h = vx = vy = 0;
2217 // vertical
2218 } else {
2219 w = 0;
2220 h = widths.defHeight;
2221 vx = getWidth(cid) / 2;
2222 vy = widths.defVY;
2223 if (widths.nExcepsV > 0 && cid >= widths.excepsV[0].first) {
2224 a = 0;
2225 b = widths.nExcepsV;
2226 // invariant: widths.excepsV[a].first <= cid < widths.excepsV[b].first
2227 while (b - a > 1) {
2228 m = (a + b) / 2;
2229 if (widths.excepsV[m].last <= cid) {
2230 a = m;
2231 } else {
2232 b = m;
2235 if (cid <= widths.excepsV[a].last) {
2236 h = widths.excepsV[a].height;
2237 vx = widths.excepsV[a].vx;
2238 vy = widths.excepsV[a].vy;
2243 *dx = w;
2244 *dy = h;
2245 *ox = vx;
2246 *oy = vy;
2248 return n;
2251 int GfxCIDFont::getWMode() {
2252 return cMap ? cMap->getWMode() : 0;
2255 CharCodeToUnicode *GfxCIDFont::getToUnicode() {
2256 if (ctu) {
2257 ctu->incRefCnt();
2259 return ctu;
2262 GooString *GfxCIDFont::getCollection() {
2263 return cMap ? cMap->getCollection() : (GooString *)NULL;
2266 int GfxCIDFont::mapCodeToGID(FoFiTrueType *ff, int cmapi,
2267 Unicode unicode, GBool wmode) {
2268 Gushort gid = ff->mapCodeToGID(cmapi,unicode);
2269 if (wmode) {
2270 Gushort vgid = ff->mapToVertGID(gid);
2271 if (vgid != 0) gid = vgid;
2273 return gid;
2276 int *GfxCIDFont::getCodeToGIDMap(FoFiTrueType *ff, int *mapsizep) {
2277 #define N_UCS_CANDIDATES 2
2278 /* space characters */
2279 static const unsigned long spaces[] = {
2280 0x2000,0x2001,0x2002,0x2003,0x2004,0x2005,0x2006,0x2007,
2281 0x2008,0x2009,0x200A,0x00A0,0x200B,0x2060,0x3000,0xFEFF,
2284 static const char *adobe_cns1_cmaps[] = {
2285 "UniCNS-UTF32-V",
2286 "UniCNS-UCS2-V",
2287 "UniCNS-UTF32-H",
2288 "UniCNS-UCS2-H",
2291 static const char *adobe_gb1_cmaps[] = {
2292 "UniGB-UTF32-V",
2293 "UniGB-UCS2-V",
2294 "UniGB-UTF32-H",
2295 "UniGB-UCS2-H",
2298 static const char *adobe_japan1_cmaps[] = {
2299 "UniJIS-UTF32-V",
2300 "UniJIS-UCS2-V",
2301 "UniJIS-UTF32-H",
2302 "UniJIS-UCS2-H",
2305 static const char *adobe_japan2_cmaps[] = {
2306 "UniHojo-UTF32-V",
2307 "UniHojo-UCS2-V",
2308 "UniHojo-UTF32-H",
2309 "UniHojo-UCS2-H",
2312 static const char *adobe_korea1_cmaps[] = {
2313 "UniKS-UTF32-V",
2314 "UniKS-UCS2-V",
2315 "UniKS-UTF32-H",
2316 "UniKS-UCS2-H",
2319 static struct CMapListEntry {
2320 const char *collection;
2321 const char *scriptTag;
2322 const char *languageTag;
2323 const char *toUnicodeMap;
2324 const char **CMaps;
2325 } CMapList[] = {
2327 "Adobe-CNS1",
2328 "hani", "CHN ",
2329 "Adobe-CNS1-UCS2",
2330 adobe_cns1_cmaps,
2333 "Adobe-GB1",
2334 "hani", "CHN ",
2335 "Adobe-GB1-UCS2",
2336 adobe_gb1_cmaps,
2339 "Adobe-Japan1",
2340 "kana", "JAN ",
2341 "Adobe-Japan1-UCS2",
2342 adobe_japan1_cmaps,
2345 "Adobe-Japan2",
2346 "kana", "JAN ",
2347 "Adobe-Japan2-UCS2",
2348 adobe_japan2_cmaps,
2351 "Adobe-Korea1",
2352 "hang", "KOR ",
2353 "Adobe-Korea1-UCS2",
2354 adobe_korea1_cmaps,
2356 {0, 0, 0, 0}
2358 Unicode *humap = 0;
2359 Unicode *vumap = 0;
2360 Unicode *tumap = 0;
2361 int *codeToGID = 0;
2362 unsigned long n;
2363 int i;
2364 unsigned long code;
2365 int wmode;
2366 const char **cmapName;
2367 CMap *cMap;
2368 CMapListEntry *lp;
2369 int cmap;
2370 int cmapPlatform, cmapEncoding;
2371 Ref embID;
2373 *mapsizep = 0;
2374 if (!ctu) return NULL;
2375 if (getCollection()->cmp("Adobe-Identity") == 0) return NULL;
2376 if (getEmbeddedFontID(&embID)) {
2377 /* if this font is embedded font,
2378 * CIDToGIDMap should be embedded in PDF file
2379 * and already set. So return it.
2381 *mapsizep = getCIDToGIDLen();
2382 return getCIDToGID();
2385 /* we use only unicode cmap */
2386 cmap = -1;
2387 for (i = 0; i < ff->getNumCmaps(); ++i) {
2388 cmapPlatform = ff->getCmapPlatform(i);
2389 cmapEncoding = ff->getCmapEncoding(i);
2390 if (cmapPlatform == 3 && cmapEncoding == 10) {
2391 /* UCS-4 */
2392 cmap = i;
2393 /* use UCS-4 cmap */
2394 break;
2395 } else if (cmapPlatform == 3 && cmapEncoding == 1) {
2396 /* Unicode */
2397 cmap = i;
2398 } else if (cmapPlatform == 0 && cmap < 0) {
2399 cmap = i;
2402 if (cmap < 0)
2403 return NULL;
2405 wmode = getWMode();
2406 for (lp = CMapList;lp->collection != 0;lp++) {
2407 if (strcmp(lp->collection,getCollection()->getCString()) == 0) {
2408 break;
2411 n = 65536;
2412 tumap = new Unicode[n];
2413 humap = new Unicode[n*N_UCS_CANDIDATES];
2414 memset(humap,0,sizeof(Unicode)*n*N_UCS_CANDIDATES);
2415 if (lp->collection != 0) {
2416 CharCodeToUnicode *tctu;
2417 GooString tname(lp->toUnicodeMap);
2419 if ((tctu = CharCodeToUnicode::parseCMapFromFile(&tname,16)) != 0) {
2420 CharCode cid;
2421 for (cid = 0;cid < n ;cid++) {
2422 int len;
2423 Unicode *ucodes;
2425 len = tctu->mapToUnicode(cid,&ucodes);
2426 if (len == 1) {
2427 tumap[cid] = ucodes[0];
2428 } else {
2429 /* if not single character, ignore it */
2430 tumap[cid] = 0;
2433 delete tctu;
2435 vumap = new Unicode[n];
2436 memset(vumap,0,sizeof(Unicode)*n);
2437 for (cmapName = lp->CMaps;*cmapName != 0;cmapName++) {
2438 GooString cname(*cmapName);
2440 if ((cMap = globalParams->getCMap(getCollection(),&cname))
2441 != 0) {
2442 if (cMap->getWMode()) {
2443 cMap->setReverseMap(vumap,n,1);
2444 } else {
2445 cMap->setReverseMap(humap,n,N_UCS_CANDIDATES);
2447 cMap->decRefCnt();
2450 ff->setupGSUB(lp->scriptTag, lp->languageTag);
2451 } else {
2452 error(errSyntaxError, -1, "Unknown character collection {0:t}\n",
2453 getCollection());
2454 if ((ctu = getToUnicode()) != 0) {
2455 CharCode cid;
2456 for (cid = 0;cid < n ;cid++) {
2457 Unicode *ucode;
2459 if (ctu->mapToUnicode(cid, &ucode))
2460 humap[cid*N_UCS_CANDIDATES] = ucode[0];
2461 else
2462 humap[cid*N_UCS_CANDIDATES] = 0;
2463 for (i = 1;i < N_UCS_CANDIDATES;i++) {
2464 humap[cid*N_UCS_CANDIDATES+i] = 0;
2467 ctu->decRefCnt();
2470 // map CID -> Unicode -> GID
2471 codeToGID = (int *)gmallocn(n, sizeof(int));
2472 for (code = 0; code < n; ++code) {
2473 Unicode unicode;
2474 unsigned long gid;
2476 unicode = 0;
2477 gid = 0;
2478 if (humap != 0) {
2479 for (i = 0;i < N_UCS_CANDIDATES
2480 && gid == 0 && (unicode = humap[code*N_UCS_CANDIDATES+i]) != 0;i++) {
2481 gid = mapCodeToGID(ff,cmap,unicode,gFalse);
2484 if (gid == 0 && vumap != 0) {
2485 unicode = vumap[code];
2486 if (unicode != 0) {
2487 gid = mapCodeToGID(ff,cmap,unicode,gTrue);
2488 if (gid == 0 && tumap != 0) {
2489 if ((unicode = tumap[code]) != 0) {
2490 gid = mapCodeToGID(ff,cmap,unicode,gTrue);
2495 if (gid == 0 && tumap != 0) {
2496 if ((unicode = tumap[code]) != 0) {
2497 gid = mapCodeToGID(ff,cmap,unicode,gFalse);
2500 if (gid == 0) {
2501 /* special handling space characters */
2502 const unsigned long *p;
2504 if (humap != 0) unicode = humap[code];
2505 if (unicode != 0) {
2506 /* check if code is space character , so map code to 0x0020 */
2507 for (p = spaces;*p != 0;p++) {
2508 if (*p == unicode) {
2509 unicode = 0x20;
2510 gid = mapCodeToGID(ff,cmap,unicode,wmode);
2511 break;
2516 codeToGID[code] = gid;
2518 *mapsizep = n;
2519 if (humap != 0) delete[] humap;
2520 if (tumap != 0) delete[] tumap;
2521 if (vumap != 0) delete[] vumap;
2522 return codeToGID;
2525 double GfxCIDFont::getWidth(CID cid) {
2526 double w;
2527 int a, b, m;
2529 w = widths.defWidth;
2530 if (widths.nExceps > 0 && cid >= widths.exceps[0].first) {
2531 a = 0;
2532 b = widths.nExceps;
2533 // invariant: widths.exceps[a].first <= cid < widths.exceps[b].first
2534 while (b - a > 1) {
2535 m = (a + b) / 2;
2536 if (widths.exceps[m].first <= cid) {
2537 a = m;
2538 } else {
2539 b = m;
2542 if (cid <= widths.exceps[a].last) {
2543 w = widths.exceps[a].width;
2546 return w;
2549 double GfxCIDFont::getWidth (char* s, int len) {
2550 int nUsed;
2551 CharCode c;
2553 CID cid = cMap->getCID(s, len, &c, &nUsed);
2554 return getWidth(cid);
2557 //------------------------------------------------------------------------
2558 // GfxFontDict
2559 //------------------------------------------------------------------------
2561 GfxFontDict::GfxFontDict(XRef *xref, Ref *fontDictRef, Dict *fontDict) {
2562 int i;
2563 Object obj1, obj2;
2564 Ref r;
2566 numFonts = fontDict->getLength();
2567 fonts = (GfxFont **)gmallocn(numFonts, sizeof(GfxFont *));
2568 for (i = 0; i < numFonts; ++i) {
2569 fontDict->getValNF(i, &obj1);
2570 obj1.fetch(xref, &obj2);
2571 if (obj2.isDict()) {
2572 if (obj1.isRef()) {
2573 r = obj1.getRef();
2574 } else {
2575 // no indirect reference for this font, so invent a unique one
2576 // (legal generation numbers are five digits, so any 6-digit
2577 // number would be safe)
2578 r.num = i;
2579 if (fontDictRef) {
2580 r.gen = 100000 + fontDictRef->num;
2581 } else {
2582 r.gen = 999999;
2585 fonts[i] = GfxFont::makeFont(xref, fontDict->getKey(i),
2586 r, obj2.getDict());
2587 if (fonts[i] && !fonts[i]->isOk()) {
2588 // XXX: it may be meaningful to distinguish between
2589 // NULL and !isOk() so that when we do lookups
2590 // we can tell the difference between a missing font
2591 // and a font that is just !isOk()
2592 fonts[i]->decRefCnt();
2593 fonts[i] = NULL;
2595 } else {
2596 error(errSyntaxError, -1, "font resource is not a dictionary");
2597 fonts[i] = NULL;
2599 obj1.free();
2600 obj2.free();
2604 GfxFontDict::~GfxFontDict() {
2605 int i;
2607 for (i = 0; i < numFonts; ++i) {
2608 if (fonts[i]) {
2609 fonts[i]->decRefCnt();
2612 gfree(fonts);
2615 GfxFont *GfxFontDict::lookup(char *tag) {
2616 int i;
2618 for (i = 0; i < numFonts; ++i) {
2619 if (fonts[i] && fonts[i]->matches(tag)) {
2620 return fonts[i];
2623 return NULL;