Coverage Report

Created: 2026-02-26 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/xpdf-4.06/xpdf/GfxFont.cc
Line
Count
Source
1
//========================================================================
2
//
3
// GfxFont.cc
4
//
5
// Copyright 1996-2003 Glyph & Cog, LLC
6
//
7
//========================================================================
8
9
#include <aconf.h>
10
11
#include <stdio.h>
12
#include <stdlib.h>
13
#include <string.h>
14
#include <ctype.h>
15
#include <math.h>
16
#include <limits.h>
17
#include "gmem.h"
18
#include "gmempp.h"
19
#include "GList.h"
20
#include "GHash.h"
21
#include "Error.h"
22
#include "Object.h"
23
#include "Dict.h"
24
#include "GlobalParams.h"
25
#include "CMap.h"
26
#include "CharCodeToUnicode.h"
27
#include "FontEncodingTables.h"
28
#include "BuiltinFontTables.h"
29
#include "FoFiIdentifier.h"
30
#include "FoFiType1.h"
31
#include "FoFiType1C.h"
32
#include "FoFiTrueType.h"
33
#include "GfxFont.h"
34
35
//------------------------------------------------------------------------
36
37
struct Base14FontMapEntry {
38
  const char *altName;
39
  const char *base14Name;
40
};
41
42
static Base14FontMapEntry base14FontMap[] = {
43
  { "Arial",                        "Helvetica" },
44
  { "Arial,Bold",                   "Helvetica-Bold" },
45
  { "Arial,BoldItalic",             "Helvetica-BoldOblique" },
46
  { "Arial,Italic",                 "Helvetica-Oblique" },
47
  { "Arial-Bold",                   "Helvetica-Bold" },
48
  { "Arial-BoldItalic",             "Helvetica-BoldOblique" },
49
  { "Arial-BoldItalicMT",           "Helvetica-BoldOblique" },
50
  { "Arial-BoldMT",                 "Helvetica-Bold" },
51
  { "Arial-Italic",                 "Helvetica-Oblique" },
52
  { "Arial-ItalicMT",               "Helvetica-Oblique" },
53
  { "ArialMT",                      "Helvetica" },
54
  { "Courier",                      "Courier" },
55
  { "Courier,Bold",                 "Courier-Bold" },
56
  { "Courier,BoldItalic",           "Courier-BoldOblique" },
57
  { "Courier,Italic",               "Courier-Oblique" },
58
  { "Courier-Bold",                 "Courier-Bold" },
59
  { "Courier-BoldOblique",          "Courier-BoldOblique" },
60
  { "Courier-Oblique",              "Courier-Oblique" },
61
  { "CourierNew",                   "Courier" },
62
  { "CourierNew,Bold",              "Courier-Bold" },
63
  { "CourierNew,BoldItalic",        "Courier-BoldOblique" },
64
  { "CourierNew,Italic",            "Courier-Oblique" },
65
  { "CourierNew-Bold",              "Courier-Bold" },
66
  { "CourierNew-BoldItalic",        "Courier-BoldOblique" },
67
  { "CourierNew-Italic",            "Courier-Oblique" },
68
  { "CourierNewPS-BoldItalicMT",    "Courier-BoldOblique" },
69
  { "CourierNewPS-BoldMT",          "Courier-Bold" },
70
  { "CourierNewPS-ItalicMT",        "Courier-Oblique" },
71
  { "CourierNewPSMT",               "Courier" },
72
  { "Helvetica",                    "Helvetica" },
73
  { "Helvetica,Bold",               "Helvetica-Bold" },
74
  { "Helvetica,BoldItalic",         "Helvetica-BoldOblique" },
75
  { "Helvetica,Italic",             "Helvetica-Oblique" },
76
  { "Helvetica-Bold",               "Helvetica-Bold" },
77
  { "Helvetica-BoldItalic",         "Helvetica-BoldOblique" },
78
  { "Helvetica-BoldOblique",        "Helvetica-BoldOblique" },
79
  { "Helvetica-Italic",             "Helvetica-Oblique" },
80
  { "Helvetica-Oblique",            "Helvetica-Oblique" },
81
  { "Symbol",                       "Symbol" },
82
  { "Symbol,Bold",                  "Symbol" },
83
  { "Symbol,BoldItalic",            "Symbol" },
84
  { "Symbol,Italic",                "Symbol" },
85
  { "Times-Bold",                   "Times-Bold" },
86
  { "Times-BoldItalic",             "Times-BoldItalic" },
87
  { "Times-Italic",                 "Times-Italic" },
88
  { "Times-Roman",                  "Times-Roman" },
89
  { "TimesNewRoman",                "Times-Roman" },
90
  { "TimesNewRoman,Bold",           "Times-Bold" },
91
  { "TimesNewRoman,BoldItalic",     "Times-BoldItalic" },
92
  { "TimesNewRoman,Italic",         "Times-Italic" },
93
  { "TimesNewRoman-Bold",           "Times-Bold" },
94
  { "TimesNewRoman-BoldItalic",     "Times-BoldItalic" },
95
  { "TimesNewRoman-Italic",         "Times-Italic" },
96
  { "TimesNewRomanPS",              "Times-Roman" },
97
  { "TimesNewRomanPS-Bold",         "Times-Bold" },
98
  { "TimesNewRomanPS-BoldItalic",   "Times-BoldItalic" },
99
  { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
100
  { "TimesNewRomanPS-BoldMT",       "Times-Bold" },
101
  { "TimesNewRomanPS-Italic",       "Times-Italic" },
102
  { "TimesNewRomanPS-ItalicMT",     "Times-Italic" },
103
  { "TimesNewRomanPSMT",            "Times-Roman" },
104
  { "TimesNewRomanPSMT,Bold",       "Times-Bold" },
105
  { "TimesNewRomanPSMT,BoldItalic", "Times-BoldItalic" },
106
  { "TimesNewRomanPSMT,Italic",     "Times-Italic" },
107
  { "ZapfDingbats",                 "ZapfDingbats" }
108
};
109
110
//------------------------------------------------------------------------
111
112
// index: {fixed:0, sans-serif:4, serif:8} + bold*2 + italic
113
// NB: must be in same order as psSubstFonts in PSOutputDev.cc
114
static const char *base14SubstFonts[14] = {
115
  "Courier",
116
  "Courier-Oblique",
117
  "Courier-Bold",
118
  "Courier-BoldOblique",
119
  "Helvetica",
120
  "Helvetica-Oblique",
121
  "Helvetica-Bold",
122
  "Helvetica-BoldOblique",
123
  "Times-Roman",
124
  "Times-Italic",
125
  "Times-Bold",
126
  "Times-BoldItalic",
127
  // the last two are never used for substitution
128
  "Symbol",
129
  "ZapfDingbats"
130
};
131
132
//------------------------------------------------------------------------
133
134
0
static int readFromStream(void *data) {
135
0
  return ((Stream *)data)->getChar();
136
0
}
137
138
//------------------------------------------------------------------------
139
// GfxFontLoc
140
//------------------------------------------------------------------------
141
142
0
GfxFontLoc::GfxFontLoc() {
143
0
  path = NULL;
144
0
  fontNum = 0;
145
0
  oblique = 0;
146
0
  encoding = NULL;
147
0
  substIdx = -1;
148
0
}
149
150
0
GfxFontLoc::~GfxFontLoc() {
151
0
  if (path) {
152
0
    delete path;
153
0
  }
154
0
  if (encoding) {
155
0
    delete encoding;
156
0
  }
157
0
}
158
159
//------------------------------------------------------------------------
160
// GfxFont
161
//------------------------------------------------------------------------
162
163
GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA,
164
0
         Ref idA, Dict *fontDict) {
165
0
  GString *nameA;
166
0
  Ref embFontIDA;
167
0
  GfxFontType typeA;
168
0
  GfxFont *font;
169
0
  Object obj1;
170
171
  // get base font name
172
0
  nameA = NULL;
173
0
  fontDict->lookup("BaseFont", &obj1);
174
0
  if (obj1.isName()) {
175
0
    nameA = new GString(obj1.getName());
176
0
  } else if (obj1.isString()) {
177
0
    nameA = obj1.getString()->copy();
178
0
  }
179
0
  obj1.free();
180
181
  // get embedded font ID and font type
182
0
  typeA = getFontType(xref, fontDict, &embFontIDA);
183
184
  // create the font object
185
0
  font = NULL;
186
0
  if (typeA < fontCIDType0) {
187
0
    font = new Gfx8BitFont(xref, tagA, idA, nameA, typeA, embFontIDA,
188
0
         fontDict);
189
0
  } else {
190
0
    font = new GfxCIDFont(xref, tagA, idA, nameA, typeA, embFontIDA,
191
0
        fontDict);
192
0
  }
193
194
0
  return font;
195
0
}
196
197
0
GfxFont *GfxFont::makeDefaultFont(XRef *xref) {
198
0
  Object type, subtype, baseFont;
199
0
  type.initName("Font");
200
0
  subtype.initName("Type1");
201
0
  baseFont.initName("Helvetica");
202
0
  Object fontDict;
203
0
  fontDict.initDict(xref);
204
0
  fontDict.dictAdd(copyString("Type"), &type);
205
0
  fontDict.dictAdd(copyString("Subtype"), &subtype);
206
0
  fontDict.dictAdd(copyString("BaseFont"), &baseFont);
207
208
0
  Ref r;
209
0
  r.gen = 100000;
210
0
  r.num = GfxFontDict::hashFontObject(&fontDict);
211
212
0
  GfxFont *font = makeFont(xref, "undef", r, fontDict.getDict());
213
0
  fontDict.free();
214
215
0
  return font;
216
0
}
217
218
GfxFont::GfxFont(const char *tagA, Ref idA, GString *nameA,
219
0
     GfxFontType typeA, Ref embFontIDA) {
220
0
  ok = gFalse;
221
0
  tag = new GString(tagA);
222
0
  id = idA;
223
0
  name = nameA;
224
0
  type = typeA;
225
0
  embFontID = embFontIDA;
226
0
  embFontName = NULL;
227
0
  hasToUnicode = gFalse;
228
0
}
229
230
0
GfxFont::~GfxFont() {
231
0
  delete tag;
232
0
  if (name) {
233
0
    delete name;
234
0
  }
235
0
  if (embFontName) {
236
0
    delete embFontName;
237
0
  }
238
0
}
239
240
// This function extracts three pieces of information:
241
// 1. the "expected" font type, i.e., the font type implied by
242
//    Font.Subtype, DescendantFont.Subtype, and
243
//    FontDescriptor.FontFile3.Subtype
244
// 2. the embedded font object ID
245
// 3. the actual font type - determined by examining the embedded font
246
//    if there is one, otherwise equal to the expected font type
247
// If the expected and actual font types don't match, a warning
248
// message is printed.  The expected font type is not used for
249
// anything else.
250
0
GfxFontType GfxFont::getFontType(XRef *xref, Dict *fontDict, Ref *embID) {
251
0
  GfxFontType t, expectedType;
252
0
  FoFiIdentifierType fft;
253
0
  Dict *fontDict2;
254
0
  Object subtype, fontDesc, obj1, obj2, obj3, obj4;
255
0
  GBool isType0, err;
256
257
0
  t = fontUnknownType;
258
0
  embID->num = embID->gen = -1;
259
0
  err = gFalse;
260
261
0
  fontDict->lookup("Subtype", &subtype);
262
0
  expectedType = fontUnknownType;
263
0
  isType0 = gFalse;
264
0
  if (subtype.isName("Type1") || subtype.isName("MMType1")) {
265
0
    expectedType = fontType1;
266
0
  } else if (subtype.isName("Type1C")) {
267
0
    expectedType = fontType1C;
268
0
  } else if (subtype.isName("Type3")) {
269
0
    expectedType = fontType3;
270
0
  } else if (subtype.isName("TrueType")) {
271
0
    expectedType = fontTrueType;
272
0
  } else if (subtype.isName("Type0")) {
273
0
    isType0 = gTrue;
274
0
  } else {
275
0
    error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
276
0
    subtype.isName() ? subtype.getName() : "???");
277
0
  }
278
0
  subtype.free();
279
280
0
  fontDict2 = fontDict;
281
0
  if (fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
282
0
    if (obj1.arrayGetLength() == 0) {
283
0
      error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
284
0
      obj2.initNull();
285
0
    } else if (obj1.arrayGet(0, &obj2)->isDict()) {
286
0
      if (!isType0) {
287
0
  error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
288
0
      }
289
0
      fontDict2 = obj2.getDict();
290
0
      fontDict2->lookup("Subtype", &subtype);
291
0
      if (subtype.isName("CIDFontType0")) {
292
0
  if (isType0) {
293
0
    expectedType = fontCIDType0;
294
0
  }
295
0
      } else if (subtype.isName("CIDFontType2")) {
296
0
  if (isType0) {
297
0
    expectedType = fontCIDType2;
298
0
  }
299
0
      }
300
0
      subtype.free();
301
0
    }
302
0
  } else {
303
0
    obj2.initNull();
304
0
  }
305
306
  // NB: the PDF spec doesn't say anything about precedence, but Adobe
307
  // uses FontFile3 over FontFile2 if both are present.
