Coverage Report

Created: 2026-02-04 06: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
501k
static int readFromStream(void *data) {
135
501k
  return ((Stream *)data)->getChar();
136
501k
}
137
138
//------------------------------------------------------------------------
139
// GfxFontLoc
140
//------------------------------------------------------------------------
141
142
3.69k
GfxFontLoc::GfxFontLoc() {
143
3.69k
  path = NULL;
144
3.69k
  fontNum = 0;
145
3.69k
  oblique = 0;
146
3.69k
  encoding = NULL;
147
3.69k
  substIdx = -1;
148
3.69k
}
149
150
3.69k
GfxFontLoc::~GfxFontLoc() {
151
3.69k
  if (path) {
152
0
    delete path;
153
0
  }
154
3.69k
  if (encoding) {
155
0
    delete encoding;
156
0
  }
157
3.69k
}
158
159
//------------------------------------------------------------------------
160
// GfxFont
161
//------------------------------------------------------------------------
162
163
GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA,
164
38.7k
         Ref idA, Dict *fontDict) {
165
38.7k
  GString *nameA;
166
38.7k
  Ref embFontIDA;
167
38.7k
  GfxFontType typeA;
168
38.7k
  GfxFont *font;
169
38.7k
  Object obj1;
170
171
  // get base font name
172
38.7k
  nameA = NULL;
173
38.7k
  fontDict->lookup("BaseFont", &obj1);
174
38.7k
  if (obj1.isName()) {
175
18.9k
    nameA = new GString(obj1.getName());
176
19.8k
  } else if (obj1.isString()) {
177
7
    nameA = obj1.getString()->copy();
178
7
  }
179
38.7k
  obj1.free();
180
181
  // get embedded font ID and font type
182
38.7k
  typeA = getFontType(xref, fontDict, &embFontIDA);
183
184
  // create the font object
185
38.7k
  font = NULL;
186
38.7k
  if (typeA < fontCIDType0) {
187
25.8k
    font = new Gfx8BitFont(xref, tagA, idA, nameA, typeA, embFontIDA,
188
25.8k
         fontDict);
189
25.8k
  } else {
190
12.8k
    font = new GfxCIDFont(xref, tagA, idA, nameA, typeA, embFontIDA,
191
12.8k
        fontDict);
192
12.8k
  }
193
194
38.7k
  return font;
195
38.7k
}
196
197
9.58k
GfxFont *GfxFont::makeDefaultFont(XRef *xref) {
198
9.58k
  Object type, subtype, baseFont;
199
9.58k
  type.initName("Font");
200
9.58k
  subtype.initName("Type1");
201
9.58k
  baseFont.initName("Helvetica");
202
9.58k
  Object fontDict;
203
9.58k
  fontDict.initDict(xref);
204
9.58k
  fontDict.dictAdd(copyString("Type"), &type);
205
9.58k
  fontDict.dictAdd(copyString("Subtype"), &subtype);
206
9.58k
  fontDict.dictAdd(copyString("BaseFont"), &baseFont);
207
208
9.58k
  Ref r;
209
9.58k
  r.gen = 100000;
210
9.58k
  r.num = GfxFontDict::hashFontObject(&fontDict);
211
212
9.58k
  GfxFont *font = makeFont(xref, "undef", r, fontDict.getDict());
213
9.58k
  fontDict.free();
214
215
9.58k
  return font;
216
9.58k
}
217
218
GfxFont::GfxFont(const char *tagA, Ref idA, GString *nameA,
219
38.7k
     GfxFontType typeA, Ref embFontIDA) {
220
38.7k
  ok = gFalse;
221
38.7k
  tag = new GString(tagA);
222
38.7k
  id = idA;
223
38.7k
  name = nameA;
224
38.7k
  type = typeA;
225
38.7k
  embFontID = embFontIDA;
226
38.7k
  embFontName = NULL;
227
38.7k
  hasToUnicode = gFalse;
228
38.7k
}
229
230
38.7k
GfxFont::~GfxFont() {
231
38.7k
  delete tag;
232
38.7k
  if (name) {
233
18.9k
    delete name;
234
18.9k
  }
235
38.7k
  if (embFontName) {
236
14.7k
    delete embFontName;
237
14.7k
  }
238
38.7k
}
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
38.7k
GfxFontType GfxFont::getFontType(XRef *xref, Dict *fontDict, Ref *embID) {
251
38.7k
  GfxFontType t, expectedType;
252
38.7k
  FoFiIdentifierType fft;
253
38.7k
  Dict *fontDict2;
254
38.7k
  Object subtype, fontDesc, obj1, obj2, obj3, obj4;
255
38.7k
  GBool isType0, err;
256
257
38.7k
  t = fontUnknownType;
258
38.7k
  embID->num = embID->gen = -1;
259
38.7k
  err = gFalse;
260
261
38.7k
  fontDict->lookup("Subtype", &subtype);
262
38.7k
  expectedType = fontUnknownType;
263
38.7k
  isType0 = gFalse;
264
38.7k
  if (subtype.isName("Type1") || subtype.isName("MMType1")) {
265
14.2k
    expectedType = fontType1;
266
24.4k
  } else if (subtype.isName("Type1C")) {
267
7
    expectedType = fontType1C;
268
24.4k
  } else if (subtype.isName("Type3")) {
269
536
    expectedType = fontType3;
270
23.9k
  } else if (subtype.isName("TrueType")) {
271
1.41k
    expectedType = fontTrueType;
272
22.5k
  } else if (subtype.isName("Type0")) {
273
14.6k
    isType0 = gTrue;
274
14.6k
  } else {
275
7.87k
    error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
276
7.87k
    subtype.isName() ? subtype.getName() : "???");
277
7.87k
  }
278
38.7k
  subtype.free();
279
280
38.7k
  fontDict2 = fontDict;
281
38.7k
  if (fontDict->lookup("DescendantFonts", &obj1)->isArray()) {
282
18.6k
    if (obj1.arrayGetLength() == 0) {
283
0
      error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
284
0
      obj2.initNull();
285
18.6k
    } else if (obj1.arrayGet(0, &obj2)->isDict()) {
286
18.2k
      if (!isType0) {
287
5.33k
  error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
288
5.33k
      }
289
18.2k
      fontDict2 = obj2.getDict();
290
18.2k
      fontDict2->lookup("Subtype", &subtype);
291
18.2k
      if (subtype.isName("CIDFontType0")) {
292
13.3k
  if (isType0) {
293
12.0k
    expectedType = fontCIDType0;
294
12.0k
  }
295
13.3k
      } else if (subtype.isName("CIDFontType2")) {
296
764
  if (isType0) {
297
751
    expectedType = fontCIDType2;
298
751
  }
299
764
      }
300
18.2k
      subtype.free();
301
18.2k
    }
302
20.0k
  } else {
303
20.0k
    obj2.initNull();
304
20.0k
  }
305
306
  // NB: the PDF spec doesn't say anything about precedence, but Adobe
307
  // uses FontFile3 over FontFile2 if both are present.
308
38.7k
  if (fontDict2->lookup("FontDescriptor", &fontDesc)->isDict()) {
309
19.3k
    if (fontDesc.dictLookupNF("FontFile3", &obj3)->isRef()) {
310
8.90k
      *embID = obj3.getRef();
311
8.90k
      if (obj3.fetch(xref, &obj4)->isStream()) {
312
8.85k
  obj4.streamGetDict()->lookup("Subtype", &subtype);
313
8.85k
  if (subtype.isName("Type1")) {
314
18
    if (expectedType != fontType1) {
315
15
      err = gTrue;
316
15
      expectedType = isType0 ? fontCIDType0 : fontType1;
317
15
    }
318
8.83k
  } else if (subtype.isName("Type1C")) {
319
1.49k
    if (expectedType == fontType1) {
320
1.36k
      expectedType = fontType1C;
321
1.36k
    } else if (expectedType != fontType1C) {
322
125
      err = gTrue;
323
125
      expectedType = isType0 ? fontCIDType0C : fontType1C;
324
125
    }
325
7.34k
  } else if (subtype.isName("TrueType")) {
326
0
    if (expectedType != fontTrueType) {
327
0
      err = gTrue;
328
0
      expectedType = isType0 ? fontCIDType2 : fontTrueType;
329
0
    }
330
7.34k
  } else if (subtype.isName("CIDFontType0C")) {
331
105
    if (expectedType == fontCIDType0) {
332
64
      expectedType = fontCIDType0C;
333
64
    } else {
334
41
      err = gTrue;
335
41
      expectedType = isType0 ? fontCIDType0C : fontType1C;
336
41
    }
337
7.24k
  } else if (subtype.isName("OpenType")) {
338
40
    if (expectedType == fontTrueType) {
339
0
      expectedType = fontTrueTypeOT;
340
40
    } else if (expectedType == fontType1) {
341
0
      expectedType = fontType1COT;
342
40
    } else if (expectedType == fontCIDType0) {
343
37
      expectedType = fontCIDType0COT;
344
37
    } else if (expectedType == fontCIDType2) {
345
0
      expectedType = fontCIDType2OT;
346
3
    } else {
347
3
      err = gTrue;
348
3
    }
349
7.20k
  } else {
350
7.20k
    error(errSyntaxError, -1, "Unknown font type '{0:s}'",
351
7.20k
    subtype.isName() ? subtype.getName() : "???");
352
7.20k
  }
353
8.85k
  subtype.free();
354
8.85k
      }
355
8.90k
      obj4.free();
356
8.90k
    }
357
19.3k
    obj3.free();
358
19.3k
    if (embID->num == -1) {
359
10.4k
      if (fontDesc.dictLookupNF("FontFile2", &obj3)->isRef()) {
360
1.97k
  *embID = obj3.getRef();
361
1.97k
  if (isType0) {
362
634
    expectedType = fontCIDType2;
363
1.33k
  } else if (expectedType != fontTrueType) {
364
22
    err = gTrue;
365
22
  }
366
1.97k
      }
367
10.4k
      obj3.free();
368
10.4k
    }
369
19.3k
    if (embID->num == -1) {
370
8.44k
      if (fontDesc.dictLookupNF("FontFile", &obj3)->isRef()) {
371
1.67k
  *embID = obj3.getRef();
372
1.67k
  if (expectedType != fontType1) {
373
503
    err = gTrue;
374
503
  }
375
1.67k
      }
376
8.44k
      obj3.free();
377
8.44k
    }
378
19.3k
  }
