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, 2018 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 38 39 40 41 42
//
// 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
43 44 45 46 47 48 49 50 51 52
#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
53 54
#include <math.h>
#include <limits.h>
55
#include <algorithm>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
56 57 58 59 60 61 62 63 64
#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"
65
#include "UnicodeTypeTable.h"
66
#include <fofi/FoFiIdentifier.h>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
67 68 69 70
#include <fofi/FoFiType1.h>
#include <fofi/FoFiType1C.h>
#include <fofi/FoFiTrueType.h>
#include "GfxFont.h"
71
#include "PSOutputDev.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
72 73 74

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

75
struct Base14FontMapEntry {
76
  const char *altName;
77
  const char *base14Name;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
78 79
};

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

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
//------------------------------------------------------------------------

// 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"
};

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

176 177 178 179
static int parseCharName(char *charName, Unicode *uBuf, int uLen,
			 GBool names, GBool ligatures, 
			 GBool numeric, GBool hex, GBool variants);

180 181 182 183 184 185
//------------------------------------------------------------------------

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

186 187 188 189 190
//------------------------------------------------------------------------
// GfxFontLoc
//------------------------------------------------------------------------

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

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

Kristian Høgsberg's avatar
Kristian Høgsberg committed
206 207 208 209
//------------------------------------------------------------------------
// GfxFont
//------------------------------------------------------------------------

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

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

223 224 225 226
  // get embedded font ID and font type
  typeA = getFontType(xref, fontDict, &embFontIDA);

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

  return font;
}

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

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

270 271 272 273 274 275 276 277 278
void GfxFont::incRefCnt() {
  refCnt++;
}

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

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
// 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;
  GBool isType0, err;

  t = fontUnknownType;
  embID->num = embID->gen = -1;
  err = gFalse;

Albert Astals Cid's avatar
Albert Astals Cid committed
299
  Object subtype = fontDict->lookup("Subtype");
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  expectedType = fontUnknownType;
  isType0 = gFalse;
  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")) {
    isType0 = gTrue;
  } else {
    error(errSyntaxWarning, -1, "Unknown font type: '{0:s}'",
	  subtype.isName() ? subtype.getName() : "???");
  }

  fontDict2 = fontDict;
Albert Astals Cid's avatar
Albert Astals Cid committed
318 319 320 321
  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()) {
322 323
    if (obj1.arrayGetLength() == 0) {
      error(errSyntaxWarning, -1, "Empty DescendantFonts array in font");
Albert Astals Cid's avatar
Albert Astals Cid committed
324 325 326 327 328
    } else {
      obj2 = obj1.arrayGet(0);
      if (obj2.isDict()) {
	if (!isType0) {
	  error(errSyntaxWarning, -1, "Non-CID font with DescendantFonts array");
329
	}
Albert Astals Cid's avatar
Albert Astals Cid committed
330 331 332 333 334 335 336 337 338 339
	fontDict2 = obj2.getDict();
	subtype = fontDict2->lookup("Subtype");
	if (subtype.isName("CIDFontType0")) {
	  if (isType0) {
	    expectedType = fontCIDType0;
	  }
	} else if (subtype.isName("CIDFontType2")) {
	  if (isType0) {
	    expectedType = fontCIDType2;
	  }
340 341 342 343 344
	}
      }
    }
  }

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

  t = fontUnknownType;
  if (embID->num >= 0) {
Albert Astals Cid's avatar
Albert Astals Cid committed
413 414
    Object obj3(embID->num, embID->gen);
    Object obj4 = obj3.fetch(xref);
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 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    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) {
    err = gTrue;
  }

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

  return t;
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
463 464 465 466 467 468 469 470
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
471 472
  Object obj1 = fontDict->lookup("FontDescriptor");
  if (obj1.isDict()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
473 474

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

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

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

    // get stretch
Albert Astals Cid's avatar
Albert Astals Cid committed
499
    obj2 = obj1.dictLookup("FontStretch");
500 501 502 503 504 505 506 507 508 509
    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;
510
      else error(errSyntaxWarning, -1, "Invalid Font Stretch");
511 512 513
    }
    
    // get weight