308
0
  if (fontDict2->lookup("FontDescriptor", &fontDesc)->isDict()) {
309
0
    if (fontDesc.dictLookupNF("FontFile3", &obj3)->isRef()) {
310
0
      *embID = obj3.getRef();
311
0
      if (obj3.fetch(xref, &obj4)->isStream()) {
312
0
  obj4.streamGetDict()->lookup("Subtype", &subtype);
313
0
  if (subtype.isName("Type1")) {
314
0
    if (expectedType != fontType1) {
315
0
      err = gTrue;
316
0
      expectedType = isType0 ? fontCIDType0 : fontType1;
317
0
    }
318
0
  } else if (subtype.isName("Type1C")) {
319
0
    if (expectedType == fontType1) {
320
0
      expectedType = fontType1C;
321
0
    } else if (expectedType != fontType1C) {
322
0
      err = gTrue;
323
0
      expectedType = isType0 ? fontCIDType0C : fontType1C;
324
0
    }
325
0
  } else if (subtype.isName("TrueType")) {
326
0
    if (expectedType != fontTrueType) {
327
0
      err = gTrue;
328
0
      expectedType = isType0 ? fontCIDType2 : fontTrueType;
329
0
    }
330
0
  } else if (subtype.isName("CIDFontType0C")) {
331
0
    if (expectedType == fontCIDType0) {
332
0
      expectedType = fontCIDType0C;
333
0
    } else {
334
0
      err = gTrue;
335
0
      expectedType = isType0 ? fontCIDType0C : fontType1C;
336
0
    }
337
0
  } else if (subtype.isName("OpenType")) {
338
0
    if (expectedType == fontTrueType) {
339
0
      expectedType = fontTrueTypeOT;
340
0
    } else if (expectedType == fontType1) {
341
0
      expectedType = fontType1COT;
342
0
    } else if (expectedType == fontCIDType0) {
343
0
      expectedType = fontCIDType0COT;
344
0
    } else if (expectedType == fontCIDType2) {
345
0
      expectedType = fontCIDType2OT;
346
0
    } else {
347
0
      err = gTrue;
348
0
    }
349
0
  } else {
350
0
    error(errSyntaxError, -1, "Unknown font type '{0:s}'",
351
0
    subtype.isName() ? subtype.getName() : "???");
352
0
  }
353
0
  subtype.free();
354
0
      }
355
0
      obj4.free();
356
0
    }
357
0
    obj3.free();
358
0
    if (embID->num == -1) {
359
0
      if (fontDesc.dictLookupNF("FontFile2", &obj3)->isRef()) {
360
0
  *embID = obj3.getRef();
361
0
  if (isType0) {
362
0
    expectedType = fontCIDType2;
363
0
  } else if (expectedType != fontTrueType) {
364
0
    err = gTrue;
365
0
  }
366
0
      }
367
0
      obj3.free();
368
0
    }
369
0
    if (embID->num == -1) {
370
0
      if (fontDesc.dictLookupNF("FontFile", &obj3)->isRef()) {
371
0
  *embID = obj3.getRef();
372
0
  if (expectedType != fontType1) {
373
0
    err = gTrue;
374
0
  }
375
0
      }
376
0
      obj3.free();
377
0
    }
378
0
  }
379
0
  fontDesc.free();
380
381
0
  t = fontUnknownType;
382
0
  if (embID->num >= 0) {
383
0
    obj3.initRef(embID->num, embID->gen);
384
0
    obj3.fetch(xref, &obj4);
385
0
    if (obj4.isStream()) {
386
0
      obj4.streamReset();
387
0
      fft = FoFiIdentifier::identifyStream(&readFromStream, obj4.getStream());
388
0
      obj4.streamClose();
389
0
      switch (fft) {
390
0
      case fofiIdType1PFA:
391
0
      case fofiIdType1PFB:
392
0
  t = fontType1;
393
0
  break;
394
0
      case fofiIdCFF8Bit:
395
0
  t = isType0 ? fontCIDType0C : fontType1C;
396
0
  break;
397
0
      case fofiIdCFFCID:
398
0
  t = fontCIDType0C;
399
0
  break;
400
0
      case fofiIdTrueType:
401
0
      case fofiIdTrueTypeCollection:
402
0
  t = isType0 ? fontCIDType2 : fontTrueType;
403
0
  break;
404
0
      case fofiIdOpenTypeCFF8Bit:
405
0
  t = isType0 ? fontCIDType0COT : fontType1COT;
406
0
  break;
407
0
      case fofiIdOpenTypeCFFCID:
408
0
  t = fontCIDType0COT;
409
0
  break;
410
0
      default:
411
0
  error(errSyntaxError, -1, "Embedded font file may be invalid");
412
0
  break;
413
0
      }
414
0
    } else {
415
0
      error(errSyntaxError, -1, "Embedded font object is wrong type");
416
0
    }
417
0
    obj4.free();
418
0
    obj3.free();
419
0
  }
420
421
  // If the embedded font doesn't exist, or it's not a stream object,
422
  // or we couldn't identify its type, then remove the reference so
423
  // nothing tries to use it later.
424
0
  if (t == fontUnknownType) {
425
0
    embID->num = -1;
426
0
    embID->gen = -1;
427
0
    t = expectedType;
428
0
  }
429
430
0
  if (t != expectedType) {
431
0
    err = gTrue;
432
0
  }
433
434
0
  if (err) {
435
0
    error(errSyntaxWarning, -1,
436
0
    "Mismatch between font type and embedded font file");
437
0
  }
438
439
0
  obj2.free();
440
0
  obj1.free();
441
442
0
  return t;
443
0
}
444
445
0
void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
446
0
  Object obj1, obj2, obj3, obj4;
447
0
  double t, t2;
448
0
  int i;
449
450
  // assume Times-Roman by default (for substitution purposes)
451
0
  flags = fontSerif;
452
453
0
  if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
454
455
    // get flags
456
0
    if (obj1.dictLookup("Flags", &obj2)->isInt()) {
457
0
      flags = obj2.getInt();
458
0
    }
459
0
    obj2.free();
460
461
    // get name
462
0
    obj1.dictLookup("FontName", &obj2);
463
0
    if (obj2.isName()) {
464
0
      embFontName = new GString(obj2.getName());
465
0
    }
466
0
    obj2.free();
467
468
    // look for MissingWidth
469
0
    obj1.dictLookup("MissingWidth", &obj2);
470
0
    if (obj2.isNum()) {
471
0
      missingWidth = obj2.getNum();
472
0
    }
473
0
    obj2.free();
474
475
    // font FontBBox
476
0
    if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
477
0
      for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
478
0
  if (obj2.arrayGet(i, &obj3)->isNum()) {
479
0
    fontBBox[i] = 0.001 * obj3.getNum();
480
0
  }
481
0
  obj3.free();
482
0
      }
483
0
    }
484
0
    obj2.free();
485
486
    // get Ascent (but also look at CapHeight)
487
0
    obj1.dictLookup("Ascent", &obj2);
488
0
    obj1.dictLookup("CapHeight", &obj3);
489
0
    if (obj2.isNum() || obj3.isNum()) {
490
0
      if (obj2.isNum()) {
491
0
  t = 0.001 * obj2.getNum();
492
  // some broken font descriptors specify a negative ascent
493
0
  if (t < 0) {
494
0
    t = -t;
495
0
  }
496
0
      } else {
497
0
  t = 0;
498
0
      }
499
0
      if (obj3.isNum()) {
500
0
  t2 = 0.001 * obj3.getNum();
501
  // some broken font descriptors specify a negative ascent
502
0
  if (t2 < 0) {
503
0
    t2 = -t2;
504
0
  }
505
0
      } else {
506
0
  t2 = 0;
507
0
      }
508
0
      if (t != 0 && t < 1.9) {
509
0
  declaredAscent = t;
510
0
      }
511
      // The ascent is generally expected to be in the (0.55, 1.9) range.
512
      // If Ascent and/or CapHeight is in that range, use the smaller one
513
      // (because the most common problem is that Ascent is too large).
514
      // Otherwise check for a value in (0, 0.55], and use that.
515
0
      if (t > 0.55 && t < 1.9) {
516
0
  if (t2 > 0.55 && t2 < 1.9) {
517
0
    ascent = (t < t2) ? t : t2;
518
0
  } else {
519
0
    ascent = t;
520
0
  }
521
0
      } else if (t2 > 0.55 && t2 < 1.9) {
522
0
  ascent = t2;
523
0
      } else if (fontBBox[3] > 0.55 && fontBBox[3] < 1.9 &&
524
0
     fontBBox[1] < fontBBox[3]) {
525
0
  ascent = fontBBox[3];
526
0
      } else if (t > 0 && t < 1.9) {
527
0
  ascent = t;
528
0
      } else if (t2 > 0 && t2 < 1.9) {
529
0
  ascent = t2;
530
0
      }
531
0
    }
532
0
    obj2.free();
533
0
    obj3.free();
534
535
    // get Descent
536
0
    obj1.dictLookup("Descent", &obj2);
537
0
    if (obj2.isNum()) {
538
0
      t = 0.001 * obj2.getNum();
539
      // some broken font descriptors specify a positive descent
540
0
      if (t > 0) {
541
0
  t = -t;
542
0
      }
543
      // some broken font descriptors set ascent and descent to 0
544
0
      if (t < 0 && t > -1.9) {
545
0
  descent = t;
546
0
      } else if (fontBBox[1] > -1.9 && fontBBox[1] <= 0 &&
547
0
     fontBBox[1] < fontBBox[3]) {
548
0
  descent = fontBBox[1];
549
0
      }
550
0
    }
551
0
    obj2.free();
552
553
0
  }
554
0
  obj1.free();
555
556
  // scan font name for bold/italic tags and update the flags
557
0
  if (name) {
558
0
    i = name->getLength();
559
0
    if (i > 2 && !strncmp(name->getCString() + i - 2, "MT", 2)) {
560
0
      i -= 2;
561
0
    }
562
0
    if (i > 6 && !strncmp(name->getCString() + i - 6, "Italic", 6)) {
563
0
      flags |= fontItalic;
564
0
      i -= 6;
565
0
    } else if (i > 2 && !strncmp(name->getCString() + i - 2, "It", 2)) {
566
0
      flags |= fontItalic;
567
0
      i -= 2;
568
0
    } else if (i > 7 && !strncmp(name->getCString() + i - 7, "Oblique", 7)) {
569
0
      flags |= fontItalic;
570
0
      i -= 7;
571
0
    }
572
0
    if (i > 0) {
573
0
      char c = name->getChar(i-1);
574
0
      if (!((c >= 'A' && c <= 'Z') ||
575
0
      (c >= 'a' && c <= 'z') ||
576
0
      (c >= '0' && c <= '9'))) {
577
0
  --i;
578
0
      }
579
0
    }
580
0
    if (i > 4 && !strncmp(name->getCString() + i - 4, "Bold", 4)) {
581
0
      flags |= fontBold;
582
0
    }
583
0
  }
584
0
}
585
586
CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits,
587
0
                CharCodeToUnicode *ctu) {
588
0
  GString *buf;
589
0
  Object obj1;
590
0
  char buf2[4096];
591
0
  int n;
592
593
0
  if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
594
0
    obj1.free();
595
0
    return NULL;
596
0
  }
597
0
  buf = new GString();
598
0
  obj1.streamReset();
599
0
  while ((n = obj1.streamGetBlock(buf2, sizeof(buf2))) > 0) {
600
0
    buf->append(buf2, n);
601
0
  }
602
0
  obj1.streamClose();
603
0
  obj1.free();
604
0
  if (ctu) {
605
0
    ctu->mergeCMap(buf, nBits);
606
0
  } else {
607
0
    ctu = CharCodeToUnicode::parseCMap(buf, nBits);
608
0
  }
609
0
  delete buf;
610
0
  hasToUnicode = gTrue;
611
0
  return ctu;