379
38.7k
  fontDesc.free();
380
381
38.7k
  t = fontUnknownType;
382
38.7k
  if (embID->num >= 0) {
383
12.5k
    obj3.initRef(embID->num, embID->gen);
384
12.5k
    obj3.fetch(xref, &obj4);
385
12.5k
    if (obj4.isStream()) {
386
12.1k
      obj4.streamReset();
387
12.1k
      fft = FoFiIdentifier::identifyStream(&readFromStream, obj4.getStream());
388
12.1k
      obj4.streamClose();
389
12.1k
      switch (fft) {
390
1.30k
      case fofiIdType1PFA:
391
1.30k
      case fofiIdType1PFB:
392
1.30k
  t = fontType1;
393
1.30k
  break;
394
1.94k
      case fofiIdCFF8Bit:
395
1.94k
  t = isType0 ? fontCIDType0C : fontType1C;
396
1.94k
  break;
397
47
      case fofiIdCFFCID:
398
47
  t = fontCIDType0C;
399
47
  break;
400
1.91k
      case fofiIdTrueType:
401
1.91k
      case fofiIdTrueTypeCollection:
402
1.91k
  t = isType0 ? fontCIDType2 : fontTrueType;
403
1.91k
  break;
404
3
      case fofiIdOpenTypeCFF8Bit:
405
3
  t = isType0 ? fontCIDType0COT : fontType1COT;
406
3
  break;
407
0
      case fofiIdOpenTypeCFFCID:
408
0
  t = fontCIDType0COT;
409
0
  break;
410
6.95k
      default:
411
6.95k
  error(errSyntaxError, -1, "Embedded font file may be invalid");
412
6.95k
  break;
413
12.1k
      }
414
12.1k
    } else {
415
385
      error(errSyntaxError, -1, "Embedded font object is wrong type");
416
385
    }
417
12.5k
    obj4.free();
418
12.5k
    obj3.free();
419
12.5k
  }
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
38.7k
  if (t == fontUnknownType) {
425
33.5k
    embID->num = -1;
426
33.5k
    embID->gen = -1;
427
33.5k
    t = expectedType;
428
33.5k
  }
429
430
38.7k
  if (t != expectedType) {
431
872
    err = gTrue;
432
872
  }
433
434
38.7k
  if (err) {
435
1.23k
    error(errSyntaxWarning, -1,
436
1.23k
    "Mismatch between font type and embedded font file");
437
1.23k
  }
438
439
38.7k
  obj2.free();
440
38.7k
  obj1.free();
441
442
38.7k
  return t;
443
38.7k
}
444
445
38.7k
void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
446
38.7k
  Object obj1, obj2, obj3, obj4;
447
38.7k
  double t, t2;
448
38.7k
  int i;
449
450
  // assume Times-Roman by default (for substitution purposes)
451
38.7k
  flags = fontSerif;
452
453
38.7k
  if (fontDict->lookup("FontDescriptor", &obj1)->isDict()) {
454
455
    // get flags
456
16.6k
    if (obj1.dictLookup("Flags", &obj2)->isInt()) {
457
13.9k
      flags = obj2.getInt();
458
13.9k
    }
459
16.6k
    obj2.free();
460
461
    // get name
462
16.6k
    obj1.dictLookup("FontName", &obj2);
463
16.6k
    if (obj2.isName()) {
464
14.6k
      embFontName = new GString(obj2.getName());
465
14.6k
    }
466
16.6k
    obj2.free();
467
468
    // look for MissingWidth
469
16.6k
    obj1.dictLookup("MissingWidth", &obj2);
470
16.6k
    if (obj2.isNum()) {
471
67
      missingWidth = obj2.getNum();
472
67
    }
473
16.6k
    obj2.free();
474
475
    // font FontBBox
476
16.6k
    if (obj1.dictLookup("FontBBox", &obj2)->isArray()) {
477
71.0k
      for (i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
478
56.8k
  if (obj2.arrayGet(i, &obj3)->isNum()) {
479
52.8k
    fontBBox[i] = 0.001 * obj3.getNum();
480
52.8k
  }
481
56.8k
  obj3.free();
482
56.8k
      }
483
14.2k
    }
484
16.6k
    obj2.free();
485
486
    // get Ascent (but also look at CapHeight)
487
16.6k
    obj1.dictLookup("Ascent", &obj2);
488
16.6k
    obj1.dictLookup("CapHeight", &obj3);
489
16.6k
    if (obj2.isNum() || obj3.isNum()) {
490
13.9k
      if (obj2.isNum()) {
491
12.4k
  t = 0.001 * obj2.getNum();
492
  // some broken font descriptors specify a negative ascent
493
12.4k
  if (t < 0) {
494
5
    t = -t;
495
5
  }
496
12.4k
      } else {
497
1.47k
  t = 0;
498
1.47k
      }
499
13.9k
      if (obj3.isNum()) {
500
11.8k
  t2 = 0.001 * obj3.getNum();
501
  // some broken font descriptors specify a negative ascent
502
11.8k
  if (t2 < 0) {
503
2
    t2 = -t2;
504
2
  }
505
11.8k
      } else {
506
2.03k
  t2 = 0;
507
2.03k
      }
508
13.9k
      if (t != 0 && t < 1.9) {
509
12.0k
  declaredAscent = t;
510
12.0k
      }
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
13.9k
      if (t > 0.55 && t < 1.9) {
516
11.9k
  if (t2 > 0.55 && t2 < 1.9) {
517
9.97k
    ascent = (t < t2) ? t : t2;
518
9.97k
  } else {
519
1.94k
    ascent = t;
520
1.94k
  }
521
11.9k
      } else if (t2 > 0.55 && t2 < 1.9) {
522
1.39k
  ascent = t2;
523
1.39k
      } else if (fontBBox[3] > 0.55 && fontBBox[3] < 1.9 &&
524
401
     fontBBox[1] < fontBBox[3]) {
525
401
  ascent = fontBBox[3];
526
401
      } else if (t > 0 && t < 1.9) {
527
24
  ascent = t;
528
201
      } else if (t2 > 0 && t2 < 1.9) {
529
0
  ascent = t2;
530
0
      }
531
13.9k
    }
532
16.6k
    obj2.free();
533
16.6k
    obj3.free();
534
535
    // get Descent
536
16.6k
    obj1.dictLookup("Descent", &obj2);
537
16.6k
    if (obj2.isNum()) {
538
15.1k
      t = 0.001 * obj2.getNum();
539
      // some broken font descriptors specify a positive descent
540
15.1k
      if (t > 0) {
541
69
  t = -t;
542
69
      }
543
      // some broken font descriptors set ascent and descent to 0
544
15.1k
      if (t < 0 && t > -1.9) {
545
14.6k
  descent = t;
546
14.6k
      } else if (fontBBox[1] > -1.9 && fontBBox[1] <= 0 &&
547
448
     fontBBox[1] < fontBBox[3]) {
548
339
  descent = fontBBox[1];
549
339
      }
550
15.1k
    }
551
16.6k
    obj2.free();
552
553
16.6k
  }
554
38.7k
  obj1.free();
555
556
  // scan font name for bold/italic tags and update the flags
557
38.7k
  if (name) {
558
18.9k
    i = name->getLength();
559
18.9k
    if (i > 2 && !strncmp(name->getCString() + i - 2, "MT", 2)) {
560
558
      i -= 2;
561
558
    }
562
18.9k
    if (i > 6 && !strncmp(name->getCString() + i - 6, "Italic", 6)) {
563
171
      flags |= fontItalic;
564
171
      i -= 6;
565
18.7k
    } else if (i > 2 && !strncmp(name->getCString() + i - 2, "It", 2)) {
566
2
      flags |= fontItalic;
567
2
      i -= 2;
568
18.7k
    } else if (i > 7 && !strncmp(name->getCString() + i - 7, "Oblique", 7)) {
569
50
      flags |= fontItalic;
570
50
      i -= 7;
571
50
    }
572
18.9k
    if (i > 0) {
573
18.8k
      char c = name->getChar(i-1);
574
18.8k
      if (!((c >= 'A' && c <= 'Z') ||
575
16.6k
      (c >= 'a' && c <= 'z') ||
576
2.07k
      (c >= '0' && c <= '9'))) {
577
544
  --i;
578
544
      }
579
18.8k
    }
580
18.9k
    if (i > 4 && !strncmp(name->getCString() + i - 4, "Bold", 4)) {
581
1.07k
      flags |= fontBold;
582
1.07k
    }
583
18.9k
  }