Albert Astals Cid's avatar
Albert Astals Cid committed
514
    obj2 = obj1.dictLookup("FontWeight");
515 516 517 518 519 520 521 522 523 524
    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;
525
      else error(errSyntaxWarning, -1, "Invalid Font Weight");
526 527
    }

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

    // get Ascent and Descent
Albert Astals Cid's avatar
Albert Astals Cid committed
535
    obj2 = obj1.dictLookup("Ascent");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
536 537
    if (obj2.isNum()) {
      t = 0.001 * obj2.getNum();
538 539 540 541 542 543 544
      // 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
545 546 547
	ascent = t;
      }
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
548
    obj2 = obj1.dictLookup("Descent");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
549 550
    if (obj2.isNum()) {
      t = 0.001 * obj2.getNum();
551 552 553 554
      // some broken font descriptors specify a positive descent
      if (t > 0) {
	t = -t;
      }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
555
      // some broken font descriptors set ascent and descent to 0
556
      if (t != 0 && t > -3) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
557 558 559 560 561
	descent = t;
      }
    }

    // font FontBBox
Albert Astals Cid's avatar
Albert Astals Cid committed
562 563 564 565 566
    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
567 568 569 570 571 572 573 574 575 576 577
	  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
578 579
  Object obj1 = fontDict->lookup("ToUnicode");
  if (!obj1.isStream()) {
580
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
581 582
  }
  buf = new GooString();
583
  obj1.getStream()->fillGooString(buf);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
584 585 586 587 588 589
  obj1.streamClose();
  if (ctu) {
    ctu->mergeCMap(buf, nBits);
  } else {
    ctu = CharCodeToUnicode::parseCMap(buf, nBits);
  }
590
  hasToUnicode = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
591 592 593 594
  delete buf;
  return ctu;
}

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

602
  if (type == fontType3) {
603
    return nullptr;
604 605 606 607 608
  }

  //----- embedded font
  if (embFontID.num >= 0) {
    embed = gTrue;
Albert Astals Cid's avatar
Albert Astals Cid committed
609 610
    Object refObj(embFontID.num, embFontID.gen);
    Object embFontObj = refObj.fetch(xref);
611 612 613 614 615 616 617 618 619 620
    if (!embFontObj.isStream()) {
      error(errSyntaxError, -1, "Embedded font object is wrong type");
      embed = gFalse;
    }
    if (embed) {
      if (ps) {
	switch (type) {
	case fontType1:
	case fontType1C:
	case fontType1COT:
621
	  embed = ps->getEmbedType1();
622 623 624
	  break;
	case fontTrueType:
	case fontTrueTypeOT:
625
	  embed = ps->getEmbedTrueType();
626 627 628
	  break;
	case fontCIDType0C:
	case fontCIDType0COT:
629
	  embed = ps->getEmbedCIDPostScript();
630 631 632
	  break;
	case fontCIDType2:
	case fontCIDType2OT:
633
	  embed = ps->getEmbedCIDTrueType();
634 635 636 637 638 639 640 641 642 643 644 645
	  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
646 647 648
    }
  }

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

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
  //----- 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);
677
    if ((path = globalParams->findBase14FontFile(base14Name, this))) {
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 712 713 714
      if ((fontLoc = getExternalFont(path, gFalse))) {
	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
715
  }
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

  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
735 736
      error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
	    base14SubstFonts[substIdx], name ? name->getCString() : "null");
737 738 739 740 741 742 743 744 745 746 747
      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) {
	if ((fontLoc = getExternalFont(path, gFalse))) {
Albert Astals Cid's avatar
Albert Astals Cid committed
748 749
	  error(errSyntaxWarning, -1, "Substituting font '{0:s}' for '{1:s}'",
		  base14SubstFonts[substIdx], name ? name->getCString() : "");
750 751 752 753 754 755 756 757
	  name = new GooString(base14SubstFonts[substIdx]);
	  fontLoc->substIdx = substIdx;
	  return fontLoc;
	}
      }
    }

    // failed to find a substitute font
758
    return nullptr;
Ed Avis's avatar
Ed Avis committed
759
  }
760 761

  // failed to find a substitute font
762
  return nullptr;
763 764 765 766 767 768 769
}