612
0
}
613
614
0
GfxFontLoc *GfxFont::locateFont(XRef *xref, GBool ps) {
615
0
  GfxFontLoc *fontLoc;
616
0
  SysFontType sysFontType;
617
0
  FoFiIdentifierType fft;
618
0
  GString *path, *base14Name, *substName;
619
0
  PSFontParam16 *psFont16;
620
0
  Object refObj, embFontObj;
621
0
  int substIdx, fontNum;
622
0
  double oblique;
623
0
  GBool embed;
624
625
0
  if (type == fontType3) {
626
0
    return NULL;
627
0
  }
628
629
  //----- embedded font
630
0
  if (embFontID.num >= 0) {
631
0
    embed = gTrue;
632
0
    refObj.initRef(embFontID.num, embFontID.gen);
633
0
    refObj.fetch(xref, &embFontObj);
634
0
    if (!embFontObj.isStream()) {
635
0
      error(errSyntaxError, -1, "Embedded font object is wrong type");
636
0
      embed = gFalse;
637
0
    }
638
0
    embFontObj.free();
639
0
    refObj.free();
640
0
    if (embed) {
641
0
      if (ps) {
642
0
  switch (type) {
643
0
  case fontType1:
644
0
  case fontType1C:
645
0
  case fontType1COT:
646
0
    embed = globalParams->getPSEmbedType1();
647
0
    break;
648
0
  case fontTrueType:
649
0
  case fontTrueTypeOT:
650
0
    embed = globalParams->getPSEmbedTrueType();
651
0
    break;
652
0
  case fontCIDType0C:
653
0
  case fontCIDType0COT:
654
0
    embed = globalParams->getPSEmbedCIDPostScript();
655
0
    break;
656
0
  case fontCIDType2:
657
0
  case fontCIDType2OT:
658
0
    embed = globalParams->getPSEmbedCIDTrueType();
659
0
    break;
660
0
  default:
661
0
    break;
662
0
  }
663
0
      }
664
0
      if (embed) {
665
0
  fontLoc = new GfxFontLoc();
666
0
  fontLoc->locType = gfxFontLocEmbedded;
667
0
  fontLoc->fontType = type;
668
0
  fontLoc->embFontID = embFontID;
669
0
  return fontLoc;
670
0
      }
671
0
    }
672
0
  }
673
674
  //----- PS passthrough
675
0
  if (ps && name && !isCIDFont() && globalParams->getPSFontPassthrough()) {
676
0
    fontLoc = new GfxFontLoc();
677
0
    fontLoc->locType = gfxFontLocResident;
678
0
    fontLoc->fontType = fontType1;
679
0
    fontLoc->path = name->copy();
680
0
    return fontLoc;
681
0
  }
682
683
  //----- external font file (fontFile, fontDir)
684
0
  if (name && (path = globalParams->findFontFile(name))) {
685
0
    if ((fontLoc = getExternalFont(path, 0, 0, isCIDFont()))) {
686
0
      return fontLoc;
687
0
    }
688
0
  }
689
690
  //----- PS resident Base-14 font
691
0
  if (ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
692
0
    fontLoc = new GfxFontLoc();
693
0
    fontLoc->locType = gfxFontLocResident;
694
0
    fontLoc->fontType = fontType1;
695
0
    fontLoc->path = new GString(((Gfx8BitFont *)this)->base14->base14Name);
696
0
    return fontLoc;
697
0
  }
698
699
  //----- external font file for Base-14 font
700
0
  if (!ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
701
0
    base14Name = new GString(((Gfx8BitFont *)this)->base14->base14Name);
702
0
    path = globalParams->findBase14FontFile(base14Name, &fontNum, &oblique);
703
0
    delete base14Name;
704
0
    if (path && (fontLoc = getExternalFont(path, fontNum, oblique, gFalse))) {
705
0
      return fontLoc;
706
0
    }
707
0
  }
708
709
  //----- system font
710
0
  if (name && (path = globalParams->findSystemFontFile(name, &sysFontType,
711
0
                   &fontNum))) {
712
0
    fontLoc = new GfxFontLoc();
713
0
    fontLoc->locType = gfxFontLocExternal;
714
0
    fontLoc->path = path;
715
0
    fontLoc->fontNum = fontNum;
716
0
    fft = FoFiIdentifier::identifyFile(fontLoc->path->getCString());
717
0
    switch (fft) {
718
0
    case fofiIdType1PFA:
719
0
    case fofiIdType1PFB:
720
0
      fontLoc->fontType = fontType1;
721
0
      break;
722
0
    case fofiIdCFF8Bit:
723
0
      fontLoc->fontType = fontType1C;
724
0
      break;
725
0
    case fofiIdCFFCID:
726
0
      fontLoc->fontType = fontCIDType0C;
727
0
      break;
728
0
    case fofiIdTrueType:
729
0
    case fofiIdTrueTypeCollection:
730
0
      fontLoc->fontType = isCIDFont() ? fontCIDType2 : fontTrueType;
731
0
      break;
732
0
    case fofiIdOpenTypeCFF8Bit:
733
0
      fontLoc->fontType = fontType1COT;
734
0
      break;
735
0
    case fofiIdOpenTypeCFFCID:
736
0
      fontLoc->fontType = fontCIDType0COT;
737
0
      break;
738
0
    case fofiIdDfont:
739
0
      fontLoc->fontType = isCIDFont() ? fontCIDType2 : fontTrueType;
740
0
      break;
741
0
    case fofiIdUnknown:
742
0
    case fofiIdError:
743
0
    default:
744
0
      delete fontLoc;
745
0
      fontLoc = NULL;
746
0
      break;
747
0
    }
748
0
    if (fontLoc) {
749
0
      return fontLoc;
750
0
    }
751
0
  }
752
753
0
  if (!isCIDFont()) {
754
755
    //----- 8-bit PS resident font
756
0
    if (ps) {
757
0
      if (name && (path = globalParams->getPSResidentFont(name))) {
758
0
  fontLoc = new GfxFontLoc();
759
0
  fontLoc->locType = gfxFontLocResident;
760
0
  fontLoc->fontType = fontType1;
761
0
  fontLoc->path = path;
762
0
  return fontLoc;
763
0
      }
764
0
    }
765
766
    //----- 8-bit font substitution
767
0
    if (flags & fontFixedWidth) {
768
0
      substIdx = 0;
769
0
    } else if (flags & fontSerif) {
770
0
      substIdx = 8;
771
0
    } else {
772
0
      substIdx = 4;
773
0
    }
774
0
    if (isBold()) {
775
0
      substIdx += 2;
776
0
    }
777
0
    if (isItalic()) {
778
0
      substIdx += 1;
779
0
    }
780
0
    substName = new GString(base14SubstFonts[substIdx]);
781
0
    if (ps) {
782
0
      error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:t}'",
783
0
      base14SubstFonts[substIdx], name);
784
0
      fontLoc = new GfxFontLoc();
785
0
      fontLoc->locType = gfxFontLocResident;
786
0
      fontLoc->fontType = fontType1;
787
0
      fontLoc->path = substName;
788
0
      fontLoc->substIdx = substIdx;
789
0
      return fontLoc;
790
0
    } else {
791
0
      path = globalParams->findBase14FontFile(substName, &fontNum, &oblique);
792
0
      delete substName;
793
0
      if (path) {
794
0
  if ((fontLoc = getExternalFont(path, fontNum, oblique, gFalse))) {
795
0
    error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:t}'",
796
0
    base14SubstFonts[substIdx], name);
797
0
    fontLoc->substIdx = substIdx;
798
0
    return fontLoc;
799
0
  }
800
0
      }
801
0
    }
802
803
    // failed to find a substitute font
804
0
    return NULL;
805
0
  }
806
807
  //----- 16-bit PS resident font
808
0
  if (ps && name && ((psFont16 = globalParams->getPSResidentFont16(
809
0
           name,
810
0
           ((GfxCIDFont *)this)->getWMode())))) {
811
0
    fontLoc = new GfxFontLoc();
812
0
    fontLoc->locType = gfxFontLocResident;
813
0
    fontLoc->fontType = fontCIDType0; // this is not used
814
0
    fontLoc->path = psFont16->psFontName->copy();
815
0
    fontLoc->encoding = psFont16->encoding->copy();
816
0
    fontLoc->wMode = psFont16->wMode;
817
0
    return fontLoc;
818
0
  }
819
0
  if (ps && ((psFont16 = globalParams->getPSResidentFontCC(
820
0
         ((GfxCIDFont *)this)->getCollection(),
821
0
         ((GfxCIDFont *)this)->getWMode())))) {
822
0
    error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
823
0
    psFont16->psFontName, name);
824
0
    fontLoc = new GfxFontLoc();
825
0
    fontLoc->locType = gfxFontLocResident;
826
0
    fontLoc->fontType = fontCIDType0; // this is not used
827
0
    fontLoc->path = psFont16->psFontName->copy();
828
0
    fontLoc->encoding = psFont16->encoding->copy();
829
0
    fontLoc->wMode = psFont16->wMode;
830
0
    return fontLoc;
831
0
  }
832
833
  //----- CID font substitution
834
0
  if ((path = globalParams->findCCFontFile(
835
0
        ((GfxCIDFont *)this)->getCollection()))) {
836
0
    if ((fontLoc = getExternalFont(path, 0, 0, gTrue))) {
837
0
      error(errSyntaxWarning, -1, "Substituting font '{0:t}' for '{1:t}'",
838
0
      fontLoc->path, name);
839
0
      return fontLoc;
840
0
    }
841
0
  }
842
843
  // failed to find a substitute font
844
0
  return NULL;
845
0
}
846
847
0
GfxFontLoc *GfxFont::locateBase14Font(GString *base14Name) {
848
0
  GString *path;
849
0
  int fontNum;
850
0
  double oblique;
851
852
0
  path = globalParams->findBase14FontFile(base14Name, &fontNum, &oblique);
853
0
  if (!path) {
854
0
    return NULL;
855
0
  }
856
0
  return getExternalFont(path, fontNum, oblique, gFalse);
857
0
}
858
859
GfxFontLoc *GfxFont::getExternalFont(GString *path, int fontNum,
860
0
             double oblique, GBool cid) {
861
0
  FoFiIdentifierType fft;
862
0
  GfxFontType fontType;
863
0
  GfxFontLoc *fontLoc;
864
865
0
  fft = FoFiIdentifier::identifyFile(path->getCString());
866
0
  switch (fft) {
867
0
  case fofiIdType1PFA:
868
0
  case fofiIdType1PFB:
869
0
    fontType = fontType1;
870
0
    break;
871
0
  case fofiIdCFF8Bit:
872
0
    fontType = fontType1C;
873
0
    break;
874
0
  case fofiIdCFFCID:
875
0
    fontType = fontCIDType0C;
876
0
    break;
877
0
  case fofiIdTrueType:
878
0
  case fofiIdTrueTypeCollection:
879
0
    fontType = cid ? fontCIDType2 : fontTrueType;
880
0
    break;
881
0
  case fofiIdOpenTypeCFF8Bit:
882
0
    fontType = fontType1COT;
883
0
    break;
884
0
  case fofiIdOpenTypeCFFCID:
885
0
    fontType = fontCIDType0COT;
886
0
    break;
887
0
  case fofiIdDfont:
888
0
    fontType = cid ? fontCIDType2 : fontTrueType;
889
0
    break;
890
0
  case fofiIdUnknown:
891
0
  case fofiIdError:
892
0
  default:
893
0
    fontType = fontUnknownType;
894
0
    break;
895
0
  }
896
0
  if (fontType == fontUnknownType ||
897
0
      (cid ? (fontType < fontCIDType0)
898
0
           : (fontType >= fontCIDType0))) {
899
0
    delete path;
900
0
    return NULL;
901
0
  }
902
0
  fontLoc = new GfxFontLoc();
903
0
  fontLoc->locType = gfxFontLocExternal;
904
0
  fontLoc->fontType = fontType;
905
0
  fontLoc->path = path;
906
0
  fontLoc->fontNum = fontNum;
907
0
  fontLoc->oblique = oblique;
908
0
  return fontLoc;
909
0
}
910
911
0
char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
912
0
  char *buf;
913
0
  Object obj1, obj2;
914
0
  Stream *str;
915
0
  int size, n;
916
917
0
  obj1.initRef(embFontID.num, embFontID.gen);
918
0
  obj1.fetch(xref, &obj2);
919
0
  if (!obj2.isStream()) {
920
0
    error(errSyntaxError, -1, "Embedded font file is not a stream");
921
0
    obj2.free();
922
0
    obj1.free();
923
0
    embFontID.num = -1;
924
0
    return NULL;
925
0
  }
926
0
  str = obj2.getStream();
927
928
0
  size = 4096;
929
0
  buf = (char *)gmalloc(size);
930
0
  *len = 0;
931
0
  str->reset();
932
0
  do {
933
0
    if (*len > size - 4096) {
934
0
      if (size > INT_MAX / 2) {
935
0
  error(errSyntaxError, -1, "Embedded font file is too large");
936
0
  break;
937
0
      }
938
0
      size *= 2;
939
0
      buf = (char *)grealloc(buf, size);
940
0
    }
941
0
    n = str->getBlock(buf + *len, 4096);
942
0
    *len += n;
943
0
  } while (n == 4096);
944
0
  str->close();
945
946
0
  obj2.free();
947
0
  obj1.free();
948
949
0
  return buf;
950
0
}
951
952
//------------------------------------------------------------------------
953
// Gfx8BitFont
954
//------------------------------------------------------------------------
955
956
Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
957
       GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
958
0
  GfxFont(tagA, idA, nameA, typeA, embFontIDA)
959
0
{
960
0
  GString *name2;
961
0
  BuiltinFont *builtinFont;
962
0
  const char **baseEnc;
963
0
  char *buf;
964
0
  int len;
965
0
  FoFiType1 *ffT1;
966
0
  FoFiType1C *ffT1C;
967
0
  int code, code2;
968
0
  char *charName;
969
0
  GBool missing, hex;
970
0
  Unicode toUnicode[256];
971
0
  CharCodeToUnicode *utu, *ctu2;
972
0
  Unicode uBuf[8];
973
0
  double mul;
974
0
  int firstChar, lastChar;
975
0
  Gushort w;
976
0
  Object obj1, obj2, obj3;
977
0
  int n, i, a, b, m;
978
979
0
  ctu = NULL;
980
981
  // do font name substitution for various aliases of the Base 14 font
982
  // names
983
0
  base14 = NULL;
984
0
  if (name) {
985
0
    name2 = name->copy();
986
0
    i = 0;
987
0
    while (i < name2->getLength()) {
988
0
      if (name2->getChar(i) == ' ') {
989
0
  name2->del(i);
990
0
      } else {
991
0
  ++i;
992
0
      }
993
0
    }
994
0
    a = 0;
995
0
    b = sizeof(base14FontMap) / sizeof(Base14FontMapEntry);
996
    // invariant: base14FontMap[a].altName <= name2 < base14FontMap[b].altName
997
0
    while (b - a > 1) {
998
0
      m = (a + b) / 2;
999
0
      if (name2->cmp(base14FontMap[m].altName) >= 0) {
1000
0
  a = m;
1001
0
      } else {
1002
0
  b = m;
1003
0
      }
1004
0
    }
1005
0
    if (!name2->cmp(base14FontMap[a].altName)) {
1006
0
      base14 = &base14FontMap[a];
1007
0
    }
1008
0
    delete name2;
1009
0
  }
1010
1011
  // is it a built-in font?
1012
0
  builtinFont = NULL;
1013
0
  if (base14) {
1014
0
    for (i = 0; i < nBuiltinFonts; ++i) {
1015
0
      if (!strcmp(base14->base14Name, builtinFonts[i].name)) {
1016
0
  builtinFont = &builtinFonts[i];
1017
0
  break;
1018
0
      }
1019
0
    }
1020
0
  }
1021
1022
  // default ascent/descent values
1023
0
  if (builtinFont) {
1024
0
    missingWidth = builtinFont->missingWidth;
1025
0
    ascent = 0.001 * builtinFont->ascent;
1026
0
    descent = 0.001 * builtinFont->descent;
1027
0
    declaredAscent = ascent;
1028
0
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
1029
0
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
1030
0
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
1031
0
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
1032
0
  } else {
1033
0
    missingWidth = 0;
1034
0
    ascent = 0.75;
1035
0
    descent = -0.25;
1036
0
    declaredAscent = ascent;
1037
0
    fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1038
0
  }
1039
1040
  // get info from font descriptor
1041
0
  readFontDescriptor(xref, fontDict);
1042
1043
  // for Base-14 fonts (even if embedded), don't trust the
1044
  // ascent/descent/bbox values from the font descriptor
1045
0
  if (builtinFont) {
1046
0
    ascent = 0.001 * builtinFont->ascent;
1047
0
    descent = 0.001 * builtinFont->descent;
1048
0
    declaredAscent = ascent;
1049
0
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
1050
0
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
1051
0
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
1052
0
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
1053
0
  }
1054
1055
  // get font matrix
1056
0
  fontMat[0] = fontMat[3] = 1;
1057
0
  fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
1058
0
  if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
1059
0
    for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
1060
0
      if (obj1.arrayGet(i, &obj2)->isNum()) {
1061
0
  fontMat[i] = obj2.getNum();
1062
0
      }
1063
0
      obj2.free();
1064
0
    }