584
38.7k
}
585
586
CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits,
587
34.4k
                CharCodeToUnicode *ctu) {
588
34.4k
  GString *buf;
589
34.4k
  Object obj1;
590
34.4k
  char buf2[4096];
591
34.4k
  int n;
592
593
34.4k
  if (!fontDict->lookup("ToUnicode", &obj1)->isStream()) {
594
21.3k
    obj1.free();
595
21.3k
    return NULL;
596
21.3k
  }
597
13.0k
  buf = new GString();
598
13.0k
  obj1.streamReset();
599
26.1k
  while ((n = obj1.streamGetBlock(buf2, sizeof(buf2))) > 0) {
600
13.0k
    buf->append(buf2, n);
601
13.0k
  }
602
13.0k
  obj1.streamClose();
603
13.0k
  obj1.free();
604
13.0k
  if (ctu) {
605
4.61k
    ctu->mergeCMap(buf, nBits);
606
8.47k
  } else {
607
8.47k
    ctu = CharCodeToUnicode::parseCMap(buf, nBits);
608
8.47k
  }
609
13.0k
  delete buf;
610
13.0k
  hasToUnicode = gTrue;
611
13.0k
  return ctu;
612
34.4k
}
613
614
16.0k
GfxFontLoc *GfxFont::locateFont(XRef *xref, GBool ps) {
615
16.0k
  GfxFontLoc *fontLoc;
616
16.0k
  SysFontType sysFontType;
617
16.0k
  FoFiIdentifierType fft;
618
16.0k
  GString *path, *base14Name, *substName;
619
16.0k
  PSFontParam16 *psFont16;
620
16.0k
  Object refObj, embFontObj;
621
16.0k
  int substIdx, fontNum;
622
16.0k
  double oblique;
623
16.0k
  GBool embed;
624
625
16.0k
  if (type == fontType3) {
626
0
    return NULL;
627
0
  }
628
629
  //----- embedded font
630
16.0k
  if (embFontID.num >= 0) {
631
3.69k
    embed = gTrue;
632
3.69k
    refObj.initRef(embFontID.num, embFontID.gen);
633
3.69k
    refObj.fetch(xref, &embFontObj);
634
3.69k
    if (!embFontObj.isStream()) {
635
0
      error(errSyntaxError, -1, "Embedded font object is wrong type");
636
0
      embed = gFalse;
637
0
    }
638
3.69k
    embFontObj.free();
639
3.69k
    refObj.free();
640
3.69k
    if (embed) {
641
3.69k
      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
3.69k
      if (embed) {
665
3.69k
  fontLoc = new GfxFontLoc();
666
3.69k
  fontLoc->locType = gfxFontLocEmbedded;
667
3.69k
  fontLoc->fontType = type;
668
3.69k
  fontLoc->embFontID = embFontID;
669
3.69k
  return fontLoc;
670
3.69k
      }
671
3.69k
    }
672
3.69k
  }
673
674
  //----- PS passthrough
675
12.3k
  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
12.3k
  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
12.3k
  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
12.3k
  if (!ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
701
10.7k
    base14Name = new GString(((Gfx8BitFont *)this)->base14->base14Name);
702
10.7k
    path = globalParams->findBase14FontFile(base14Name, &fontNum, &oblique);
703
10.7k
    delete base14Name;
704
10.7k
    if (path && (fontLoc = getExternalFont(path, fontNum, oblique, gFalse))) {
705
0
      return fontLoc;
706
0
    }
707
10.7k
  }
708
709
  //----- system font
710
12.3k
  if (name && (path = globalParams->findSystemFontFile(name, &sysFontType,
711
11.9k
                   &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
12.3k
  if (!isCIDFont()) {
754
755
    //----- 8-bit PS resident font
756
12.3k
    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
12.3k
    if (flags & fontFixedWidth) {
768
268
      substIdx = 0;
769
12.0k
    } else if (flags & fontSerif) {
770
11.2k
      substIdx = 8;
771
11.2k
    } else {
772
768
      substIdx = 4;
773
768
    }
774
12.3k
    if (isBold()) {
775
35
      substIdx += 2;
776
35
    }
777
12.3k
    if (isItalic()) {
778
1
      substIdx += 1;
779
1
    }
780
12.3k
    substName = new GString(base14SubstFonts[substIdx]);
781
12.3k
    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
12.3k
    } else {
791
12.3k
      path = globalParams->findBase14FontFile(substName, &fontNum, &oblique);
792
12.3k
      delete substName;
793
12.3k
      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
12.3k
    }
802
803
    // failed to find a substitute font
804
12.3k
    return NULL;
805
12.3k
  }
806
807
  //----- 16-bit PS resident font
808
31
  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
31
  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
31
  if ((path = globalParams->findCCFontFile(
835
31
        ((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
31
  return NULL;
845
31
}
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
3.24k
char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
912
3.24k
  char *buf;
913
3.24k
  Object obj1, obj2;
914
3.24k
  Stream *str;
915
3.24k
  int size, n;
916
917
3.24k
  obj1.initRef(embFontID.num, embFontID.gen);
918
3.24k
  obj1.fetch(xref, &obj2);
919
3.24k
  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
3.24k
  str = obj2.getStream();
927
928
3.24k
  size = 4096;
929
3.24k
  buf = (char *)gmalloc(size);
930
3.24k
  *len = 0;
931
3.24k
  str->reset();
932
8.12k
  do {
933
8.12k
    if (*len > size - 4096) {
934
3.94k
      if (size > INT_MAX / 2) {
935
0
  error(errSyntaxError, -1, "Embedded font file is too large");
936
0
  break;
937
0
      }
938
3.94k
      size *= 2;
939
3.94k
      buf = (char *)grealloc(buf, size);
940
3.94k
    }
941
8.12k
    n = str->getBlock(buf + *len, 4096);
942
8.12k
    *len += n;
943
8.12k
  } while (n == 4096);
944
3.24k
  str->close();
945
946
3.24k
  obj2.free();
947
3.24k
  obj1.free();
948
949
3.24k
  return buf;
950
3.24k
}
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
25.8k
  GfxFont(tagA, idA, nameA, typeA, embFontIDA)
959
25.8k
{
960
25.8k
  GString *name2;
961
25.8k
  BuiltinFont *builtinFont;
962
25.8k
  const char **baseEnc;
963
25.8k
  char *buf;
964
25.8k
  int len;
965
25.8k
  FoFiType1 *ffT1;
966
25.8k
  FoFiType1C *ffT1C;
967
25.8k
  int code, code2;
968
25.8k
  char *charName;
969
25.8k
  GBool missing, hex;
970
25.8k
  Unicode toUnicode[256];
971
25.8k
  CharCodeToUnicode *utu, *ctu2;
972
25.8k
  Unicode uBuf[8];
973
25.8k
  double mul;
974
25.8k
  int firstChar, lastChar;
975
25.8k
  Gushort w;
976
25.8k
  Object obj1, obj2, obj3;
977
25.8k
  int n, i, a, b, m;
978
979
25.8k
  ctu = NULL;
980
981
  // do font name substitution for various aliases of the Base 14 font
982
  // names
983
25.8k
  base14 = NULL;
984
25.8k
  if (name) {
985
17.9k
    name2 = name->copy();
986
17.9k
    i = 0;
987
230k
    while (i < name2->getLength()) {
988
212k
      if (name2->getChar(i) == ' ') {
989
2.16k
  name2->del(i);
990
210k
      } else {
991
210k
  ++i;
992
210k
      }
993
212k
    }
994
17.9k
    a = 0;
995
17.9k
    b = sizeof(base14FontMap) / sizeof(Base14FontMapEntry);
996
    // invariant: base14FontMap[a].altName <= name2 < base14FontMap[b].altName
997
126k
    while (b - a > 1) {
998
108k
      m = (a + b) / 2;
999
108k
      if (name2->cmp(base14FontMap[m].altName) >= 0) {
1000
60.2k
  a = m;
1001
60.2k
      } else {
1002
48.0k
  b = m;
1003
48.0k
      }
1004
108k
    }
1005
17.9k
    if (!name2->cmp(base14FontMap[a].altName)) {
1006
10.8k
      base14 = &base14FontMap[a];
1007
10.8k
    }
1008
17.9k
    delete name2;
1009
17.9k
  }
1010
1011
  // is it a built-in font?
1012
25.8k
  builtinFont = NULL;
1013
25.8k
  if (base14) {
1014
56.3k
    for (i = 0; i < nBuiltinFonts; ++i) {
1015
56.3k
      if (!strcmp(base14->base14Name, builtinFonts[i].name)) {
1016
10.8k
  builtinFont = &builtinFonts[i];
1017
10.8k
  break;
1018
10.8k
      }
1019
56.3k
    }
1020
10.8k
  }
1021
1022
  // default ascent/descent values
1023
25.8k
  if (builtinFont) {
1024
10.8k
    missingWidth = builtinFont->missingWidth;
1025
10.8k
    ascent = 0.001 * builtinFont->ascent;
1026
10.8k
    descent = 0.001 * builtinFont->descent;
1027
10.8k
    declaredAscent = ascent;
1028
10.8k
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
1029
10.8k
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
1030
10.8k
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
1031
10.8k
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
1032
15.0k
  } else {
1033
15.0k
    missingWidth = 0;
1034
15.0k
    ascent = 0.75;
1035
15.0k
    descent = -0.25;
1036
15.0k
    declaredAscent = ascent;
1037
15.0k
    fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1038
15.0k
  }
1039
1040
  // get info from font descriptor
1041
25.8k
  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
25.8k
  if (builtinFont) {
1046
10.8k
    ascent = 0.001 * builtinFont->ascent;
1047
10.8k
    descent = 0.001 * builtinFont->descent;
1048
10.8k
    declaredAscent = ascent;
1049
10.8k
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
1050
10.8k
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
1051
10.8k
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
1052
10.8k
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
1053
10.8k
  }
1054
1055
  // get font matrix
1056
25.8k
  fontMat[0] = fontMat[3] = 1;
1057
25.8k
  fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
1058
25.8k
  if (fontDict->lookup("FontMatrix", &obj1)->isArray()) {
1059
2.82k
    for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
1060
2.36k
      if (obj1.arrayGet(i, &obj2)->isNum()) {
1061
2.15k
  fontMat[i] = obj2.getNum();
1062
2.15k
      }
1063
2.36k
      obj2.free();
1064
2.36k
    }
1065
453
  }
1066
25.8k
  obj1.free();
1067
1068
  // get Type 3 bounding box, font definition, and resources
1069
25.8k
  if (type == fontType3) {
1070
519
    if (fontDict->lookup("FontBBox", &obj1)->isArray()) {
1071
1.60k
      for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
1072
1.28k
  if (obj1.arrayGet(i, &obj2)->isNum()) {
1073
1.20k
    fontBBox[i] = obj2.getNum();
1074
1.20k
  }
1075
1.28k
  obj2.free();
1076
1.28k
      }
1077
323
    }
1078
519
    obj1.free();
1079
519
    if (!fontDict->lookup("CharProcs", &charProcs)->isDict()) {
1080
90
      error(errSyntaxError, -1,
1081
90
      "Missing or invalid CharProcs dictionary in Type 3 font");
1082
90
      charProcs.free();
1083
90
    }
1084
519
    if (!fontDict->lookup("Resources", &resources)->isDict()) {
1085
387
      resources.free();
1086
387
    }
1087
519
  }
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
25.8k
  hasEncoding = gFalse;
1105
25.8k
  usesMacRomanEnc = gFalse;
1106
25.8k
  baseEnc = NULL;
1107
25.8k
  baseEncFromFontFile = gFalse;
1108
25.8k
  fontDict->lookup("Encoding", &obj1);
1109
25.8k
  if (obj1.isDict()) {
1110
3.31k
    obj1.dictLookup("BaseEncoding", &obj2);
1111
3.31k
    if (obj2.isName("MacRomanEncoding")) {
1112
0
      hasEncoding = gTrue;
1113
0
      usesMacRomanEnc = gTrue;
1114
0
      baseEnc = macRomanEncoding;
1115
3.31k
    } else if (obj2.isName("MacExpertEncoding")) {
1116
0
      hasEncoding = gTrue;
1117
0
      baseEnc = macExpertEncoding;
1118
3.31k
    } else if (obj2.isName("WinAnsiEncoding")) {
1119
328
      hasEncoding = gTrue;
1120
328
      baseEnc = winAnsiEncoding;
1121
328
    }
1122
3.31k
    obj2.free();
1123
22.5k
  } else if (obj1.isName("MacRomanEncoding")) {
1124
1.03k
    hasEncoding = gTrue;
1125
1.03k
    usesMacRomanEnc = gTrue;
1126
1.03k
    baseEnc = macRomanEncoding;
1127
21.5k
  } else if (obj1.isName("MacExpertEncoding")) {
1128
0
    hasEncoding = gTrue;
1129
0
    baseEnc = macExpertEncoding;
1130
21.5k
  } else if (obj1.isName("WinAnsiEncoding")) {
1131
1.00k
    hasEncoding = gTrue;
1132
1.00k
    baseEnc = winAnsiEncoding;
1133
1.00k
  }
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
25.8k
  if (builtinFont && embFontID.num < 0 &&
1140
10.8k
      (builtinFont->defaultBaseEnc == symbolEncoding ||
1141
10.8k
       builtinFont->defaultBaseEnc == zapfDingbatsEncoding) &&
1142
40
      !obj1.isDict()) {
1143
40
    baseEnc = NULL;
1144
40
  }
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
25.8k
  ffT1 = NULL;
1150
25.8k
  ffT1C = NULL;
1151
25.8k
  buf = NULL;
1152
25.8k
  if (type == fontType1 && embFontID.num >= 0) {
1153
1.30k
    if ((buf = readEmbFontFile(xref, &len))) {
1154
1.30k
      if ((ffT1 = FoFiType1::make(buf, len))) {
1155
1.30k
  if (ffT1->getName()) {
1156
459
    if (embFontName) {
1157
442
      delete embFontName;
1158
442
    }
1159
459
    embFontName = new GString(ffT1->getName());
1160
459
  }
1161
1.30k
  if (!baseEnc) {
1162
1.28k
    baseEnc = (const char **)ffT1->getEncoding();
1163
1.28k
    baseEncFromFontFile = gTrue;
1164
1.28k
  }
1165
1.30k
      }
1166
1.30k
      gfree(buf);
1167
1.30k
    }
1168
24.5k
  } else if (type == fontType1C && embFontID.num >= 0) {
1169
1.93k
    if ((buf = readEmbFontFile(xref, &len))) {
1170
1.93k
      if ((ffT1C = FoFiType1C::make(buf, len))) {
1171
1.13k
  if (ffT1C->getName()) {
1172
1.13k
    if (embFontName) {
1173
982
      delete embFontName;
1174
982
    }
1175
1.13k
    embFontName = new GString(ffT1C->getName());
1176
1.13k
  }
1177
1.13k
  if (!baseEnc) {
1178
665
    baseEnc = (const char **)ffT1C->getEncoding();
1179
665
    baseEncFromFontFile = gTrue;
1180
665
  }
1181
1.13k
      }
1182
1.93k
      gfree(buf);
1183
1.93k
    }
1184
1.93k
  }
1185
1186
  // get default base encoding
1187
25.8k
  if (!baseEnc) {
1188
22.2k
    if (builtinFont && embFontID.num < 0) {
1189
10.0k
      baseEnc = builtinFont->defaultBaseEnc;
1190
10.0k
      hasEncoding = gTrue;
1191
12.1k
    } else if (type == fontTrueType) {
1192
1.27k
      baseEnc = winAnsiEncoding;
1193
10.9k
    } else {
1194
10.9k
      baseEnc = standardEncoding;
1195
10.9k
    }
1196
22.2k
  }
1197
1198
  // copy the base encoding
1199
6.65M
  for (i = 0; i < 256; ++i) {
1200
6.62M
    enc[i] = (char *)baseEnc[i];
1201
6.62M
    if ((encFree[i] = (char)baseEncFromFontFile) && enc[i]) {
1202
151k
      enc[i] = copyString(baseEnc[i]);
1203
151k
    }
1204
6.62M
  }
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
25.8k
  if (type == fontType1C && embFontID.num >= 0 && baseEncFromFontFile) {
1211
170k
    for (i = 0; i < 256; ++i) {
1212
170k
      if (!enc[i] && standardEncoding[i]) {
1213
69.1k
  enc[i] = (char *)standardEncoding[i];
1214
69.1k
  encFree[i] = gFalse;
1215
69.1k
      }
1216
170k
    }
1217
665
  }
1218
1219
  // merge differences into encoding
1220
25.8k
  if (obj1.isDict()) {
1221
3.31k
    obj1.dictLookup("Differences", &obj2);
1222
3.31k
    if (obj2.isArray()) {
1223
1.82k
      hasEncoding = gTrue;
1224
1.82k
      code = 0;
1225
292k
      for (i = 0; i < obj2.arrayGetLength(); ++i) {
1226
291k
  obj2.arrayGet(i, &obj3);
1227
291k
  if (obj3.isInt()) {
1228
50.5k
    code = obj3.getInt();
1229
240k
  } else if (obj3.isName()) {
1230
146k
    if (code >= 0 && code < 256) {
1231
144k
      if (encFree[code]) {
1232
24.0k
        gfree(enc[code]);
1233
24.0k
      }
1234
144k
      enc[code] = copyString(obj3.getName());
1235
144k
      encFree[code] = gTrue;
1236
144k
    }
1237
146k
    ++code;
1238
146k
  } else {
1239
93.9k
    error(errSyntaxError, -1,
1240
93.9k
    "Wrong type in font encoding resource differences ({0:s})",
1241
93.9k
    obj3.getTypeName());
1242
93.9k
  }
1243
291k
  obj3.free();
1244
291k
      }
1245
1.82k
    }
1246
3.31k
    obj2.free();
1247
3.31k
  }
1248
25.8k
  obj1.free();
1249
25.8k
  if (ffT1) {
1250
1.30k
    delete ffT1;
1251
1.30k
  }
1252
25.8k
  if (ffT1C) {
1253
1.13k
    delete ffT1C;
1254
1.13k
  }
1255
1256
  //----- build the mapping to Unicode -----
1257
1258
  // pass 1: use the name-to-Unicode mapping table
1259
25.8k
  missing = hex = gFalse;
1260
6.65M
  for (code = 0; code < 256; ++code) {
1261
6.62M
    if ((charName = enc[code])) {
1262
4.09M
      if (!(toUnicode[code] = globalParams->mapNameToUnicode(charName)) &&
1263
52.8k
    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
42.7k
  if ((strlen(charName) == 3 &&
1268
14.3k
       isalpha(charName[0] & 0xff) &&
1269
14.2k
       isxdigit(charName[1] & 0xff) && isxdigit(charName[2] & 0xff) &&
1270
12.2k
       ((charName[1] >= 'a' && charName[1] <= 'f') ||
1271
12.1k
        (charName[1] >= 'A' && charName[1] <= 'F') ||
1272
12.1k
        (charName[2] >= 'a' && charName[2] <= 'f') ||
1273
11.5k
        (charName[2] >= 'A' && charName[2] <= 'F'))) ||
1274
41.9k
      (strlen(charName) == 2 &&
1275
4.05k
       isxdigit(charName[0] & 0xff) && isxdigit(charName[1] & 0xff) &&
1276
1.05k
       ((charName[0] >= 'a' && charName[0] <= 'f') ||
1277
757
        (charName[0] >= 'A' && charName[0] <= 'F') ||
1278
65
        (charName[1] >= 'a' && charName[1] <= 'f') ||
1279
1.72k
        (charName[1] >= 'A' && charName[1] <= 'F')))) {
1280
1.72k
    hex = gTrue;
1281
1.72k
  }
1282
42.7k
  missing = gTrue;
1283
42.7k
      }
1284
4.09M
    } else {
1285
2.53M
      toUnicode[code] = 0;
1286
2.53M
    }
1287
6.62M
  }
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
25.8k
  usedNumericHeuristic = gFalse;
1301
25.8k
  if (missing && globalParams->getMapNumericCharNames()) {
1302
344k
    for (code = 0; code < 256; ++code) {
1303
343k
      if ((charName = enc[code]) && !toUnicode[code] &&
1304
47.8k
    strcmp(charName, ".notdef")) {
1305
42.7k
  n = (int)strlen(charName);
1306
42.7k
  code2 = -1;
1307
42.7k
  if (hex && n == 3 && isalpha(charName[0] & 0xff) &&
1308
5.74k
      isxdigit(charName[1] & 0xff) && isxdigit(charName[2] & 0xff)) {
1309
5.33k
    sscanf(charName+1, "%x", &code2);
1310
37.3k
  } else if (hex && n == 2 &&
1311
1.49k
       isxdigit(charName[0] & 0xff) &&
1312
1.35k
       isxdigit(charName[1] & 0xff)) {
1313
1.01k
    sscanf(charName, "%x", &code2);
1314
36.3k
  } else if (!hex && n >= 2 && n <= 4 &&
1315
25.6k
       isdigit(charName[0] & 0xff) && isdigit(charName[1] & 0xff)) {
1316
43
    code2 = atoi(charName);
1317
36.3k
  } else if (n >= 3 && n <= 5 &&
1318
26.7k
       isdigit(charName[1] & 0xff) && isdigit(charName[2] & 0xff)) {
1319
24.0k
    code2 = atoi(charName+1);
1320
24.0k
  } else if (n >= 4 && n <= 6 &&
1321
1.28k
       isdigit(charName[2] & 0xff) && isdigit(charName[3] & 0xff)) {
1322
50
    code2 = atoi(charName+2);
1323
12.2k
  } else if (n >= 7 && charName[0] == 'u' && charName[1] == 'n' &&
1324
170
       charName[2] == 'i' &&
1325
154
       isxdigit(charName[3] & 0xff) &&
1326
137
       isxdigit(charName[4] & 0xff) &&
1327
135
       isxdigit(charName[5] & 0xff) &&
1328
134
       isxdigit(charName[6] & 0xff)) {
1329
133
    sscanf(charName + 3, "%x", &code2);
1330
133
  }
1331
42.7k
  if (code2 >= 0 && code2 <= 0xffff) {
1332
30.6k
    toUnicode[code] = (Unicode)code2;
1333
30.6k
    usedNumericHeuristic = gTrue;
1334
30.6k
  }
1335
42.7k
      }
1336
343k
    }
1337
1338
  // if the 'mapUnknownCharNames' flag is set, do a simple pass-through
1339
  // mapping for unknown character names
1340
24.5k
  } 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
25.8k
  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
25.8k
  readToUnicodeCMap(fontDict, 8, ctu);
1356
1357
  // look for a Unicode-to-Unicode mapping
1358
25.8k
  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
6.65M
  for (code = 0; code < 256; ++code) {
1381
6.62M
    widths[code] = missingWidth * 0.001;
1382
6.62M
  }
1383
1384
  // use widths from font dict, if present
1385
25.8k
  fontDict->lookup("FirstChar", &obj1);
1386
25.8k
  firstChar = obj1.isInt() ? obj1.getInt() : 0;
1387
25.8k
  obj1.free();
1388
25.8k
  if (firstChar < 0 || firstChar > 255) {
1389
11
    firstChar = 0;
1390
11
  }
1391
25.8k
  fontDict->lookup("LastChar", &obj1);
1392
25.8k
  lastChar = obj1.isInt() ? obj1.getInt() : 255;
1393
25.8k
  obj1.free();
1394
25.8k
  if (lastChar < 0 || lastChar > 255) {
1395
2
    lastChar = 255;
1396
2
  }
1397
25.8k
  mul = (type == fontType3) ? fontMat[0] : 0.001;
1398
25.8k
  fontDict->lookup("Widths", &obj1);
1399
25.8k
  if (obj1.isArray()) {
1400
5.23k
    flags |= fontFixedWidth;
1401
5.23k
    if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
1402
953
      lastChar = firstChar + obj1.arrayGetLength() - 1;
1403
953
    }
1404
317k
    for (code = firstChar; code <= lastChar; ++code) {
1405
312k
      obj1.arrayGet(code - firstChar, &obj2);
1406
312k
      if (obj2.isNum()) {
1407
306k
  widths[code] = obj2.getNum() * mul;
1408
306k
  if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
1409
286k
    flags &= ~fontFixedWidth;
1410
286k
  }
1411
306k
      }
1412
312k
      obj2.free();
1413
312k
    }
1414
1415
  // use widths from built-in font
1416
20.6k
  } else if (builtinFont) {
1417
    // this is a kludge for broken PDF files that encode char 32
1418
    // as .notdef
1419
10.8k
    if (builtinFont->widths->getWidth("space", &w)) {
1420
10.8k
      widths[32] = 0.001 * w;
1421
10.8k
    }
1422
2.78M
    for (code = 0; code < 256; ++code) {
1423
2.77M
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1424
1.67M
  widths[code] = 0.001 * w;
1425
1.67M
      }
1426
2.77M
    }
1427
1428
  // couldn't find widths -- use defaults 
1429
10.8k
  } 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
9.83k
    if (isFixedWidth()) {
1434
1.32k
      i = 0;
1435
8.51k
    } else if (isSerif()) {
1436
8.09k
      i = 8;
1437
8.09k
    } else {
1438
416
      i = 4;
1439
416
    }
1440
9.83k
    if (isBold()) {
1441
183
      i += 2;
1442
183
    }
1443
9.83k
    if (isItalic()) {
1444
4
      i += 1;
1445
4
    }
1446
9.83k
    builtinFont = builtinFontSubst[i];
1447
    // this is a kludge for broken PDF files that encode char 32
1448
    // as .notdef
1449
9.83k
    if (builtinFont->widths->getWidth("space", &w)) {
1450
9.83k
      widths[32] = 0.001 * w;
1451
9.83k
    }
1452
2.52M
    for (code = 0; code < 256; ++code) {
1453
2.51M
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
1454
1.48M
  widths[code] = 0.001 * w;
1455
1.48M
      }
1456
2.51M
    }
1457
9.83k
  }