GfxFontLoc *GfxFont::locateBase14Font(GooString *base14Name) {
  GooString *path;

  path = globalParams->findFontFile(base14Name);
  if (!path) {
770
    return nullptr;
Ed Avis's avatar
Ed Avis committed
771
  }
772 773 774 775 776 777 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 809 810 811
  return getExternalFont(path, gFalse);
}

GfxFontLoc *GfxFont::getExternalFont(GooString *path, GBool cid) {
  FoFiIdentifierType fft;
  GfxFontType fontType;
  GfxFontLoc *fontLoc;

  fft = FoFiIdentifier::identifyFile(path->getCString());
  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;
812
    return nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
813
  }
814 815 816 817 818
  fontLoc = new GfxFontLoc();
  fontLoc->locType = gfxFontLocExternal;
  fontLoc->fontType = fontType;
  fontLoc->path = path;
  return fontLoc;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
819 820 821 822 823 824
}

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

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

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

  return buf;
}

841 842 843 844 845 846 847 848 849 850 851 852 853

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" },
854
  { nullptr,    nullptr }
855 856 857 858 859 860 861 862 863 864
};

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

Kristian Høgsberg's avatar
Kristian Høgsberg committed
868 869 870 871
//------------------------------------------------------------------------
// Gfx8BitFont
//------------------------------------------------------------------------

872 873 874
// 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.
875
static GBool parseNumericName(const char *s, GBool hex, unsigned int *u) {
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  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) {
      return gFalse;
    }
  } 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)
    return gFalse;

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

  if (*endptr == '\0') {
    if (u)
      *u = v;
    return gTrue;
  }
  return gFalse;
}

// Returns gTrue if the font has character names like xx or Axx which
// should be parsed for hex or decimal values.
static GBool testForNumericNames(Dict *fontDict, GBool hex) {
  GBool numeric = gTrue;

Albert Astals Cid's avatar
Albert Astals Cid committed
920
  Object enc = fontDict->lookup("Encoding");
921 922 923 924
  if (!enc.isDict()) {
    return gFalse;
  }

Albert Astals Cid's avatar
Albert Astals Cid committed
925
  Object diff = enc.dictLookup("Differences");
926 927 928 929 930
  if (!diff.isArray()) {
    return gFalse;
  }

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

  return numeric;
}

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

971
  refCnt = 1;
972
  ctu = nullptr;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
973 974 975

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

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

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  // for non-embedded fonts, don't trust the ascent/descent/bbox
  // values from the font descriptor
  if (builtinFont && embFontID.num < 0) {
    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
1043 1044 1045
  // 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
1046 1047
  obj1 = fontDict->lookup("FontMatrix");
  if (obj1.isArray()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1048
    for (i = 0; i < 6 && i < obj1.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1049 1050
      Object obj2 = obj1.arrayGet(i);
      if (obj2.isNum()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1051 1052 1053 1054 1055 1056 1057
	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
1058 1059
    obj1 = fontDict->lookup("FontBBox");
    if (obj1.isArray()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1060
      for (i = 0; i < 4 && i < obj1.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1061 1062
	Object obj2 = obj1.arrayGet(i);
	if (obj2.isNum()) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1063 1064 1065 1066
	  fontBBox[i] = obj2.getNum();
	}
      }
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1067 1068
    charProcs = fontDict->lookup("CharProcs");
    if (!charProcs.isDict()) {
1069 1070
      error(errSyntaxError, -1,
	    "Missing or invalid CharProcs dictionary in Type 3 font");
Albert Astals Cid's avatar
Albert Astals Cid committed
1071
      charProcs.setToNull();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1072
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
1073 1074 1075
    resources = fontDict->lookup("Resources");
    if (!resources.isDict()) {
      resources.setToNull();
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    }
  }

  //----- 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
1088
  //        - TrueType --> WinAnsiEncoding
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1089 1090 1091 1092 1093 1094 1095
  //        - others --> StandardEncoding
  // and then add a list of differences (if any) from
  // FontDict.Encoding.Differences.

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

1124
  // check embedded font file for base encoding
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1125 1126
  // (only for Type 1 fonts - trying to get an encoding out of a
  // TrueType font is a losing proposition)
1127 1128 1129
  ffT1 = nullptr;
  ffT1C = nullptr;
  buf = nullptr;
1130 1131 1132 1133 1134 1135 1136 1137
  if (type == fontType1 && embFontID.num >= 0) {
    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
1138
	}
1139 1140 1141
	if (!baseEnc) {
	  baseEnc = (const char **)ffT1->getEncoding();
	  baseEncFromFontFile = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1142 1143
	}
      }
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
      gfree(buf);
    }
  } else if (type == fontType1C && embFontID.num >= 0) {
    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();
	  baseEncFromFontFile = gTrue;
	}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1159
      }