1065
0
  }
1066
0
  obj1.free();
1067
1068
  // get Type 3 bounding box, font definition, and resources
1069
0
  if (type == fontType3) {
1070
0
    if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
1071
0
      for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
1072
0
  if (obj1.arrayGet(i, &obj2)->isNum()) {
1073
0
    fontBBox[i] = obj2.getNum();
1074
0
  }
1075
0
  obj2.free();
1076
0
      }
1077
0
    }
1078
0
    obj1.free();
1079
0
    if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
1080
0
      error(errSyntaxError, -1,
1081
0
      "Missing or invalid CharProcs dictionary in Type 3 font");
1082
0
      charProcs.free();
1083
0
    }
1084
0
    if (!fontDict->lookup("Resources", &resources)->isDict()) {
1085
0
      resources.free();
1086
0
    }
1087
0
  }
1088
1089
  //----- build the font encoding -----
1090
1091
  // Encodings start with a base encoding, which can come from
1092
  // (in order of priority):
1093
  //   1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
1094
  //        - MacRoman / MacExpert / WinAnsi / Standard
1095
  //   2. embedded or external font file
1096
  //   3. default:
1097
  //        - builtin --> builtin encoding
1098
  //        - TrueType --> WinAnsiEncoding
1099
  //        - others --> StandardEncoding
1100
  // and then add a list of differences (if any) from
1101
  // FontDict.Encoding.Differences.
1102
1103
  // check FontDict for base encoding
1104
0
  hasEncoding = gFalse;
1105
0
  usesMacRomanEnc = gFalse;
1106
0
  baseEnc = NULL;
1107
0
  baseEncFromFontFile = gFalse;
1108
0
  fontDict->lookup("Encoding", &obj1);
1109
0
  if (obj1.isDict()) {
1110
0
    obj1.dictLookup("BaseEncoding", &obj2);
1111
0
    if (obj2.isName("MacRomanEncoding")) {
1112
0
      hasEncoding = gTrue;
1113
0
      usesMacRomanEnc = gTrue;
1114
0
      baseEnc = macRomanEncoding;
1115
0
    } else if (obj2.isName("MacExpertEncoding")) {
1116
0
      hasEncoding = gTrue;
1117
0
      baseEnc = macExpertEncoding;
1118
0
    } else if (obj2.isName("WinAnsiEncoding")) {
1119
0
      hasEncoding = gTrue;
1120
0
      baseEnc = winAnsiEncoding;
1121
0
    }
1122
0
    obj2.free();
1123
0
  } else if (obj1.isName("MacRomanEncoding")) {
1124
0
    hasEncoding = gTrue;
1125
0
    usesMacRomanEnc = gTrue;
1126
0
    baseEnc = macRomanEncoding;
1127
0
  } else if (obj1.isName("MacExpertEncoding")) {
1128
0
    hasEncoding = gTrue;
1129
0
    baseEnc = macExpertEncoding;
1130
0
  } else if (obj1.isName("WinAnsiEncoding")) {
1131
0
    hasEncoding = gTrue;
1132
0
    baseEnc = winAnsiEncoding;
1133
0
  }
1134
1135
  // a non-embedded Symbol or ZapfDingbats font should never use one
1136
  // of the non-symbol encodings -- I've encountered PDF files that
1137
  // set the Encoding to WinAnsiEncoding, which doesn't make any sense
1138
  // (and other viewers also seem to ignore it)
1139
0
  if (builtinFont && embFontID.num < 0 &&
1140
0
      (builtinFont->defaultBaseEnc == symbolEncoding ||
1141
0
       builtinFont->defaultBaseEnc == zapfDingbatsEncoding) &&
1142
0
      !obj1.isDict()) {
1143
0
    baseEnc = NULL;
1144
0
  }
1145
1146
  // check embedded font file for base encoding
1147
  // (only for Type 1 fonts - trying to get an encoding out of a
1148
  // TrueType font is a losing proposition)
1149
0
  ffT1 = NULL;
1150
0
  ffT1C = NULL;
1151
0
  buf = NULL;
1152
0
  if (type == fontType1 && embFontID.num >= 0) {
1153
0
    if ((buf = readEmbFontFile(xref, &len))) {
1154
0
      if ((ffT1 = FoFiType1::make(buf, len))) {
1155
0
  if (ffT1->getName()) {
1156
0
    if (embFontName) {
1157
0
      delete embFontName;
1158
0
    }
1159
0
    embFontName = new GString(ffT1->getName());
1160
0
  }
1161
0
  if (!baseEnc) {
1162
0
    baseEnc = (const char **)ffT1->getEncoding();
1163
0
    baseEncFromFontFile = gTrue;
1164
0
  }
1165
0
      }
1166
0
      gfree(buf);
1167
0
    }
1168
0
  } else if (type == fontType1C && embFontID.num >= 0) {
1169
0
    if ((buf = readEmbFontFile(xref, &len))) {
1170
0
      if ((ffT1C = FoFiType1C::make(buf, len))) {
1171
0
  if (ffT1C->getName()) {
1172
0
    if (embFontName) {
1173
0
      delete embFontName;
1174
0
    }
1175
0
    embFontName = new GString(ffT1C->getName());
1176
0
  }
1177
0
  if (!baseEnc) {
1178
0
    baseEnc = (const char **)ffT1C->getEncoding();
1179
0
    baseEncFromFontFile = gTrue;
1180
0
  }
1181
0
      }
1182
0
      gfree(buf);
1183
0
    }
1184
0
  }
1185
1186
  // get default base encoding
1187
0
  if (!baseEnc) {
1188
0
    if (builtinFont && embFontID.num < 0) {
1189
0
      baseEnc = builtinFont->defaultBaseEnc;
1190
0
      hasEncoding = gTrue;
1191
0
    } else if (type == fontTrueType) {
1192
0
      baseEnc = winAnsiEncoding;
1193
0
    } else {
1194
0
      baseEnc = standardEncoding;
1195
0
    }
1196
0
  }
1197
1198
  // copy the base encoding
1199
0
  for (i = 0; i < 256; ++i) {
1200
0
    enc[i] = (char *)baseEnc[i];
1201
0
    if ((encFree[i] = (char)baseEncFromFontFile) && enc[i]) {
1202
0
      enc[i] = copyString(baseEnc[i]);
1203
0
    }
1204
0
  }
1205
1206
  // some Type 1C font files have empty encodings, which can break the
1207
  // T1C->T1 conversion (since the 'seac' operator depends on having
1208
  // the accents in the encoding), so we fill in any gaps from
1209
  // StandardEncoding
1210
0
  if (type == fontType1C && embFontID.num >= 0 && baseEncFromFontFile) {
1211
0
    for (i = 0; i < 256; ++i) {
1212
0
      if (!enc[i] && standardEncoding[i]) {
1213
0
  enc[i] = (char *)standardEncoding[i];
1214
0
  encFree[i] = gFalse;
1215
0
      }
1216
0
    }
1217
0
  }
1218
1219
  // merge differences into encoding
1220
0
  if (obj1.isDict()) {
1221
0
    obj1.dictLookup("Differences", &obj2);
1222
0
    if (obj2.isArray()) {
1223
0
      hasEncoding = gTrue;
1224
0
      code = 0;
1225
0
      for (i = 0; i < obj2.arrayGetLength(); ++i) {
1226
0
  obj2.arrayGet(i, &obj3);
1227
0
  if (obj3.isInt()) {
1228
0
    code = obj3.getInt();
1229
0
  } else if (obj3.isName()) {
1230
0
    if (code >= 0 && code < 256) {
1231
0
      if (encFree[code]) {
1232
0
        gfree(enc[code]);
1233
0
      }
1234
0
      enc[code] = copyString(obj3.getName());
1235
0
      encFree[code] = gTrue;
1236
0
    }
1237
0
    ++code;
1238
0
  } else {
1239
0
    error(errSyntaxError, -1,
1240
0
    "Wrong type in font encoding resource differences ({0:s})",
1241
0
    obj3.getTypeName());
1242
0
  }
1243
0
  obj3.free();
1244
0
      }
1245
0
    }
1246
0
    obj2.free();
1247
0
  }
1248
0
  obj1.free();
1249
0
  if (ffT1) {
1250
0
    delete ffT1;
1251
0
  }
1252
0
  if (ffT1C) {
1253
0
    delete ffT1C;
1254
0
  }
1255
1256
  //----- build the mapping to Unicode -----
1257
1258
  // pass 1: use the name-to-Unicode mapping table
1259
0
  missing = hex = gFalse;
1260
0
  for (code = 0; code < 256; ++code) {
1261
0
    if ((charName = enc[code])) {
1262
0
      if (!(toUnicode[code] = globalParams->mapNameToUnicode(charName)) &&
1263
0
    strcmp(charName, ".notdef")) {
1264
  // if it wasn't in the name-to-Unicode table, check for a
1265
  // name that looks like 'Axx' or 'xx', where 'A' is any letter
1266
  // and 'xx' is two hex digits
1267
0
  if ((strlen(charName) == 3 &&
1268
0
       isalpha(charName[0] & 0xff) &&
1269
0
       isxdigit(charName[1] & 0xff) && isxdigit(charName[2] & 0xff) &&
1270
0
       ((charName[1] >= 'a' && charName[1] <= 'f') ||
1271
0
        (charName[1] >= 'A' && charName[1] <= 'F') ||
1272
0
        (charName[2] >= 'a' && charName[2] <= 'f') ||
1273
0
        (charName[2] >= 'A' && charName[2] <= 'F'))) ||
1274
0
      (strlen(charName) == 2 &&
1275
0
       isxdigit(charName[0] & 0xff) && isxdigit(charName[1] & 0xff) &&
1276
0
       ((charName[0] >= 'a' && charName[0] <= 'f') ||
1277
0
        (charName[0] >= 'A' && charName[0] <= 'F') ||
1278
0
        (charName[1] >= 'a' && charName[1] <= 'f') ||
1279
0
        (charName[1] >= 'A' && charName[1] <= 'F')))) {
1280
0
    hex = gTrue;
1281
0
  }
1282
0
  missing = gTrue;
1283
0
      }
1284
0
    } else {
1285
0
      toUnicode[code] = 0;
1286
0
    }
1287
0
  }
1288
1289
  // pass 2: try to fill in the missing chars, looking for names of
1290
  // any of the following forms:
1291
  // - 'xx'
1292
  // - 'Axx'
1293
  // - 'nn'
1294
  // - 'Ann'
1295
  // - 'ABnn'
1296
  // - 'unixxxx' (possibly followed by garbage - some Arabic files
1297
  //             use 'uni0628.medi', etc.)
1298
  // where 'A' and 'B' are any letters, 'xx' is two hex digits, 'xxxx'
1299
  // is four hex digits, and 'nn' is 2-4 decimal digits
1300
0
  usedNumericHeuristic = gFalse;
1301
0
  if (missing && globalParams->getMapNumericCharNames()) {
1302
0
    for (code = 0; code < 256; ++code) {
1303
0
      if ((charName = enc[code]) && !toUnicode[code] &&
1304
0
    strcmp(charName, ".notdef")) {
1305
0
  n = (int)strlen(charName);
1306
0
  code2 = -1;
1307
0
  if (hex && n == 3 && isalpha(charName[0] & 0xff) &&
1308
0
      isxdigit(charName[1] & 0xff) && isxdigit(charName[2] & 0xff)) {
1309
0
    sscanf(charName+1, "%x", &code2);
1310
0
  } else if (hex && n == 2 &&
1311
0
       isxdigit(charName[0] & 0xff) &&
1312
0
       isxdigit(charName[1] & 0xff)) {
1313
0
    sscanf(charName, "%x", &code2);
1314
0
  } else if (!hex && n >= 2 && n <= 4 &&
1315
0
       isdigit(charName[0] & 0xff) && isdigit(charName[1] & 0xff)) {
1316
0
    code2 = atoi(charName);
1317
0
  } else if (n >= 3 && n <= 5 &&
1318
0
       isdigit(charName[1] & 0xff) && isdigit(charName[2] & 0xff)) {
1319
0
    code2 = atoi(charName+1);
1320
0
  } else if (n >= 4 && n <= 6 &&
1321
0
       isdigit(charName[2] & 0xff) && isdigit(charName[3] & 0xff)) {
1322
0
    code2 = atoi(charName+2);
1323
0
  } else if (n >= 7 && charName[0] == 'u' && charName[1] == 'n' &&
1324
0
       charName[2] == 'i' &&
1325
0
       isxdigit(charName[3] & 0xff) &&
1326
0
       isxdigit(charName[4] & 0xff) &&
1327
0
       isxdigit(charName[5] & 0xff) &&
1328
0
       isxdigit(charName[6] & 0xff)) {
1329
0
    sscanf(charName + 3, "%x", &code2);
1330
0
  }
1331
0
  if (code2 >= 0 && code2 <= 0xffff) {
1332
0
    toUnicode[code] = (Unicode)code2;
1333
0
    usedNumericHeuristic = gTrue;
1334
0
  }
1335
0
      }
1336
0
    }
1337
1338
  // if the 'mapUnknownCharNames' flag is set, do a simple pass-through
1339
  // mapping for unknown character names
1340
0
  } else if (missing && globalParams->getMapUnknownCharNames()) {
1341
0
    for (code = 0; code < 256; ++code) {
1342
0
      if (!toUnicode[code]) {
1343
0
  toUnicode[code] = code;
1344
0
      }
1345
0
    }
1346
0
  }
