GfxFont.cc 71.2 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1 2 3 4 5 6 7 8
//========================================================================
//
// GfxFont.cc
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================

9 10 11 12
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
13 14 15
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
16
// Copyright (C) 2005, 2006, 2008-2010, 2012, 2014, 2015, 2017-2019 Albert Astals Cid <aacid@kde.org>
17 18 19 20 21 22 23 24
// Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
// Copyright (C) 2006 Takashi Iwai <tiwai@suse.de>
// Copyright (C) 2007 Julien Rebetez <julienr@svn.gnome.org>
// Copyright (C) 2007 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2007 Koji Otani <sho@bbr.jp>
// Copyright (C) 2007 Ed Catmur <ed@catmur.co.uk>
// Copyright (C) 2008 Jonathan Kew <jonathan_kew@sil.org>
// Copyright (C) 2008 Ed Avis <eda@waniasset.com>
Hib Eris's avatar
Hib Eris committed
25
// Copyright (C) 2008, 2010 Hib Eris <hib@hiberis.nl>
Peter Kerzum's avatar
Peter Kerzum committed
26
// Copyright (C) 2009 Peter Kerzum <kerzum@yandex-team.ru>
27
// Copyright (C) 2009, 2010 David Benjamin <davidben@mit.edu>
28
// Copyright (C) 2011 Axel Strübing <axel.struebing@freenet.de>
29
// Copyright (C) 2011, 2012, 2014 Adrian Johnson <ajohnson@redneon.com>
Albert Astals Cid's avatar
Albert Astals Cid committed
30
// Copyright (C) 2012 Yi Yang <ahyangyi@gmail.com>
suzuki toshiya's avatar
suzuki toshiya committed
31
// Copyright (C) 2012 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp>
Thomas Freitag's avatar
Thomas Freitag committed
32
// Copyright (C) 2012, 2017 Thomas Freitag <Thomas.Freitag@alfa.de>
Albert Astals Cid's avatar
Albert Astals Cid committed
33
// Copyright (C) 2013-2016, 2018 Jason Crain <jason@aquaticape.us>
34
// Copyright (C) 2014 Olly Betts <olly@survex.com>
35
// Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by the LiMux project of the city of Munich
36
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
37
// Copyright (C) 2019 LE GARREC Vincent <legarrec.vincent@gmail.com>
38 39 40 41 42 43
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================

Kristian Høgsberg's avatar
Kristian Høgsberg committed
44 45
#include <config.h>

46 47 48 49 50 51
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <climits>
52
#include <algorithm>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
53 54 55 56 57 58 59 60 61
#include "goo/gmem.h"
#include "Error.h"
#include "Object.h"
#include "Dict.h"
#include "GlobalParams.h"
#include "CMap.h"
#include "CharCodeToUnicode.h"
#include "FontEncodingTables.h"
#include "BuiltinFontTables.h"
62
#include "UnicodeTypeTable.h"
63
#include <fofi/FoFiIdentifier.h>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
64 65 66 67
#include <fofi/FoFiType1.h>
#include <fofi/FoFiType1C.h>
#include <fofi/FoFiTrueType.h>
#include "GfxFont.h"
68
#include "PSOutputDev.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
69 70 71

//------------------------------------------------------------------------

72
struct Base14FontMapEntry {
73
  const char *altName;
74
  const char *base14Name;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
75 76
};