1458
25.8k
  obj1.free();
1459
1460
25.8k
  ok = gTrue;
1461
25.8k
}
1462
1463
25.8k
Gfx8BitFont::~Gfx8BitFont() {
1464
25.8k
  int i;
1465
1466
6.65M
  for (i = 0; i < 256; ++i) {
1467
6.62M
    if (encFree[i] && enc[i]) {
1468
281k
      gfree(enc[i]);
1469
281k
    }
1470
6.62M
  }
1471
25.8k
  ctu->decRefCnt();
1472
25.8k
  if (charProcs.isDict()) {
1473
429
    charProcs.free();
1474
429
  }
1475
25.8k
  if (resources.isDict()) {
1476
132
    resources.free();
1477
132
  }
1478
25.8k
}
1479
1480
int Gfx8BitFont::getNextChar(char *s, int len, CharCode *code,
1481
           Unicode *u, int uSize, int *uLen,
1482
5.82M
           double *dx, double *dy, double *ox, double *oy) {
1483
5.82M
  CharCode c;
1484
1485
5.82M
  *code = c = (CharCode)(*s & 0xff);
1486
5.82M
  *uLen = ctu->mapToUnicode(c, u, uSize);
1487
5.82M
  *dx = widths[c];
1488
5.82M
  *dy = *ox = *oy = 0;
1489
5.82M
  return 1;
1490
5.82M
}
1491
1492
0
CharCodeToUnicode *Gfx8BitFont::getToUnicode() {
1493
0
  ctu->incRefCnt();
1494
0
  return ctu;
1495
0
}
1496
1497
1.18k
int *Gfx8BitFont::getCodeToGIDMap(FoFiTrueType *ff) {
1498
1.18k
  int *map;
1499
1.18k
  int cmapPlatform, cmapEncoding;
1500
1.18k
  int unicodeCmap, macRomanCmap, macUnicodeCmap, msSymbolCmap, cmap;
1501
1.18k
  GBool nonsymbolic, useMacRoman, useUnicode;
1502
1.18k
  char *charName;
1503
1.18k
  Unicode u;
1504
1.18k
  int code, i, n;
1505
1506
1.18k
  map = (int *)gmallocn(256, sizeof(int));
1507
304k
  for (i = 0; i < 256; ++i) {
1508
303k
    map[i] = 0;
1509
303k
  }
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
1.18k
  unicodeCmap = macRomanCmap = macUnicodeCmap = msSymbolCmap = -1;
1515
2.35k
  for (i = 0; i < ff->getNumCmaps(); ++i) {
1516
1.16k
    cmapPlatform = ff->getCmapPlatform(i);
1517
1.16k
    cmapEncoding = ff->getCmapEncoding(i);
1518
1.16k
    if (cmapPlatform == 3 && cmapEncoding == 1) {
1519
1
      unicodeCmap = i;
1520
1.16k
    } else if (cmapPlatform == 1 && cmapEncoding == 0) {
1521
798
      macRomanCmap = i;
1522
798
    } else if (cmapPlatform == 0 && cmapEncoding <= 4) {
1523
109
      macUnicodeCmap = i;
1524
258
    } else if (cmapPlatform == 3 && cmapEncoding == 0) {
1525
1
      msSymbolCmap = i;
1526
1
    }
1527
1.16k
  }
1528
1.18k
  useMacRoman = gFalse;
1529
1.18k
  useUnicode = gFalse;
1530
1.18k
  nonsymbolic = !(flags & fontSymbolic);
1531
1.18k
  if (embFontID.num < 0 && hasEncoding && unicodeCmap >= 0) { 
1532
0
    cmap = unicodeCmap;
1533
0
    useUnicode = gTrue;
1534
1.18k
  } else if (!nonsymbolic && msSymbolCmap >= 0) {
1535
1
    cmap = msSymbolCmap;
1536
1.18k
  } else if (unicodeCmap >= 0) {
1537
1
    cmap = unicodeCmap;
1538
1
    useUnicode = nonsymbolic;
1539
1.18k
  } 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
1.18k
  } else if (macUnicodeCmap >= 0) {
1545
41
    cmap = macUnicodeCmap;
1546
41
    useUnicode = nonsymbolic;
1547
1.14k
  } else if (macRomanCmap >= 0) {
1548
798
    cmap = macRomanCmap;
1549
798
    useMacRoman = nonsymbolic;
1550
798
  } else {
1551
344
    cmap = 0;
1552
344
  }
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
1.18k
  if (useMacRoman) {
1558
62.1k
    for (i = 0; i < 256; ++i) {
1559
61.9k
      if ((charName = enc[i])) {
1560
54.2k
  if ((code = globalParams->getMacRomanCharCode(charName))) {
1561
49.6k
    map[i] = ff->mapCodeToGID(cmap, code);
1562
49.6k
  } else if (unicodeCmap >= 0 &&
1563
0
       (u = globalParams->mapNameToUnicode(charName))) {
1564
0
    map[i] = ff->mapCodeToGID(unicodeCmap, u);
1565
0
  }
1566
54.2k
      } else if (unicodeCmap >= 0 &&
1567
0
     (n = ctu->mapToUnicode((CharCode)i, &u, 1))) {
1568
0
  map[i] = ff->mapCodeToGID(cmap, u);
1569
7.74k
      } else {
1570
7.74k
  map[i] = -1;
1571
7.74k
      }
1572
61.9k
    }
1573
1574
  // map Unicode through the cmap
1575
943
  } else if (useUnicode) {
1576
514
    for (i = 0; i < 256; ++i) {
1577
512
      if (((charName = enc[i]) &&
1578
448
     (u = globalParams->mapNameToUnicode(charName))) ||
1579
448
    (n = ctu->mapToUnicode((CharCode)i, &u, 1))) {
1580
448
  map[i] = ff->mapCodeToGID(cmap, u);
1581
448
      } else {
1582
64
  map[i] = -1;
1583
64
      }
1584
512
    }
1585
1586
  // map the char codes through the cmap, possibly with an offset of
1587
  // 0xf000
1588
941
  } else {
1589
241k
    for (i = 0; i < 256; ++i) {
1590
240k
      if (!(map[i] = ff->mapCodeToGID(cmap, i))) {
1591
216k
  map[i] = ff->mapCodeToGID(cmap, 0xf000 + i);
1592
216k
      }
1593
240k
    }
1594
941
  }