1347
1348
  // construct the char code -> Unicode mapping object
1349
0
  ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1350
1351
  // merge in a ToUnicode CMap, if there is one -- this overwrites
1352
  // existing entries in ctu, i.e., the ToUnicode CMap takes
1353
  // precedence, but the other encoding info is allowed to fill in any
1354
  // holes
1355
0
  readToUnicodeCMap(fontDict, 8, ctu);
1356
1357
  // look for a Unicode-to-Unicode mapping
1358
0
  if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1359
0
    for (i = 0; i < 256; ++i) {
1360
0
      toUnicode[i] = 0;
1361
0
    }
1362
0
    ctu2 = CharCodeToUnicode::make8BitToUnicode(toUnicode);
1363
0
    for (i = 0; i < 256; ++i) {
1364
0
      n = ctu->mapToUnicode((CharCode)i, uBuf, 8);
1365
0
      if (n >= 1) {
1366
0
  n = utu->mapToUnicode((CharCode)uBuf[0], uBuf, 8);
1367
0
  if (n >= 1) {
1368
0
    ctu2->setMapping((CharCode)i, uBuf, n);
1369
0
  }
1370
0
      }
1371
0
    }
1372
0
    utu->decRefCnt();
1373
0
    delete ctu;
1374
0
    ctu = ctu2;
1375
0
  }
1376
1377
  //----- get the character widths -----
1378
1379
  // initialize all widths
1380
0
  for (code = 0; code < 256; ++code) {
1381
0
    widths[code] = missingWidth * 0.001;
1382
0
  }
1383
1384
  // use widths from font dict, if present
1385
0
  fontDict->lookup("FirstChar", &obj1);
1386
0
  firstChar = obj1.isInt() ? obj1.getInt() : 0;
1387
0
  obj1.free();
1388
0
  if (firstChar < 0 || firstChar > 255) {
1389
0
    firstChar = 0;
1390
0
  }
1391
0
  fontDict->lookup("LastChar", &obj1);
1392
0
  lastChar = obj1.isInt() ? obj1.getInt() : 255;
1393
0
  obj1.free();
1394
0
  if (lastChar < 0 || lastChar > 255) {
1395
0
    lastChar = 255;
1396
0
  }
1397
0
  mul = (type == fontType3) ? fontMat[0] : 0.001;
1398
0
  fontDict->lookup("Widths", &obj1);
1399
0
  if (obj1.isArray()) {
1400
0
    flags |= fontFixedWidth;
1401
0
    if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
1402
0
      lastChar = firstChar + obj1.arrayGetLength() - 1;
1403
0
    }
1404
0
    for (code = firstChar; code <= lastChar; ++code) {
1405
0
      obj1.arrayGet(code - firstChar, &obj2);
1406
0
      if (obj2.isNum()) {
1407
0
  widths[code] = obj2.getNum() * mul;
1408
0
  if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
1409
0
    flags &= ~fontFixedWidth;
1410
0
  }
1411
0
      }
1412
0
      obj2.free();
1413
0
    }
1414
1415
  // use widths from built-in font
1416
0
  } else if (builtinFont) {
1417
    // this is a kludge for broken PDF files that encode char 32
1418
    // as .notdef
1419
0
    if (builtinFont->widths->getWidth("space", &w)) {
1420
0
      widths[32] = 0.001 * w;
1421
0
    }
1422
0
    for (code = 0; code < 256; ++code) {
1423
0
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1424
0
  widths[code] = 0.001 * w;
1425
0
      }
1426
0
    }
1427
1428
  // couldn't find widths -- use defaults 
1429
0
  } else {
1430
    // this is technically an error -- the Widths entry is required
1431
    // for all but the Base-14 fonts -- but certain PDF generators
1432
    // apparently don't include widths for Arial and TimesNewRoman
1433
0
    if (isFixedWidth()) {
1434
0
      i = 0;
1435
0
    } else if (isSerif()) {
1436
0
      i = 8;
1437
0
    } else {
1438
0
      i = 4;
1439
0
    }
1440
0
    if (isBold()) {
1441
0
      i += 2;
1442
0
    }
1443
0
    if (isItalic()) {
1444
0
      i += 1;
1445
0
    }
1446
0
    builtinFont = builtinFontSubst[i];
1447
    // this is a kludge for broken PDF files that encode char 32
1448
    // as .notdef
1449
0
    if (builtinFont->widths->getWidth("space", &w)) {
1450
0
      widths[32] = 0.001 * w;
1451
0
    }
1452
0
    for (code = 0; code < 256; ++code) {
1453
0
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1454
0
  widths[code] = 0.001 * w;
1455
0
      }
1456
0
    }
1457
0
  }
1458
0
  obj1.free();
1459
1460
0
  ok = gTrue;
1461
0
}
1462
1463
0
Gfx8BitFont::~Gfx8BitFont() {
1464
0
  int i;
1465
1466
0
  for (i = 0; i < 256; ++i) {
1467
0
    if (encFree[i] && enc[i]) {
1468
0
      gfree(enc[i]);
1469
0
    }
1470
0
  }
1471
0
  ctu->decRefCnt();
1472
0
  if (charProcs.isDict()) {
1473
0
    charProcs.free();
1474
0
  }
1475
0
  if (resources.isDict()) {
1476
0
    resources.free();
1477
0
  }
1478
0
}
1479
1480
int Gfx8BitFont::getNextChar(char *s, int len, CharCode *code,
1481
           Unicode *u, int uSize, int *uLen,
1482
0
           double *dx, double *dy, double *ox, double *oy) {
1483
0
  CharCode c;
1484
1485
0
  *code = c = (CharCode)(*s & 0xff);
1486
0
  *uLen = ctu->mapToUnicode(c, u, uSize);
1487
0
  *dx = widths[c];
1488
0
  *dy = *ox = *oy = 0;
1489
0
  return 1;
1490
0
}
1491
1492
0
CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
1493
0
  ctu->incRefCnt();
1494
0
  return ctu;
1495
0
}
1496
1497
0
int *Gfx8BitFont::getCodeToGIDMap(FoFiTrueType *ff) {
1498
0
  int *map;
1499
0
  int cmapPlatform, cmapEncoding;
1500
0
  int unicodeCmap, macRomanCmap, macUnicodeCmap, msSymbolCmap, cmap;
1501
0
  GBool nonsymbolic, useMacRoman, useUnicode;
1502
0
  char *charName;
1503
0
  Unicode u;
1504
0
  int code, i, n;
1505
1506
0
  map = (int *)gmallocn(256, sizeof(int));
1507
0
  for (i = 0; i < 256; ++i) {
1508
0
    map[i] = 0;
1509
0
  }
1510
1511
  // This is based on the cmap/encoding selection algorithm in the PDF
1512
  // 2.0 spec, but with some differences to match up with Adobe's
1513
  // behavior.
1514
0
  unicodeCmap = macRomanCmap = macUnicodeCmap = msSymbolCmap = -1;
1515
0
  for (i = 0; i < ff->getNumCmaps(); ++i) {
1516
0
    cmapPlatform = ff->getCmapPlatform(i);
1517
0
    cmapEncoding = ff->getCmapEncoding(i);
1518
0
    if (cmapPlatform == 3 && cmapEncoding == 1) {
1519
0
      unicodeCmap = i;
1520
0
    } else if (cmapPlatform == 1 && cmapEncoding == 0) {
1521
0
      macRomanCmap = i;
1522
0
    } else if (cmapPlatform == 0 && cmapEncoding <= 4) {
1523
0
      macUnicodeCmap = i;
1524
0
    } else if (cmapPlatform == 3 && cmapEncoding == 0) {
1525
0
      msSymbolCmap = i;
1526
0
    }
1527
0
  }
1528
0
  useMacRoman = gFalse;
1529
0
  useUnicode = gFalse;
1530
0
  nonsymbolic = !(flags & fontSymbolic);
1531
0
  if (embFontID.num < 0 && hasEncoding && unicodeCmap >= 0) { 
1532
0
    cmap = unicodeCmap;
1533
0
    useUnicode = gTrue;
1534
0
  } else if (!nonsymbolic && msSymbolCmap >= 0) {
1535
0
    cmap = msSymbolCmap;
1536
0
  } else if (unicodeCmap >= 0) {
1537
0
    cmap = unicodeCmap;
1538
0
    useUnicode = nonsymbolic;
1539
0
  } else if (usesMacRomanEnc && macRomanCmap >= 0) {
1540
    // MacRoman cmap has higher precedence than Mac Unicode only if
1541
    // the font uses the MacRoman encoding
1542
0
    cmap = macRomanCmap;
1543
0
    useMacRoman = gTrue;
1544
0
  } else if (macUnicodeCmap >= 0) {
1545
0
    cmap = macUnicodeCmap;
1546
0
    useUnicode = nonsymbolic;
1547
0
  } else if (macRomanCmap >= 0) {
1548
0
    cmap = macRomanCmap;
1549
0
    useMacRoman = nonsymbolic;
1550
0
  } else {
1551
0
    cmap = 0;
1552
0
  }
1553
1554
  // reverse map the char names through MacRomanEncoding, then map the
1555
  // char codes through the cmap; fall back on Unicode if that doesn't
1556
  // work
1557
0
  if (useMacRoman) {
1558
0
    for (i = 0; i < 256; ++i) {
1559
0
      if ((charName = enc[i])) {
1560
0
  if ((code = globalParams->getMacRomanCharCode(charName))) {
1561
0
    map[i] = ff->mapCodeToGID(cmap, code);
1562
0
  } else if (unicodeCmap >= 0 &&
1563
0
       (u = globalParams->mapNameToUnicode(charName))) {
1564
0
    map[i] = ff->mapCodeToGID(unicodeCmap, u);
1565
0
  }
1566
0
      } else if (unicodeCmap >= 0 &&
1567
0
     (n = ctu->mapToUnicode((CharCode)i, &u, 1))) {
1568
0
  map[i] = ff->mapCodeToGID(cmap, u);
1569
0
      } else {
1570
0
  map[i] = -1;
1571
0
      }
1572
0
    }
1573
1574
  // map Unicode through the cmap
1575
0
  } else if (useUnicode) {
1576
0
    for (i = 0; i < 256; ++i) {
1577
0
      if (((charName = enc[i]) &&
1578
0
     (u = globalParams->mapNameToUnicode(charName))) ||
1579
0
    (n = ctu->mapToUnicode((CharCode)i, &u, 1))) {
1580
0
  map[i] = ff->mapCodeToGID(cmap, u);
1581
0
      } else {
1582
0
  map[i] = -1;
1583
0
      }
1584
0
    }
1585
1586
  // map the char codes through the cmap, possibly with an offset of
1587
  // 0xf000
1588
0
  } else {
1589
0
    for (i = 0; i < 256; ++i) {
1590
0
      if (!(map[i] = ff->mapCodeToGID(cmap, i))) {
1591
0
  map[i] = ff->mapCodeToGID(cmap, 0xf000 + i);
1592
0
      }
1593
0
    }
1594
0
  }
1595
1596
  // try the TrueType 'post' table to handle any unmapped characters
1597
0
  for (i = 0; i < 256; ++i) {
1598
0
    if (map[i] <= 0 && (charName = enc[i])) {
1599
0
      map[i] = ff->mapNameToGID(charName);
1600
0
    }
1601
0
  }
1602
1603
0
  return map;
1604
0
}
1605
1606
0
int *Gfx8BitFont::getCodeToGIDMap(FoFiType1C *ff) {
1607
0
  int *map;
1608
0
  GHash *nameToGID;
1609
0
  int i, gid;
1610
1611
0
  map = (int *)gmallocn(256, sizeof(int));
1612
0
  for (i = 0; i < 256; ++i) {
1613
0
    map[i] = 0;
1614
0
  }
1615
1616
0
  nameToGID = ff->getNameToGIDMap();
1617
0
  for (i = 0; i < 256; ++i) {
1618
0
    if (!enc[i]) {
1619
0
      continue;
1620
0
    }
1621
0
    gid = nameToGID->lookupInt(enc[i]);
1622
0
    if (gid < 0 || gid >= 65536) {
1623
0
      continue;
1624
0
    }
1625
0
    map[i] = gid;
1626
0
  }
1627
1628
0
  delete nameToGID;
1629
1630
0
  return map;
1631
0
}
1632
1633
0
Dict *Gfx8BitFont::getCharProcs() {
1634
0
  return charProcs.isDict() ? charProcs.getDict() : (Dict *)NULL;
1635
0
}
1636
1637
0
Object *Gfx8BitFont::getCharProc(int code, Object *proc) {
1638
0
  if (enc[code] && charProcs.isDict()) {
1639
0
    charProcs.dictLookup(enc[code], proc);
1640
0
  } else {
1641
0
    proc->initNull();
1642
0
  }
1643
0
  return proc;
1644
0
}
1645
1646
0
Object *Gfx8BitFont::getCharProcNF(int code, Object *proc) {
1647
0
  if (enc[code] && charProcs.isDict()) {
1648
0
    charProcs.dictLookupNF(enc[code], proc);
1649
0
  } else {
1650
0
    proc->initNull();
1651
0
  }
1652
0
  return proc;
1653
0
}
1654
1655
0
Dict *Gfx8BitFont::getResources() {
1656
0
  return resources.isDict() ? resources.getDict() : (Dict *)NULL;
1657
0
}
1658
1659
0
GBool Gfx8BitFont::problematicForUnicode() {
1660
0
  GString *nameLC;
1661
0
  GBool symbolic;
1662
1663
  // potential inputs:
1664
  // - font is embedded (GfxFont.embFontID.num >= 0)
1665
  // - font name (GfxFont.name)
1666
  // - font type (GfxFont.type)
1667
  // - Base-14 font (Gfx8BitFont.base14 != NULL)
1668
  // - symbolic (GfxFont.flags & fontSymbolic)
1669
  // - has Encoding array (Gfx8BitFont.hasEncoding)
1670
  // - extracted base encoding from embedded font file
1671
  //   (Gfx8BitFont.baseEncFromFontFile)
1672
  // - has a ToUnicode map (GfxFont.hasToUnicode)
1673
  // - used the numeric glyph name heuristic
1674
  //   (Gfx8BitFont.usedNumericHeuristic)
1675
1676
0
  if (name) {
1677
0
    nameLC = name->copy();
1678
0
    nameLC->lowerCase();
1679
0
    symbolic = strstr(nameLC->getCString(), "dingbat") ||
1680
0
               strstr(nameLC->getCString(), "wingding") ||
1681
0
               strstr(nameLC->getCString(), "commpi");
1682
0
    delete nameLC;
1683
0
    if (symbolic) {
1684
0
      return gFalse;
1685
0
    }
1686
0
  }
1687
1688
0
  if (embFontID.num >= 0) {
1689
0
    switch (type) {
1690
0
    case fontType1:
1691
0
    case fontType1C:
1692
0
    case fontType1COT:
1693
0
      return !hasToUnicode && (!hasEncoding || usedNumericHeuristic);
1694
1695
0
    case fontType3:
1696
      // this never happens -- Type 3 fonts don't set embFontID
1697
0
      return !hasToUnicode && (!hasEncoding || usedNumericHeuristic);
1698
1699
0
    case fontTrueType:
1700
0
    case fontTrueTypeOT:
1701
0
      return !hasToUnicode && !hasEncoding;
1702
1703
0
    default:
1704
0
      return !hasToUnicode;
1705
0
    }
1706
1707
0
  } else if (type == fontType3) {
1708
0
    return !hasToUnicode && (!hasEncoding || usedNumericHeuristic);
1709
1710
0
  } else {
1711
    // NB: type will be fontTypeUnknown if the PDF specifies an
1712
    // invalid font type -- which is ok, if we have a ToUnicode map or
1713
    // an encoding
1714
0
    return !hasToUnicode && !hasEncoding;
1715
0
  }
1716
0
}
1717
1718
0
GBool Gfx8BitFont::parensAreSwapped(XRef *xref) {
1719
0
  return gFalse;
1720
0
}
1721
1722
//------------------------------------------------------------------------
1723
// GfxCIDFont
1724
//------------------------------------------------------------------------
1725
1726
GfxCIDFont::GfxCIDFont(XRef *xref, const char *tagA, Ref idA, GString *nameA,
1727
           GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
1728
0
  GfxFont(tagA, idA, nameA, typeA, embFontIDA)
1729
0
{
1730
0
  Dict *desFontDict;
1731
0
  Object desFontDictObj;
1732
0
  Object obj1, obj2, obj3, obj4, obj5, obj6;
1733
0
  CharCodeToUnicode *utu;
1734
0
  CharCode c;
1735
0
  Unicode uBuf[8];
1736
0
  int c1, c2;
1737
0
  int excepsSize, i, j, k, n;
1738
1739
0
  missingWidth = 0;
1740
0
  ascent = 0.95;
1741
0
  descent = -0.35;
1742
0
  declaredAscent = ascent;
1743
0
  fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1744
0
  collection = NULL;
1745
0
  cMap = NULL;
1746
0
  ctu = NULL;
1747
0
  ctuUsesCharCode = gTrue;
1748
0
  widths.defWidth = 1.0;
1749
0
  widths.defHeight = -1.0;
1750
0
  widths.defVY = 0.880;
1751
0
  widths.exceps = NULL;
1752
0
  widths.nExceps = 0;
1753
0
  widths.excepsV = NULL;
1754
0
  widths.nExcepsV = 0;
1755
0
  cidToGID = NULL;
1756
0
  cidToGIDLen = 0;
1757
1758
  // get the descendant font
1759
0
  if (!fontDict->lookup("DescendantFonts", &obj1)->isArray() ||
1760
0
      obj1.arrayGetLength() == 0) {
1761
0
    error(errSyntaxError, -1,
1762
0
    "Missing or empty DescendantFonts entry in Type 0 font");
1763
0
    obj1.free();
1764
0
    goto err1;
1765
0
  }
1766
0
  if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
1767
0
    error(errSyntaxError, -1, "Bad descendant font in Type 0 font");
1768
0
    goto err2;
1769
0
  }
1770
0
  obj1.free();
1771
0
  desFontDict = desFontDictObj.getDict();
1772
1773
  // get info from font descriptor
1774
0
  readFontDescriptor(xref, desFontDict);
1775
1776
  //----- encoding info -----
1777
1778
  // char collection
1779
0
  if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
1780
0
    error(errSyntaxError, -1,
1781
0
    "Missing CIDSystemInfo dictionary in Type 0 descendant font");
1782
0
    goto err2;
1783
0
  }