1160
      gfree(buf);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1161 1162 1163 1164 1165
    }
  }

  // get default base encoding
  if (!baseEnc) {
1166
    if (builtinFont && embFontID.num < 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1167 1168 1169 1170 1171 1172 1173 1174 1175
      baseEnc = builtinFont->defaultBaseEnc;
      hasEncoding = gTrue;
    } else if (type == fontTrueType) {
      baseEnc = winAnsiEncoding;
    } else {
      baseEnc = standardEncoding;
    }
  }

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  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
1192 1193
  // copy the base encoding
  for (i = 0; i < 256; ++i) {
1194
    enc[i] = (char *)baseEnc[i];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1195 1196 1197 1198 1199 1200 1201 1202 1203
    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
1204
  if (type == fontType1C && embFontID.num >= 0 && baseEncFromFontFile) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1205 1206
    for (i = 0; i < 256; ++i) {
      if (!enc[i] && standardEncoding[i]) {
1207
	enc[i] = (char *)standardEncoding[i];
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1208 1209 1210 1211 1212 1213 1214
	encFree[i] = gFalse;
      }
    }
  }

  // merge differences into encoding
  if (obj1.isDict()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1215
    Object obj2 = obj1.dictLookup("Differences");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1216
    if (obj2.isArray()) {
1217
      encodingName->Set("Custom");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1218 1219 1220
      hasEncoding = gTrue;
      code = 0;
      for (i = 0; i < obj2.arrayGetLength(); ++i) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1221
	Object obj3 = obj2.arrayGet(i);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
	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());
	    encFree[code] = gTrue;
	  }
	  ++code;
	} else {
1234 1235
	  error(errSyntaxError, -1,
		"Wrong type in font encoding resource differences ({0:s})",
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1236 1237 1238 1239 1240
		obj3.getTypeName());
	}
      }
    }
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
1241 1242
  delete ffT1;
  delete ffT1C;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1243 1244 1245 1246 1247

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

  // pass 1: use the name-to-Unicode mapping table
  missing = hex = gFalse;
1248
  GBool isZapfDingbats = name && name->endsWith("ZapfDingbats");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1249 1250
  for (code = 0; code < 256; ++code) {
    if ((charName = enc[code])) {
1251 1252 1253 1254 1255 1256 1257
      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
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
	// 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]) &&
1270 1271 1272
	     // 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
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	      (charName[1] >= 'A' && charName[1] <= 'F')))) {
	  hex = gTrue;
	}
	missing = gTrue;
      }
    } else {
      toUnicode[code] = 0;
    }
  }

1283 1284
  numeric = testForNumericNames(fontDict, hex);

1285 1286 1287
  // construct the char code -> Unicode mapping object
  ctu = CharCodeToUnicode::make8BitToUnicode(toUnicode);

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

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

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

  // 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
1327
  readToUnicodeCMap(fontDict, 16, ctu);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1328 1329 1330 1331 1332 1333 1334 1335 1336

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

  // initialize all widths
  for (code = 0; code < 256; ++code) {
    widths[code] = missingWidth * 0.001;
  }

  // use widths from font dict, if present
Albert Astals Cid's avatar
Albert Astals Cid committed
1337
  obj1 = fontDict->lookup("FirstChar");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1338 1339 1340 1341
  firstChar = obj1.isInt() ? obj1.getInt() : 0;
  if (firstChar < 0 || firstChar > 255) {
    firstChar = 0;
  }