1595
1596
  // try the TrueType 'post' table to handle any unmapped characters
1597
304k
  for (i = 0; i < 256; ++i) {
1598
303k
    if (map[i] <= 0 && (charName = enc[i])) {
1599
236k
      map[i] = ff->mapNameToGID(charName);
1600
236k
    }
1601
303k
  }
1602
1603
1.18k
  return map;
1604
1.18k
}
1605
1606
726
int *Gfx8BitFont::getCodeToGIDMap(FoFiType1C *ff) {
1607
726
  int *map;
1608
726
  GHash *nameToGID;
1609
726
  int i, gid;
1610
1611
726
  map = (int *)gmallocn(256, sizeof(int));
1612
186k
  for (i = 0; i < 256; ++i) {
1613
185k
    map[i] = 0;
1614
185k
  }
1615
1616
726
  nameToGID = ff->getNameToGIDMap();
1617
186k
  for (i = 0; i < 256; ++i) {
1618
185k
    if (!enc[i]) {
1619
38.3k
      continue;
1620
38.3k
    }
1621
147k
    gid = nameToGID->lookupInt(enc[i]);
1622
147k
    if (gid < 0 || gid >= 65536) {
1623
0
      continue;
1624
0
    }
1625
147k
    map[i] = gid;
1626
147k
  }
1627
1628
726
  delete nameToGID;
1629
1630
726
  return map;
1631
726
}
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
1.34M
Object *Gfx8BitFont::getCharProcNF(int code, Object *proc) {
1647
1.34M
  if (enc[code] && charProcs.isDict()) {
1648
819k
    charProcs.dictLookupNF(enc[code], proc);
1649
819k
  } else {
1650
526k
    proc->initNull();
1651
526k
  }
1652
1.34M
  return proc;
1653
1.34M
}
1654
1655
1.34M
Dict *Gfx8BitFont::getResources() {
1656
1.34M
  return resources.isDict() ? resources.getDict() : (Dict *)NULL;
1657
1.34M
}
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
12.8k
  GfxFont(tagA, idA, nameA, typeA, embFontIDA)