1784
0
  obj1.dictLookup("Registry", &obj2);
1785
0
  obj1.dictLookup("Ordering", &obj3);
1786
0
  if (!obj2.isString() || !obj3.isString()) {
1787
0
    error(errSyntaxError, -1,
1788
0
    "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
1789
0
    goto err3;
1790
0
  }
1791
0
  collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
1792
0
  obj3.free();
1793
0
  obj2.free();
1794
0
  obj1.free();
1795
1796
  // encoding (i.e., CMap)
1797
0
  if (fontDict->lookup("Encoding", &obj1)->isNull()) {
1798
0
    error(errSyntaxError, -1, "Missing Encoding entry in Type 0 font");
1799
0
    goto err2;
1800
0
  }
1801
0
  if (!(cMap = CMap::parse(NULL, collection, &obj1))) {
1802
0
    goto err2;
1803
0
  }
1804
1805
  // check for fonts that use the Identity-H encoding (cmap), and the
1806
  // Adobe-Identity character collection
1807
0
  identityEnc = obj1.isName("Identity-H") &&
1808
0
                !collection->cmp("Adobe-Identity");
1809
1810
0
  obj1.free();
1811
1812
  // CIDToGIDMap
1813
  // (the PDF 1.7 spec only allows these for TrueType fonts, but
1814
  // Acrobat apparently also allows them for OpenType CFF fonts -- and
1815
  // the PDF 2.0 spec has removed the prohibition)
1816
0
  hasIdentityCIDToGID = gFalse;
1817
0
  desFontDict->lookup("CIDToGIDMap", &obj1);
1818
0
  if (obj1.isStream()) {
1819
0
    cidToGIDLen = 0;
1820
0
    i = 64;
1821
0
    cidToGID = (int *)gmallocn(i, sizeof(int));
1822
0
    obj1.streamReset();
1823
0
    while ((c1 = obj1.streamGetChar()) != EOF &&
1824
0
     (c2 = obj1.streamGetChar()) != EOF) {
1825
0
      if (cidToGIDLen == i) {
1826
0
  i *= 2;
1827
0
  cidToGID = (int *)greallocn(cidToGID, i, sizeof(int));
1828
0
      }
1829
0
      cidToGID[cidToGIDLen++] = (c1 << 8) + c2;
1830
0
    }
1831
0
    obj1.streamClose();
1832
0
    identityEnc = gFalse;
1833
0
  } else if (obj1.isName("Identity")) {
1834
0
    hasIdentityCIDToGID = gTrue;
1835
0
  } else if (!obj1.isNull()) {
1836
0
    error(errSyntaxError, -1, "Invalid CIDToGIDMap entry in CID font");
1837
0
  }
1838
0
  obj1.free();
1839
1840
  // look for a ToUnicode CMap
1841
0
  hasKnownCollection = gFalse;
1842
0
  if (globalParams->getUseTrueTypeUnicodeMapping()) {
1843
0
    readTrueTypeUnicodeMapping(xref);
1844
0
  }
1845
0
  if (!ctu) {
1846
0
    ctu = readToUnicodeCMap(fontDict, 16, NULL);
1847
0
  }
1848
0
  if (!ctu) {
1849
0
    ctuUsesCharCode = gFalse;
1850
1851
    // use an identity mapping for the "Adobe-Identity" and
1852
    // "Adobe-UCS" collections
1853
0
    if (!collection->cmp("Adobe-Identity") ||
1854
0
  !collection->cmp("Adobe-UCS")) {
1855
0
      ctu = CharCodeToUnicode::makeIdentityMapping();
1856
1857
    // look for a user-supplied .cidToUnicode file
1858
0
    } else if ((ctu = globalParams->getCIDToUnicode(collection))) {
1859
0
      hasKnownCollection = gTrue;
1860
1861
0
    } else {
1862
0
      error(errSyntaxError, -1,
1863
0
      "Unknown character collection '{0:t}'", collection);
1864
1865
      // fall back to an identity mapping
1866
0
      ctu = CharCodeToUnicode::makeIdentityMapping();
1867
0
    }
1868
0
  }
1869
1870
  // look for a Unicode-to-Unicode mapping
1871
0
  if (name && (utu = globalParams->getUnicodeToUnicode(name))) {
1872
0
    if (ctu) {
1873
0
      if (ctu->isIdentity()) {
1874
0
  ctu->decRefCnt();
1875
0
  ctu = utu;
1876
0
      } else {
1877
0
  for (c = 0; c < ctu->getLength(); ++c) {
1878
0
    n = ctu->mapToUnicode(c, uBuf, 8);
1879
0
    if (n >= 1) {
1880
0
      n = utu->mapToUnicode((CharCode)uBuf[0], uBuf, 8);
1881
0
      if (n >= 1) {
1882
0
        ctu->setMapping(c, uBuf, n);
1883
0
      }
1884
0
    }
1885
0
  }
1886
0
  utu->decRefCnt();
1887
0
      }
1888
0
    } else {
1889
0
      ctu = utu;
1890
0
    }
1891
0
  }
1892
1893
  //----- character metrics -----
1894
1895
  // default char width
1896
0
  if (desFontDict->lookup("DW", &obj1)->isNum()) {
1897
0
    widths.defWidth = obj1.getNum() * 0.001;
1898
0
  }
1899
0
  obj1.free();
1900
1901
  // char width exceptions
1902
0
  if (desFontDict->lookup("W", &obj1)->isArray()) {
1903
0
    excepsSize = 0;
1904
0
    i = 0;
1905
0
    while (i + 1 < obj1.arrayGetLength()) {
1906
0
      obj1.arrayGet(i, &obj2);
1907
0
      obj1.arrayGet(i + 1, &obj3);
1908
0
      if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
1909
0
  if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
1910
0
    if (widths.nExceps == excepsSize) {
1911
0
      excepsSize += 16;
1912
0
      widths.exceps = (GfxFontCIDWidthExcep *)
1913
0
        greallocn(widths.exceps,
1914
0
      excepsSize, sizeof(GfxFontCIDWidthExcep));
1915
0
    }
1916
0
    widths.exceps[widths.nExceps].first = obj2.getInt();
1917
0
    widths.exceps[widths.nExceps].last = obj3.getInt();
1918
0
    widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1919
0
    ++widths.nExceps;
1920
0
  } else {
1921
0
    error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1922
0
  }
1923
0
  obj4.free();
1924
0
  i += 3;
1925
0
      } else if (obj2.isInt() && obj3.isArray()) {
1926
0
  if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
1927
0
    excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
1928
0
    widths.exceps = (GfxFontCIDWidthExcep *)
1929
0
      greallocn(widths.exceps,
1930
0
          excepsSize, sizeof(GfxFontCIDWidthExcep));
1931
0
  }
1932
0
  j = obj2.getInt();
1933
0
  for (k = 0; k < obj3.arrayGetLength(); ++k) {
1934
0
    if (obj3.arrayGet(k, &obj4)->isNum()) {
1935
0
      widths.exceps[widths.nExceps].first = j;
1936
0
      widths.exceps[widths.nExceps].last = j;
1937
0
      widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1938
0
      ++j;
1939
0
      ++widths.nExceps;
1940
0
    } else {
1941
0
      error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1942
0
    }
1943
0
    obj4.free();
1944
0
  }
1945
0
  i += 2;
1946
0
      } else {
1947
0
  error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1948
0
  ++i;
1949
0
      }
1950
0
      obj3.free();
1951
0
      obj2.free();
1952
0
    }
1953
0
  }
1954
0
  obj1.free();
1955
1956
  // default metrics for vertical font
1957
0
  if (desFontDict->lookup("DW2", &obj1)->isArray() &&
1958
0
      obj1.arrayGetLength() == 2) {
1959
0
    if (obj1.arrayGet(0, &obj2)->isNum()) {
1960
0
      widths.defVY = obj2.getNum() * 0.001;
1961
0
    }
1962
0
    obj2.free();
1963
0
    if (obj1.arrayGet(1, &obj2)->isNum()) {
1964
0
      widths.defHeight = obj2.getNum() * 0.001;
1965
0
    }
1966
0
    obj2.free();
1967
0
  }
1968
0
  obj1.free();
1969
1970
  // char metric exceptions for vertical font
