beta-0.89.2
[luatex.git] / source / libs / poppler / poppler-src / poppler / GfxFont.cc
blob81f59037f7f54d7758f26f44fcb118738add544e
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-2015 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 { "Times-Bold", "Times-Bold" },
122 { "Times-BoldItalic", "Times-BoldItalic" },
123 { "Times-Italic", "Times-Italic" },
124 { "Times-Roman", "Times-Roman" },
125 { "TimesNewRoman", "Times-Roman" },
126 { "TimesNewRoman,Bold", "Times-Bold" },
127 { "TimesNewRoman,BoldItalic", "Times-BoldItalic" },
128 { "TimesNewRoman,Italic", "Times-Italic" },
129 { "TimesNewRoman-Bold", "Times-Bold" },
130 { "TimesNewRoman-BoldItalic", "Times-BoldItalic" },
131 { "TimesNewRoman-Italic", "Times-Italic" },
132 { "TimesNewRomanPS", "Times-Roman" },
133 { "TimesNewRomanPS-Bold", "Times-Bold" },
134 { "TimesNewRomanPS-BoldItalic", "Times-BoldItalic" },
135 { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
136 { "TimesNewRomanPS-BoldMT", "Times-Bold" },
137 { "TimesNewRomanPS-Italic", "Times-Italic" },
138 { "TimesNewRomanPS-ItalicMT", "Times-Italic" },
139 { "TimesNewRomanPSMT", "Times-Roman" },
140 { "TimesNewRomanPSMT,Bold", "Times-Bold" },
141 { "TimesNewRomanPSMT,BoldItalic", "Times-BoldItalic" },
142 { "TimesNewRomanPSMT,Italic", "Times-Italic" },
143 { "ZapfDingbats", "ZapfDingbats" }
146 //------------------------------------------------------------------------
148 // index: {fixed:0, sans-serif:4, serif:8} + bold*2 + italic
149 // NB: must be in same order as psSubstFonts in PSOutputDev.cc
150 static const char *base14SubstFonts[14] = {
151 "Courier",
152 "Courier-Oblique",
153 "Courier-Bold",
154 "Courier-BoldOblique",
155 "Helvetica",
156 "Helvetica-Oblique",
157 "Helvetica-Bold",
158 "Helvetica-BoldOblique",
159 "Times-Roman",
160 "Times-Italic",
161 "Times-Bold",
162 "Times-BoldItalic",
163 // the last two are never used for substitution
164 "Symbol",
165 "ZapfDingbats"
168 //------------------------------------------------------------------------
170 static int parseCharName(char *charName, Unicode *uBuf, int uLen,
171 GBool names, GBool ligatures,
172 GBool numeric, GBool hex, GBool variants);
174 //------------------------------------------------------------------------
176 static int readFromStream(void *data) {
177 return ((Stream *)data)->getChar();
180 //------------------------------------------------------------------------
181 // GfxFontLoc
182 //------------------------------------------------------------------------
184 GfxFontLoc::GfxFontLoc() {
185 path = NULL;
186 fontNum = 0;
187 encoding = NULL;
188 substIdx = -1;
191 GfxFontLoc::~GfxFontLoc() {
192 if (path) {
193 delete path;
195 if (encoding) {
196 delete encoding;
200 //------------------------------------------------------------------------
201 // GfxFont
202 //------------------------------------------------------------------------
204 GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
205 GooString *nameA;
206 Ref embFontIDA;
207 GfxFontType typeA;
208 GfxFont *font;
209 Object obj1;
211 // get base font name
212 nameA = NULL;
213 fontDict->lookup("BaseFont", &obj1);
214 if (obj1.isName()) {
215 nameA = new GooString(obj1.getName());
217 obj1.free();
219 // get embedded font ID and font type
220 typeA = getFontType(xref, fontDict, &embFontIDA);
222 // create the font object
223 font = NULL;
224 if (typeA < fontCIDType0) {
225 font = new Gfx8BitFont(xref, tagA, idA, nameA, typeA, embFontIDA,
226 fontDict);
227 } else {
228 font = new GfxCIDFont(xref, tagA, idA, nameA, typeA, embFontIDA,
229 fontDict);
232 return font;
235 GfxFont::GfxFont(const char *tagA, Ref idA, GooString *nameA,
236 GfxFontType typeA, Ref embFontIDA) {
237 ok = gFalse;
238 tag = new GooString(tagA);
239 id = idA;
240 name = nameA;
241 type = typeA;
242 embFontID = embFontIDA;
243 embFontName = NULL;
244 family = NULL;
245 stretch = StretchNotDefined;
246 weight = WeightNotDefined;
247 refCnt = 1;
248 encodingName = new GooString("");
249 hasToUnicode = gFalse;
252 GfxFont::~GfxFont() {
253 delete tag;
254 delete family;
255 if (name) {
256 delete name;
258 if (embFontName) {
259 delete embFontName;
261 if (encodingName) {
262 delete encodingName;
266 void GfxFont::incRefCnt() {
267 refCnt++;
270 void GfxFont::decRefCnt() {
271 if (--refCnt == 0)
272 delete this;
275 // This function extracts three pieces of information:
276 // 1. the "expected" font type, i.e., the font type implied by
277 // Font.Subtype, DescendantFont.Subtype, and
278 // FontDescriptor.FontFile3.Subtype
279 // 2. the embedded font object ID
280 // 3. the actual font type - determined by examining the embedded font
281 // if there is one, otherwise equal to the expected font type
282 // If the expected and actual font types don't match, a warning
283 // message is printed. The expected font type is not used for
284 // anything else.
285 GfxFontType GfxFont::getFontType(XRef *xref, Dict *fontDict, Ref *embID) {
286 GfxFontType t, expectedType;
287 FoFiIdentifierType fft;
288 Dict *fontDict2;
289 Object subtype, fontDesc, obj1, obj2, obj3, obj4;
290 GBool isType0, err;
292 t = fontUnknownType;
293 embID->num = embID->gen = -1;
294 err = gFalse;
296 fontDict->lookup("Subtype", &subtype);
297 expectedType = fontUnknownType;
298 isType0 = gFalse;
299 if (subtype.isName("Type1") || subtype.isName("MMType1")) {
300 expectedType = fontType1;
301 } else if (subtype.isName("Type1C")) {
302 expectedType = fontType1C;
303 } else if (subtype.isName("Type3")) {
304 expectedType = fontType3;
305 } else if (subtype.isName("TrueType")) {
306 expectedType = fontTrueType;
307 } else if (subtype.isName("Type0")) {
308 isType0 = gTrue;
309 } else {
310 error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
311 subtype.isName() ? subtype.getName() : "???");
313 subtype.free();
315 fontDict2 = fontDict;
316 if (fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
317 if (obj1.arrayGetLength() == 0) {
318 error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
319 obj2.initNull();
320 } else if (obj1.arrayGet(0, &obj2)->isDict()) {
321 if (!isType0) {
322 error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
324 fontDict2 = obj2.getDict();
325 fontDict2->lookup("Subtype", &subtype);
326 if (subtype.isName("CIDFontType0")) {
327 if (isType0) {
328 expectedType = fontCIDType0;
330 } else if (subtype.isName("CIDFontType2")) {
331 if (isType0) {
332 expectedType = fontCIDType2;
335 subtype.free();
337 } else {
338 obj2.initNull();
341 if (fontDict2->lookup("FontDescriptor", &fontDesc)->isDict()) {
342 if (fontDesc.dictLookupNF("FontFile", &obj3)->isRef()) {
343 *embID = obj3.getRef();
344 if (expectedType != fontType1) {
345 err = gTrue;
348 obj3.free();
349 if (embID->num == -1 &&
350 fontDesc.dictLookupNF("FontFile2", &obj3)->isRef()) {
351 *embID = obj3.getRef();
352 if (isType0) {
353 expectedType = fontCIDType2;
354 } else if (expectedType != fontTrueType) {
355 err = gTrue;
358 obj3.free();
359 if (embID->num == -1 &&
360 fontDesc.dictLookupNF("FontFile3", &obj3)->isRef()) {
361 *embID = obj3.getRef();
362 if (obj3.fetch(xref, &obj4)->isStream()) {
363 obj4.streamGetDict()->lookup("Subtype", &subtype);
364 if (subtype.isName("Type1")) {
365 if (expectedType != fontType1) {
366 err = gTrue;
367 expectedType = isType0 ? fontCIDType0 : fontType1;
369 } else if (subtype.isName("Type1C")) {
370 if (expectedType == fontType1) {
371 expectedType = fontType1C;
372 } else if (expectedType != fontType1C) {
373 err = gTrue;
374 expectedType = isType0 ? fontCIDType0C : fontType1C;
376 } else if (subtype.isName("TrueType")) {
377 if (expectedType != fontTrueType) {
378 err = gTrue;
379 expectedType = isType0 ? fontCIDType2 : fontTrueType;
381 } else if (subtype.isName("CIDFontType0C")) {
382 if (expectedType == fontCIDType0) {
383 expectedType = fontCIDType0C;
384 } else {
385 err = gTrue;
386 expectedType = isType0 ? fontCIDType0C : fontType1C;
388 } else if (subtype.isName("OpenType")) {
389 if (expectedType == fontTrueType) {
390 expectedType = fontTrueTypeOT;
391 } else if (expectedType == fontType1) {
392 expectedType = fontType1COT;
393 } else if (expectedType == fontCIDType0) {
394 expectedType = fontCIDType0COT;
395 } else if (expectedType == fontCIDType2) {
396 expectedType = fontCIDType2OT;
397 } else {
398 err = gTrue;
400 } else {
401 error(errSyntaxError, -1, "Unknown font type '{0:s}'",
402 subtype.isName() ? subtype.getName() : "???");
404 subtype.free();
406 obj4.free();
408 obj3.free();
410 fontDesc.free();
412 t = fontUnknownType;
413 if (embID->num >= 0) {
414 obj3.initRef(embID->num, embID->gen);
415 obj3.fetch(xref, &obj4);
416 if (obj4.isStream()) {
417 obj4.streamReset();
418 fft = FoFiIdentifier::identifyStream(&readFromStream, obj4.getStream());
419 obj4.streamClose();
420 switch (fft) {
421 case fofiIdType1PFA:
422 case fofiIdType1PFB:
423 t = fontType1;
424 break;
425 case fofiIdCFF8Bit:
426 t = isType0 ? fontCIDType0C : fontType1C;
427 break;
428 case fofiIdCFFCID:
429 t = fontCIDType0C;
430 break;
431 case fofiIdTrueType:
432 case fofiIdTrueTypeCollection:
433 t = isType0 ? fontCIDType2 : fontTrueType;
434 break;
435 case fofiIdOpenTypeCFF8Bit:
436 t = expectedType; // hack: open type always == expected type? s. bug-poppler20605.pdf
437 break;
438 case fofiIdOpenTypeCFFCID:
439 t = fontCIDType0COT;
440 break;
441 default:
442 error(errSyntaxError, -1, "Embedded font file may be invalid");
443 break;
446 obj4.free();
447 obj3.free();
450 if (t == fontUnknownType) {
451 t = expectedType;
454 if (t != expectedType) {
455 err = gTrue;
458 if (err) {
459 error(errSyntaxWarning, -1,
460 "Mismatch between font type and embedded font file");
463 obj2.free();
464 obj1.free();
466 return t;
469 void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
470 Object obj1, obj2, obj3, obj4;
471 double t;
472 int i;
474 // assume Times-Roman by default (for substitution purposes)
475 flags = fontSerif;
477 missingWidth = 0;
479 if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
481 // get flags
482 if (obj1.dictLookup("Flags", &obj2)->isInt()) {
483 flags = obj2.getInt();
485 obj2.free();
487 // get name
488 obj1.dictLookup("FontName", &obj2);
489 if (obj2.isName()) {
490 embFontName = new GooString(obj2.getName());
492 obj2.free();
493 if (embFontName == NULL) {
494 // get name with typo
495 obj1.dictLookup("Fontname", &obj2);
496 if (obj2.isName()) {
497 embFontName = new GooString(obj2.getName());
498 error(errSyntaxWarning, -1, "The file uses Fontname instead of FontName please notify the creator that the file is broken");
500 obj2.free();
503 // get family
504 obj1.dictLookup("FontFamily", &obj2);
505 if (obj2.isString()) family = new GooString(obj2.getString());
506 obj2.free();
508 // get stretch
509 obj1.dictLookup("FontStretch", &obj2);
510 if (obj2.isName()) {
511 if (strcmp(obj2.getName(), "UltraCondensed") == 0) stretch = UltraCondensed;
512 else if (strcmp(obj2.getName(), "ExtraCondensed") == 0) stretch = ExtraCondensed;
513 else if (strcmp(obj2.getName(), "Condensed") == 0) stretch = Condensed;
514 else if (strcmp(obj2.getName(), "SemiCondensed") == 0) stretch = SemiCondensed;
515 else if (strcmp(obj2.getName(), "Normal") == 0) stretch = Normal;
516 else if (strcmp(obj2.getName(), "SemiExpanded") == 0) stretch = SemiExpanded;
517 else if (strcmp(obj2.getName(), "Expanded") == 0) stretch = Expanded;
518 else if (strcmp(obj2.getName(), "ExtraExpanded") == 0) stretch = ExtraExpanded;
519 else if (strcmp(obj2.getName(), "UltraExpanded") == 0) stretch = UltraExpanded;
520 else error(errSyntaxWarning, -1, "Invalid Font Stretch");
522 obj2.free();
524 // get weight
525 obj1.dictLookup("FontWeight", &obj2);
526 if (obj2.isNum()) {
527 if (obj2.getNum() == 100) weight = W100;
528 else if (obj2.getNum() == 200) weight = W200;
529 else if (obj2.getNum() == 300) weight = W300;
530 else if (obj2.getNum() == 400) weight = W400;
531 else if (obj2.getNum() == 500) weight = W500;
532 else if (obj2.getNum() == 600) weight = W600;
533 else if (obj2.getNum() == 700) weight = W700;
534 else if (obj2.getNum() == 800) weight = W800;
535 else if (obj2.getNum() == 900) weight = W900;
536 else error(errSyntaxWarning, -1, "Invalid Font Weight");
538 obj2.free();
540 // look for MissingWidth
541 obj1.dictLookup("MissingWidth", &obj2);
542 if (obj2.isNum()) {
543 missingWidth = obj2.getNum();
545 obj2.free();
547 // get Ascent and Descent
548 obj1.dictLookup("Ascent", &obj2);
549 if (obj2.isNum()) {
550 t = 0.001 * obj2.getNum();
551 // some broken font descriptors specify a negative ascent
552 if (t < 0) {
553 t = -t;
555 // some broken font descriptors set ascent and descent to 0;
556 // others set it to ridiculous values (e.g., 32768)
557 if (t != 0 && t < 3) {
558 ascent = t;
561 obj2.free();
562 obj1.dictLookup("Descent", &obj2);
563 if (obj2.isNum()) {
564 t = 0.001 * obj2.getNum();
565 // some broken font descriptors specify a positive descent
566 if (t > 0) {
567 t = -t;
569 // some broken font descriptors set ascent and descent to 0
570 if (t != 0 && t > -3) {
571 descent = t;
574 obj2.free();
576 // font FontBBox
577 if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
578 for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
579 if (obj2.arrayGet(i, &obj3)->isNum()) {
580 fontBBox[i] = 0.001 * obj3.getNum();
582 obj3.free();
585 obj2.free();
588 obj1.free();
591 CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits,
592 CharCodeToUnicode *ctu) {
593 GooString *buf;
594 Object obj1;
596 if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
597 obj1.free();
598 return NULL;
600 buf = new GooString();
601 obj1.getStream()->fillGooString(buf);
602 obj1.streamClose();
603 obj1.free();
604 if (ctu) {
605 ctu->mergeCMap(buf, nBits);
606 } else {
607 ctu = CharCodeToUnicode::parseCMap(buf, nBits);
609 hasToUnicode = gTrue;
610 delete buf;
611 return ctu;
614 GfxFontLoc *GfxFont::locateFont(XRef *xref, PSOutputDev *ps) {
615 GfxFontLoc *fontLoc;
616 SysFontType sysFontType;
617 GooString *path, *base14Name, *substName;
618 PSFontParam16 *psFont16;
619 Object refObj, embFontObj;
620 int substIdx, fontNum;
621 GBool embed;
623 if (type == fontType3) {
624 return NULL;
627 //----- embedded font
628 if (embFontID.num >= 0) {
629 embed = gTrue;
630 refObj.initRef(embFontID.num, embFontID.gen);
631 refObj.fetch(xref, &embFontObj);
632 if (!embFontObj.isStream()) {
633 error(errSyntaxError, -1, "Embedded font object is wrong type");
634 embed = gFalse;
636 embFontObj.free();
637 refObj.free();
638 if (embed) {
639 if (ps) {
640 switch (type) {
641 case fontType1:
642 case fontType1C:
643 case fontType1COT:
644 embed = ps->getEmbedType1();
645 break;
646 case fontTrueType:
647 case fontTrueTypeOT:
648 embed = ps->getEmbedTrueType();
649 break;
650 case fontCIDType0C:
651 case fontCIDType0COT:
652 embed = ps->getEmbedCIDPostScript();
653 break;
654 case fontCIDType2:
655 case fontCIDType2OT:
656 embed = ps->getEmbedCIDTrueType();
657 break;
658 default:
659 break;
662 if (embed) {
663 fontLoc = new GfxFontLoc();
664 fontLoc->locType = gfxFontLocEmbedded;
665 fontLoc->fontType = type;
666 fontLoc->embFontID = embFontID;
667 return fontLoc;
672 //----- PS passthrough
673 if (ps && !isCIDFont() && ps->getFontPassthrough()) {
674 fontLoc = new GfxFontLoc();
675 fontLoc->locType = gfxFontLocResident;
676 fontLoc->fontType = fontType1;
677 fontLoc->path = name->copy();
678 return fontLoc;
681 //----- PS resident Base-14 font
682 if (ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
683 fontLoc = new GfxFontLoc();
684 fontLoc->locType = gfxFontLocResident;
685 fontLoc->fontType = fontType1;
686 fontLoc->path = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
687 return fontLoc;
690 //----- external font file (fontFile, fontDir)
691 if (name && (path = globalParams->findFontFile(name))) {
692 if ((fontLoc = getExternalFont(path, isCIDFont()))) {
693 return fontLoc;
697 //----- external font file for Base-14 font
698 if (!ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
699 base14Name = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
700 if ((path = globalParams->findBase14FontFile(base14Name, this))) {
701 if ((fontLoc = getExternalFont(path, gFalse))) {
702 delete base14Name;
703 return fontLoc;
706 delete base14Name;
709 //----- system font
710 if ((path = globalParams->findSystemFontFile(this, &sysFontType,
711 &fontNum))) {
712 if (isCIDFont()) {
713 if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
714 fontLoc = new GfxFontLoc();
715 fontLoc->locType = gfxFontLocExternal;
716 fontLoc->fontType = fontCIDType2;
717 fontLoc->path = path;
718 fontLoc->fontNum = fontNum;
719 return fontLoc;
721 } else {
722 if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
723 fontLoc = new GfxFontLoc();
724 fontLoc->locType = gfxFontLocExternal;
725 fontLoc->fontType = fontTrueType;
726 fontLoc->path = path;
727 return fontLoc;
728 } else if (sysFontType == sysFontPFA || sysFontType == sysFontPFB) {
729 fontLoc = new GfxFontLoc();
730 fontLoc->locType = gfxFontLocExternal;
731 fontLoc->fontType = fontType1;
732 fontLoc->path = path;
733 fontLoc->fontNum = fontNum;
734 return fontLoc;
737 delete path;
740 if (!isCIDFont()) {
742 //----- 8-bit PS resident font
743 if (name && ps) {
744 if ((path = globalParams->getPSResidentFont(name))) {
745 fontLoc = new GfxFontLoc();
746 fontLoc->locType = gfxFontLocResident;
747 fontLoc->fontType = fontType1;
748 fontLoc->path = path;
749 return fontLoc;
753 //----- 8-bit font substitution
754 if (flags & fontFixedWidth) {
755 substIdx = 0;
756 } else if (flags & fontSerif) {
757 substIdx = 8;
758 } else {
759 substIdx = 4;
761 if (isBold()) {
762 substIdx += 2;
764 if (isItalic()) {
765 substIdx += 1;
767 substName = new GooString(base14SubstFonts[substIdx]);
768 if (ps) {
769 error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
770 base14SubstFonts[substIdx], name ? name->getCString() : "null");
771 fontLoc = new GfxFontLoc();
772 fontLoc->locType = gfxFontLocResident;
773 fontLoc->fontType = fontType1;
774 fontLoc->path = substName;
775 fontLoc->substIdx = substIdx;
776 return fontLoc;
777 } else {
778 path = globalParams->findFontFile(substName);
779 delete substName;
780 if (path) {
781 if ((fontLoc = getExternalFont(path, gFalse))) {
782 error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
783 base14SubstFonts[substIdx], name ? name->getCString() : "");
784 name = new GooString(base14SubstFonts[substIdx]);
785 fontLoc->substIdx = substIdx;
786 return fontLoc;
791 // failed to find a substitute font
792 return NULL;
795 //----- 16-bit PS resident font
796 if (ps && ((psFont16 = globalParams->getPSResidentFont16(
797 name,
798 ((GfxCIDFont *)this)->getWMode())))) {
799 fontLoc = new GfxFontLoc();
800 fontLoc->locType = gfxFontLocResident;
801 fontLoc->fontType = fontCIDType0; // this is not used
802 fontLoc->path = psFont16->psFontName->copy();
803 fontLoc->encoding = psFont16->encoding->copy();
804 fontLoc->wMode = psFont16->wMode;
805 return fontLoc;
807 if (ps && ((psFont16 = globalParams->getPSResidentFontCC(
808 ((GfxCIDFont *)this)->getCollection(),
809 ((GfxCIDFont *)this)->getWMode())))) {
810 error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
811 psFont16->psFontName, name);
812 fontLoc = new GfxFontLoc();
813 fontLoc->locType = gfxFontLocResident;
814 fontLoc->fontType = fontCIDType0; // this is not used
815 fontLoc->path = psFont16->psFontName->copy();
816 fontLoc->encoding = psFont16->encoding->copy();
817 fontLoc->wMode = psFont16->wMode;
818 return fontLoc;
821 //----- CID font substitution
822 if ((path = globalParams->findCCFontFile(
823 ((GfxCIDFont *)this)->getCollection()))) {
824 if ((fontLoc = getExternalFont(path, gTrue))) {
825 error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
826 fontLoc->path, name);
827 return fontLoc;
831 // failed to find a substitute font
832 return NULL;
835 GfxFontLoc *GfxFont::locateBase14Font(GooString *base14Name) {
836 GooString *path;
838 path = globalParams->findFontFile(base14Name);
839 if (!path) {
840 return NULL;
842 return getExternalFont(path, gFalse);
845 GfxFontLoc *GfxFont::getExternalFont(GooString *path, GBool cid) {
846 FoFiIdentifierType fft;
847 GfxFontType fontType;
848 GfxFontLoc *fontLoc;
850 fft = FoFiIdentifier::identifyFile(path->getCString());
851 switch (fft) {
852 case fofiIdType1PFA:
853 case fofiIdType1PFB:
854 fontType = fontType1;
855 break;
856 case fofiIdCFF8Bit:
857 fontType = fontType1C;
858 break;
859 case fofiIdCFFCID:
860 fontType = fontCIDType0C;
861 break;
862 case fofiIdTrueType:
863 case fofiIdTrueTypeCollection:
864 fontType = cid ? fontCIDType2 : fontTrueType;
865 break;
866 case fofiIdOpenTypeCFF8Bit:
867 fontType = fontType1COT;
868 break;
869 case fofiIdOpenTypeCFFCID:
870 fontType = fontCIDType0COT;
871 break;
872 case fofiIdUnknown:
873 case fofiIdError:
874 default:
875 fontType = fontUnknownType;
876 break;
878 if (fontType == fontUnknownType ||
879 (cid ? (fontType < fontCIDType0)
880 : (fontType >= fontCIDType0))) {
881 delete path;
882 return NULL;
884 fontLoc = new GfxFontLoc();
885 fontLoc->locType = gfxFontLocExternal;
886 fontLoc->fontType = fontType;
887 fontLoc->path = path;
888 return fontLoc;
891 char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
892 char *buf;
893 Object obj1, obj2;
894 Stream *str;
896 obj1.initRef(embFontID.num, embFontID.gen);
897 obj1.fetch(xref, &obj2);
898 if (!obj2.isStream()) {
899 error(errSyntaxError, -1, "Embedded font file is not a stream");
900 obj2.free();
901 obj1.free();
902 embFontID.num = -1;
903 *len = 0;
904 return NULL;
906 str = obj2.getStream();
908 buf = (char*)str->toUnsignedChars(len);
909 str->close();
911 obj2.free();
912 obj1.free();
914 return buf;
918 struct AlternateNameMap {
919 const char *name;
920 const char *alt;
923 static const AlternateNameMap alternateNameMap[] =
925 { "fi", "f_i" },
926 { "fl", "f_l" },
927 { "ff", "f_f" },
928 { "ffi", "f_f_i" },
929 { "ffl", "f_f_l" },
930 { 0, 0 }
933 const char *GfxFont::getAlternateName(const char *name) {
934 const AlternateNameMap *map = alternateNameMap;
935 while (map->name) {
936 if (strcmp(name, map->name) == 0) {
937 return map->alt;
939 map++;
941 return 0;
944 //------------------------------------------------------------------------
945 // Gfx8BitFont
946 //------------------------------------------------------------------------
948 // Parse character names of the form 'Axx', 'xx', 'Ann', 'ABnn', or
949 // 'nn', where 'A' and 'B' are any letters, 'xx' is two hex digits,
950 // and 'nn' is decimal digits.
951 static GBool parseNumericName(char *s, GBool hex, unsigned int *u) {
952 char *endptr;
954 // Strip leading alpha characters.
955 if (hex) {
956 int n = 0;
958 // Get string length while ignoring junk at end.
959 while (isalnum(s[n]))
960 ++n;
962 // Only 2 hex characters with optional leading alpha is allowed.
963 if (n == 3 && isalpha(*s)) {
964 ++s;
965 } else if (n != 2) {
966 return gFalse;
968 } else {
969 // Strip up to two alpha characters.
970 for (int i = 0; i < 2 && isalpha(*s); ++i)
971 ++s;
974 int v = strtol(s, &endptr, hex ? 16 : 10);
976 if (endptr == s)
977 return gFalse;
979 // Skip trailing junk characters.
980 while (*endptr != '\0' && !isalnum(*endptr))
981 ++endptr;
983 if (*endptr == '\0') {
984 if (u)
985 *u = v;
986 return gTrue;
988 return gFalse;
991 // Returns gTrue if the font has character names like xx or Axx which
992 // should be parsed for hex or decimal values.
993 static GBool testForNumericNames(Dict *fontDict, GBool hex) {
994 Object enc, diff, obj;
995 GBool numeric = gTrue;
997 fontDict->lookup("Encoding", &enc);
998 if (!enc.isDict()) {
999 enc.free();
1000 return gFalse;
1003 enc.dictLookup("Differences", &diff);
1004 enc.free();
1005 if (!diff.isArray()) {
1006 diff.free();
1007 return gFalse;
1010 for (int i = 0; i < diff.arrayGetLength() && numeric; ++i) {
1011 diff.arrayGet(i, &obj);
1012 if (obj.isInt()) {
1013 // All sequences must start between character codes 0 and 5.
1014 if (obj.getInt() > 5)
1015 numeric = gFalse;
1016 } else if (obj.isName()) {
1017 // All character names must sucessfully parse.
1018 if (!parseNumericName(obj.getName(), hex, NULL))
1019 numeric = gFalse;
1020 } else {
1021 numeric = gFalse;
1023 obj.free();
1026 diff.free();
1027 return numeric;
1030 Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GooString *nameA,
1031 GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
1032 GfxFont(tagA, idA, nameA, typeA, embFontIDA) {
1033 GooString *name2;
1034 BuiltinFont *builtinFont;
1035 const char **baseEnc;
1036 GBool baseEncFromFontFile;
1037 char *buf;
1038 int len;
1039 FoFiType1 *ffT1;
1040 FoFiType1C *ffT1C;
1041 int code;
1042 char *charName;
1043 GBool missing, hex;
1044 GBool numeric;
1045 Unicode toUnicode[256];
1046 CharCodeToUnicode *utu, *ctu2;
1047 Unicode uBuf[8];
1048 double mul;
1049 int firstChar, lastChar;
1050 Gushort w;
1051 Object obj1, obj2, obj3;
1052 int n, i, a, b, m;
1054 refCnt = 1;
1055 ctu = NULL;
1057 // do font name substitution for various aliases of the Base 14 font
1058 // names
1059 base14 = NULL;
1060 if (name) {
1061 name2 = name->copy();
1062 i = 0;
1063 while (i < name2->getLength()) {
1064 if (name2->getChar(i) == ' ') {
1065 name2->del(i);
1066 } else {
1067 ++i;
1070 a = 0;
1071 b = sizeof(base14FontMap) / sizeof(Base14FontMapEntry);
1072 // invariant: base14FontMap[a].altName <= name2 < base14FontMap[b].altName
1073 while (b - a > 1) {
1074 m = (a + b) / 2;
1075 if (name2->cmp(base14FontMap[m].altName) >= 0) {
1076 a = m;
1077 } else {
1078 b = m;
1081 if (!name2->cmp(base14FontMap[a].altName)) {
1082 base14 = &base14FontMap[a];
1084 delete name2;
1087 // is it a built-in font?
1088 builtinFont = NULL;
1089 if (base14) {
1090 for (i = 0; i < nBuiltinFonts; ++i) {
1091 if (!strcmp(base14->base14Name, builtinFonts[i].name)) {
1092 builtinFont = &builtinFonts[i];
1093 break;
1098 // default ascent/descent values
1099 if (builtinFont) {
1100 ascent = 0.001 * builtinFont->ascent;
1101 descent = 0.001 * builtinFont->descent;
1102 fontBBox[0] = 0.001 * builtinFont->bbox[0];
1103 fontBBox[1] = 0.001 * builtinFont->bbox[1];
1104 fontBBox[2] = 0.001 * builtinFont->bbox[2];
1105 fontBBox[3] = 0.001 * builtinFont->bbox[3];
1106 } else {
1107 ascent = 0.95;
1108 descent = -0.35;
1109 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1112 // get info from font descriptor
1113 readFontDescriptor(xref, fontDict);
1115 // for non-embedded fonts, don't trust the ascent/descent/bbox
1116 // values from the font descriptor
1117 if (builtinFont && embFontID.num < 0) {
1118 ascent = 0.001 * builtinFont->ascent;
1119 descent = 0.001 * builtinFont->descent;
1120 fontBBox[0] = 0.001 * builtinFont->bbox[0];
1121 fontBBox[1] = 0.001 * builtinFont->bbox[1];
1122 fontBBox[2] = 0.001 * builtinFont->bbox[2];
1123 fontBBox[3] = 0.001 * builtinFont->bbox[3];
1126 // get font matrix
1127 fontMat[0] = fontMat[3] = 1;
1128 fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
1129 if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
1130 for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
1131 if (obj1.arrayGet(i, &obj2)->isNum()) {
1132 fontMat[i] = obj2.getNum();
1134 obj2.free();
1137 obj1.free();
1139 // get Type 3 bounding box, font definition, and resources
1140 if (type == fontType3) {
1141 if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
1142 for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
1143 if (obj1.arrayGet(i, &obj2)->isNum()) {
1144 fontBBox[i] = obj2.getNum();
1146 obj2.free();
1149 obj1.free();
1150 if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
1151 error(errSyntaxError, -1,
1152 "Missing or invalid CharProcs dictionary in Type 3 font");
1153 charProcs.free();
1155 if (!fontDict->lookup("Resources", &resources)->isDict()) {
1156 resources.free();
1160 //----- build the font encoding -----
1162 // Encodings start with a base encoding, which can come from
1163 // (in order of priority):
1164 // 1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
1165 // - MacRoman / MacExpert / WinAnsi / Standard
1166 // 2. embedded or external font file
1167 // 3. default:
1168 // - builtin --> builtin encoding
1169 // - TrueType --> WinAnsiEncoding
1170 // - others --> StandardEncoding
1171 // and then add a list of differences (if any) from
1172 // FontDict.Encoding.Differences.
1174 // check FontDict for base encoding
1175 hasEncoding = gFalse;
1176 usesMacRomanEnc = gFalse;
1177 baseEnc = NULL;
1178 baseEncFromFontFile = gFalse;
1179 fontDict->lookup("Encoding", &obj1);
1180 if (obj1.isDict()) {
1181 obj1.dictLookup("BaseEncoding", &obj2);
1182 if (obj2.isName("MacRomanEncoding")) {
1183 hasEncoding = gTrue;
1184 usesMacRomanEnc = gTrue;
1185 baseEnc = macRomanEncoding;
1186 } else if (obj2.isName("MacExpertEncoding")) {
1187 hasEncoding = gTrue;
1188 baseEnc = macExpertEncoding;
1189 } else if (obj2.isName("WinAnsiEncoding")) {
1190 hasEncoding = gTrue;
1191 baseEnc = winAnsiEncoding;
1193 obj2.free();
1194 } else if (obj1.isName("MacRomanEncoding")) {
1195 hasEncoding = gTrue;
1196 usesMacRomanEnc = gTrue;
1197 baseEnc = macRomanEncoding;
1198 } else if (obj1.isName("MacExpertEncoding")) {
1199 hasEncoding = gTrue;
1200 baseEnc = macExpertEncoding;
1201 } else if (obj1.isName("WinAnsiEncoding")) {
1202 hasEncoding = gTrue;
1203 baseEnc = winAnsiEncoding;
1206 // check embedded font file for base encoding
1207 // (only for Type 1 fonts - trying to get an encoding out of a
1208 // TrueType font is a losing proposition)
1209 ffT1 = NULL;
1210 ffT1C = NULL;
1211 buf = NULL;
1212 if (type == fontType1 && embFontID.num >= 0) {
1213 if ((buf = readEmbFontFile(xref, &len))) {
1214 if ((ffT1 = FoFiType1::make(buf, len))) {
1215 if (ffT1->getName()) {
1216 if (embFontName) {
1217 delete embFontName;
1219 embFontName = new GooString(ffT1->getName());
1221 if (!baseEnc) {
1222 baseEnc = (const char **)ffT1->getEncoding();
1223 baseEncFromFontFile = gTrue;
1226 gfree(buf);
1228 } else if (type == fontType1C && embFontID.num >= 0) {
1229 if ((buf = readEmbFontFile(xref, &len))) {
1230 if ((ffT1C = FoFiType1C::make(buf, len))) {
1231 if (ffT1C->getName()) {
1232 if (embFontName) {
1233 delete embFontName;
1235 embFontName = new GooString(ffT1C->getName());
1237 if (!baseEnc) {
1238 baseEnc = (const char **)ffT1C->getEncoding();
1239 baseEncFromFontFile = gTrue;
1242 gfree(buf);
1246 // get default base encoding
1247 if (!baseEnc) {
1248 if (builtinFont && embFontID.num < 0) {
1249 baseEnc = builtinFont->defaultBaseEnc;
1250 hasEncoding = gTrue;
1251 } else if (type == fontTrueType) {
1252 baseEnc = winAnsiEncoding;
1253 } else {
1254 baseEnc = standardEncoding;
1258 if (baseEncFromFontFile) {
1259 encodingName->Set("Builtin");
1260 } else if (baseEnc == winAnsiEncoding) {
1261 encodingName->Set("WinAnsi");
1262 } else if (baseEnc == macRomanEncoding) {
1263 encodingName->Set("MacRoman");
1264 } else if (baseEnc == macExpertEncoding) {
1265 encodingName->Set("MacExpert");
1266 } else if (baseEnc == symbolEncoding) {
1267 encodingName->Set("Symbol");
1268 } else if (baseEnc == zapfDingbatsEncoding) {
1269 encodingName->Set("ZapfDingbats");
1270 } else {
1271 encodingName->Set("Standard");
1274 // copy the base encoding
1275 for (i = 0; i < 256; ++i) {
1276 enc[i] = (char *)baseEnc[i];
1277 if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
1278 enc[i] = copyString(baseEnc[i]);
1282 // some Type 1C font files have empty encodings, which can break the
1283 // T1C->T1 conversion (since the 'seac' operator depends on having
1284 // the accents in the encoding), so we fill in any gaps from
1285 // StandardEncoding
1286 if (type == fontType1C && embFontID.num >= 0 && baseEncFromFontFile) {
1287 for (i = 0; i < 256; ++i) {
1288 if (!enc[i] && standardEncoding[i]) {
1289 enc[i] = (char *)standardEncoding[i];
1290 encFree[i] = gFalse;
1295 // merge differences into encoding
1296 if (obj1.isDict()) {
1297 obj1.dictLookup("Differences", &obj2);
1298 if (obj2.isArray()) {
1299 encodingName->Set("Custom");
1300 hasEncoding = gTrue;
1301 code = 0;
1302 for (i = 0; i < obj2.arrayGetLength(); ++i) {
1303 obj2.arrayGet(i, &obj3);
1304 if (obj3.isInt()) {
1305 code = obj3.getInt();
1306 } else if (obj3.isName()) {
1307 if (code >= 0 && code < 256) {
1308 if (encFree[code]) {
1309 gfree(enc[code]);
1311 enc[code] = copyString(obj3.getName());
1312 encFree[code] = gTrue;
1314 ++code;
1315 } else {
1316 error(errSyntaxError, -1,
1317 "Wrong type in font encoding resource differences ({0:s})",
1318 obj3.getTypeName());
1320 obj3.free();
1323 obj2.free();
1325 obj1.free();
1326 if (ffT1) {
1327 delete ffT1;
1329 if (ffT1C) {
1330 delete ffT1C;
1333 //----- build the mapping to Unicode -----
1335 // pass 1: use the name-to-Unicode mapping table
1336 missing = hex = gFalse;
1337 GBool isZapfDingbats = name && name->endsWith("ZapfDingbats");
1338 for (code = 0; code < 256; ++code) {
1339 if ((charName = enc[code])) {
1340 if (isZapfDingbats) {
1341 // include ZapfDingbats names
1342 toUnicode[code] = globalParams->mapNameToUnicodeAll(charName);
1343 } else {
1344 toUnicode[code] = globalParams->mapNameToUnicodeText(charName);
1346 if (!toUnicode[code] && strcmp(charName, ".notdef")) {
1347 // if it wasn't in the name-to-Unicode table, check for a
1348 // name that looks like 'Axx' or 'xx', where 'A' is any letter
1349 // and 'xx' is two hex digits
1350 if ((strlen(charName) == 3 &&
1351 isalpha(charName[0]) &&
1352 isxdigit(charName[1]) && isxdigit(charName[2]) &&
1353 ((charName[1] >= 'a' && charName[1] <= 'f') ||
1354 (charName[1] >= 'A' && charName[1] <= 'F') ||
1355 (charName[2] >= 'a' && charName[2] <= 'f') ||
1356 (charName[2] >= 'A' && charName[2] <= 'F'))) ||
1357 (strlen(charName) == 2 &&
1358 isxdigit(charName[0]) && isxdigit(charName[1]) &&
1359 // Only check idx 1 to avoid misidentifying a decimal
1360 // number like a0
1361 ((charName[1] >= 'a' && charName[1] <= 'f') ||
1362 (charName[1] >= 'A' && charName[1] <= 'F')))) {
1363 hex = gTrue;
1365 missing = gTrue;
1367 } else {
1368 toUnicode[code] = 0;
1372 numeric = testForNumericNames(fontDict, hex);
1374 // construct the char code -> Unicode mapping object
1375 ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1377 // pass 1a: Expand ligatures in the Alphabetic Presentation Form
1378 // block (eg "fi", "ffi") to normal form
1379 for (code = 0; code < 256; ++code) {
1380 if (unicodeIsAlphabeticPresentationForm(toUnicode[code])) {
1381 Unicode *normalized = unicodeNormalizeNFKC(&toUnicode[code], 1, &len, NULL);
1382 if (len > 1)
1383 ctu->setMapping((CharCode)code, normalized, len);
1384 gfree(normalized);
1388 // pass 2: try to fill in the missing chars, looking for ligatures, numeric
1389 // references and variants
1390 if (missing) {
1391 for (code = 0; code < 256; ++code) {
1392 if (!toUnicode[code]) {
1393 if ((charName = enc[code]) && strcmp(charName, ".notdef")
1394 && (n = parseCharName(charName, uBuf, sizeof(uBuf)/sizeof(*uBuf),
1395 gFalse, // don't check simple names (pass 1)
1396 gTrue, // do check ligatures
1397 numeric,
1398 hex,
1399 gTrue))) { // do check variants
1400 ctu->setMapping((CharCode)code, uBuf, n);
1401 continue;
1404 // if the 'mapUnknownCharNames' flag is set, do a simple pass-through
1405 // mapping for unknown character names
1406 if (globalParams->getMapUnknownCharNames()) {
1407 uBuf[0] = code;
1408 ctu->setMapping((CharCode)code, uBuf, 1);
1414 // merge in a ToUnicode CMap, if there is one -- this overwrites
1415 // existing entries in ctu, i.e., the ToUnicode CMap takes
1416 // precedence, but the other encoding info is allowed to fill in any
1417 // holes
1418 readToUnicodeCMap(fontDict, 16, ctu);
1420 // look for a Unicode-to-Unicode mapping
1421 if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1422 Unicode *uAux;
1423 for (i = 0; i < 256; ++i) {
1424 toUnicode[i] = 0;
1426 ctu2 = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1427 for (i = 0; i < 256; ++i) {
1428 n = ctu->mapToUnicode((CharCode)i, &uAux);
1429 if (n >= 1) {
1430 n = utu->mapToUnicode((CharCode)uAux[0], &uAux);
1431 if (n >= 1) {
1432 ctu2->setMapping((CharCode)i, uAux, n);
1436 utu->decRefCnt();
1437 delete ctu;
1438 ctu = ctu2;
1441 //----- get the character widths -----
1443 // initialize all widths
1444 for (code = 0; code < 256; ++code) {
1445 widths[code] = missingWidth * 0.001;
1448 // use widths from font dict, if present
1449 fontDict->lookup("FirstChar", &obj1);
1450 firstChar = obj1.isInt() ? obj1.getInt() : 0;
1451 obj1.free();
1452 if (firstChar < 0 || firstChar > 255) {
1453 firstChar = 0;
1455 fontDict->lookup("LastChar", &obj1);
1456 lastChar = obj1.isInt() ? obj1.getInt() : 255;
1457 obj1.free();
1458 if (lastChar < 0 || lastChar > 255) {
1459 lastChar = 255;
1461 mul = (type == fontType3) ? fontMat[0] : 0.001;
1462 fontDict->lookup("Widths", &obj1);
1463 if (obj1.isArray()) {
1464 flags |= fontFixedWidth;
1465 if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
1466 lastChar = firstChar + obj1.arrayGetLength() - 1;
1468 for (code = firstChar; code <= lastChar; ++code) {
1469 obj1.arrayGet(code - firstChar, &obj2);
1470 if (obj2.isNum()) {
1471 widths[code] = obj2.getNum() * mul;
1472 if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
1473 flags &= ~fontFixedWidth;
1476 obj2.free();
1479 // use widths from built-in font
1480 } else if (builtinFont) {
1481 // this is a kludge for broken PDF files that encode char 32
1482 // as .notdef
1483 if (builtinFont->widths->getWidth("space", &w)) {
1484 widths[32] = 0.001 * w;
1486 for (code = 0; code < 256; ++code) {
1487 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1488 widths[code] = 0.001 * w;
1492 // couldn't find widths -- use defaults
1493 } else {
1494 // this is technically an error -- the Widths entry is required
1495 // for all but the Base-14 fonts -- but certain PDF generators
1496 // apparently don't include widths for Arial and TimesNewRoman
1497 if (isFixedWidth()) {
1498 i = 0;
1499 } else if (isSerif()) {
1500 i = 8;
1501 } else {
1502 i = 4;
1504 if (isBold()) {
1505 i += 2;
1507 if (isItalic()) {
1508 i += 1;
1510 builtinFont = builtinFontSubst[i];
1511 // this is a kludge for broken PDF files that encode char 32
1512 // as .notdef
1513 if (builtinFont->widths->getWidth("space", &w)) {
1514 widths[32] = 0.001 * w;
1516 for (code = 0; code < 256; ++code) {
1517 if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1518 widths[code] = 0.001 * w;
1522 obj1.free();
1524 ok = gTrue;
1527 Gfx8BitFont::~Gfx8BitFont() {
1528 int i;
1530 for (i = 0; i < 256; ++i) {
1531 if (encFree[i] && enc[i]) {
1532 gfree(enc[i]);
1535 ctu->decRefCnt();
1536 if (charProcs.isDict()) {
1537 charProcs.free();
1539 if (resources.isDict()) {
1540 resources.free();
1544 // This function is in part a derived work of the Adobe Glyph Mapping
1545 // Convention: http://www.adobe.com/devnet/opentype/archives/glyph.html
1546 // Algorithmic comments are excerpted from that document to aid
1547 // maintainability.
1548 static int parseCharName(char *charName, Unicode *uBuf, int uLen,
1549 GBool names, GBool ligatures,
1550 GBool numeric, GBool hex, GBool variants)
1552 if (uLen <= 0) {
1553 error(errInternal, -1, "Zero-length output buffer (recursion overflow?) in "
1554 "parseCharName, component \"{0:s}\"", charName);
1555 return 0;
1557 // Step 1: drop all the characters from the glyph name starting with the
1558 // first occurrence of a period (U+002E FULL STOP), if any.
1559 if (variants) {
1560 char *var_part = strchr(charName, '.');
1561 if (var_part == charName) {
1562 return 0; // .notdef or similar
1563 } else if (var_part != NULL) {
1564 // parse names of the form 7.oldstyle, P.swash, s.sc, etc.
1565 char *main_part = gstrndup(charName, var_part - charName);
1566 GBool namesRecurse = gTrue, variantsRecurse = gFalse;
1567 int n = parseCharName(main_part, uBuf, uLen, namesRecurse, ligatures,
1568 numeric, hex, variantsRecurse);
1569 gfree(main_part);
1570 return n;
1573 // Step 2: split the remaining string into a sequence of components, using
1574 // underscore (U+005F LOW LINE) as the delimiter.
1575 if (ligatures && strchr(charName, '_')) {
1576 // parse names of the form A_a (e.g. f_i, T_h, l_quotesingle)
1577 char *lig_part, *lig_end, *lig_copy;
1578 int n = 0, m;
1579 lig_part = lig_copy = copyString(charName);
1580 do {
1581 if ((lig_end = strchr(lig_part, '_')))
1582 *lig_end = '\0';
1583 if (lig_part[0] != '\0') {
1584 GBool namesRecurse = gTrue, ligaturesRecurse = gFalse;
1585 if ((m = parseCharName(lig_part, uBuf + n, uLen - n, namesRecurse,
1586 ligaturesRecurse, numeric, hex, variants)))
1587 n += m;
1588 else
1589 error(errSyntaxWarning, -1, "Could not parse ligature component \"{0:s}\" of \"{1:s}\" in "
1590 "parseCharName", lig_part, charName);
1592 lig_part = lig_end + 1;
1593 } while (lig_end && n < uLen);
1594 gfree(lig_copy);
1595 return n;
1597 // Step 3: map each component to a character string according to the
1598 // procedure below, and concatenate those strings; the result is the
1599 // character string to which the glyph name is mapped.
1600 // 3.1. if the font is Zapf Dingbats (PostScript FontName ZapfDingbats), and
1601 // the component is in the ZapfDingbats list, then map it to the
1602 // corresponding character in that list.
1603 // 3.2. otherwise, if the component is in the Adobe Glyph List, then map it
1604 // to the corresponding character in that list.
1605 if (names && (uBuf[0] = globalParams->mapNameToUnicodeText(charName))) {
1606 return 1;
1608 if (globalParams->getMapNumericCharNames()) {
1609 unsigned int n = strlen(charName);
1610 // 3.3. otherwise, if the component is of the form "uni" (U+0075 U+006E
1611 // U+0069) followed by a sequence of uppercase hexadecimal digits (0 .. 9,
1612 // A .. F, i.e. U+0030 .. U+0039, U+0041 .. U+0046), the length of that
1613 // sequence is a multiple of four, and each group of four digits represents
1614 // a number in the set {0x0000 .. 0xD7FF, 0xE000 .. 0xFFFF}, then interpret
1615 // each such number as a Unicode scalar value and map the component to the
1616 // string made of those scalar values. Note that the range and digit length
1617 // restrictions mean that the "uni" prefix can be used only with Unicode
1618 // values from the Basic Multilingual Plane (BMP).
1619 if (n >= 7 && (n % 4) == 3 && !strncmp(charName, "uni", 3)) {
1620 int i;
1621 unsigned int m;
1622 for (i = 0, m = 3; i < uLen && m < n; m += 4) {
1623 if (isxdigit(charName[m]) && isxdigit(charName[m + 1]) &&
1624 isxdigit(charName[m + 2]) && isxdigit(charName[m + 3])) {
1625 unsigned int u;
1626 sscanf(charName + m, "%4x", &u);
1627 if (u <= 0xD7FF || (0xE000 <= u && u <= 0xFFFF)) {
1628 uBuf[i++] = u;
1632 return i;
1634 // 3.4. otherwise, if the component is of the form "u" (U+0075) followed by
1635 // a sequence of four to six uppercase hexadecimal digits {0 .. 9, A .. F}
1636 // (U+0030 .. U+0039, U+0041 .. U+0046), and those digits represent a
1637 // number in {0x0000 .. 0xD7FF, 0xE000 .. 0x10FFFF}, then interpret this
1638 // number as a Unicode scalar value and map the component to the string
1639 // made of this scalar value.
1640 if (n >= 5 && n <= 7 && charName[0] == 'u' && isxdigit(charName[1]) &&
1641 isxdigit(charName[2]) && isxdigit(charName[3]) && isxdigit(charName[4])
1642 && (n <= 5 || isxdigit(charName[5]))
1643 && (n <= 6 || isxdigit(charName[6]))) {
1644 unsigned int u;
1645 sscanf(charName + 1, "%x", &u);
1646 if (u <= 0xD7FF || (0xE000 <= u && u <= 0x10FFFF)) {
1647 uBuf[0] = u;
1648 return 1;
1651 // Not in Adobe Glyph Mapping convention: look for names like xx
1652 // or Axx and parse for hex or decimal values.
1653 if (numeric && parseNumericName(charName, hex, uBuf))
1654 return 1;
1656 // 3.5. otherwise, map the component to the empty string
1657 return 0;
1660 int Gfx8BitFont::getNextChar(char *s, int len, CharCode *code,
1661 Unicode **u, int *uLen,
1662 double *dx, double *dy, double *ox, double *oy) {
1663 CharCode c;
1665 *code = c = (CharCode)(*s & 0xff);
1666 *uLen = ctu->mapToUnicode(c, u);
1667 *dx = widths[c];
1668 *dy = *ox = *oy = 0;
1669 return 1;
1672 CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
1673 ctu->incRefCnt();
1674 return ctu;
1677 int *Gfx8BitFont::getCodeToGIDMap(FoFiTrueType *ff) {
1678 int *map;
1679 int cmapPlatform, cmapEncoding;
1680 int unicodeCmap, macRomanCmap, msSymbolCmap, cmap;
1681 GBool useMacRoman, useUnicode;
1682 char *charName;
1683 Unicode u;
1684 int code, i, n;
1686 map = (int *)gmallocn(256, sizeof(int));
1687 for (i = 0; i < 256; ++i) {
1688 map[i] = 0;
1691 // To match up with the Adobe-defined behaviour, we choose a cmap
1692 // like this:
1693 // 1. If the PDF font has an encoding:
1694 // 1a. If the PDF font specified MacRomanEncoding and the
1695 // TrueType font has a Macintosh Roman cmap, use it, and
1696 // reverse map the char names through MacRomanEncoding to
1697 // get char codes.
1698 // 1b. If the PDF font is not symbolic or the PDF font is not
1699 // embedded, and the TrueType font has a Microsoft Unicode
1700 // cmap or a non-Microsoft Unicode cmap, use it, and use the
1701 // Unicode indexes, not the char codes.
1702 // 1c. If the PDF font is symbolic and the TrueType font has a
1703 // Microsoft Symbol cmap, use it, and use char codes
1704 // directly (possibly with an offset of 0xf000).
1705 // 1d. If the TrueType font has a Macintosh Roman cmap, use it,
1706 // as in case 1a.
1707 // 2. If the PDF font does not have an encoding or the PDF font is
1708 // symbolic:
1709 // 2a. If the TrueType font has a Macintosh Roman cmap, use it,
1710 // and use char codes directly (possibly with an offset of
1711 // 0xf000).
1712 // 2b. If the TrueType font has a Microsoft Symbol cmap, use it,
1713 // and use char codes directly (possible with an offset of
1714 // 0xf000).
1715 // 3. If none of these rules apply, use the first cmap and hope for
1716 // the best (this shouldn't happen).
1717 unicodeCmap = macRomanCmap = msSymbolCmap = -1;
1718 for (i = 0; i < ff->getNumCmaps(); ++i) {
1719 cmapPlatform = ff->getCmapPlatform(i);
1720 cmapEncoding = ff->getCmapEncoding(i);
1721 if ((cmapPlatform == 3 && cmapEncoding == 1) ||
1722 cmapPlatform == 0) {
1723 unicodeCmap = i;
1724 } else if (cmapPlatform == 1 && cmapEncoding == 0) {
1725 macRomanCmap = i;
1726 } else if (cmapPlatform == 3 && cmapEncoding == 0) {
1727 msSymbolCmap = i;
1730 cmap = 0;
1731 useMacRoman = gFalse;
1732 useUnicode = gFalse;
1733 if (hasEncoding || type == fontType1) {
1734 if (usesMacRomanEnc && macRomanCmap >= 0) {
1735 cmap = macRomanCmap;
1736 useMacRoman = gTrue;
1737 } else if ((!(flags & fontSymbolic) || embFontID.num < 0) &&
1738 unicodeCmap >= 0) {
1739 cmap = unicodeCmap;
1740 useUnicode = gTrue;
1741 } else if ((flags & fontSymbolic) && msSymbolCmap >= 0) {
1742 cmap = msSymbolCmap;
1743 } else if ((flags & fontSymbolic) && macRomanCmap >= 0) {
1744 cmap = macRomanCmap;
1745 } else if (macRomanCmap >= 0) {
1746 cmap = macRomanCmap;
1747 useMacRoman = gTrue;
1749 } else {
1750 if (msSymbolCmap >= 0) {
1751 cmap = msSymbolCmap;
1752 } else if (macRomanCmap >= 0) {
1753 cmap = macRomanCmap;
1757 // reverse map the char names through MacRomanEncoding, then map the
1758 // char codes through the cmap
1759 if (useMacRoman) {
1760 for (i = 0; i < 256; ++i) {
1761 if ((charName = enc[i])) {
1762 if ((code = globalParams->getMacRomanCharCode(charName))) {
1763 map[i] = ff->mapCodeToGID(cmap, code);
1765 } else {
1766 map[i] = -1;
1770 // map Unicode through the cmap
1771 } else if (useUnicode) {
1772 Unicode *uAux;
1773 for (i = 0; i < 256; ++i) {
1774 if (((charName = enc[i]) && (u = globalParams->mapNameToUnicodeAll(charName))))
1775 map[i] = ff->mapCodeToGID(cmap, u);
1776 else
1778 n = ctu->mapToUnicode((CharCode)i, &uAux);
1779 if (n > 0) map[i] = ff->mapCodeToGID(cmap, uAux[0]);
1780 else map[i] = -1;
1784 // map the char codes through the cmap, possibly with an offset of
1785 // 0xf000
1786 } else {
1787 for (i = 0; i < 256; ++i) {
1788 if (!(map[i] = ff->mapCodeToGID(cmap, i))) {
1789 map[i] = ff->mapCodeToGID(cmap, 0xf000 + i);
1794 // try the TrueType 'post' table to handle any unmapped characters
1795 for (i = 0; i < 256; ++i) {
1796 if (map[i] <= 0 && (charName = enc[i])) {
1797 map[i] = ff->mapNameToGID(charName);
1801 return map;
1804 Dict *Gfx8BitFont::getCharProcs() {
1805 return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
1808 Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
1809 if (enc[code] && charProcs.isDict()) {
1810 charProcs.dictLookup(enc[code], proc);
1811 } else {
1812 proc->initNull();
1814 return proc;
1817 Dict *Gfx8BitFont::getResources() {
1818 return resources.isDict() ? resources.getDict() : (Dict *)NULL;
1821 //------------------------------------------------------------------------
1822 // GfxCIDFont
1823 //------------------------------------------------------------------------
1825 struct cmpWidthExcepFunctor {
1826 bool operator()(const GfxFontCIDWidthExcep &w1,
1827 const GfxFontCIDWidthExcep &w2) {
1828 return w1.first < w2.first;
1832 struct cmpWidthExcepVFunctor {
1833 bool operator()(const GfxFontCIDWidthExcepV &w1,
1834 const GfxFontCIDWidthExcepV &w2) {
1835 return w1.first < w2.first;
1839 GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GooString *nameA,
1840 GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
1841 GfxFont(tagA, idA, nameA, typeA, embFontIDA)
1843 Dict *desFontDict;
1844 Object desFontDictObj;
1845 Object obj1, obj2, obj3, obj4, obj5, obj6;
1846 CharCodeToUnicode *utu;
1847 CharCode c;
1848 Unicode *uBuf;
1849 int c1, c2;
1850 int excepsSize, i, j, k, n;
1852 refCnt = 1;
1853 ascent = 0.95;
1854 descent = -0.35;
1855 fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1856 collection = NULL;
1857 cMap = NULL;
1858 ctu = NULL;
1859 ctuUsesCharCode = gTrue;
1860 widths.defWidth = 1.0;
1861 widths.defHeight = -1.0;
1862 widths.defVY = 0.880;
1863 widths.exceps = NULL;
1864 widths.nExceps = 0;
1865 widths.excepsV = NULL;
1866 widths.nExcepsV = 0;
1867 cidToGID = NULL;
1868 cidToGIDLen = 0;
1870 // get the descendant font
1871 if (!fontDict->lookup("DescendantFonts", &obj1)->isArray() ||
1872 obj1.arrayGetLength() == 0) {
1873 error(errSyntaxError, -1, "Missing or empty DescendantFonts entry in Type 0 font");
1874 obj1.free();
1875 goto err1;
1877 if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
1878 error(errSyntaxError, -1, "Bad descendant font in Type 0 font");
1879 goto err3;
1881 obj1.free();
1882 desFontDict = desFontDictObj.getDict();
1884 // get info from font descriptor
1885 readFontDescriptor(xref, desFontDict);
1887 //----- encoding info -----
1889 // char collection
1890 if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
1891 error(errSyntaxError, -1, "Missing CIDSystemInfo dictionary in Type 0 descendant font");
1892 goto err3;
1894 obj1.dictLookup("Registry", &obj2);
1895 obj1.dictLookup("Ordering", &obj3);
1896 if (!obj2.isString() || !obj3.isString()) {
1897 error(errSyntaxError, -1, "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
1898 goto err3;
1900 collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
1901 obj3.free();
1902 obj2.free();
1903 obj1.free();
1905 // look for a ToUnicode CMap
1906 if (!(ctu = readToUnicodeCMap(fontDict, 16, NULL))) {
1907 ctuUsesCharCode = gFalse;
1909 // use an identity mapping for the "Adobe-Identity" and
1910 // "Adobe-UCS" collections
1911 if (!collection->cmp("Adobe-Identity") ||
1912 !collection->cmp("Adobe-UCS")) {
1913 ctu = CharCodeToUnicode::makeIdentityMapping();
1914 } else {
1915 // look for a user-supplied .cidToUnicode file
1916 if (!(ctu = globalParams->getCIDToUnicode(collection))) {
1917 // I'm not completely sure that this is the best thing to do
1918 // but it seems to produce better results when the .cidToUnicode
1919 // files from the poppler-data package are missing. At least
1920 // we know that assuming the Identity mapping is definitely wrong.
1921 // -- jrmuizel
1922 static const char * knownCollections [] = {
1923 "Adobe-CNS1",
1924 "Adobe-GB1",
1925 "Adobe-Japan1",
1926 "Adobe-Japan2",
1927 "Adobe-Korea1",
1929 for (size_t i = 0; i < sizeof(knownCollections)/sizeof(knownCollections[0]); i++) {
1930 if (collection->cmp(knownCollections[i]) == 0) {
1931 error(errSyntaxError, -1, "Missing language pack for '{0:t}' mapping", collection);
1932 goto err2;
1935 error(errSyntaxError, -1, "Unknown character collection '{0:t}'",
1936 collection);
1937 // fall-through, assuming the Identity mapping -- this appears
1938 // to match Adobe's behavior
1943 // look for a Unicode-to-Unicode mapping
1944 if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1945 if (ctu) {
1946 for (c = 0; c < ctu->getLength(); ++c) {
1947 n = ctu->mapToUnicode(c, &uBuf);
1948 if (n >= 1) {
1949 n = utu->mapToUnicode((CharCode)uBuf[0], &uBuf);
1950 if (n >= 1) {
1951 ctu->setMapping(c, uBuf, n);
1955 utu->decRefCnt();
1956 } else {
1957 ctu = utu;
1961 // encoding (i.e., CMap)
1962 if (fontDict->lookup("Encoding", &obj1)->isNull()) {
1963 error(errSyntaxError, -1, "Missing Encoding entry in Type 0 font");
1964 goto err2;
1966 if (!(cMap = CMap::parse(NULL, collection, &obj1))) {
1967 goto err2;
1969 obj1.free();
1970 if (cMap->getCMapName()) {
1971 encodingName->Set(cMap->getCMapName()->getCString());
1972 } else {
1973 encodingName->Set("Custom");
1976 // CIDToGIDMap (for embedded TrueType fonts)
1977 if (type == fontCIDType2 || type == fontCIDType2OT) {
1978 desFontDict->lookup("CIDToGIDMap", &obj1);
1979 if (obj1.isStream()) {
1980 cidToGIDLen = 0;
1981 i = 64;
1982 cidToGID = (int *)gmallocn(i, sizeof(int));
1983 obj1.streamReset();
1984 while ((c1 = obj1.streamGetChar()) != EOF &&
1985 (c2 = obj1.streamGetChar()) != EOF) {
1986 if (cidToGIDLen == i) {
1987 i *= 2;
1988 cidToGID = (int *)greallocn(cidToGID, i, sizeof(int));
1990 cidToGID[cidToGIDLen++] = (c1 << 8) + c2;
1992 } else if (!obj1.isName("Identity") && !obj1.isNull()) {
1993 error(errSyntaxError, -1, "Invalid CIDToGIDMap entry in CID font");
1995 obj1.free();
1998 //----- character metrics -----
2000 // default char width
2001 if (desFontDict->lookup("DW", &obj1)->isInt()) {
2002 widths.defWidth = obj1.getInt() * 0.001;
2004 obj1.free();
2006 // char width exceptions
2007 if (desFontDict->lookup("W", &obj1)->isArray()) {
2008 excepsSize = 0;
2009 i = 0;
2010 while (i + 1 < obj1.arrayGetLength()) {
2011 obj1.arrayGet(i, &obj2);
2012 obj1.arrayGet(i + 1, &obj3);
2013 if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
2014 if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
2015 if (widths.nExceps == excepsSize) {
2016 excepsSize += 16;
2017 widths.exceps = (GfxFontCIDWidthExcep *)
2018 greallocn(widths.exceps,
2019 excepsSize, sizeof(GfxFontCIDWidthExcep));
2021 widths.exceps[widths.nExceps].first = obj2.getInt();
2022 widths.exceps[widths.nExceps].last = obj3.getInt();
2023 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
2024 ++widths.nExceps;
2025 } else {
2026 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2028 obj4.free();
2029 i += 3;
2030 } else if (obj2.isInt() && obj3.isArray()) {
2031 if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
2032 excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
2033 widths.exceps = (GfxFontCIDWidthExcep *)
2034 greallocn(widths.exceps,
2035 excepsSize, sizeof(GfxFontCIDWidthExcep));
2037 j = obj2.getInt();
2038 for (k = 0; k < obj3.arrayGetLength(); ++k) {
2039 if (obj3.arrayGet(k, &obj4)->isNum()) {
2040 widths.exceps[widths.nExceps].first = j;
2041 widths.exceps[widths.nExceps].last = j;
2042 widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
2043 ++j;
2044 ++widths.nExceps;
2045 } else {
2046 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2048 obj4.free();
2050 i += 2;
2051 } else {
2052 error(errSyntaxError, -1, "Bad widths array in Type 0 font");
2053 ++i;
2055 obj3.free();
2056 obj2.free();
2058 std::sort(widths.exceps, widths.exceps + widths.nExceps,
2059 cmpWidthExcepFunctor());
2061 obj1.free();
2063 // default metrics for vertical font
2064 if (desFontDict->lookup("DW2", &obj1)->isArray() &&
2065 obj1.arrayGetLength() == 2) {
2066 if (obj1.arrayGet(0, &obj2)->isNum()) {
2067 widths.defVY = obj2.getNum() * 0.001;
2069 obj2.free();
2070 if (obj1.arrayGet(1, &obj2)->isNum()) {
2071 widths.defHeight = obj2.getNum() * 0.001;
2073 obj2.free();
2075 obj1.free();
2077 // char metric exceptions for vertical font
2078 if (desFontDict->lookup("W2", &obj1)->isArray()) {
2079 excepsSize = 0;
2080 i = 0;
2081 while (i + 1 < obj1.arrayGetLength()) {
2082 obj1.arrayGet(i, &obj2);
2083 obj1.arrayGet(i+ 1, &obj3);
2084 if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
2085 if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
2086 obj1.arrayGet(i + 3, &obj5)->isNum() &&
2087 obj1.arrayGet(i + 4, &obj6)->isNum()) {
2088 if (widths.nExcepsV == excepsSize) {
2089 excepsSize += 16;
2090 widths.excepsV = (GfxFontCIDWidthExcepV *)
2091 greallocn(widths.excepsV,
2092 excepsSize, sizeof(GfxFontCIDWidthExcepV));
2094 widths.excepsV[widths.nExcepsV].first = obj2.getInt();
2095 widths.excepsV[widths.nExcepsV].last = obj3.getInt();
2096 widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2097 widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2098 widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2099 ++widths.nExcepsV;
2100 } else {
2101 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2103 obj6.free();
2104 obj5.free();
2105 obj4.free();
2106 i += 5;
2107 } else if (obj2.isInt() && obj3.isArray()) {
2108 if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
2109 excepsSize =
2110 (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
2111 widths.excepsV = (GfxFontCIDWidthExcepV *)
2112 greallocn(widths.excepsV,
2113 excepsSize, sizeof(GfxFontCIDWidthExcepV));
2115 j = obj2.getInt();
2116 for (k = 0; k < obj3.arrayGetLength(); k += 3) {
2117 if (obj3.arrayGet(k, &obj4)->isNum() &&
2118 obj3.arrayGet(k+1, &obj5)->isNum() &&
2119 obj3.arrayGet(k+2, &obj6)->isNum()) {
2120 widths.excepsV[widths.nExcepsV].first = j;
2121 widths.excepsV[widths.nExcepsV].last = j;
2122 widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2123 widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2124 widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2125 ++j;
2126 ++widths.nExcepsV;
2127 } else {
2128 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2130 obj6.free();
2131 obj5.free();
2132 obj4.free();
2134 i += 2;
2135 } else {
2136 error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2137 ++i;
2139 obj3.free();
2140 obj2.free();
2142 std::sort(widths.excepsV, widths.excepsV + widths.nExcepsV,
2143 cmpWidthExcepVFunctor());
2145 obj1.free();
2147 desFontDictObj.free();
2148 ok = gTrue;
2149 return;
2151 err3:
2152 obj3.free();
2153 obj2.free();
2154 err2:
2155 obj1.free();
2156 desFontDictObj.free();
2157 err1:;
2160 GfxCIDFont::~GfxCIDFont() {
2161 if (collection) {
2162 delete collection;
2164 if (cMap) {
2165 cMap->decRefCnt();
2167 if (ctu) {
2168 ctu->decRefCnt();
2170 gfree(widths.exceps);
2171 gfree(widths.excepsV);
2172 if (cidToGID) {
2173 gfree(cidToGID);
2177 int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
2178 Unicode **u, int *uLen,
2179 double *dx, double *dy, double *ox, double *oy) {
2180 CID cid;
2181 CharCode c;
2182 double w, h, vx, vy;
2183 int n, a, b, m;
2185 if (!cMap) {
2186 *code = 0;
2187 *uLen = 0;
2188 *dx = *dy = 0;
2189 return 1;
2192 *code = (CharCode)(cid = cMap->getCID(s, len, &c, &n));
2193 if (ctu) {
2194 if (hasToUnicode) {
2195 int i = 0, c = 0;
2196 while (i < n) {
2197 c = (c << 8 ) + (s[i] & 0xff);
2198 ++i;
2200 *uLen = ctu->mapToUnicode(c, u);
2201 } else {
2202 *uLen = ctu->mapToUnicode(cid, u);
2204 } else {
2205 *uLen = 0;
2208 // horizontal
2209 if (cMap->getWMode() == 0) {
2210 w = getWidth(cid);
2211 h = vx = vy = 0;
2213 // vertical
2214 } else {
2215 w = 0;
2216 h = widths.defHeight;
2217 vx = getWidth(cid) / 2;
2218 vy = widths.defVY;
2219 if (widths.nExcepsV > 0 && cid >= widths.excepsV[0].first) {
2220 a = 0;
2221 b = widths.nExcepsV;
2222 // invariant: widths.excepsV[a].first <= cid < widths.excepsV[b].first
2223 while (b - a > 1) {
2224 m = (a + b) / 2;
2225 if (widths.excepsV[m].last <= cid) {
2226 a = m;
2227 } else {
2228 b = m;
2231 if (cid <= widths.excepsV[a].last) {
2232 h = widths.excepsV[a].height;
2233 vx = widths.excepsV[a].vx;
2234 vy = widths.excepsV[a].vy;
2239 *dx = w;
2240 *dy = h;
2241 *ox = vx;
2242 *oy = vy;
2244 return n;
2247 int GfxCIDFont::getWMode() {
2248 return cMap ? cMap->getWMode() : 0;
2251 CharCodeToUnicode *GfxCIDFont::getToUnicode() {
2252 if (ctu) {
2253 ctu->incRefCnt();
2255 return ctu;
2258 GooString *GfxCIDFont::getCollection() {
2259 return cMap ? cMap->getCollection() : (GooString *)NULL;
2262 int GfxCIDFont::mapCodeToGID(FoFiTrueType *ff, int cmapi,
2263 Unicode unicode, GBool wmode) {
2264 Gushort gid = ff->mapCodeToGID(cmapi,unicode);
2265 if (wmode) {
2266 Gushort vgid = ff->mapToVertGID(gid);
2267 if (vgid != 0) gid = vgid;
2269 return gid;
2272 int *GfxCIDFont::getCodeToGIDMap(FoFiTrueType *ff, int *mapsizep) {
2273 #define N_UCS_CANDIDATES 2
2274 /* space characters */
2275 static const unsigned long spaces[] = {
2276 0x2000,0x2001,0x2002,0x2003,0x2004,0x2005,0x2006,0x2007,
2277 0x2008,0x2009,0x200A,0x00A0,0x200B,0x2060,0x3000,0xFEFF,
2280 static const char *adobe_cns1_cmaps[] = {
2281 "UniCNS-UTF32-V",
2282 "UniCNS-UCS2-V",
2283 "UniCNS-UTF32-H",
2284 "UniCNS-UCS2-H",
2287 static const char *adobe_gb1_cmaps[] = {
2288 "UniGB-UTF32-V",
2289 "UniGB-UCS2-V",
2290 "UniGB-UTF32-H",
2291 "UniGB-UCS2-H",
2294 static const char *adobe_japan1_cmaps[] = {
2295 "UniJIS-UTF32-V",
2296 "UniJIS-UCS2-V",
2297 "UniJIS-UTF32-H",
2298 "UniJIS-UCS2-H",
2301 static const char *adobe_japan2_cmaps[] = {
2302 "UniHojo-UTF32-V",
2303 "UniHojo-UCS2-V",
2304 "UniHojo-UTF32-H",
2305 "UniHojo-UCS2-H",
2308 static const char *adobe_korea1_cmaps[] = {
2309 "UniKS-UTF32-V",
2310 "UniKS-UCS2-V",
2311 "UniKS-UTF32-H",
2312 "UniKS-UCS2-H",
2315 static struct CMapListEntry {
2316 const char *collection;
2317 const char *scriptTag;
2318 const char *languageTag;
2319 const char *toUnicodeMap;
2320 const char **CMaps;
2321 } CMapList[] = {
2323 "Adobe-CNS1",
2324 "hani", "CHN ",
2325 "Adobe-CNS1-UCS2",
2326 adobe_cns1_cmaps,
2329 "Adobe-GB1",
2330 "hani", "CHN ",
2331 "Adobe-GB1-UCS2",
2332 adobe_gb1_cmaps,
2335 "Adobe-Japan1",
2336 "kana", "JAN ",
2337 "Adobe-Japan1-UCS2",
2338 adobe_japan1_cmaps,
2341 "Adobe-Japan2",
2342 "kana", "JAN ",
2343 "Adobe-Japan2-UCS2",
2344 adobe_japan2_cmaps,
2347 "Adobe-Korea1",
2348 "hang", "KOR ",
2349 "Adobe-Korea1-UCS2",
2350 adobe_korea1_cmaps,
2352 {0, 0, 0, 0}
2354 Unicode *humap = 0;
2355 Unicode *vumap = 0;
2356 Unicode *tumap = 0;
2357 int *codeToGID = 0;
2358 unsigned long n;
2359 int i;
2360 unsigned long code;
2361 int wmode;
2362 const char **cmapName;
2363 CMap *cMap;
2364 CMapListEntry *lp;
2365 int cmap;
2366 int cmapPlatform, cmapEncoding;
2367 Ref embID;
2369 *mapsizep = 0;
2370 if (!ctu) return NULL;
2371 if (getCollection()->cmp("Adobe-Identity") == 0) return NULL;
2372 if (getEmbeddedFontID(&embID)) {
2373 /* if this font is embedded font,
2374 * CIDToGIDMap should be embedded in PDF file
2375 * and already set. So return it.
2377 *mapsizep = getCIDToGIDLen();
2378 return getCIDToGID();
2381 /* we use only unicode cmap */
2382 cmap = -1;
2383 for (i = 0; i < ff->getNumCmaps(); ++i) {
2384 cmapPlatform = ff->getCmapPlatform(i);
2385 cmapEncoding = ff->getCmapEncoding(i);
2386 if (cmapPlatform == 3 && cmapEncoding == 10) {
2387 /* UCS-4 */
2388 cmap = i;
2389 /* use UCS-4 cmap */
2390 break;
2391 } else if (cmapPlatform == 3 && cmapEncoding == 1) {
2392 /* Unicode */
2393 cmap = i;
2394 } else if (cmapPlatform == 0 && cmap < 0) {
2395 cmap = i;
2398 if (cmap < 0)
2399 return NULL;
2401 wmode = getWMode();
2402 for (lp = CMapList;lp->collection != 0;lp++) {
2403 if (strcmp(lp->collection,getCollection()->getCString()) == 0) {
2404 break;
2407 n = 65536;
2408 tumap = new Unicode[n];
2409 humap = new Unicode[n*N_UCS_CANDIDATES];
2410 memset(humap,0,sizeof(Unicode)*n*N_UCS_CANDIDATES);
2411 if (lp->collection != 0) {
2412 CharCodeToUnicode *tctu;
2413 GooString tname(lp->toUnicodeMap);
2415 if ((tctu = CharCodeToUnicode::parseCMapFromFile(&tname,16)) != 0) {
2416 CharCode cid;
2417 for (cid = 0;cid < n ;cid++) {
2418 int len;
2419 Unicode *ucodes;
2421 len = tctu->mapToUnicode(cid,&ucodes);
2422 if (len == 1) {
2423 tumap[cid] = ucodes[0];
2424 } else {
2425 /* if not single character, ignore it */
2426 tumap[cid] = 0;
2429 delete tctu;
2431 vumap = new Unicode[n];
2432 memset(vumap,0,sizeof(Unicode)*n);
2433 for (cmapName = lp->CMaps;*cmapName != 0;cmapName++) {
2434 GooString cname(*cmapName);
2436 if ((cMap = globalParams->getCMap(getCollection(),&cname))
2437 != 0) {
2438 if (cMap->getWMode()) {
2439 cMap->setReverseMap(vumap,n,1);
2440 } else {
2441 cMap->setReverseMap(humap,n,N_UCS_CANDIDATES);
2443 cMap->decRefCnt();
2446 ff->setupGSUB(lp->scriptTag, lp->languageTag);
2447 } else {
2448 error(errSyntaxError, -1, "Unknown character collection {0:t}\n",
2449 getCollection());
2450 if ((ctu = getToUnicode()) != 0) {
2451 CharCode cid;
2452 for (cid = 0;cid < n ;cid++) {
2453 Unicode *ucode;
2455 if (ctu->mapToUnicode(cid, &ucode))
2456 humap[cid*N_UCS_CANDIDATES] = ucode[0];
2457 else
2458 humap[cid*N_UCS_CANDIDATES] = 0;
2459 for (i = 1;i < N_UCS_CANDIDATES;i++) {
2460 humap[cid*N_UCS_CANDIDATES+i] = 0;
2463 ctu->decRefCnt();
2466 // map CID -> Unicode -> GID
2467 codeToGID = (int *)gmallocn(n, sizeof(int));
2468 for (code = 0; code < n; ++code) {
2469 Unicode unicode;
2470 unsigned long gid;
2472 unicode = 0;
2473 gid = 0;
2474 if (humap != 0) {
2475 for (i = 0;i < N_UCS_CANDIDATES
2476 && gid == 0 && (unicode = humap[code*N_UCS_CANDIDATES+i]) != 0;i++) {
2477 gid = mapCodeToGID(ff,cmap,unicode,gFalse);
2480 if (gid == 0 && vumap != 0) {
2481 unicode = vumap[code];
2482 if (unicode != 0) {
2483 gid = mapCodeToGID(ff,cmap,unicode,gTrue);
2484 if (gid == 0 && tumap != 0) {
2485 if ((unicode = tumap[code]) != 0) {
2486 gid = mapCodeToGID(ff,cmap,unicode,gTrue);
2491 if (gid == 0 && tumap != 0) {
2492 if ((unicode = tumap[code]) != 0) {
2493 gid = mapCodeToGID(ff,cmap,unicode,gFalse);
2496 if (gid == 0) {
2497 /* special handling space characters */
2498 const unsigned long *p;
2500 if (humap != 0) unicode = humap[code];
2501 if (unicode != 0) {
2502 /* check if code is space character , so map code to 0x0020 */
2503 for (p = spaces;*p != 0;p++) {
2504 if (*p == unicode) {
2505 unicode = 0x20;
2506 gid = mapCodeToGID(ff,cmap,unicode,wmode);
2507 break;
2512 codeToGID[code] = gid;
2514 *mapsizep = n;
2515 if (humap != 0) delete[] humap;
2516 if (tumap != 0) delete[] tumap;
2517 if (vumap != 0) delete[] vumap;
2518 return codeToGID;
2521 double GfxCIDFont::getWidth(CID cid) {
2522 double w;
2523 int a, b, m;
2525 w = widths.defWidth;
2526 if (widths.nExceps > 0 && cid >= widths.exceps[0].first) {
2527 a = 0;
2528 b = widths.nExceps;
2529 // invariant: widths.exceps[a].first <= cid < widths.exceps[b].first
2530 while (b - a > 1) {
2531 m = (a + b) / 2;
2532 if (widths.exceps[m].first <= cid) {
2533 a = m;
2534 } else {
2535 b = m;
2538 if (cid <= widths.exceps[a].last) {
2539 w = widths.exceps[a].width;
2542 return w;
2545 double GfxCIDFont::getWidth (char* s, int len) {
2546 int nUsed;
2547 CharCode c;
2549 CID cid = cMap->getCID(s, len, &c, &nUsed);
2550 return getWidth(cid);
2553 //------------------------------------------------------------------------
2554 // GfxFontDict
2555 //------------------------------------------------------------------------
2557 GfxFontDict::GfxFontDict(XRef *xref, Ref *fontDictRef, Dict *fontDict) {
2558 int i;
2559 Object obj1, obj2;
2560 Ref r;
2562 numFonts = fontDict->getLength();
2563 fonts = (GfxFont **)gmallocn(numFonts, sizeof(GfxFont *));
2564 for (i = 0; i < numFonts; ++i) {
2565 fontDict->getValNF(i, &obj1);
2566 obj1.fetch(xref, &obj2);
2567 if (obj2.isDict()) {
2568 if (obj1.isRef()) {
2569 r = obj1.getRef();
2570 } else {
2571 // no indirect reference for this font, so invent a unique one
2572 // (legal generation numbers are five digits, so any 6-digit
2573 // number would be safe)
2574 r.num = i;
2575 if (fontDictRef) {
2576 r.gen = 100000 + fontDictRef->num;
2577 } else {
2578 r.gen = 999999;
2581 fonts[i] = GfxFont::makeFont(xref, fontDict->getKey(i),
2582 r, obj2.getDict());
2583 if (fonts[i] && !fonts[i]->isOk()) {
2584 // XXX: it may be meaningful to distinguish between
2585 // NULL and !isOk() so that when we do lookups
2586 // we can tell the difference between a missing font
2587 // and a font that is just !isOk()
2588 fonts[i]->decRefCnt();
2589 fonts[i] = NULL;
2591 } else {
2592 error(errSyntaxError, -1, "font resource is not a dictionary");
2593 fonts[i] = NULL;
2595 obj1.free();
2596 obj2.free();
2600 GfxFontDict::~GfxFontDict() {
2601 int i;
2603 for (i = 0; i < numFonts; ++i) {
2604 if (fonts[i]) {
2605 fonts[i]->decRefCnt();
2608 gfree(fonts);
2611 GfxFont *GfxFontDict::lookup(char *tag) {
2612 int i;
2614 for (i = 0; i < numFonts; ++i) {
2615 if (fonts[i] && fonts[i]->matches(tag)) {
2616 return fonts[i];
2619 return NULL;