1729
12.8k
{
1730
12.8k
  Dict *desFontDict;
1731
12.8k
  Object desFontDictObj;
1732
12.8k
  Object obj1, obj2, obj3, obj4, obj5, obj6;
1733
12.8k
  CharCodeToUnicode *utu;
1734
12.8k
  CharCode c;
1735
12.8k
  Unicode uBuf[8];
1736
12.8k
  int c1, c2;
1737
12.8k
  int excepsSize, i, j, k, n;
1738
1739
12.8k
  missingWidth = 0;
1740
12.8k
  ascent = 0.95;
1741
12.8k
  descent = -0.35;
1742
12.8k
  declaredAscent = ascent;
1743
12.8k
  fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
1744
12.8k
  collection = NULL;
1745
12.8k
  cMap = NULL;
1746
12.8k
  ctu = NULL;
1747
12.8k
  ctuUsesCharCode = gTrue;
1748
12.8k
  widths.defWidth = 1.0;
1749
12.8k
  widths.defHeight = -1.0;
1750
12.8k
  widths.defVY = 0.880;
1751
12.8k
  widths.exceps = NULL;
1752
12.8k
  widths.nExceps = 0;
1753
12.8k
  widths.excepsV = NULL;
1754
12.8k
  widths.nExcepsV = 0;
1755
12.8k
  cidToGID = NULL;
1756
12.8k
  cidToGIDLen = 0;
1757
1758
  // get the descendant font
1759
12.8k
  if (!fontDict->lookup("DescendantFonts", &obj1)->isArray() ||
1760
12.8k
      obj1.arrayGetLength() == 0) {
1761
7
    error(errSyntaxError, -1,
1762
7
    "Missing or empty DescendantFonts entry in Type 0 font");
1763
7
    obj1.free();
1764
7
    goto err1;
1765
7
  }
1766
12.8k
  if (!obj1.arrayGet(0, &desFontDictObj)->isDict()) {
1767
4
    error(errSyntaxError, -1, "Bad descendant font in Type 0 font");
1768
4
    goto err2;
1769
4
  }
1770
12.8k
  obj1.free();
1771
12.8k
  desFontDict = desFontDictObj.getDict();
1772
1773
  // get info from font descriptor
1774
12.8k
  readFontDescriptor(xref, desFontDict);
1775
1776
  //----- encoding info -----
1777
1778
  // char collection
1779
12.8k
  if (!desFontDict->lookup("CIDSystemInfo", &obj1)->isDict()) {
1780
1.49k
    error(errSyntaxError, -1,
1781
1.49k
    "Missing CIDSystemInfo dictionary in Type 0 descendant font");
1782
1.49k
    goto err2;
1783
1.49k
  }
1784
11.3k
  obj1.dictLookup("Registry", &obj2);
1785
11.3k
  obj1.dictLookup("Ordering", &obj3);
1786
11.3k
  if (!obj2.isString() || !obj3.isString()) {
1787
1.32k
    error(errSyntaxError, -1,
1788
1.32k
    "Invalid CIDSystemInfo dictionary in Type 0 descendant font");
1789
1.32k
    goto err3;
1790
1.32k
  }
1791
10.0k
  collection = obj2.getString()->copy()->append('-')->append(obj3.getString());
1792
10.0k
  obj3.free();
1793
10.0k
  obj2.free();
1794
10.0k
  obj1.free();
1795
1796
  // encoding (i.e., CMap)
1797
10.0k
  if (fontDict->lookup("Encoding", &obj1)->isNull()) {
1798
1
    error(errSyntaxError, -1, "Missing Encoding entry in Type 0 font");
1799
1
    goto err2;
1800
1
  }
1801
10.0k
  if (!(cMap = CMap::parse(NULL, collection, &obj1))) {
1802
1.44k
    goto err2;
1803
1.44k
  }
1804
1805
  // check for fonts that use the Identity-H encoding (cmap), and the
1806
  // Adobe-Identity character collection
1807
8.58k
  identityEnc = obj1.isName("Identity-H") &&
1808
524
                !collection->cmp("Adobe-Identity");
1809
1810
8.58k
  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
8.58k
  hasIdentityCIDToGID = gFalse;
1817
8.58k
  desFontDict->lookup("CIDToGIDMap", &obj1);
1818
8.58k
  if (obj1.isStream()) {
1819
20
    cidToGIDLen = 0;
1820
20
    i = 64;
1821
20
    cidToGID = (int *)gmallocn(i, sizeof(int));
1822
20
    obj1.streamReset();
1823
263k
    while ((c1 = obj1.streamGetChar()) != EOF &&
1824
263k
     (c2 = obj1.streamGetChar()) != EOF) {
1825
263k
      if (cidToGIDLen == i) {
1826
55
  i *= 2;
1827
55
  cidToGID = (int *)greallocn(cidToGID, i, sizeof(int));
1828
55
      }
1829
263k
      cidToGID[cidToGIDLen++] = (c1 << 8) + c2;
1830
263k
    }
1831
20
    obj1.streamClose();
1832
20
    identityEnc = gFalse;
1833
8.56k
  } else if (obj1.isName("Identity")) {
1834
421
    hasIdentityCIDToGID = gTrue;
1835
8.13k
  } else if (!obj1.isNull()) {
1836
7
    error(errSyntaxError, -1, "Invalid CIDToGIDMap entry in CID font");
1837
7
  }
1838
8.58k
  obj1.free();
1839
1840
  // look for a ToUnicode CMap
1841
8.58k
  hasKnownCollection = gFalse;
1842
8.58k
  if (globalParams->getUseTrueTypeUnicodeMapping()) {
1843
0
    readTrueTypeUnicodeMapping(xref);
1844
0
  }
1845
8.58k
  if (!ctu) {
1846
8.58k
    ctu = readToUnicodeCMap(fontDict, 16, NULL);
1847
8.58k
  }
1848
8.58k
  if (!ctu) {
1849
8.41k
    ctuUsesCharCode = gFalse;
1850
1851
    // use an identity mapping for the "Adobe-Identity" and
1852
    // "Adobe-UCS" collections
1853
8.41k
    if (!collection->cmp("Adobe-Identity") ||
1854
8.33k
  !collection->cmp("Adobe-UCS")) {
1855
78
      ctu = CharCodeToUnicode::makeIdentityMapping();
1856
1857
    // look for a user-supplied .cidToUnicode file
1858
8.33k
    } else if ((ctu = globalParams->getCIDToUnicode(collection))) {
1859
0
      hasKnownCollection = gTrue;
1860
1861
8.33k
    } else {
1862
8.33k
      error(errSyntaxError, -1,
1863
8.33k
      "Unknown character collection '{0:t}'", collection);
1864
1865
      // fall back to an identity mapping
1866
8.33k
      ctu = CharCodeToUnicode::makeIdentityMapping();
1867
8.33k
    }
1868
8.41k
  }
1869
1870
  // look for a Unicode-to-Unicode mapping
1871
8.58k
  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
8.58k
  if (desFontDict->lookup("DW", &obj1)->isNum()) {
1897
491
    widths.defWidth = obj1.getNum() * 0.001;
1898
491
  }
1899
8.58k
  obj1.free();
1900
1901
  // char width exceptions
1902
8.58k
  if (desFontDict->lookup("W", &obj1)->isArray()) {
1903
8.51k
    excepsSize = 0;
1904
8.51k
    i = 0;
1905
61.5k
    while (i + 1 < obj1.arrayGetLength()) {
1906
53.0k
      obj1.arrayGet(i, &obj2);
1907
53.0k
      obj1.arrayGet(i + 1, &obj3);
1908
53.0k
      if (obj2.isInt() && obj3.isInt() && i + 2 < obj1.arrayGetLength()) {
1909
16.7k
  if (obj1.arrayGet(i + 2, &obj4)->isNum()) {
1910
16.6k
    if (widths.nExceps == excepsSize) {
1911
50
      excepsSize += 16;
1912
50
      widths.exceps = (GfxFontCIDWidthExcep *)
1913
50
        greallocn(widths.exceps,
1914
50
      excepsSize, sizeof(GfxFontCIDWidthExcep));
1915
50
    }
1916
16.6k
    widths.exceps[widths.nExceps].first = obj2.getInt();
1917
16.6k
    widths.exceps[widths.nExceps].last = obj3.getInt();
1918
16.6k
    widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1919
16.6k
    ++widths.nExceps;
1920
16.6k
  } else {
1921
138
    error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1922
138
  }
1923
16.7k
  obj4.free();
1924
16.7k
  i += 3;
1925
36.2k
      } else if (obj2.isInt() && obj3.isArray()) {
1926
19.8k
  if (widths.nExceps + obj3.arrayGetLength() > excepsSize) {
1927
8.76k
    excepsSize = (widths.nExceps + obj3.arrayGetLength() + 15) & ~15;
1928
8.76k
    widths.exceps = (GfxFontCIDWidthExcep *)
1929
8.76k
      greallocn(widths.exceps,
1930
8.76k
          excepsSize, sizeof(GfxFontCIDWidthExcep));
1931
8.76k
  }
1932
19.8k
  j = obj2.getInt();
1933
72.1k
  for (k = 0; k < obj3.arrayGetLength(); ++k) {
1934
52.3k
    if (obj3.arrayGet(k, &obj4)->isNum()) {
1935
51.6k
      widths.exceps[widths.nExceps].first = j;
1936
51.6k
      widths.exceps[widths.nExceps].last = j;
1937
51.6k
      widths.exceps[widths.nExceps].width = obj4.getNum() * 0.001;
1938
51.6k
      ++j;
1939
51.6k
      ++widths.nExceps;
1940
51.6k
    } else {
1941
660
      error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1942
660
    }
1943
52.3k
    obj4.free();
1944
52.3k
  }
1945
19.8k
  i += 2;
1946
19.8k
      } else {
1947
16.4k
  error(errSyntaxError, -1, "Bad widths array in Type 0 font");
1948
16.4k
  ++i;
1949
16.4k
      }
1950
53.0k
      obj3.free();
1951
53.0k
      obj2.free();
1952
53.0k
    }
1953
8.51k
  }
1954
8.58k
  obj1.free();
1955
1956
  // default metrics for vertical font
1957
8.58k
  if (desFontDict->lookup("DW2", &obj1)->isArray() &&
1958
8
      obj1.arrayGetLength() == 2) {
1959
5
    if (obj1.arrayGet(0, &obj2)->isNum()) {
1960
5
      widths.defVY = obj2.getNum() * 0.001;
1961
5
    }
1962
5
    obj2.free();
1963
5
    if (obj1.arrayGet(1, &obj2)->isNum()) {
1964
4
      widths.defHeight = obj2.getNum() * 0.001;
1965
4
    }
1966
5
    obj2.free();
1967
5
  }
1968
8.58k
  obj1.free();
1969
1970
  // char metric exceptions for vertical font
1971
8.58k
  if (desFontDict->lookup("W2", &obj1)->isArray()) {
1972
17
    excepsSize = 0;
1973
17
    i = 0;
1974
38
    while (i + 1 < obj1.arrayGetLength()) {
1975
21
      obj1.arrayGet(i, &obj2);
1976
21
      obj1.arrayGet(i+ 1, &obj3);
1977
21
      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
21
      } else if (obj2.isInt() && obj3.isArray()) {
2001
16
  if (widths.nExcepsV + obj3.arrayGetLength() / 3 > excepsSize) {
2002
15
    excepsSize =
2003
15
      (widths.nExcepsV + obj3.arrayGetLength() / 3 + 15) & ~15;
2004
15
    widths.excepsV = (GfxFontCIDWidthExcepV *)
2005
15
      greallocn(widths.excepsV,
2006
15
          excepsSize, sizeof(GfxFontCIDWidthExcepV));
2007
15
  }
2008
16
  j = obj2.getInt();
2009
61
  for (k = 0; k + 2 < obj3.arrayGetLength(); k += 3) {
2010
45
    if (obj3.arrayGet(k, &obj4)->isNum() &&
2011
35
        obj3.arrayGet(k+1, &obj5)->isNum() &&
2012
14
        obj3.arrayGet(k+2, &obj6)->isNum()) {
2013
5
      widths.excepsV[widths.nExcepsV].first = j;
2014
5
      widths.excepsV[widths.nExcepsV].last = j;
2015
5
      widths.excepsV[widths.nExcepsV].height = obj4.getNum() * 0.001;
2016
5
      widths.excepsV[widths.nExcepsV].vx = obj5.getNum() * 0.001;
2017
5
      widths.excepsV[widths.nExcepsV].vy = obj6.getNum() * 0.001;
2018
5
      ++j;
2019
5
      ++widths.nExcepsV;
2020
40
    } else {
2021
40
      error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2022
40
    }
2023
45
    obj6.free();
2024
45
    obj5.free();
2025
45
    obj4.free();
2026
45
  }
2027
16
  i += 2;
2028
16
      } else {
2029
5
  error(errSyntaxError, -1, "Bad widths (W2) array in Type 0 font");
2030
5
  ++i;
2031
5
      }
2032
21
      obj3.free();
2033
21
      obj2.free();
2034
21
    }
2035
17
  }