Albert Astals Cid's avatar
Albert Astals Cid committed
1342
  obj1 = fontDict->lookup("LastChar");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1343 1344 1345 1346 1347
  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
1348
  obj1 = fontDict->lookup("Widths");
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1349 1350 1351 1352 1353 1354
  if (obj1.isArray()) {
    flags |= fontFixedWidth;
    if (obj1.arrayGetLength() < lastChar - firstChar + 1) {
      lastChar = firstChar + obj1.arrayGetLength() - 1;
    }
    for (code = firstChar; code <= lastChar; ++code) {
Albert Astals Cid's avatar
Albert Astals Cid committed
1355
      Object obj2 = obj1.arrayGet(code - firstChar);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1356 1357
      if (obj2.isNum()) {
	widths[code] = obj2.getNum() * mul;
1358
	if (fabs(widths[code] - widths[firstChar]) > 0.00001) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1359 1360 1361 1362 1363 1364 1365 1366 1367 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 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	  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;
    }
    for (code = 0; code < 256; ++code) {
      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;
    }
    for (code = 0; code < 256; ++code) {
      if (enc[code] && builtinFont->widths->getWidth(enc[code], &w)) {
	widths[code] = 0.001 * w;
      }
    }
  }

  ok = gTrue;
}

Gfx8BitFont::~Gfx8BitFont() {
  int i;

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

1422 1423 1424 1425 1426 1427 1428 1429 1430
// 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,
			 GBool names, GBool ligatures,
			 GBool numeric, GBool hex, GBool variants)
{
  if (uLen <= 0) {
1431 1432
    error(errInternal, -1, "Zero-length output buffer (recursion overflow?) in "
	  "parseCharName, component \"{0:s}\"", charName);
1433 1434 1435 1436 1437 1438 1439 1440
    return 0;
  }
  // Step 1: drop all the characters from the glyph name starting with the
  // first occurrence of a period (U+002E FULL STOP), if any.
  if (variants) {
    char *var_part = strchr(charName, '.');
    if (var_part == charName) {
      return 0;	// .notdef or similar
1441
    } else if (var_part != nullptr) {
1442
      // parse names of the form 7.oldstyle, P.swash, s.sc, etc.
1443
      char *main_part = copyString(charName, var_part - charName);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
      GBool namesRecurse = gTrue, variantsRecurse = gFalse;
      int n = parseCharName(main_part, uBuf, uLen, namesRecurse, ligatures,
			    numeric, hex, variantsRecurse);
      gfree(main_part);
      return n;
    }
  }
  // Step 2: split the remaining string into a sequence of components, using
  // underscore (U+005F LOW LINE) as the delimiter.
  if (ligatures && strchr(charName, '_')) {
    // parse names of the form A_a (e.g. f_i, T_h, l_quotesingle)
    char *lig_part, *lig_end, *lig_copy;
    int n = 0, m;
    lig_part = lig_copy = copyString(charName);
    do {
      if ((lig_end = strchr(lig_part, '_')))
	*lig_end = '\0';
      if (lig_part[0] != '\0') {
	GBool namesRecurse = gTrue, ligaturesRecurse = gFalse;
	if ((m = parseCharName(lig_part, uBuf + n, uLen - n, namesRecurse,
			       ligaturesRecurse, numeric, hex, variants)))
	  n += m;
	else
1467
	  error(errSyntaxWarning, -1, "Could not parse ligature component \"{0:s}\" of \"{1:s}\" in "
1468
		"parseCharName", lig_part, charName);
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
      }
      lig_part = lig_end + 1;
    } while (lig_end && n < uLen);
    gfree(lig_copy);
    return n;
  }
  // Step 3: map each component to a character string according to the
  // procedure below, and concatenate those strings; the result is the
  // character string to which the glyph name is mapped.
  // 3.1. if the font is Zapf Dingbats (PostScript FontName ZapfDingbats), and
  // the component is in the ZapfDingbats list, then map it to the
  // corresponding character in that list.
  // 3.2. otherwise, if the component is in the Adobe Glyph List, then map it
  // to the corresponding character in that list.
1483
  if (names && (uBuf[0] = globalParams->mapNameToUnicodeText(charName))) {
1484 1485
    return 1;
  }
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
  unsigned int n = strlen(charName);
  // 3.3. otherwise, if the component is of the form "uni" (U+0075 U+006E
  // U+0069) followed by a sequence of uppercase hexadecimal digits (0 .. 9,
  // A .. F, i.e. U+0030 .. U+0039, U+0041 .. U+0046), the length of that
  // sequence is a multiple of four, and each group of four digits represents
  // a number in the set {0x0000 .. 0xD7FF, 0xE000 .. 0xFFFF}, then interpret
  // each such number as a Unicode scalar value and map the component to the
  // string made of those scalar values. Note that the range and digit length
  // restrictions mean that the "uni" prefix can be used only with Unicode
  // values from the Basic Multilingual Plane (BMP).
  if (n >= 7 && (n % 4) == 3 && !strncmp(charName, "uni", 3)) {
    int i;
    unsigned int m;
    for (i = 0, m = 3; i < uLen && m < n; m += 4) {
      if (isxdigit(charName[m]) && isxdigit(charName[m + 1]) &&
          isxdigit(charName[m + 2]) && isxdigit(charName[m + 3])) {
        unsigned int u;
        sscanf(charName + m, "%4x", &u);
        if (u <= 0xD7FF || (0xE000 <= u && u <= 0xFFFF)) {
          uBuf[i++] = u;
        }
1507 1508
      }
    }
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    return i;
  }
  // 3.4. otherwise, if the component is of the form "u" (U+0075) followed by
  // a sequence of four to six uppercase hexadecimal digits {0 .. 9, A .. F}
  // (U+0030 .. U+0039, U+0041 .. U+0046), and those digits represent a
  // number in {0x0000 .. 0xD7FF, 0xE000 .. 0x10FFFF}, then interpret this
  // number as a Unicode scalar value and map the component to the string
  // made of this scalar value.
  if (n >= 5 && n <= 7 && charName[0] == 'u' && isxdigit(charName[1]) &&
      isxdigit(charName[2]) && isxdigit(charName[3]) && isxdigit(charName[4])
      && (n <= 5 || isxdigit(charName[5]))
      && (n <= 6 || isxdigit(charName[6]))) {
    unsigned int u;
    sscanf(charName + 1, "%x", &u);
    if (u <= 0xD7FF || (0xE000 <= u && u <= 0x10FFFF)) {
      uBuf[0] = u;
1525
      return 1;
1526
    }
1527
  }
1528 1529 1530 1531
  // Not in Adobe Glyph Mapping convention: look for names like xx
  // or Axx and parse for hex or decimal values.
  if (numeric && parseNumericName(charName, hex, uBuf))
    return 1;
1532 1533 1534 1535
  // 3.5. otherwise, map the component to the empty string
  return 0;
}