77
static const Base14FontMapEntry base14FontMap[] = {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
78 79 80 81 82 83 84 85 86 87 88
  { "Arial",                        "Helvetica" },
  { "Arial,Bold",                   "Helvetica-Bold" },
  { "Arial,BoldItalic",             "Helvetica-BoldOblique" },
  { "Arial,Italic",                 "Helvetica-Oblique" },
  { "Arial-Bold",                   "Helvetica-Bold" },
  { "Arial-BoldItalic",             "Helvetica-BoldOblique" },
  { "Arial-BoldItalicMT",           "Helvetica-BoldOblique" },
  { "Arial-BoldMT",                 "Helvetica-Bold" },
  { "Arial-Italic",                 "Helvetica-Oblique" },
  { "Arial-ItalicMT",               "Helvetica-Oblique" },
  { "ArialMT",                      "Helvetica" },
89
  { "Courier",                      "Courier" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
90 91
  { "Courier,Bold",                 "Courier-Bold" },
  { "Courier,BoldItalic",           "Courier-BoldOblique" },
92
  { "Courier,Italic",               "Courier-Oblique" },
93 94 95
  { "Courier-Bold",                 "Courier-Bold" },
  { "Courier-BoldOblique",          "Courier-BoldOblique" },
  { "Courier-Oblique",              "Courier-Oblique" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
96 97 98 99 100 101 102 103 104 105 106
  { "CourierNew",                   "Courier" },
  { "CourierNew,Bold",              "Courier-Bold" },
  { "CourierNew,BoldItalic",        "Courier-BoldOblique" },
  { "CourierNew,Italic",            "Courier-Oblique" },
  { "CourierNew-Bold",              "Courier-Bold" },
  { "CourierNew-BoldItalic",        "Courier-BoldOblique" },
  { "CourierNew-Italic",            "Courier-Oblique" },
  { "CourierNewPS-BoldItalicMT",    "Courier-BoldOblique" },
  { "CourierNewPS-BoldMT",          "Courier-Bold" },
  { "CourierNewPS-ItalicMT",        "Courier-Oblique" },
  { "CourierNewPSMT",               "Courier" },
107
  { "Helvetica",                    "Helvetica" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
108 109 110
  { "Helvetica,Bold",               "Helvetica-Bold" },
  { "Helvetica,BoldItalic",         "Helvetica-BoldOblique" },
  { "Helvetica,Italic",             "Helvetica-Oblique" },
111
  { "Helvetica-Bold",               "Helvetica-Bold" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
112
  { "Helvetica-BoldItalic",         "Helvetica-BoldOblique" },
113
  { "Helvetica-BoldOblique",        "Helvetica-BoldOblique" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
114
  { "Helvetica-Italic",             "Helvetica-Oblique" },
115 116
  { "Helvetica-Oblique",            "Helvetica-Oblique" },
  { "Symbol",                       "Symbol" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
117 118 119
  { "Symbol,Bold",                  "Symbol" },
  { "Symbol,BoldItalic",            "Symbol" },
  { "Symbol,Italic",                "Symbol" },
120 121 122 123
  { "SymbolMT",                     "Symbol" },
  { "SymbolMT,Bold",                "Symbol" },
  { "SymbolMT,BoldItalic",          "Symbol" },
  { "SymbolMT,Italic",              "Symbol" },
124 125 126 127
  { "Times-Bold",                   "Times-Bold" },
  { "Times-BoldItalic",             "Times-BoldItalic" },
  { "Times-Italic",                 "Times-Italic" },
  { "Times-Roman",                  "Times-Roman" },
Kristian Høgsberg's avatar
Kristian Høgsberg committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  { "TimesNewRoman",                "Times-Roman" },
  { "TimesNewRoman,Bold",           "Times-Bold" },
  { "TimesNewRoman,BoldItalic",     "Times-BoldItalic" },
  { "TimesNewRoman,Italic",         "Times-Italic" },
  { "TimesNewRoman-Bold",           "Times-Bold" },
  { "TimesNewRoman-BoldItalic",     "Times-BoldItalic" },
  { "TimesNewRoman-Italic",         "Times-Italic" },
  { "TimesNewRomanPS",              "Times-Roman" },
  { "TimesNewRomanPS-Bold",         "Times-Bold" },
  { "TimesNewRomanPS-BoldItalic",   "Times-BoldItalic" },
  { "TimesNewRomanPS-BoldItalicMT", "Times-BoldItalic" },
  { "TimesNewRomanPS-BoldMT",       "Times-Bold" },
  { "TimesNewRomanPS-Italic",       "Times-Italic" },
  { "TimesNewRomanPS-ItalicMT",     "Times-Italic" },
  { "TimesNewRomanPSMT",            "Times-Roman" },
  { "TimesNewRomanPSMT,Bold",       "Times-Bold" },
  { "TimesNewRomanPSMT,BoldItalic", "Times-BoldItalic" },
145 146
  { "TimesNewRomanPSMT,Italic",     "Times-Italic" },
  { "ZapfDingbats",                 "ZapfDingbats" }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
147 148
};

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
//------------------------------------------------------------------------

// index: {fixed:0, sans-serif:4, serif:8} + bold*2 + italic
// NB: must be in same order as psSubstFonts in PSOutputDev.cc
static const char *base14SubstFonts[14] = {
  "Courier",
  "Courier-Oblique",
  "Courier-Bold",
  "Courier-BoldOblique",
  "Helvetica",
  "Helvetica-Oblique",
  "Helvetica-Bold",
  "Helvetica-BoldOblique",
  "Times-Roman",
  "Times-Italic",
  "Times-Bold",
  "Times-BoldItalic",
  // the last two are never used for substitution
  "Symbol",
  "ZapfDingbats"
};

//------------------------------------------------------------------------

173
static int parseCharName(char *charName, Unicode *uBuf, int uLen,
174 175
			 bool names, bool ligatures, 
			 bool numeric, bool hex, bool variants);
176

177 178 179 180 181 182
//------------------------------------------------------------------------

static int readFromStream(void *data) {
  return ((Stream *)data)->getChar();
}

183 184 185 186 187
//------------------------------------------------------------------------
// GfxFontLoc
//------------------------------------------------------------------------

GfxFontLoc::GfxFontLoc() {
188
  path = nullptr;
189
  fontNum = 0;
190
  encoding = nullptr;
191 192 193 194 195 196 197 198 199 200 201 202
  substIdx = -1;
}

GfxFontLoc::~GfxFontLoc() {
  if (path) {
    delete path;
  }
  if (encoding) {
    delete encoding;
  }
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
203 204 205 206
//------------------------------------------------------------------------
// GfxFont
//------------------------------------------------------------------------

207
GfxFont *GfxFont::makeFont(XRef *xref, const char *tagA, Ref idA, Dict *fontDict) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
208
  GooString *nameA;
209 210
  Ref embFontIDA;
  GfxFontType typeA;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
211 212 213
  GfxFont *font;

  // get base font name
214
  nameA = nullptr;
Albert Astals Cid's avatar
Albert Astals Cid committed
215
  Object obj1 = fontDict->lookup("BaseFont");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
216 217 218 219
  if (obj1.isName()) {
    nameA = new GooString(obj1.getName());
  }

220 221 222 223
  // get embedded font ID and font type
  typeA = getFontType(xref, fontDict, &embFontIDA);

  // create the font object
224
  font = nullptr;
225 226 227
  if (typeA < fontCIDType0) {
    font = new Gfx8BitFont(xref, tagA, idA, nameA, typeA, embFontIDA,
			   fontDict);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
228
  } else {
229 230
    font = new GfxCIDFont(xref, tagA, idA, nameA, typeA, embFontIDA,
			  fontDict);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
231 232 233 234 235
  }

  return font;
}

Albert Astals Cid's avatar
Albert Astals Cid committed
236
GfxFont::GfxFont(const char *tagA, Ref idA, const GooString *nameA,
237
		 GfxFontType typeA, Ref embFontIDA) {
238
  ok = false;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
239 240 241
  tag = new GooString(tagA);
  id = idA;
  name = nameA;
242 243
  type = typeA;
  embFontID = embFontIDA;
244 245
  embFontName = nullptr;
  family = nullptr;
246 247
  stretch = StretchNotDefined;
  weight = WeightNotDefined;
248
  refCnt = 1;
249
  encodingName = new GooString("");
250
  hasToUnicode = false;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
251 252 253 254
}

GfxFont::~GfxFont() {
  delete tag;
255
  delete family;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
256 257 258 259 260 261
  if (name) {
    delete name;
  }
  if (embFontName) {
    delete embFontName;
  }
262 263 264
  if (encodingName) {
    delete encodingName;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
265 266
}

267 268 269 270 271 272 273 274 275
void GfxFont::incRefCnt() {
  refCnt++;
}

void GfxFont::decRefCnt() {
  if (--refCnt == 0)
    delete this;
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289
// This function extracts three pieces of information:
// 1. the "expected" font type, i.e., the font type implied by
//    Font.Subtype, DescendantFont.Subtype, and
//    FontDescriptor.FontFile3.Subtype
// 2. the embedded font object ID
// 3. the actual font type - determined by examining the embedded font
//    if there is one, otherwise equal to the expected font type
// If the expected and actual font types don't match, a warning
// message is printed.  The expected font type is not used for
// anything else.
GfxFontType GfxFont::getFontType(XRef *xref, Dict *fontDict, Ref *embID) {
  GfxFontType t, expectedType;
  FoFiIdentifierType fft;
  Dict *fontDict2;
290
  bool isType0, err;
291 292

  t = fontUnknownType;
293
  *embID = Ref::INVALID();
294
  err = false;
295

Albert Astals Cid's avatar
Albert Astals Cid committed
296
  Object subtype = fontDict->lookup("Subtype");
297
  expectedType = fontUnknownType;
298
  isType0 = false;
299 300 301 302 303 304 305 306 307
  if (subtype.isName("Type1") || subtype.isName("MMType1")) {
    expectedType = fontType1;
  } else if (subtype.isName("Type1C")) {
    expectedType = fontType1C;
  } else if (subtype.isName("Type3")) {
    expectedType = fontType3;
  } else if (subtype.isName("TrueType")) {
    expectedType = fontTrueType;
  } else if (subtype.isName("Type0")) {
308
    isType0 = true;
309 310 311 312 313 314
  } else {
    error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
	  subtype.isName() ? subtype.getName() : "???");
  }

  fontDict2 = fontDict;
Albert Astals Cid's avatar
Albert Astals Cid committed
315 316 317 318
  Object obj1 = fontDict->lookup("DescendantFonts");
  Object obj2; // Do not move to inside the if
               // we need it around so that fontDict2 remains valid
  if (obj1.isArray()) {
319 320
    if (obj1.arrayGetLength() == 0) {
      error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
Albert Astals Cid's avatar
Albert Astals Cid committed
321 322 323 324 325
    } else {
      obj2 = obj1.arrayGet(0);
      if (obj2.isDict()) {
	if (!isType0) {
	  error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
326
	}
Albert Astals Cid's avatar
Albert Astals Cid committed
327 328 329 330 331 332 333 334 335 336
	fontDict2 = obj2.getDict();
	subtype = fontDict2->lookup("Subtype");
	if (subtype.isName("CIDFontType0")) {
	  if (isType0) {
	    expectedType = fontCIDType0;
	  }
	} else if (subtype.isName("CIDFontType2")) {
	  if (isType0) {
	    expectedType = fontCIDType2;
	  }
337 338 339 340 341
	}
      }
    }
  }

Albert Astals Cid's avatar
Albert Astals Cid committed
342 343
  Object fontDesc = fontDict2->lookup("FontDescriptor");
  if (fontDesc.isDict()) {
344
    Object obj3 = fontDesc.dictLookupNF("FontFile").copy();
Albert Astals Cid's avatar
Albert Astals Cid committed
345
    if (obj3.isRef()) {
346 347
      *embID = obj3.getRef();
      if (expectedType != fontType1) {
348
	err = true;
349 350
      }
    }
351
    if (*embID == Ref::INVALID() && (obj3 = fontDesc.dictLookupNF("FontFile2").copy(), obj3.isRef())) {
352 353 354 355
      *embID = obj3.getRef();
      if (isType0) {
	expectedType = fontCIDType2;
      } else if (expectedType != fontTrueType) {
356
	err = true;
357 358
      }
    }
359
    if (*embID == Ref::INVALID() && (obj3 = fontDesc.dictLookupNF("FontFile3").copy(), obj3.isRef())) {
360
      *embID = obj3.getRef();
Albert Astals Cid's avatar
Albert Astals Cid committed
361 362 363
      Object obj4 = obj3.fetch(xref);
      if (obj4.isStream()) {
	subtype = obj4.streamGetDict()->lookup("Subtype");
364 365
	if (subtype.isName("Type1")) {
	  if (expectedType != fontType1) {
366
	    err = true;
367 368 369 370 371 372
	    expectedType = isType0 ? fontCIDType0 : fontType1;
	  }
	} else if (subtype.isName("Type1C")) {
	  if (expectedType == fontType1) {
	    expectedType = fontType1C;
	  } else if (expectedType != fontType1C) {
373
	    err = true;
374 375 376 377
	    expectedType = isType0 ? fontCIDType0C : fontType1C;
	  }
	} else if (subtype.isName("TrueType")) {
	  if (expectedType != fontTrueType) {
378
	    err = true;
379 380 381 382 383 384
	    expectedType = isType0 ? fontCIDType2 : fontTrueType;
	  }
	} else if (subtype.isName("CIDFontType0C")) {
	  if (expectedType == fontCIDType0) {
	    expectedType = fontCIDType0C;
	  } else {
385
	    err = true;
386 387 388 389 390 391 392 393 394 395 396 397
	    expectedType = isType0 ? fontCIDType0C : fontType1C;
	  }
	} else if (subtype.isName("OpenType")) {
	  if (expectedType == fontTrueType) {
	    expectedType = fontTrueTypeOT;
	  } else if (expectedType == fontType1) {
	    expectedType = fontType1COT;
	  } else if (expectedType == fontCIDType0) {
	    expectedType = fontCIDType0COT;
	  } else if (expectedType == fontCIDType2) {
	    expectedType = fontCIDType2OT;
	  } else {
398
	    err = true;
399 400 401 402 403 404 405 406 407 408
	  }
	} else {
	  error(errSyntaxError, -1, "Unknown font type '{0:s}'",
		subtype.isName() ? subtype.getName() : "???");
	}
      }
    }
  }

  t = fontUnknownType;
409
  if (*embID != Ref::INVALID()) {
410
    Object obj3(*embID);
Albert Astals Cid's avatar
Albert Astals Cid committed
411
    Object obj4 = obj3.fetch(xref);
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    if (obj4.isStream()) {
      obj4.streamReset();
      fft = FoFiIdentifier::identifyStream(&readFromStream, obj4.getStream());
      obj4.streamClose();
      switch (fft) {
      case fofiIdType1PFA:
      case fofiIdType1PFB:
	t = fontType1;
	break;
      case fofiIdCFF8Bit:
	t = isType0 ? fontCIDType0C : fontType1C;
	break;
      case fofiIdCFFCID:
	t = fontCIDType0C;
	break;
      case fofiIdTrueType:
      case fofiIdTrueTypeCollection:
	t = isType0 ? fontCIDType2 : fontTrueType;
	break;
      case fofiIdOpenTypeCFF8Bit:
	t = expectedType; // hack: open type always == expected type? s. bug-poppler20605.pdf
	break;
      case fofiIdOpenTypeCFFCID:
	t = fontCIDType0COT;
	break;
      default:
	error(errSyntaxError, -1, "Embedded font file may be invalid");
	break;
      }
    }
  }

  if (t == fontUnknownType) {
    t = expectedType;
  }

  if (t != expectedType) {
449
    err = true;
450 451 452 453 454 455 456 457 458 459
  }

  if (err) {
    error(errSyntaxWarning, -1,
	  "Mismatch between font type and embedded font file");
  }

  return t;
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
460 461 462 463 464 465 466 467
void GfxFont::readFontDescriptor(XRef *xref, Dict *fontDict) {
  double t;

  // assume Times-Roman by default (for substitution purposes)
  flags = fontSerif;

  missingWidth = 0;

Albert Astals Cid's avatar
Albert Astals Cid committed
468 469
  Object obj1 = fontDict->lookup("FontDescriptor");
  if (obj1.isDict()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
470 471

    // get flags
Albert Astals Cid's avatar
Albert Astals Cid committed
472 473
    Object obj2 = obj1.dictLookup("Flags");
    if (obj2.isInt()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
474 475 476 477
      flags = obj2.getInt();
    }

    // get name
Albert Astals Cid's avatar
Albert Astals Cid committed
478
    obj2 = obj1.dictLookup("FontName");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
479 480 481
    if (obj2.isName()) {
      embFontName = new GooString(obj2.getName());
    }
482
    if (embFontName == nullptr) {
483
      // get name with typo
Albert Astals Cid's avatar
Albert Astals Cid committed
484
      obj2 = obj1.dictLookup("Fontname");
485 486
      if (obj2.isName()) {
        embFontName = new GooString(obj2.getName());
487
        error(errSyntaxWarning, -1, "The file uses Fontname instead of FontName please notify the creator that the file is broken");
488 489
      }
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
490

491
    // get family
Albert Astals Cid's avatar
Albert Astals Cid committed
492
    obj2 = obj1.dictLookup("FontFamily");
493 494 495
    if (obj2.isString()) family = new GooString(obj2.getString());

    // get stretch
Albert Astals Cid's avatar
Albert Astals Cid committed
496
    obj2 = obj1.dictLookup("FontStretch");
497 498 499 500 501 502 503 504 505 506
    if (obj2.isName()) {
      if (strcmp(obj2.getName(), "UltraCondensed") == 0) stretch = UltraCondensed;
      else if (strcmp(obj2.getName(), "ExtraCondensed") == 0) stretch = ExtraCondensed;
      else if (strcmp(obj2.getName(), "Condensed") == 0) stretch = Condensed;
      else if (strcmp(obj2.getName(), "SemiCondensed") == 0) stretch = SemiCondensed;
      else if (strcmp(obj2.getName(), "Normal") == 0) stretch = Normal;
      else if (strcmp(obj2.getName(), "SemiExpanded") == 0) stretch = SemiExpanded;
      else if (strcmp(obj2.getName(), "Expanded") == 0) stretch = Expanded;
      else if (strcmp(obj2.getName(), "ExtraExpanded") == 0) stretch = ExtraExpanded;
      else if (strcmp(obj2.getName(), "UltraExpanded") == 0) stretch = UltraExpanded;
507
      else error(errSyntaxWarning, -1, "Invalid Font Stretch");
508 509 510
    }
    
    // get weight
Albert Astals Cid's avatar
Albert Astals Cid committed
511
    obj2 = obj1.dictLookup("FontWeight");
512 513 514 515 516 517 518 519 520 521
    if (obj2.isNum()) {
      if (obj2.getNum() == 100) weight = W100;
      else if (obj2.getNum() == 200) weight = W200;
      else if (obj2.getNum() == 300) weight = W300;
      else if (obj2.getNum() == 400) weight = W400;
      else if (obj2.getNum() == 500) weight = W500;
      else if (obj2.getNum() == 600) weight = W600;
      else if (obj2.getNum() == 700) weight = W700;
      else if (obj2.getNum() == 800) weight = W800;
      else if (obj2.getNum() == 900) weight = W900;
522
      else error(errSyntaxWarning, -1, "Invalid Font Weight");
523 524
    }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
525
    // look for MissingWidth
Albert Astals Cid's avatar
Albert Astals Cid committed
526
    obj2 = obj1.dictLookup("MissingWidth");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
527 528 529 530 531
    if (obj2.isNum()) {
      missingWidth = obj2.getNum();
    }

    // get Ascent and Descent
Albert Astals Cid's avatar
Albert Astals Cid committed
532
    obj2 = obj1.dictLookup("Ascent");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
533 534
    if (obj2.isNum()) {
      t = 0.001 * obj2.getNum();
535 536 537 538 539 540 541
      // some broken font descriptors specify a negative ascent
      if (t < 0) {
	t = -t;
      }
      // some broken font descriptors set ascent and descent to 0;
      // others set it to ridiculous values (e.g., 32768)
      if (t != 0 && t < 3) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
542 543 544
	ascent = t;
      }
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
545
    obj2 = obj1.dictLookup("Descent");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
546 547
    if (obj2.isNum()) {
      t = 0.001 * obj2.getNum();
548 549 550 551
      // some broken font descriptors specify a positive descent
      if (t > 0) {
	t = -t;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
552
      // some broken font descriptors set ascent and descent to 0
553
      if (t != 0 && t > -3) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
554 555 556 557 558
	descent = t;
      }
    }

    // font FontBBox
Albert Astals Cid's avatar
Albert Astals Cid committed
559 560 561 562 563
    obj2 = obj1.dictLookup("FontBBox");
    if (obj2.isArray()) {
      for (int i = 0; i < 4 && i < obj2.arrayGetLength(); ++i) {
	Object obj3 = obj2.arrayGet(i);
	if (obj3.isNum()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
564 565 566 567 568 569 570 571 572 573 574
	  fontBBox[i] = 0.001 * obj3.getNum();
	}
      }
    }
  }
}

CharCodeToUnicode *GfxFont::readToUnicodeCMap(Dict *fontDict, int nBits,
					      CharCodeToUnicode *ctu) {
  GooString *buf;

Albert Astals Cid's avatar
Albert Astals Cid committed
575 576
  Object obj1 = fontDict->lookup("ToUnicode");
  if (!obj1.isStream()) {
577
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
578 579
  }
  buf = new GooString();
580
  obj1.getStream()->fillGooString(buf);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
581 582 583 584 585 586
  obj1.streamClose();
  if (ctu) {
    ctu->mergeCMap(buf, nBits);
  } else {
    ctu = CharCodeToUnicode::parseCMap(buf, nBits);
  }
587
  hasToUnicode = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
588 589 590 591
  delete buf;
  return ctu;
}

592
GfxFontLoc *GfxFont::locateFont(XRef *xref, PSOutputDev *ps) {
593 594 595 596
  GfxFontLoc *fontLoc;
  SysFontType sysFontType;
  GooString *path, *base14Name, *substName;
  int substIdx, fontNum;
597
  bool embed;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
598

599
  if (type == fontType3) {
600
    return nullptr;
601 602 603
  }

  //----- embedded font
604
  if (embFontID != Ref::INVALID()) {
605
    embed = true;
606
    Object refObj(embFontID);
Albert Astals Cid's avatar
Albert Astals Cid committed
607
    Object embFontObj = refObj.fetch(xref);
608 609
    if (!embFontObj.isStream()) {
      error(errSyntaxError, -1, "Embedded font object is wrong type");
610
      embed = false;
611 612 613 614 615 616 617
    }
    if (embed) {
      if (ps) {
	switch (type) {
	case fontType1:
	case fontType1C:
	case fontType1COT:
618
	  embed = ps->getEmbedType1();
619 620 621
	  break;
	case fontTrueType:
	case fontTrueTypeOT:
622
	  embed = ps->getEmbedTrueType();
623 624 625
	  break;
	case fontCIDType0C:
	case fontCIDType0COT:
626
	  embed = ps->getEmbedCIDPostScript();
627 628 629
	  break;
	case fontCIDType2:
	case fontCIDType2OT:
630
	  embed = ps->getEmbedCIDTrueType();
631 632 633 634 635 636 637 638 639 640 641 642
	  break;
	default:
	  break;
	}
      }
      if (embed) {
	fontLoc = new GfxFontLoc();
	fontLoc->locType = gfxFontLocEmbedded;
	fontLoc->fontType = type;
	fontLoc->embFontID = embFontID;
	return fontLoc;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
643 644 645
    }
  }

646
  //----- PS passthrough
647
  if (ps && !isCIDFont() && ps->getFontPassthrough()) {
648 649 650 651 652 653
    fontLoc = new GfxFontLoc();
    fontLoc->locType = gfxFontLocResident;
    fontLoc->fontType = fontType1;
    fontLoc->path = name->copy();
    return fontLoc;
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
654

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  //----- PS resident Base-14 font
  if (ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
    fontLoc = new GfxFontLoc();
    fontLoc->locType = gfxFontLocResident;
    fontLoc->fontType = fontType1;
    fontLoc->path = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
    return fontLoc;
  }

  //----- external font file (fontFile, fontDir)
  if (name && (path = globalParams->findFontFile(name))) {
    if ((fontLoc = getExternalFont(path, isCIDFont()))) {
      return fontLoc;
    }
  }

  //----- external font file for Base-14 font
  if (!ps && !isCIDFont() && ((Gfx8BitFont *)this)->base14) {
    base14Name = new GooString(((Gfx8BitFont *)this)->base14->base14Name);
674
    if ((path = globalParams->findBase14FontFile(base14Name, this))) {
675
      if ((fontLoc = getExternalFont(path, false))) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
	delete base14Name;
	return fontLoc;
      }
    }
    delete base14Name;
  }

  //----- system font
  if ((path = globalParams->findSystemFontFile(this, &sysFontType,
					       &fontNum))) {
    if (isCIDFont()) {
      if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
	fontLoc = new GfxFontLoc();
	fontLoc->locType = gfxFontLocExternal;
	fontLoc->fontType = fontCIDType2;
	fontLoc->path = path;
	fontLoc->fontNum = fontNum;
	return fontLoc;
      }
    } else {
      if (sysFontType == sysFontTTF || sysFontType == sysFontTTC) {
	fontLoc = new GfxFontLoc();
	fontLoc->locType = gfxFontLocExternal;
	fontLoc->fontType = fontTrueType;
	fontLoc->path = path;
	return fontLoc;
      } else if (sysFontType == sysFontPFA || sysFontType == sysFontPFB) {
	fontLoc = new GfxFontLoc();
	fontLoc->locType = gfxFontLocExternal;
	fontLoc->fontType = fontType1;
	fontLoc->path = path;
	fontLoc->fontNum = fontNum;
	return fontLoc;
      }
    }
    delete path;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
712
  }
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

  if (!isCIDFont()) {

    //----- 8-bit font substitution
    if (flags & fontFixedWidth) {
      substIdx = 0;
    } else if (flags & fontSerif) {
      substIdx = 8;
    } else {
      substIdx = 4;
    }
    if (isBold()) {
      substIdx += 2;
    }
    if (isItalic()) {
      substIdx += 1;
    }
    substName = new GooString(base14SubstFonts[substIdx]);
    if (ps) {
Albert Astals Cid's avatar
Albert Astals Cid committed
732
      error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
733
	    base14SubstFonts[substIdx], name ? name->c_str() : "null");
734 735 736 737 738 739 740 741 742 743
      fontLoc = new GfxFontLoc();
      fontLoc->locType = gfxFontLocResident;
      fontLoc->fontType = fontType1;
      fontLoc->path = substName;
      fontLoc->substIdx = substIdx;
      return fontLoc;
    } else {
      path = globalParams->findFontFile(substName);
      delete substName;
      if (path) {
744
	if ((fontLoc = getExternalFont(path, false))) {
Albert Astals Cid's avatar
Albert Astals Cid committed
745
	  error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
746
		  base14SubstFonts[substIdx], name ? name->c_str() : "");
747 748 749 750 751 752 753 754
	  name = new GooString(base14SubstFonts[substIdx]);
	  fontLoc->substIdx = substIdx;
	  return fontLoc;
	}
      }
    }

    // failed to find a substitute font
755
    return nullptr;
Ed Avis's avatar
Ed Avis committed
756
  }
757 758

  // failed to find a substitute font
759
  return nullptr;
760 761
}

Albert Astals Cid's avatar
Albert Astals Cid committed
762
GfxFontLoc *GfxFont::locateBase14Font(const GooString *base14Name) {
763 764 765 766
  GooString *path;

  path = globalParams->findFontFile(base14Name);
  if (!path) {
767
    return nullptr;
Ed Avis's avatar
Ed Avis committed
768
  }
769
  return getExternalFont(path, false);
770 771
}

772
GfxFontLoc *GfxFont::getExternalFont(GooString *path, bool cid) {
773 774 775 776
  FoFiIdentifierType fft;
  GfxFontType fontType;
  GfxFontLoc *fontLoc;

777
  fft = FoFiIdentifier::identifyFile(path->c_str());
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  switch (fft) {
  case fofiIdType1PFA:
  case fofiIdType1PFB:
    fontType = fontType1;
    break;
  case fofiIdCFF8Bit:
    fontType = fontType1C;
    break;
  case fofiIdCFFCID:
    fontType = fontCIDType0C;
    break;
  case fofiIdTrueType:
  case fofiIdTrueTypeCollection:
    fontType = cid ? fontCIDType2 : fontTrueType;
    break;
  case fofiIdOpenTypeCFF8Bit:
    fontType = fontType1COT;
    break;
  case fofiIdOpenTypeCFFCID:
    fontType = fontCIDType0COT;
    break;
  case fofiIdUnknown:
  case fofiIdError:
  default:
    fontType = fontUnknownType;
    break;
  }
  if (fontType == fontUnknownType ||
      (cid ? (fontType < fontCIDType0)
           : (fontType >= fontCIDType0))) {
    delete path;
809
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
810
  }
811 812 813 814 815
  fontLoc = new GfxFontLoc();
  fontLoc->locType = gfxFontLocExternal;
  fontLoc->fontType = fontType;
  fontLoc->path = path;
  return fontLoc;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
816 817 818 819 820 821
}

char *GfxFont::readEmbFontFile(XRef *xref, int *len) {
  char *buf;
  Stream *str;

822
  Object obj1(embFontID);
Albert Astals Cid's avatar
Albert Astals Cid committed
823
  Object obj2 = obj1.fetch(xref);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
824
  if (!obj2.isStream()) {
825
    error(errSyntaxError, -1, "Embedded font file is not a stream");
826
    embFontID = Ref::INVALID();
827
    *len = 0;
828
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
829 830 831
  }
  str = obj2.getStream();

832
  buf = (char*)str->toUnsignedChars(len);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
833 834 835 836 837
  str->close();

  return buf;
}

838 839 840 841 842 843 844 845 846 847 848 849 850

struct AlternateNameMap {
  const char *name;
  const char *alt;
};

static const AlternateNameMap alternateNameMap[] =
{
  { "fi", "f_i" },
  { "fl", "f_l" },
  { "ff", "f_f" },
  { "ffi", "f_f_i" },
  { "ffl", "f_f_l" },
851
  { nullptr,    nullptr }
852 853 854 855 856 857 858 859 860 861
};

const char *GfxFont::getAlternateName(const char *name) {
  const AlternateNameMap *map = alternateNameMap;
  while (map->name) {
    if (strcmp(name, map->name) == 0) {
      return map->alt;
    }
    map++;
  }
862
  return nullptr;
863 864
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
865 866 867 868
//------------------------------------------------------------------------
// Gfx8BitFont
//------------------------------------------------------------------------

869 870 871
// Parse character names of the form 'Axx', 'xx', 'Ann', 'ABnn', or
// 'nn', where 'A' and 'B' are any letters, 'xx' is two hex digits,
// and 'nn' is decimal digits.
872
static bool parseNumericName(const char *s, bool hex, unsigned int *u) {
873 874 875 876 877 878 879 880 881 882 883 884 885 886
  char *endptr;

  // Strip leading alpha characters.
  if (hex) {
    int n = 0;

    // Get string length while ignoring junk at end.
    while (isalnum(s[n]))
      ++n;

    // Only 2 hex characters with optional leading alpha is allowed.
    if (n == 3 && isalpha(*s)) {
      ++s;
    } else if (n != 2) {
887
      return false;
888 889 890 891 892 893 894 895 896 897
    }
  } else {
    // Strip up to two alpha characters.
    for (int i = 0; i < 2 && isalpha(*s); ++i)
      ++s;
  }

  int v = strtol(s, &endptr, hex ? 16 : 10);

  if (endptr == s)
898
    return false;
899 900 901 902 903 904 905 906

  // Skip trailing junk characters.
  while (*endptr != '\0' && !isalnum(*endptr))
    ++endptr;

  if (*endptr == '\0') {
    if (u)
      *u = v;
907
    return true;
908
  }
909
  return false;
910 911
}

912
// Returns true if the font has character names like xx or Axx which
913
// should be parsed for hex or decimal values.
914 915
static bool testForNumericNames(Dict *fontDict, bool hex) {
  bool numeric = true;
916

Albert Astals Cid's avatar
Albert Astals Cid committed
917
  Object enc = fontDict->lookup("Encoding");
918
  if (!enc.isDict()) {
919
    return false;
920 921
  }

Albert Astals Cid's avatar
Albert Astals Cid committed
922
  Object diff = enc.dictLookup("Differences");
923
  if (!diff.isArray()) {
924
    return false;
925 926 927
  }

  for (int i = 0; i < diff.arrayGetLength() && numeric; ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
928
    Object obj = diff.arrayGet(i);
929 930 931
    if (obj.isInt()) {
      // All sequences must start between character codes 0 and 5.
      if (obj.getInt() > 5)
932
	numeric = false;
933
    } else if (obj.isName()) {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
934
      // All character names must successfully parse.
935
      if (!parseNumericName(obj.getName(), hex, nullptr))
936
	numeric = false;
937
    } else {
938
      numeric = false;
939 940 941 942 943 944
    }
  }

  return numeric;
}

945
Gfx8BitFont::Gfx8BitFont(XRef *xref, const char *tagA, Ref idA, GooString *nameA,
946 947
			 GfxFontType typeA, Ref embFontIDA, Dict *fontDict):
  GfxFont(tagA, idA, nameA, typeA, embFontIDA) {
948
  GooString *name2;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
949
  BuiltinFont *builtinFont;
950
  const char **baseEnc;
951
  bool baseEncFromFontFile;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
952 953 954 955 956
  char *buf;
  int len;
  FoFiType1 *ffT1;
  FoFiType1C *ffT1C;
  char *charName;
957 958
  bool missing, hex;
  bool numeric;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
959 960 961 962
  Unicode toUnicode[256];
  Unicode uBuf[8];
  double mul;
  int firstChar, lastChar;
963
  unsigned short w;
Albert Astals Cid's avatar
Albert Astals Cid committed
964
  Object obj1;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
965 966
  int n, i, a, b, m;

967
  refCnt = 1;
968
  ctu = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
969 970 971

  // do font name substitution for various aliases of the Base 14 font
  // names
972
  base14 = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
973
  if (name) {
974 975 976 977 978 979 980 981 982
    name2 = name->copy();
    i = 0;
    while (i < name2->getLength()) {
      if (name2->getChar(i) == ' ') {
	name2->del(i);
      } else {
	++i;
      }
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
983
    a = 0;
984 985
    b = sizeof(base14FontMap) / sizeof(Base14FontMapEntry);
    // invariant: base14FontMap[a].altName <= name2 < base14FontMap[b].altName
Kristian Høgsberg's avatar
Kristian Høgsberg committed
986 987
    while (b - a > 1) {
      m = (a + b) / 2;
988
      if (name2->cmp(base14FontMap[m].altName) >= 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
989 990 991 992 993
	a = m;
      } else {
	b = m;
      }
    }
994 995
    if (!name2->cmp(base14FontMap[a].altName)) {
      base14 = &base14FontMap[a];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
996
    }
997
    delete name2;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
998 999 1000
  }

  // is it a built-in font?
1001
  builtinFont = nullptr;
1002
  if (base14) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1003
    for (i = 0; i < nBuiltinFonts; ++i) {
1004
      if (!strcmp(base14->base14Name, builtinFonts[i].name)) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	builtinFont = &builtinFonts[i];
	break;
      }
    }
  }

  // default ascent/descent values
  if (builtinFont) {
    ascent = 0.001 * builtinFont->ascent;
    descent = 0.001 * builtinFont->descent;
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
  } else {
    ascent = 0.95;
    descent = -0.35;
    fontBBox[0] = fontBBox[1] = fontBBox[2] = fontBBox[3] = 0;
  }

  // get info from font descriptor
  readFontDescriptor(xref, fontDict);

1028 1029
  // for non-embedded fonts, don't trust the ascent/descent/bbox
  // values from the font descriptor
1030
  if (builtinFont && embFontID == Ref::INVALID()) {
1031 1032 1033 1034 1035 1036 1037 1038
    ascent = 0.001 * builtinFont->ascent;
    descent = 0.001 * builtinFont->descent;
    fontBBox[0] = 0.001 * builtinFont->bbox[0];
    fontBBox[1] = 0.001 * builtinFont->bbox[1];
    fontBBox[2] = 0.001 * builtinFont->bbox[2];
    fontBBox[3] = 0.001 * builtinFont->bbox[3];
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1039 1040 1041
  // get font matrix
  fontMat[0] = fontMat[3] = 1;
  fontMat[1] = fontMat[2] = fontMat[4] = fontMat[5] = 0;
Albert Astals Cid's avatar
Albert Astals Cid committed
1042 1043
  obj1 = fontDict->lookup("FontMatrix");
  if (obj1.isArray()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1044
    for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1045 1046
      Object obj2 = obj1.arrayGet(i);
      if (obj2.isNum()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1047 1048 1049 1050 1051 1052 1053
	fontMat[i] = obj2.getNum();
      }
    }
  }

  // get Type 3 bounding box, font definition, and resources
  if (type == fontType3) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1054 1055
    obj1 = fontDict->lookup("FontBBox");
    if (obj1.isArray()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1056
      for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1057 1058
	Object obj2 = obj1.arrayGet(i);
	if (obj2.isNum()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1059 1060 1061 1062
	  fontBBox[i] = obj2.getNum();
	}
      }
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1063 1064
    charProcs = fontDict->lookup("CharProcs");
    if (!charProcs.isDict()) {
1065 1066
      error(errSyntaxError, -1,
	    "Missing or invalid CharProcs dictionary in Type 3 font");
Albert Astals Cid's avatar
Albert Astals Cid committed
1067
      charProcs.setToNull();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1068
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1069 1070 1071
    resources = fontDict->lookup("Resources");
    if (!resources.isDict()) {
      resources.setToNull();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    }
  }

  //----- build the font encoding -----

  // Encodings start with a base encoding, which can come from
  // (in order of priority):
  //   1. FontDict.Encoding or FontDict.Encoding.BaseEncoding
  //        - MacRoman / MacExpert / WinAnsi / Standard
  //   2. embedded or external font file
  //   3. default:
  //        - builtin --> builtin encoding
1084
  //        - TrueType --> WinAnsiEncoding
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1085 1086 1087 1088 1089
  //        - others --> StandardEncoding
  // and then add a list of differences (if any) from
  // FontDict.Encoding.Differences.

  // check FontDict for base encoding
1090 1091
  hasEncoding = false;
  usesMacRomanEnc = false;
1092
  baseEnc = nullptr;
1093
  baseEncFromFontFile = false;
Albert Astals Cid's avatar
Albert Astals Cid committed
1094
  obj1 = fontDict->lookup("Encoding");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1095
  if (obj1.isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1096
    Object obj2 = obj1.dictLookup("BaseEncoding");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1097
    if (obj2.isName("MacRomanEncoding")) {
1098 1099
      hasEncoding = true;
      usesMacRomanEnc = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1100 1101
      baseEnc = macRomanEncoding;
    } else if (obj2.isName("MacExpertEncoding")) {
1102
      hasEncoding = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1103 1104
      baseEnc = macExpertEncoding;
    } else if (obj2.isName("WinAnsiEncoding")) {
1105
      hasEncoding = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1106 1107 1108
      baseEnc = winAnsiEncoding;
    }
  } else if (obj1.isName("MacRomanEncoding")) {
1109 1110
    hasEncoding = true;
    usesMacRomanEnc = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1111 1112
    baseEnc = macRomanEncoding;
  } else if (obj1.isName("MacExpertEncoding")) {
1113
    hasEncoding = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1114 1115
    baseEnc = macExpertEncoding;
  } else if (obj1.isName("WinAnsiEncoding")) {
1116
    hasEncoding = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1117 1118 1119
    baseEnc = winAnsiEncoding;
  }

1120
  // check embedded font file for base encoding
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1121 1122
  // (only for Type 1 fonts - trying to get an encoding out of a
  // TrueType font is a losing proposition)
1123 1124 1125
  ffT1 = nullptr;
  ffT1C = nullptr;
  buf = nullptr;
1126
  if (type == fontType1 && embFontID != Ref::INVALID()) {
1127 1128 1129 1130 1131 1132 1133
    if ((buf = readEmbFontFile(xref, &len))) {
      if ((ffT1 = FoFiType1::make(buf, len))) {
	if (ffT1->getName()) {
	  if (embFontName) {
	    delete embFontName;
	  }
	  embFontName = new GooString(ffT1->getName());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1134
	}
1135 1136
	if (!baseEnc) {
	  baseEnc = (const char **)ffT1->getEncoding();
1137
	  baseEncFromFontFile = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1138 1139
	}
      }
1140 1141
      gfree(buf);
    }
1142
  } else if (type == fontType1C && embFontID != Ref::INVALID()) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    if ((buf = readEmbFontFile(xref, &len))) {
      if ((ffT1C = FoFiType1C::make(buf, len))) {
	if (ffT1C->getName()) {
	  if (embFontName) {
	    delete embFontName;
	  }
	  embFontName = new GooString(ffT1C->getName());
	}
	if (!baseEnc) {
	  baseEnc = (const char **)ffT1C->getEncoding();
1153
	  baseEncFromFontFile = true;
1154
	}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1155
      }
1156
      gfree(buf);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1157 1158 1159 1160 1161
    }
  }

  // get default base encoding
  if (!baseEnc) {
1162
    if (builtinFont && embFontID == Ref::INVALID()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1163
      baseEnc = builtinFont->defaultBaseEnc;
1164
      hasEncoding = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1165 1166 1167 1168 1169 1170 1171
    } else if (type == fontTrueType) {
      baseEnc = winAnsiEncoding;
    } else {
      baseEnc = standardEncoding;
    }
  }

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
  if (baseEncFromFontFile) {
    encodingName->Set("Builtin");
  } else if (baseEnc == winAnsiEncoding) {
    encodingName->Set("WinAnsi");
  } else if (baseEnc == macRomanEncoding) {
    encodingName->Set("MacRoman");
  } else if (baseEnc == macExpertEncoding) {
    encodingName->Set("MacExpert");
  } else if (baseEnc == symbolEncoding) {
    encodingName->Set("Symbol");
  } else if (baseEnc == zapfDingbatsEncoding) {
    encodingName->Set("ZapfDingbats");
  } else {
    encodingName->Set("Standard");
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1188 1189
  // copy the base encoding
  for (i = 0; i < 256; ++i) {
1190
    enc[i] = (char *)baseEnc[i];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1191 1192 1193 1194 1195 1196 1197 1198 1199
    if ((encFree[i] = baseEncFromFontFile) && enc[i]) {
      enc[i] = copyString(baseEnc[i]);
    }
  }

  // some Type 1C font files have empty encodings, which can break the
  // T1C->T1 conversion (since the 'seac' operator depends on having
  // the accents in the encoding), so we fill in any gaps from
  // StandardEncoding
1200
  if (type == fontType1C && embFontID != Ref::INVALID() && baseEncFromFontFile) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1201 1202
    for (i = 0; i < 256; ++i) {
      if (!enc[i] && standardEncoding[i]) {
1203
	enc[i] = (char *)standardEncoding[i];
1204
	encFree[i] = false;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1205 1206 1207 1208 1209 1210
      }
    }
  }

  // merge differences into encoding
  if (obj1.isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1211
    Object obj2 = obj1.dictLookup("Differences");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1212
    if (obj2.isArray()) {
1213
      encodingName->Set("Custom");
1214
      hasEncoding = true;
1215
      int code = 0;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1216
      for (i = 0; i < obj2.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1217
	Object obj3 = obj2.arrayGet(i);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1218 1219 1220 1221 1222 1223 1224 1225
	if (obj3.isInt()) {
	  code = obj3.getInt();
	} else if (obj3.isName()) {
	  if (code >= 0 && code < 256) {
	    if (encFree[code]) {
	      gfree(enc[code]);
	    }
	    enc[code] = copyString(obj3.getName());
1226
	    encFree[code] = true;
1227
	    ++code;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1228 1229
	  }
	} else {
1230 1231
	  error(errSyntaxError, -1,
		"Wrong type in font encoding resource differences ({0:s})",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1232 1233 1234 1235 1236
		obj3.getTypeName());
	}
      }
    }
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
1237 1238
  delete ffT1;
  delete ffT1C;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1239 1240 1241 1242

  //----- build the mapping to Unicode -----

  // pass 1: use the name-to-Unicode mapping table
1243 1244
  missing = hex = false;
  bool isZapfDingbats = name && name->endsWith("ZapfDingbats");
1245
  for (int code = 0; code < 256; ++code) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1246
    if ((charName = enc[code])) {
1247 1248 1249 1250 1251 1252 1253
      if (isZapfDingbats) {
	// include ZapfDingbats names
	toUnicode[code] = globalParams->mapNameToUnicodeAll(charName);
      } else {
	toUnicode[code] = globalParams->mapNameToUnicodeText(charName);
      }
      if (!toUnicode[code] && strcmp(charName, ".notdef")) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
	// if it wasn't in the name-to-Unicode table, check for a
	// name that looks like 'Axx' or 'xx', where 'A' is any letter
	// and 'xx' is two hex digits
	if ((strlen(charName) == 3 &&
	     isalpha(charName[0]) &&
	     isxdigit(charName[1]) && isxdigit(charName[2]) &&
	     ((charName[1] >= 'a' && charName[1] <= 'f') ||
	      (charName[1] >= 'A' && charName[1] <= 'F') ||
	      (charName[2] >= 'a' && charName[2] <= 'f') ||
	      (charName[2] >= 'A' && charName[2] <= 'F'))) ||
	    (strlen(charName) == 2 &&
	     isxdigit(charName[0]) && isxdigit(charName[1]) &&
1266 1267 1268
	     // Only check idx 1 to avoid misidentifying a decimal
	     // number like a0
	     ((charName[1] >= 'a' && charName[1] <= 'f') ||
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1269
	      (charName[1] >= 'A' && charName[1] <= 'F')))) {
1270
	  hex = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1271
	}
1272
	missing = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1273 1274 1275 1276 1277 1278
      }
    } else {
      toUnicode[code] = 0;
    }
  }

1279 1280
  numeric = testForNumericNames(fontDict, hex);

1281 1282 1283
  // construct the char code -> Unicode mapping object
  ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);

1284 1285
  // pass 1a: Expand ligatures in the Alphabetic Presentation Form
  // block (eg "fi", "ffi") to normal form
1286
  for (int code = 0; code < 256; ++code) {
1287
    if (unicodeIsAlphabeticPresentationForm(toUnicode[code])) {
1288
      Unicode *normalized = unicodeNormalizeNFKC(&toUnicode[code], 1, &len, nullptr);
1289 1290 1291 1292 1293 1294
      if (len > 1)
        ctu->setMapping((CharCode)code, normalized, len);
      gfree(normalized);
    }
  }

1295 1296 1297
  // pass 2: try to fill in the missing chars, looking for ligatures, numeric
  // references and variants
  if (missing) {
1298
    for (int code = 0; code < 256; ++code) {
1299
      if (!toUnicode[code]) {
1300 1301
	if ((charName = enc[code]) && strcmp(charName, ".notdef")
	    && (n = parseCharName(charName, uBuf, sizeof(uBuf)/sizeof(*uBuf), 
1302 1303
				  false, // don't check simple names (pass 1)
				  true, // do check ligatures
1304
				  numeric,
1305
				  hex,
1306
				  true))) { // do check variants
1307
	  ctu->setMapping((CharCode)code, uBuf, n);
1308 1309 1310
	  continue;
	}

1311
	// do a simple pass-through
1312
	// mapping for unknown character names
1313 1314
        uBuf[0] = code;
        ctu->setMapping((CharCode)code, uBuf, 1);
1315 1316
      }
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1317 1318 1319 1320 1321 1322
  }

  // merge in a ToUnicode CMap, if there is one -- this overwrites
  // existing entries in ctu, i.e., the ToUnicode CMap takes
  // precedence, but the other encoding info is allowed to fill in any
  // holes
1323
  readToUnicodeCMap(fontDict, 16, ctu);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1324 1325 1326 1327

  //----- get the character widths -----

  // initialize all widths
1328 1329
  for (double &width : widths) {
    width = missingWidth * 0.001;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1330 1331 1332
  }

  // use widths from font dict, if present
Albert Astals Cid's avatar
Albert Astals Cid committed
1333
  obj1 = fontDict->lookup("FirstChar");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1334 1335 1336 1337
  firstChar = obj1.isInt() ? obj1.getInt() : 0;
  if (firstChar < 0 || firstChar > 255) {
    firstChar = 0;
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
1338
  obj1 = fontDict->lookup("LastChar");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1339 1340 1341 1342 1343
  lastChar = obj1.isInt() ? obj1.getInt() : 255;
  if (lastChar < 0 || lastChar > 255) {
    lastChar = 255;
  }
  mul = (type == fontType3) ? fontMat[0] : 0.001;
Albert Astals Cid's avatar
Albert Astals Cid committed
1344
  obj1 = fontDict->lookup("Widths");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1345 1346 1347 1348 1349
  if (obj1.isArray()) {
    flags |= fontFixedWidth;
    if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
      lastChar = firstChar + obj1.arrayGetLength() - 1;
    }
1350
    for (int code = firstChar; code <= lastChar; ++code) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1351
      Object obj2 = obj1.arrayGet(code - firstChar);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1352 1353
      if (obj2.isNum()) {
	widths[code] = obj2.getNum() * mul;
1354
	if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
	  flags &= ~fontFixedWidth;
	}
      }
    }

  // use widths from built-in font
  } else if (builtinFont) {
    // this is a kludge for broken PDF files that encode char 32
    // as .notdef
    if (builtinFont->widths->getWidth("space", &w)) {
      widths[32] = 0.001 * w;
    }
1367
    for (int code = 0; code < 256; ++code) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
	widths[code] = 0.001 * w;
      }
    }

  // couldn't find widths -- use defaults 
  } else {
    // this is technically an error -- the Widths entry is required
    // for all but the Base-14 fonts -- but certain PDF generators
    // apparently don't include widths for Arial and TimesNewRoman
    if (isFixedWidth()) {
      i = 0;
    } else if (isSerif()) {
      i = 8;
    } else {
      i = 4;
    }
    if (isBold()) {
      i += 2;
    }
    if (isItalic()) {
      i += 1;
    }
    builtinFont = builtinFontSubst[i];
    // this is a kludge for broken PDF files that encode char 32
    // as .notdef
    if (builtinFont->widths->getWidth("space", &w)) {
      widths[32] = 0.001 * w;
    }
1397
    for (int code = 0; code < 256; ++code) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1398 1399 1400 1401 1402 1403
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
	widths[code] = 0.001 * w;
      }
    }
  }

1404
  ok = true;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
}

Gfx8BitFont::~Gfx8BitFont() {
  int i;

  for (i = 0; i < 256; ++i) {
    if (encFree[i] && enc[i]) {
      gfree(enc[i]);
    }
  }
  ctu->decRefCnt();
}

1418 1419 1420 1421 1422
// This function is in part a derived work of the Adobe Glyph Mapping
// Convention: http://www.adobe.com/devnet/opentype/archives/glyph.html
// Algorithmic comments are excerpted from that document to aid
// maintainability.
static int parseCharName(char *charName, Unicode *uBuf, int uLen,
1423 1424
			 bool names, bool ligatures,
			 bool numeric, bool hex, bool variants)
1425 1426
{
  if (uLen <= 0) {
1427 1428
    error(errInternal, -1, "Zero-length output buffer (recursion overflow?) in "
	  "parseCharName, component \"{0:s}\"", charName);