2036
8.58k
  obj1.free();
2037
2038
8.58k
  desFontDictObj.free();
2039
8.58k
  ok = gTrue;
2040
8.58k
  return;
2041
2042
1.32k
 err3:
2043
1.32k
  obj3.free();
2044
1.32k
  obj2.free();
2045
4.26k
 err2:
2046
4.26k
  obj1.free();
2047
4.26k
  desFontDictObj.free();
2048
4.26k
 err1:
2049
4.26k
  error(errSyntaxError, -1, "Failed to parse font object for '{0:t}'", name);
2050
4.26k
}
2051
2052
12.8k
GfxCIDFont::~GfxCIDFont() {
2053
12.8k
  if (collection) {
2054
10.0k
    delete collection;
2055
10.0k
  }
2056
12.8k
  if (cMap) {
2057
8.57k
    cMap->decRefCnt();
2058
8.57k
  }
2059
12.8k
  if (ctu) {
2060
8.57k
    ctu->decRefCnt();
2061
8.57k
  }
2062
12.8k
  gfree(widths.exceps);
2063
12.8k
  gfree(widths.excepsV);
2064
12.8k
  if (cidToGID) {
2065
20
    gfree(cidToGID);
2066
20
  }
2067
12.8k
}
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
85.9k
          double *dx, double *dy, double *ox, double *oy) {
2157
85.9k
  CID cid;
2158
85.9k
  CharCode c;
2159
85.9k
  int n;
2160
2161
85.9k
  if (!cMap) {
2162
0
    *code = 0;
2163
0
    *uLen = 0;
2164
0
    *dx = *dy = 0;
2165
0
    return 1;
2166
0
  }
2167
2168
85.9k
  *code = (CharCode)(cid = cMap->getCID(s, len, &c, &n));
2169
85.9k
  if (ctu) {
2170
85.9k
    *uLen = ctu->mapToUnicode(ctuUsesCharCode ? c : cid, u, uSize);
2171
85.9k
  } else {
2172
0
    *uLen = 0;
2173
0
  }
2174
85.9k
  if (!*uLen && uSize >= 1 && globalParams->getMapUnknownCharNames()) {
2175
0
    u[0] = *code;
2176
0
    *uLen = 1;
2177
0
  }
2178
2179
  // horizontal
2180
85.9k
  if (cMap->getWMode() == 0) {
2181
85.1k
    getHorizontalMetrics(cid, dx);
2182
85.1k
    *dy = *ox = *oy = 0;
2183
2184
  // vertical
2185
85.1k
  } else {
2186
773
    getVerticalMetrics(cid, dy, ox, oy);
2187
773
    *dx = 0;
2188
773
  }
2189
2190
85.9k
  return n;
2191
85.9k
}
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
85.9k
void GfxCIDFont::getHorizontalMetrics(CID cid, double *w) {
2198
85.9k
  int i;
2199
703k
  for (i = 0; i < widths.nExceps; ++i) {
2200
628k
    if (widths.exceps[i].first <= cid && cid <= widths.exceps[i].last) {
2201
11.3k
      *w = widths.exceps[i].width;
2202
11.3k
      return;
2203
11.3k
    }
2204
628k
  }
2205
74.6k
  *w = widths.defWidth;
2206
74.6k
}
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
773
            double *vx, double *vy) {
2214
773
  int i;
2215
809
  for (i = 0; i < widths.nExcepsV; ++i) {
2216
36
    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
36
  }
2223
773
  *h = widths.defHeight;
2224
773
  getHorizontalMetrics(cid, vx);
2225
773
  *vx /= 2;
2226
773
  *vy = widths.defVY;
2227
773
}
2228
2229
18.5k
int GfxCIDFont::getWMode() {
2230
18.5k
  return cMap ? cMap->getWMode() : 0;
2231
18.5k
}
2232
2233
0
CharCodeToUnicode *GfxCIDFont::getToUnicode() {
2234
0
  if (ctu) {
2235
0
    ctu->incRefCnt();
2236
0
  }
2237
0
  return ctu;
2238
0
}
2239
2240
31
GString *GfxCIDFont::getCollection() {
2241
31
  return cMap ? cMap->getCollection() : (GString *)NULL;
2242
31
}
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
115k
GfxFontDictEntry::GfxFontDictEntry(Ref refA, Object *fontObjA) {
2411
115k
  loaded = gFalse;
2412
115k
  ref = refA;
2413
115k
  fontObjA->copy(&fontObj);
2414
115k
  font = NULL;
2415
115k
}
2416
2417
115k
GfxFontDictEntry::~GfxFontDictEntry() {
2418
  // NB: If the font has been loaded, font is non-NULL and is owned by
2419
  // GfxFontDict.uniqueFonts.
2420
115k
  if (!loaded) {
2421
80.7k
    fontObj.free();
2422
80.7k
  }
2423
115k
}
2424
2425
34.9k
void GfxFontDictEntry::load(GfxFont *fontA) {
2426
34.9k
  loaded = gTrue;
2427
34.9k
  font = fontA;
2428
34.9k
  fontObj.free();
2429
34.9k
}
2430
2431
43.6k
GfxFontDict::GfxFontDict(XRef *xrefA, Ref *fontDictRef, Dict *fontDict) {
2432
43.6k
  xref = xrefA;
2433
43.6k
  fonts = new GHash(gTrue);
2434
43.6k
  uniqueFonts = new GList();
2435
2436
159k
  for (int i = 0; i < fontDict->getLength(); ++i) {
2437
115k
    char *tag = fontDict->getKey(i);
2438
115k
    Object fontObj;
2439
115k
    fontDict->getValNF(i, &fontObj);
2440
115k
    Ref r;
2441
115k
    if (fontObj.isRef()) {
2442
76.8k
      r = fontObj.getRef();
2443
76.8k
    } else if (fontDictRef) {
2444
      // legal generation numbers are five digits, so we use a
2445
      // 6-digit number here
2446
256
      r.gen = 100000 + fontDictRef->num;
2447
256
      r.num = i;
2448
38.4k
    } else {
2449
      // no indirect reference for this font, or for the containing
2450
      // font dict, so hash the font and use that
2451
38.4k
      r.gen = 100000;
2452
38.4k
      r.num = hashFontObject(&fontObj);
2453
38.4k
    }
2454
115k
    fonts->add(new GString(tag), new GfxFontDictEntry(r, &fontObj));
2455
115k
    fontObj.free();
2456
115k
  }
2457
43.6k
}
2458
2459
43.6k
GfxFontDict::~GfxFontDict() {
2460
43.6k
  deleteGList(uniqueFonts, GfxFont);
2461
43.6k
  deleteGHash(fonts, GfxFontDictEntry);
2462
43.6k
}
2463
2464
97.0k
GfxFont *GfxFontDict::lookup(char *tag) {
2465
97.0k
  GfxFontDictEntry *entry = (GfxFontDictEntry *)fonts->lookup(tag);
2466
97.0k
  if (!entry) {
2467
34.2k
    return NULL;
2468
34.2k
  }
2469
62.8k
  load(tag, entry);
2470
62.8k
  return entry->font;
2471
97.0k
}
2472
2473
10
GfxFont *GfxFontDict::lookupByRef(Ref ref) {
2474
10
  GHashIter *iter;
2475
10
  GString *tag;
2476
10
  GfxFontDictEntry *entry;
2477
10
  fonts->startIter(&iter);
2478
39
  while (fonts->getNext(&iter, &tag, (void **)&entry)) {
2479
35
    if (entry->ref.num == ref.num && entry->ref.gen == ref.gen) {
2480
6
      fonts->killIter(&iter);
2481
6
      load(tag->getCString(), entry);
2482
6
      return entry->font;
2483
6
    }
2484
35
  }
2485
4
  return NULL;
2486
10
}
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
62.8k
void GfxFontDict::load(char *tag, GfxFontDictEntry *entry) {
2508
62.8k
  if (entry->loaded) {
2509
27.9k
    return;
2510
27.9k
  }
2511
2512
  // check for a duplicate that has already been loaded
2513
  // (don't do this for "synthetic" refs)
2514
34.9k
  if (entry->fontObj.isRef()) {
2515
39.7k
    for (int i = 0; i < uniqueFonts->getLength(); ++i) {
2516
5.54k
      GfxFont *font = (GfxFont *)uniqueFonts->get(i);
2517
5.54k
      if (font->getID()->num == entry->ref.num &&
2518
17
    font->getID()->gen == entry->ref.gen) {
2519
16
  entry->load(font);
2520
16
  return;
2521
16
      }
2522
5.54k
    }
2523
34.2k
  }
2524
2525
34.8k
  GfxFont *font = NULL;
2526
34.8k
  Object obj;
2527
34.8k
  entry->fontObj.fetch(xref, &obj);
2528
34.8k
  if (obj.isDict()) {
2529
29.1k
    font = GfxFont::makeFont(xref, tag, entry->ref, obj.getDict());
2530
29.1k
    if (font->isOk()) {
2531
24.8k
      uniqueFonts->append(font);
2532
24.8k
    } else {
2533
4.26k
      delete font;
2534
4.26k
      font = NULL;
2535
4.26k
    }
2536
29.1k
  } else {
2537
5.72k
    error(errSyntaxError, -1, "font resource is not a dictionary");
2538
5.72k
  }
2539
34.8k
  obj.free();
2540
34.8k
  entry->load(font);
2541
34.8k
}
2542
2543
// FNV-1a hash
2544
class FNVHash {
2545
public:
2546
2547
48.0k
  FNVHash() {
2548
48.0k
    h = 2166136261U;
2549
48.0k
  }
2550
2551
8.49M
  void hash(char c) {
2552
8.49M
    h ^= c & 0xff;
2553
8.49M
    h *= 16777619;
2554
8.49M
  }
2555
2556
1.05M
  void hash(char *p, int n) {
2557
1.05M
    int i;
2558
9.07M
    for (i = 0; i < n; ++i) {
2559
8.02M
      hash(p[i]);
2560
8.02M
    }
2561
1.05M
  }
2562
2563
48.0k
  int get31() {
2564
48.0k
    return (h ^ (h >> 31)) & 0x7fffffff;
2565
48.0k
  }
2566
2567
private:
2568
2569
  Guint h;
2570
};
2571
2572
48.0k
int GfxFontDict::hashFontObject(Object *obj) {
2573
48.0k
  FNVHash h;
2574
2575
48.0k
  hashFontObject1(obj, &h);
2576
48.0k
  return h.get31();
2577
48.0k
}
2578
2579
477k
void GfxFontDict::hashFontObject1(Object *obj, FNVHash *h) {
2580
477k
  Object obj2;
2581
477k
  GString *s;
2582
477k
  char *p;
2583
477k
  double r;
2584
477k
  int n, i;
2585
2586
477k
  switch (obj->getType()) {
2587
120
  case objBool:
2588
120
    h->hash('b');
2589
120
    h->hash(obj->getBool() ? 1 : 0);
2590
120
    break;
2591
100k
  case objInt:
2592
100k
    h->hash('i');
2593
100k
    n = obj->getInt();
2594
100k
    h->hash((char *)&n, sizeof(int));
2595
100k
    break;
2596
4.08k
  case objReal:
2597
4.08k
    h->hash('r');
2598
4.08k
    r = obj->getReal();
2599
4.08k
    h->hash((char *)&r, sizeof(double));
2600
4.08k
    break;
2601
4.59k
  case objString:
2602
4.59k
    h->hash('s');
2603
4.59k
    s = obj->getString();
2604
4.59k
    h->hash(s->getCString(), s->getLength());
2605
4.59k
    break;
2606
60.5k
  case objName:
2607
60.5k
    h->hash('n');
2608
60.5k
    p = obj->getName();
2609
60.5k
    h->hash(p, (int)strlen(p));
2610
60.5k
    break;
2611
63
  case objNull:
2612
63
    h->hash('z');
2613
63
    break;
2614
12.1k
  case objArray:
2615
12.1k
    h->hash('a');
2616
12.1k
    n = obj->arrayGetLength();
2617
12.1k
    h->hash((char *)&n, sizeof(int));
2618
61.3k
    for (i = 0; i < n; ++i) {
2619
49.2k
      obj->arrayGetNF(i, &obj2);
2620
49.2k
      hashFontObject1(&obj2, h);
2621
49.2k
      obj2.free();
2622
49.2k
    }
2623
12.1k
    break;
2624
24.6k
  case objDict:
2625
24.6k
    h->hash('d');
2626
24.6k
    n = obj->dictGetLength();
2627
24.6k
    h->hash((char *)&n, sizeof(int));
2628
404k
    for (i = 0; i < n; ++i) {
2629
379k
      p = obj->dictGetKey(i);
2630
379k
      h->hash(p, (int)strlen(p));
2631
379k
      obj->dictGetValNF(i, &obj2);
2632
379k
      hashFontObject1(&obj2, h);
2633
379k
      obj2.free();
2634
379k
    }
2635
24.6k
    break;
2636
271
  case objStream:
2637
    // this should never happen - streams must be indirect refs
2638
271
    break;
2639
234k
  case objRef:
2640
234k
    h->hash('f');
2641
234k
    n = obj->getRefNum();
2642
234k
    h->hash((char *)&n, sizeof(int));
2643
234k
    n = obj->getRefGen();
2644
234k
    h->hash((char *)&n, sizeof(int));
2645
234k
    break;
2646
36.0k
  default:
2647
36.0k
    h->hash('u');
2648
36.0k
    break;
2649
477k
  }
2650
477k
}