1971
0
  if (desFontDict->lookup("W2", &obj1)->isArray()) {
1972
0
    excepsSize = 0;
1973
0
    i = 0;
1974
0
    while (i + 1 < obj1.arrayGetLength()) {
1975
0
      obj1.arrayGet(i, &obj2);
1976
0
      obj1.arrayGet(i+ 1, &obj3);
1977
0
      if (obj2.isInt() && obj3.isInt() && i + 4 < obj1.arrayGetLength()) {
1978
0
  if (obj1.arrayGet(i + 2, &obj4)->isNum() &&
1979
0
      obj1.arrayGet(i + 3, &obj5)->isNum() &&
1980
0
      obj1.arrayGet(i + 4, &obj6)->isNum()) {
1981
0
    if (widths.nExcepsV == excepsSize) {
1982
0
      excepsSize += 16;
1983
0
      widths.excepsV = (GfxFontCIDWidthExcepV *)
1984
0
        greallocn(widths.excepsV,
1985
0
      excepsSize, sizeof(GfxFontCIDWidthExcepV));
1986
0
    }
1987
0
    widths.excepsV[widths.nExcepsV].first = obj2.getInt();
1988
0
    widths.excepsV[widths.nExcepsV].last = obj3.getInt();
1989
0
    widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
1990
0
    widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
1991
0
    widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
1992
0
    ++widths.nExcepsV;
1993
0
  } else {
1994
0
    error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
1995
0
  }
1996
0
  obj6.free();
1997
0
  obj5.free();
1998
0
  obj4.free();
1999
0
  i += 5;
2000
0
      } else if (obj2.isInt() && obj3.isArray()) {
2001
0
  if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
2002
0
    excepsSize =
2003
0
      (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
2004
0
    widths.excepsV = (GfxFontCIDWidthExcepV *)
2005
0
      greallocn(widths.excepsV,
2006
0
          excepsSize, sizeof(GfxFontCIDWidthExcepV));
2007
0
  }
2008
0
  j = obj2.getInt();
2009
0
  for (k = 0; k + 2 < obj3.arrayGetLength(); k += 3) {
2010
0
    if (obj3.arrayGet(k, &obj4)->isNum() &&
2011
0
        obj3.arrayGet(k+1, &obj5)->isNum() &&
2012
0
        obj3.arrayGet(k+2, &obj6)->isNum()) {
2013
0
      widths.excepsV[widths.nExcepsV].first = j;
2014
0
      widths.excepsV[widths.nExcepsV].last = j;
2015
0
      widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2016
0
      widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2017
0
      widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2018
0
      ++j;
2019
0
      ++widths.nExcepsV;
2020
0
    } else {
2021
0
      error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2022
0
    }
2023
0
    obj6.free();
2024
0
    obj5.free();
2025
0
    obj4.free();
2026
0
  }
2027
0
  i += 2;
2028
0
      } else {
2029
0
  error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2030
0
  ++i;
2031
0
      }
2032
0
      obj3.free();
2033
0
      obj2.free();
2034
0
    }
2035
0
  }
2036
0
  obj1.free();
2037
2038
0
  desFontDictObj.free();
2039
0
  ok = gTrue;
2040
0
  return;
2041
2042
0
 err3:
2043
0
  obj3.free();
2044
0
  obj2.free();
2045
0
 err2:
2046
0
  obj1.free();
2047
0
  desFontDictObj.free();
2048
0
 err1:
2049
0
  error(errSyntaxError, -1, "Failed to parse font object for '{0:t}'", name);