1536
int Gfx8BitFont::getNextChar(const char *s, int len, CharCode *code,
1537
			     Unicode **u, int *uLen,
1538
			     double *dx, double *dy, double *ox, double *oy) const {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1539 1540 1541
  CharCode c;

  *code = c = (CharCode)(*s & 0xff);
1542
  *uLen = ctu->mapToUnicode(c, u);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1543 1544 1545 1546 1547
  *dx = widths[c];
  *dy = *ox = *oy = 0;
  return 1;
}

1548
const CharCodeToUnicode *Gfx8BitFont::getToUnicode() const {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1549 1550 1551
  return ctu;
}

1552 1553
int *Gfx8BitFont::getCodeToGIDMap(FoFiTrueType *ff) {
  int *map;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1554 1555 1556 1557 1558 1559 1560
  int cmapPlatform, cmapEncoding;
  int unicodeCmap, macRomanCmap, msSymbolCmap, cmap;
  GBool useMacRoman, useUnicode;
  char *charName;
  Unicode u;
  int code, i, n;

1561
  map = (int *)gmallocn(256, sizeof(int));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1562 1563 1564 1565 1566 1567 1568
  for (i = 0; i < 256; ++i) {
    map[i] = 0;
  }

  // To match up with the Adobe-defined behaviour, we choose a cmap
  // like this:
  // 1. If the PDF font has an encoding:
Thomas Freitag's avatar
Thomas Freitag committed
1569 1570 1571 1572
  //    1a. If the TrueType font has a Microsoft Unicode
  //        cmap or a non-Microsoft Unicode cmap, use it, and use the
  //        Unicode indexes, not the char codes.
  //    1b. If the PDF font specified MacRomanEncoding and the
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1573 1574 1575 1576 1577 1578 1579 1580
  //        TrueType font has a Macintosh Roman cmap, use it, and
  //        reverse map the char names through MacRomanEncoding to
  //        get char codes.
  //    1c. If the PDF font is symbolic and the TrueType font has a
  //        Microsoft Symbol cmap, use it, and use char codes
  //        directly (possibly with an offset of 0xf000).
  //    1d. If the TrueType font has a Macintosh Roman cmap, use it,
  //        as in case 1a.
1581 1582
  // 2. If the PDF font does not have an encoding or the PDF font is
  //    symbolic:
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
  //    2a. If the TrueType font has a Macintosh Roman cmap, use it,
  //        and use char codes directly (possibly with an offset of
  //        0xf000).
  //    2b. If the TrueType font has a Microsoft Symbol cmap, use it,
  //        and use char codes directly (possible with an offset of
  //        0xf000).
  // 3. If none of these rules apply, use the first cmap and hope for
  //    the best (this shouldn't happen).
  unicodeCmap = macRomanCmap = msSymbolCmap = -1;
  for (i = 0; i < ff->getNumCmaps(); ++i) {
    cmapPlatform = ff->getCmapPlatform(i);
    cmapEncoding = ff->getCmapEncoding(i);
    if ((cmapPlatform == 3 && cmapEncoding == 1) ||
	cmapPlatform == 0) {
      unicodeCmap = i;
    } else if (cmapPlatform == 1 && cmapEncoding == 0) {
      macRomanCmap = i;
    } else if (cmapPlatform == 3 && cmapEncoding == 0) {
      msSymbolCmap = i;
    }
  }
  cmap = 0;
  useMacRoman = gFalse;
  useUnicode = gFalse;
1607
  if (hasEncoding || type == fontType1) {
Thomas Freitag's avatar
Thomas Freitag committed
1608
    if (unicodeCmap >= 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1609 1610
      cmap = unicodeCmap;
      useUnicode = gTrue;
Thomas Freitag's avatar
Thomas Freitag committed
1611 1612 1613
    } else if (usesMacRomanEnc && macRomanCmap >= 0) {
      cmap = macRomanCmap;
      useMacRoman = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1614 1615
    } else if ((flags & fontSymbolic) && msSymbolCmap >= 0) {
      cmap = msSymbolCmap;
1616 1617
    } else if ((flags & fontSymbolic) && macRomanCmap >= 0) {
      cmap = macRomanCmap;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1618 1619
    } else if (macRomanCmap >= 0) {
      cmap = macRomanCmap;
1620
      useMacRoman = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1621 1622
    }
  } else {
1623
    if (msSymbolCmap >= 0) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1624
      cmap = msSymbolCmap;
1625 1626
    } else if (macRomanCmap >= 0) {
      cmap = macRomanCmap;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    }
  }

  // reverse map the char names through MacRomanEncoding, then map the
  // char codes through the cmap
  if (useMacRoman) {
    for (i = 0; i < 256; ++i) {
      if ((charName = enc[i])) {
	if ((code = globalParams->getMacRomanCharCode(charName))) {
	  map[i] = ff->mapCodeToGID(cmap, code);
	}
1638 1639
      } else {
	map[i] = -1;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1640 1641 1642 1643 1644
      }
    }

  // map Unicode through the cmap
  } else if (useUnicode) {
1645
    Unicode *uAux;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1646
    for (i = 0; i < 256; ++i) {
1647
      if (((charName = enc[i]) && (u = globalParams->mapNameToUnicodeAll(charName))))
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1648
	map[i] = ff->mapCodeToGID(cmap, u);
1649 1650 1651 1652
      else
      {
	n = ctu->mapToUnicode((CharCode)i, &uAux);
	if (n > 0) map[i] = ff->mapCodeToGID(cmap, uAux[0]);
1653
	else map[i] = -1;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666