2050
0
}
2051
2052
0
GfxCIDFont::~GfxCIDFont() {
2053
0
  if (collection) {
2054
0
    delete collection;
2055
0
  }
2056
0
  if (cMap) {
2057
0
    cMap->decRefCnt();
2058
0
  }
2059
0
  if (ctu) {
2060
0
    ctu->decRefCnt();
2061
0
  }
2062
0
  gfree(widths.exceps);
2063
0
  gfree(widths.excepsV);
2064
0
  if (cidToGID) {
2065
0
    gfree(cidToGID);
2066
0
  }
2067
0
}
2068
2069
// Construct a code-to-Unicode mapping, based on the TrueType Unicode
2070
// cmap (if present).  Constructs ctu if succesful; leaves ctu = null
2071
// otherwise.  Always leaves ctu = null for non-TrueType fonts.
2072
0
void GfxCIDFont::readTrueTypeUnicodeMapping(XRef *xref) {
2073
0
  char *buf;
2074
0
  FoFiTrueType *ff;
2075
0
  Unicode *gidToUnicode, *codeToUnicode;
2076
0
  Unicode u;
2077
0
  int bufLen, cmapPlatform, cmapEncoding, unicodeCmap;
2078
0
  int nGlyphs, nMappings, gid, i;
2079
2080
  // must be an embedded TrueType font, with an unknown char collection
2081
0
  if ((type != fontCIDType2 && type != fontCIDType2OT) ||
2082
0
      embFontID.num < 0 ||
2083
0
      hasKnownCollection) {
2084
0
    goto err0;
2085
0
  }
2086
2087
  // read the embedded font and construct a FoFiTrueType
2088
0
  if (!(buf = readEmbFontFile(xref, &bufLen))) {
2089
0
    goto err0;
2090
0
  }
2091
0
  if (!(ff = FoFiTrueType::make(buf, bufLen, 0))) {
2092
0
    goto err1;
2093
0
  }
2094
2095
  // find the TrueType Unicode cmap
2096
0
  unicodeCmap = -1;
2097
0
  for (i = 0; i < ff->getNumCmaps(); ++i) {
2098
0
    cmapPlatform = ff->getCmapPlatform(i);
2099
0
    cmapEncoding = ff->getCmapEncoding(i);
2100
0
    if ((cmapPlatform == 3 && cmapEncoding == 1) ||
2101
0
  (cmapPlatform == 0 && cmapEncoding <= 4)) {
2102
0
      unicodeCmap = i;
2103
0
      break;
2104
0
    }
2105
0
  }
2106
0
  if (unicodeCmap < 0) {
2107
0
    goto err2;
2108
0
  }
2109
2110
  // construct reverse GID-to-Unicode map
2111
0
  nGlyphs = ff->getNumGlyphs();
2112
0
  gidToUnicode = (Unicode *)gmallocn(nGlyphs, sizeof(Unicode));
2113
0
  memset(gidToUnicode, 0, nGlyphs * sizeof(Unicode));
2114
0
  nMappings = 0;
2115
0
  for (u = 1; u <= 0xffff; ++u) {
2116
0
    gid = ff->mapCodeToGID(unicodeCmap, (int)u);
2117
0
    if (gid > 0 && gid < nGlyphs) {
2118
0
      gidToUnicode[gid] = u;
2119
0
      ++nMappings;
2120
0
    }
2121
0
  }
2122
  // bail out if the Unicode cmap was completely empty
2123
0
  if (nMappings == 0) {
2124
0
    goto err3;
2125
0
  }
2126
2127
  // construct code-to-Unicode map
2128
0
  codeToUnicode = (Unicode *)gmallocn(65536, sizeof(Unicode));
2129
0
  memset(codeToUnicode, 0, 65536 * sizeof(Unicode));
2130
0
  for (i = 0; i <= 0xffff; ++i) {
2131
    // we've already checked for an identity encoding, so CID = i
2132
0
    if (cidToGID && i < cidToGIDLen) {
2133
0
      gid = cidToGID[i];
2134
0
    } else {
2135
0
      gid = i;
2136
0
    }
2137
0
    if (gid < nGlyphs && gidToUnicode[gid] > 0) {
2138
0
      codeToUnicode[i] = gidToUnicode[gid];
2139
0
    }
2140
0
  }
2141
0
  ctu = CharCodeToUnicode::make16BitToUnicode(codeToUnicode);
2142
2143
0
  gfree(codeToUnicode);
2144
0
 err3:
2145
0
  gfree(gidToUnicode);
2146
0
 err2:
2147
0
  delete ff;
2148
0
 err1:
2149
0
  gfree(buf);
2150
0
 err0:
2151
0
  return;
2152
0
}
2153
2154
int GfxCIDFont::getNextChar(char *s, int len, CharCode *code,
2155
          Unicode *u, int uSize, int *uLen,
2156
0
          double *dx, double *dy, double *ox, double *oy) {
2157
0
  CID cid;
2158
0
  CharCode c;
2159
0
  int n;
2160
2161
0
  if (!cMap) {
2162
0
    *code = 0;
2163
0
    *uLen = 0;
2164
0
    *dx = *dy = 0;
2165
0
    return 1;
2166
0
  }
2167
2168
0
  *code = (CharCode)(cid = cMap->getCID(s, len, &c, &n));
2169
0
  if (ctu) {
2170
0
    *uLen = ctu->mapToUnicode(ctuUsesCharCode ? c : cid, u, uSize);
2171
0
  } else {
2172
0
    *uLen = 0;
2173
0
  }
2174
0
  if (!*uLen && uSize >= 1 && globalParams->getMapUnknownCharNames()) {
2175
0
    u[0] = *code;
2176
0
    *uLen = 1;
2177
0
  }
2178
2179
  // horizontal
2180
0
  if (cMap->getWMode() == 0) {
2181
0
    getHorizontalMetrics(cid, dx);
2182
0
    *dy = *ox = *oy = 0;
2183
2184
  // vertical
2185
0
  } else {
2186
0
    getVerticalMetrics(cid, dy, ox, oy);
2187
0
    *dx = 0;
2188
0
  }
2189
2190
0
  return n;
2191
0
}
2192
2193
// NB: Section 9.7.4.3 in the PDF 2.0 spec says that, in the case of
2194
// duplicate entries in the metrics, the first entry should be used.
2195
// This means we need to leave the metrics in the original order and
2196
// perform a linear search.  (Or use a more complex data structure.)
2197
0
void GfxCIDFont::getHorizontalMetrics(CID cid, double *w) {
2198
0
  int i;
2199
0
  for (i = 0; i < widths.nExceps; ++i) {
2200
0
    if (widths.exceps[i].first <= cid && cid <= widths.exceps[i].last) {
2201
0
      *w = widths.exceps[i].width;
2202
0
      return;
2203
0
    }
2204
0
  }
2205
0
  *w = widths.defWidth;
2206
0
}
2207
2208
// NB: Section 9.7.4.3 in the PDF 2.0 spec says that, in the case of
2209
// duplicate entries in the metrics, the first entry should be used.
2210
// This means we need to leave the metrics in the original order and
2211
// perform a linear search.  (Or use a more complex data structure.)
2212
void GfxCIDFont::getVerticalMetrics(CID cid, double *h,
2213
0
            double *vx, double *vy) {
2214
0
  int i;
2215
0
  for (i = 0; i < widths.nExcepsV; ++i) {
2216
0
    if (widths.excepsV[i].first <= cid && cid <= widths.excepsV[i].last) {
2217
0
      *h = widths.excepsV[i].height;
2218
0
      *vx = widths.excepsV[i].vx;
2219
0
      *vy = widths.excepsV[i].vy;
2220
0
      return;
2221
0
    }
2222
0
  }
2223
0
  *h = widths.defHeight;
2224
0
  getHorizontalMetrics(cid, vx);
2225
0
  *vx /= 2;
2226
0
  *vy = widths.defVY;
2227
0
}
2228
2229
0
int GfxCIDFont::getWMode() {
2230
0
  return cMap ? cMap->getWMode() : 0;
2231
0
}
2232
2233
0
CharCodeToUnicode *GfxCIDFont::getToUnicode() {
2234
0
  if (ctu) {
2235
0
    ctu->incRefCnt();
2236
0
  }
2237
0
  return ctu;
2238
0
}
2239
2240
0
GString *GfxCIDFont::getCollection() {
2241
0
  return cMap ? cMap->getCollection() : (GString *)NULL;
2242
0
}
2243
2244
0
double GfxCIDFont::getWidth(CID cid) {
2245
0
  double w;
2246
2247
0
  getHorizontalMetrics(cid, &w);
2248
0
  return w;
2249
0
}
2250
2251
0
GBool GfxCIDFont::problematicForUnicode() {
2252
0
  GString *nameLC;
2253
0
  GBool symbolic;
2254
2255
  // potential inputs:
2256
  // - font is embedded (GfxFont.embFontID.num >= 0)
2257
  // - font name (GfxFont.name)
2258
  // - font type (GfxFont.type)
2259
  // - symbolic (GfxFont.flags & fontSymbolic)
2260
  // - has a ToUnicode map (GfxFont.hasToUnicode)
2261
  // - collection is Adobe-Identity or Adobe-UCS
2262
  //   (GfxCIDFont.collection - compare string)
2263
  // - collection is known AdobeCJK (GfxCIDFont.hasKnownCollection)
2264
  // - has non-Identity CIDToGIDMap (GfxCIDFont.cidToGID != NULL)
2265
  // - has Identity CIDToGIDMap (GfxCIDFont.hasIdentityCIDToGID)
2266
2267
0
  if (name) {
2268
0
    nameLC = name->copy();
2269
0
    nameLC->lowerCase();
2270
0
    symbolic = strstr(nameLC->getCString(), "dingbat") ||
2271
0
               strstr(nameLC->getCString(), "wingding") ||
2272
0
               strstr(nameLC->getCString(), "commpi");
2273
0
    delete nameLC;
2274
0
    if (symbolic) {
2275
0
      return gFalse;
2276
0
    }
2277
0
  }
2278
2279
0
  if (embFontID.num >= 0) {
2280
0
    switch (type) {
2281
0
    case fontCIDType0:
2282
0
    case fontCIDType0C:
2283
0
    case fontCIDType0COT:
2284
0
      return !hasToUnicode && !hasKnownCollection;
2285
2286
0
    case fontCIDType2:
2287
0
    case fontCIDType2OT:
2288
0
      return !hasToUnicode && !hasKnownCollection;
2289
2290
0
    default:
2291
0
      return !hasToUnicode;
2292
0
    }
2293
2294
0
  } else {
2295
0
    return !hasToUnicode;
2296
0
  }
2297
0
}
2298
2299
0
GBool GfxCIDFont::parensAreSwapped(XRef *xref) {
2300
0
  char *buf = NULL;
2301
0
  FoFiTrueType *ff = NULL;
2302
0
  int bufLen;
2303
0
  int unicodeCmap, leftParenGID, rightParenGID, leftParenCID, rightParenCID;
2304
0
  Unicode leftParenUnicode, rightParenUnicode;
2305
0
  GBool swapped;
2306
2307
  // only relevant for embedded TrueType fonts, with unknown char
2308
  // collections, and with ToUnicode maps
2309
0
  if ((type != fontCIDType2 && type != fontCIDType2OT) ||
2310
0
      embFontID.num < 0 ||
2311
0
      hasKnownCollection ||
2312
0
      !hasToUnicode) {
2313
0
    return gFalse;
2314
0
  }
2315
2316
  // read the embedded font and construct a FoFiTrueType
2317
0
  if (!(buf = readEmbFontFile(xref, &bufLen))) {
2318
0
    goto err;
2319
0
  }
2320
0
  if (!(ff = FoFiTrueType::make(buf, bufLen, 0))) {
2321
0
    goto err;
2322
0
  }
2323
2324
  // find the TrueType Unicode cmap
2325
0
  unicodeCmap = -1;
2326
0
  for (int i = 0; i < ff->getNumCmaps(); ++i) {
2327
0
    int cmapPlatform = ff->getCmapPlatform(i);
2328
0
    int cmapEncoding = ff->getCmapEncoding(i);
2329
0
    if ((cmapPlatform == 3 && cmapEncoding == 1) ||
2330
0
  (cmapPlatform == 0 && cmapEncoding <= 4)) {
2331
0
      unicodeCmap = i;
2332
0
      break;
2333
0
    }
2334
0
  }
2335
0
  if (unicodeCmap < 0) {
2336
0
    goto err;
2337
0
  }
2338
2339
  // map parens to GIDs using the TrueType Unicode cmap
2340
0
  leftParenGID = ff->mapCodeToGID(unicodeCmap, 0x28);
2341
0
  rightParenGID = ff->mapCodeToGID(unicodeCmap, 0x29);
2342
0
  if (leftParenGID == 0 || rightParenGID == 0) {
2343
0
    goto err;
2344
0
  }
2345
2346
  // map GIDs to CIDs using the inverted CIDToGID map
2347
0
  leftParenCID = -1;
2348
0
  rightParenCID = -1;
2349
0
  if (cidToGID) {
2350
0
    for (int i = 0;
2351
0
   i <= cidToGIDLen && leftParenCID < 0 && rightParenCID < 0;
2352
0
   ++i) {
2353
0
      if (cidToGID[i] == leftParenGID) {
2354
0
  leftParenCID = i;
2355
0
      } else if (cidToGID[i] == rightParenGID) {
2356
0
  rightParenCID = i;
2357
0
      }
2358
0
    }
2359
0
    if (leftParenCID < 0 || rightParenCID < 0) {
2360
0
      goto err;
2361
0
    }
2362
0
  } else {
2363
0
    leftParenCID = leftParenGID;
2364
0
    rightParenCID = rightParenGID;
2365
0
  }
2366
2367
  // map CIDs to Unicode using the ToUnicode map
2368
0
  if (ctu->mapToUnicode((CharCode)leftParenCID, &leftParenUnicode, 1) < 1 ||
2369
0
      ctu->mapToUnicode((CharCode)rightParenCID, &rightParenUnicode, 1) < 1) {
2370
0
    goto err;
2371
0
  }
2372
2373
  // check for swap
2374
0
  swapped = leftParenUnicode == 0x29 && rightParenUnicode == 0x28;
2375
2376
0
  delete ff;
2377
0
  ff = NULL;
2378
0
  gfree(buf);
2379
0
  buf = NULL;
2380
2381
0
  return swapped;
2382
2383
0
 err:
2384
0
  if (ff) {
2385
0
    delete ff;
2386
0
  }
2387
0
  if (buf) {
2388
0
    gfree(buf);
2389
0
  }
2390
0
  return gFalse;
2391
0
}
2392
2393
//------------------------------------------------------------------------
2394
// GfxFontDict
2395
//------------------------------------------------------------------------
2396
2397
class GfxFontDictEntry {
2398
public:
2399
2400
  GfxFontDictEntry(Ref refA, Object *fontObjA);
2401
  ~GfxFontDictEntry();
2402
  void load(GfxFont *fontA);
2403
2404
  GBool loaded;
2405
  Ref ref;
2406
  Object fontObj;   // valid if unloaded
2407
  GfxFont *font;    // valid if loaded
2408
};
2409
2410
0
GfxFontDictEntry::GfxFontDictEntry(Ref refA, Object *fontObjA) {
2411
0
  loaded = gFalse;
2412
0
  ref = refA;
2413
0
  fontObjA->copy(&fontObj);
2414
0
  font = NULL;
2415
0
}
2416
2417
0
GfxFontDictEntry::~GfxFontDictEntry() {
2418
  // NB: If the font has been loaded, font is non-NULL and is owned by
2419
  // GfxFontDict.uniqueFonts.
2420
0
  if (!loaded) {
2421
0
    fontObj.free();
2422
0
  }
2423
0
}
2424
2425
0
void GfxFontDictEntry::load(GfxFont *fontA) {
2426
0
  loaded = gTrue;
2427
0
  font = fontA;
2428
0
  fontObj.free();
2429
0
}
2430
2431
0
GfxFontDict::GfxFontDict(XRef *xrefA, Ref *fontDictRef, Dict *fontDict) {
2432
0
  xref = xrefA;
2433
0
  fonts = new GHash(gTrue);
2434
0
  uniqueFonts = new GList();
2435
2436
0
  for (int i = 0; i < fontDict->getLength(); ++i) {
2437
0
    char *tag = fontDict->getKey(i);
2438
0
    Object fontObj;
2439
0
    fontDict->getValNF(i, &fontObj);
2440
0
    Ref r;
2441
0
    if (fontObj.isRef()) {
2442
0
      r = fontObj.getRef();
2443
0
    } else if (fontDictRef) {
2444
      // legal generation numbers are five digits, so we use a
2445
      // 6-digit number here
2446
0
      r.gen = 100000 + fontDictRef->num;
2447
0
      r.num = i;
2448
0
    } else {
2449
      // no indirect reference for this font, or for the containing
2450
      // font dict, so hash the font and use that
2451
0
      r.gen = 100000;
2452
0
      r.num = hashFontObject(&fontObj);
2453
0
    }
2454
0
    fonts->add(new GString(tag), new GfxFontDictEntry(r, &fontObj));
2455
0
    fontObj.free();
2456
0
  }
2457
0
}
2458
2459
0
GfxFontDict::~GfxFontDict() {
2460
0
  deleteGList(uniqueFonts, GfxFont);
2461
0
  deleteGHash(fonts, GfxFontDictEntry);
2462
0
}
2463
2464
0
GfxFont *GfxFontDict::lookup(char *tag) {
2465
0
  GfxFontDictEntry *entry = (GfxFontDictEntry *)fonts->lookup(tag);
2466
0
  if (!entry) {
2467
0
    return NULL;
2468
0
  }
2469
0
  load(tag, entry);
2470
0
  return entry->font;
2471
0
}
2472
2473
0
GfxFont *GfxFontDict::lookupByRef(Ref ref) {
2474
0
  GHashIter *iter;
2475
0
  GString *tag;
2476
0
  GfxFontDictEntry *entry;
2477
0
  fonts->startIter(&iter);
2478
0
  while (fonts->getNext(&iter, &tag, (void **)&entry)) {
2479
0
    if (entry->ref.num == ref.num && entry->ref.gen == ref.gen) {
2480
0
      fonts->killIter(&iter);
2481
0
      load(tag->getCString(), entry);
2482
0
      return entry->font;
2483
0
    }
2484
0
  }
2485
0
  return NULL;
2486
0
}
2487
2488
0
int GfxFontDict::getNumFonts() {
2489
0
  loadAll();
2490
0
  return uniqueFonts->getLength();
2491
0
}
2492
2493
0
GfxFont *GfxFontDict::getFont(int i) {
2494
0
  return (GfxFont *)uniqueFonts->get(i);
2495
0
}
2496
2497
0
void GfxFontDict::loadAll() {
2498
0
  GHashIter *iter;
2499
0
  GString *tag;
2500
0
  GfxFontDictEntry *entry;
2501
0
  fonts->startIter(&iter);
2502
0
  while (fonts->getNext(&iter, &tag, (void **)&entry)) {
2503
0
    load(tag->getCString(), entry);
2504
0
  }
2505
0
}
2506
2507
0
void GfxFontDict::load(char *tag, GfxFontDictEntry *entry) {
2508
0
  if (entry->loaded) {
2509
0
    return;
2510
0
  }
2511
2512
  // check for a duplicate that has already been loaded
2513
  // (don't do this for "synthetic" refs)
2514
0
  if (entry->fontObj.isRef()) {
2515
0
    for (int i = 0; i < uniqueFonts->getLength(); ++i) {
2516
0
      GfxFont *font = (GfxFont *)uniqueFonts->get(i);
2517
0
      if (font->getID()->num == entry->ref.num &&
2518
0
    font->getID()->gen == entry->ref.gen) {
2519
0
  entry->load(font);
2520
0
  return;
2521
0
      }
2522
0
    }
2523
0
  }
2524
2525
0
  GfxFont *font = NULL;
2526
0
  Object obj;
2527
0
  entry->fontObj.fetch(xref, &obj);
2528
0
  if (obj.isDict()) {
2529
0
    font = GfxFont::makeFont(xref, tag, entry->ref, obj.getDict());
2530
0
    if (font->isOk()) {
2531
0
      uniqueFonts->append(font);
2532
0
    } else {
2533
0
      delete font;
2534
0
      font = NULL;
2535
0
    }
2536
0
  } else {
2537
0
    error(errSyntaxError, -1, "font resource is not a dictionary");
2538
0
  }
2539
0
  obj.free();
2540
0
  entry->load(font);
2541
0
}
2542
2543
// FNV-1a hash
2544
class FNVHash {
2545
public:
2546
2547
0
  FNVHash() {
2548
0
    h = 2166136261U;
2549
0
  }
2550
2551
0
  void hash(char c) {
2552
0
    h ^= c & 0xff;
2553
0
    h *= 16777619;
2554
0
  }
2555
2556
0
  void hash(char *p, int n) {
2557
0
    int i;
2558
0
    for (i = 0; i < n; ++i) {
2559
0
      hash(p[i]);
2560
0
    }
2561
0
  }
2562
2563
0
  int get31() {
2564
0
    return (h ^ (h >> 31)) & 0x7fffffff;
2565
0
  }
2566
2567
private:
2568
2569
  Guint h;
2570
};
2571
2572
0
int GfxFontDict::hashFontObject(Object *obj) {
2573
0
  FNVHash h;
2574
2575
0
  hashFontObject1(obj, &h);
2576
0
  return h.get31();
2577
0
}
2578
2579
0
void GfxFontDict::hashFontObject1(Object *obj, FNVHash *h) {
2580
0
  Object obj2;
2581
0
  GString *s;
2582
0
  char *p;
2583
0
  double r;
2584
0
  int n, i;
2585
2586
0
  switch (obj->getType()) {
2587
0
  case objBool:
2588
0
    h->hash('b');
2589
0
    h->hash(obj->getBool() ? 1 : 0);
2590
0
    break;
2591
0
  case objInt:
2592
0
    h->hash('i');
2593
0
    n = obj->getInt();
2594
0
    h->hash((char *)&n, sizeof(int));
2595
0
    break;
2596
0
  case objReal:
2597
0
    h->hash('r');
2598
0
    r = obj->getReal();
2599
0
    h->hash((char *)&r, sizeof(double));
2600
0
    break;
2601
0
  case objString:
2602
0
    h->hash('s');
2603
0
    s = obj->getString();
2604
0
    h->hash(s->getCString(), s->getLength());
2605
0
    break;
2606
0
  case objName:
2607
0
    h->hash('n');
2608
0
    p = obj->getName();
2609
0
    h->hash(p, (int)strlen(p));
2610
0
    break;
2611
0
  case objNull:
2612
0
    h->hash('z');
2613
0
    break;
2614
0
  case objArray:
2615
0
    h->hash('a');
2616
0
    n = obj->arrayGetLength();
2617
0
    h->hash((char *)&n, sizeof(int));
2618
0
    for (i = 0; i < n; ++i) {
2619
0
      obj->arrayGetNF(i, &obj2);
2620
0
      hashFontObject1(&obj2, h);
2621
0
      obj2.free();
2622
0
    }
2623
0
    break;
2624
0
  case objDict:
2625
0
    h->hash('d');
2626
0
    n = obj->dictGetLength();
2627
0
    h->hash((char *)&n, sizeof(int));
2628
0
    for (i = 0; i < n; ++i) {
2629
0
      p = obj->dictGetKey(i);
2630
0
      h->hash(p, (int)strlen(p));
2631
0
      obj->dictGetValNF(i, &obj2);
2632
0
      hashFontObject1(&obj2, h);
2633
0
      obj2.free();
2634
0
    }
2635
0
    break;
2636
0
  case objStream:
2637
    // this should never happen - streams must be indirect refs
2638
0
    break;
2639
0
  case objRef:
2640
0
    h->hash('f');
2641
0
    n = obj->getRefNum();
2642
0
    h->hash((char *)&n, sizeof(int));
2643
0
    n = obj->getRefGen();
2644
0
    h->hash((char *)&n, sizeof(int));
2645
0
    break;
2646
0
  default:
2647
0
    h->hash('u');
2648
0
    break;
2649
0
  }
2650
0
}