fonts.js 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. var sharedUtil = require('../shared/util.js');
  17. var corePrimitives = require('./primitives.js');
  18. var coreStream = require('./stream.js');
  19. var coreGlyphList = require('./glyphlist.js');
  20. var coreFontRenderer = require('./font_renderer.js');
  21. var coreEncodings = require('./encodings.js');
  22. var coreStandardFonts = require('./standard_fonts.js');
  23. var coreUnicode = require('./unicode.js');
  24. var coreType1Parser = require('./type1_parser.js');
  25. var coreCFFParser = require('./cff_parser.js');
  26. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  27. var FontType = sharedUtil.FontType;
  28. var assert = sharedUtil.assert;
  29. var bytesToString = sharedUtil.bytesToString;
  30. var error = sharedUtil.error;
  31. var info = sharedUtil.info;
  32. var isArray = sharedUtil.isArray;
  33. var isInt = sharedUtil.isInt;
  34. var isNum = sharedUtil.isNum;
  35. var readUint32 = sharedUtil.readUint32;
  36. var shadow = sharedUtil.shadow;
  37. var string32 = sharedUtil.string32;
  38. var warn = sharedUtil.warn;
  39. var MissingDataException = sharedUtil.MissingDataException;
  40. var isSpace = sharedUtil.isSpace;
  41. var Stream = coreStream.Stream;
  42. var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode;
  43. var getDingbatsGlyphsUnicode = coreGlyphList.getDingbatsGlyphsUnicode;
  44. var FontRendererFactory = coreFontRenderer.FontRendererFactory;
  45. var StandardEncoding = coreEncodings.StandardEncoding;
  46. var MacRomanEncoding = coreEncodings.MacRomanEncoding;
  47. var SymbolSetEncoding = coreEncodings.SymbolSetEncoding;
  48. var ZapfDingbatsEncoding = coreEncodings.ZapfDingbatsEncoding;
  49. var getEncoding = coreEncodings.getEncoding;
  50. var getStdFontMap = coreStandardFonts.getStdFontMap;
  51. var getNonStdFontMap = coreStandardFonts.getNonStdFontMap;
  52. var getGlyphMapForStandardFonts = coreStandardFonts.getGlyphMapForStandardFonts;
  53. var getSupplementalGlyphMapForArialBlack = coreStandardFonts.getSupplementalGlyphMapForArialBlack;
  54. var getUnicodeRangeFor = coreUnicode.getUnicodeRangeFor;
  55. var mapSpecialUnicodeValues = coreUnicode.mapSpecialUnicodeValues;
  56. var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
  57. var Type1Parser = coreType1Parser.Type1Parser;
  58. var CFFStandardStrings = coreCFFParser.CFFStandardStrings;
  59. var CFFParser = coreCFFParser.CFFParser;
  60. var CFFCompiler = coreCFFParser.CFFCompiler;
  61. var CFF = coreCFFParser.CFF;
  62. var CFFHeader = coreCFFParser.CFFHeader;
  63. var CFFTopDict = coreCFFParser.CFFTopDict;
  64. var CFFPrivateDict = coreCFFParser.CFFPrivateDict;
  65. var CFFStrings = coreCFFParser.CFFStrings;
  66. var CFFIndex = coreCFFParser.CFFIndex;
  67. var CFFCharset = coreCFFParser.CFFCharset;
  68. var PRIVATE_USE_OFFSET_START = 0xE000;
  69. var PRIVATE_USE_OFFSET_END = 0xF8FF;
  70. var SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = false;
  71. var PDF_GLYPH_SPACE_UNITS = 1000;
  72. var SEAC_ANALYSIS_ENABLED = false;
  73. var FontFlags = {
  74. FixedPitch: 1,
  75. Serif: 2,
  76. Symbolic: 4,
  77. Script: 8,
  78. Nonsymbolic: 32,
  79. Italic: 64,
  80. AllCap: 65536,
  81. SmallCap: 131072,
  82. ForceBold: 262144
  83. };
  84. var MacStandardGlyphOrdering = ['.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
  85. function adjustWidths(properties) {
  86. if (!properties.fontMatrix) {
  87. return;
  88. }
  89. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  90. return;
  91. }
  92. var scale = 0.001 / properties.fontMatrix[0];
  93. var glyphsWidths = properties.widths;
  94. for (var glyph in glyphsWidths) {
  95. glyphsWidths[glyph] *= scale;
  96. }
  97. properties.defaultWidth *= scale;
  98. }
  99. function adjustToUnicode(properties, builtInEncoding) {
  100. if (properties.hasIncludedToUnicodeMap) {
  101. return;
  102. }
  103. if (properties.hasEncoding) {
  104. return;
  105. }
  106. if (builtInEncoding === properties.defaultEncoding) {
  107. return;
  108. }
  109. if (properties.toUnicode instanceof IdentityToUnicodeMap) {
  110. return;
  111. }
  112. var toUnicode = [],
  113. glyphsUnicodeMap = getGlyphsUnicode();
  114. for (var charCode in builtInEncoding) {
  115. var glyphName = builtInEncoding[charCode];
  116. var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  117. if (unicode !== -1) {
  118. toUnicode[charCode] = String.fromCharCode(unicode);
  119. }
  120. }
  121. properties.toUnicode.amend(toUnicode);
  122. }
  123. function getFontType(type, subtype) {
  124. switch (type) {
  125. case 'Type1':
  126. return subtype === 'Type1C' ? FontType.TYPE1C : FontType.TYPE1;
  127. case 'CIDFontType0':
  128. return subtype === 'CIDFontType0C' ? FontType.CIDFONTTYPE0C : FontType.CIDFONTTYPE0;
  129. case 'OpenType':
  130. return FontType.OPENTYPE;
  131. case 'TrueType':
  132. return FontType.TRUETYPE;
  133. case 'CIDFontType2':
  134. return FontType.CIDFONTTYPE2;
  135. case 'MMType1':
  136. return FontType.MMTYPE1;
  137. case 'Type0':
  138. return FontType.TYPE0;
  139. default:
  140. return FontType.UNKNOWN;
  141. }
  142. }
  143. function recoverGlyphName(name, glyphsUnicodeMap) {
  144. if (glyphsUnicodeMap[name] !== undefined) {
  145. return name;
  146. }
  147. var unicode = getUnicodeForGlyph(name, glyphsUnicodeMap);
  148. if (unicode !== -1) {
  149. for (var key in glyphsUnicodeMap) {
  150. if (glyphsUnicodeMap[key] === unicode) {
  151. return key;
  152. }
  153. }
  154. }
  155. info('Unable to recover a standard glyph name for: ' + name);
  156. return name;
  157. }
  158. var Glyph = function GlyphClosure() {
  159. function Glyph(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont) {
  160. this.fontChar = fontChar;
  161. this.unicode = unicode;
  162. this.accent = accent;
  163. this.width = width;
  164. this.vmetric = vmetric;
  165. this.operatorListId = operatorListId;
  166. this.isSpace = isSpace;
  167. this.isInFont = isInFont;
  168. }
  169. Glyph.prototype.matchesForCache = function (fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont) {
  170. return this.fontChar === fontChar && this.unicode === unicode && this.accent === accent && this.width === width && this.vmetric === vmetric && this.operatorListId === operatorListId && this.isSpace === isSpace && this.isInFont === isInFont;
  171. };
  172. return Glyph;
  173. }();
  174. var ToUnicodeMap = function ToUnicodeMapClosure() {
  175. function ToUnicodeMap(cmap) {
  176. this._map = cmap;
  177. }
  178. ToUnicodeMap.prototype = {
  179. get length() {
  180. return this._map.length;
  181. },
  182. forEach: function forEach(callback) {
  183. for (var charCode in this._map) {
  184. callback(charCode, this._map[charCode].charCodeAt(0));
  185. }
  186. },
  187. has: function has(i) {
  188. return this._map[i] !== undefined;
  189. },
  190. get: function get(i) {
  191. return this._map[i];
  192. },
  193. charCodeOf: function charCodeOf(v) {
  194. return this._map.indexOf(v);
  195. },
  196. amend: function amend(map) {
  197. for (var charCode in map) {
  198. this._map[charCode] = map[charCode];
  199. }
  200. }
  201. };
  202. return ToUnicodeMap;
  203. }();
  204. var IdentityToUnicodeMap = function IdentityToUnicodeMapClosure() {
  205. function IdentityToUnicodeMap(firstChar, lastChar) {
  206. this.firstChar = firstChar;
  207. this.lastChar = lastChar;
  208. }
  209. IdentityToUnicodeMap.prototype = {
  210. get length() {
  211. return this.lastChar + 1 - this.firstChar;
  212. },
  213. forEach: function forEach(callback) {
  214. for (var i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
  215. callback(i, i);
  216. }
  217. },
  218. has: function has(i) {
  219. return this.firstChar <= i && i <= this.lastChar;
  220. },
  221. get: function get(i) {
  222. if (this.firstChar <= i && i <= this.lastChar) {
  223. return String.fromCharCode(i);
  224. }
  225. return undefined;
  226. },
  227. charCodeOf: function charCodeOf(v) {
  228. return isInt(v) && v >= this.firstChar && v <= this.lastChar ? v : -1;
  229. },
  230. amend: function amend(map) {
  231. error('Should not call amend()');
  232. }
  233. };
  234. return IdentityToUnicodeMap;
  235. }();
  236. var OpenTypeFileBuilder = function OpenTypeFileBuilderClosure() {
  237. function writeInt16(dest, offset, num) {
  238. dest[offset] = num >> 8 & 0xFF;
  239. dest[offset + 1] = num & 0xFF;
  240. }
  241. function writeInt32(dest, offset, num) {
  242. dest[offset] = num >> 24 & 0xFF;
  243. dest[offset + 1] = num >> 16 & 0xFF;
  244. dest[offset + 2] = num >> 8 & 0xFF;
  245. dest[offset + 3] = num & 0xFF;
  246. }
  247. function writeData(dest, offset, data) {
  248. var i, ii;
  249. if (data instanceof Uint8Array) {
  250. dest.set(data, offset);
  251. } else if (typeof data === 'string') {
  252. for (i = 0, ii = data.length; i < ii; i++) {
  253. dest[offset++] = data.charCodeAt(i) & 0xFF;
  254. }
  255. } else {
  256. for (i = 0, ii = data.length; i < ii; i++) {
  257. dest[offset++] = data[i] & 0xFF;
  258. }
  259. }
  260. }
  261. function OpenTypeFileBuilder(sfnt) {
  262. this.sfnt = sfnt;
  263. this.tables = Object.create(null);
  264. }
  265. OpenTypeFileBuilder.getSearchParams = function OpenTypeFileBuilder_getSearchParams(entriesCount, entrySize) {
  266. var maxPower2 = 1,
  267. log2 = 0;
  268. while ((maxPower2 ^ entriesCount) > maxPower2) {
  269. maxPower2 <<= 1;
  270. log2++;
  271. }
  272. var searchRange = maxPower2 * entrySize;
  273. return {
  274. range: searchRange,
  275. entry: log2,
  276. rangeShift: entrySize * entriesCount - searchRange
  277. };
  278. };
  279. var OTF_HEADER_SIZE = 12;
  280. var OTF_TABLE_ENTRY_SIZE = 16;
  281. OpenTypeFileBuilder.prototype = {
  282. toArray: function OpenTypeFileBuilder_toArray() {
  283. var sfnt = this.sfnt;
  284. var tables = this.tables;
  285. var tablesNames = Object.keys(tables);
  286. tablesNames.sort();
  287. var numTables = tablesNames.length;
  288. var i, j, jj, table, tableName;
  289. var offset = OTF_HEADER_SIZE + numTables * OTF_TABLE_ENTRY_SIZE;
  290. var tableOffsets = [offset];
  291. for (i = 0; i < numTables; i++) {
  292. table = tables[tablesNames[i]];
  293. var paddedLength = (table.length + 3 & ~3) >>> 0;
  294. offset += paddedLength;
  295. tableOffsets.push(offset);
  296. }
  297. var file = new Uint8Array(offset);
  298. for (i = 0; i < numTables; i++) {
  299. table = tables[tablesNames[i]];
  300. writeData(file, tableOffsets[i], table);
  301. }
  302. if (sfnt === 'true') {
  303. sfnt = string32(0x00010000);
  304. }
  305. file[0] = sfnt.charCodeAt(0) & 0xFF;
  306. file[1] = sfnt.charCodeAt(1) & 0xFF;
  307. file[2] = sfnt.charCodeAt(2) & 0xFF;
  308. file[3] = sfnt.charCodeAt(3) & 0xFF;
  309. writeInt16(file, 4, numTables);
  310. var searchParams = OpenTypeFileBuilder.getSearchParams(numTables, 16);
  311. writeInt16(file, 6, searchParams.range);
  312. writeInt16(file, 8, searchParams.entry);
  313. writeInt16(file, 10, searchParams.rangeShift);
  314. offset = OTF_HEADER_SIZE;
  315. for (i = 0; i < numTables; i++) {
  316. tableName = tablesNames[i];
  317. file[offset] = tableName.charCodeAt(0) & 0xFF;
  318. file[offset + 1] = tableName.charCodeAt(1) & 0xFF;
  319. file[offset + 2] = tableName.charCodeAt(2) & 0xFF;
  320. file[offset + 3] = tableName.charCodeAt(3) & 0xFF;
  321. var checksum = 0;
  322. for (j = tableOffsets[i], jj = tableOffsets[i + 1]; j < jj; j += 4) {
  323. var quad = readUint32(file, j);
  324. checksum = checksum + quad >>> 0;
  325. }
  326. writeInt32(file, offset + 4, checksum);
  327. writeInt32(file, offset + 8, tableOffsets[i]);
  328. writeInt32(file, offset + 12, tables[tableName].length);
  329. offset += OTF_TABLE_ENTRY_SIZE;
  330. }
  331. return file;
  332. },
  333. addTable: function OpenTypeFileBuilder_addTable(tag, data) {
  334. if (tag in this.tables) {
  335. throw new Error('Table ' + tag + ' already exists');
  336. }
  337. this.tables[tag] = data;
  338. }
  339. };
  340. return OpenTypeFileBuilder;
  341. }();
  342. var ProblematicCharRanges = new Int32Array([0x0000, 0x0020, 0x007F, 0x00A1, 0x00AD, 0x00AE, 0x0600, 0x0780, 0x08A0, 0x10A0, 0x1780, 0x1800, 0x1C00, 0x1C50, 0x2000, 0x2010, 0x2011, 0x2012, 0x2028, 0x2030, 0x205F, 0x2070, 0x25CC, 0x25CD, 0x3000, 0x3001, 0xAA60, 0xAA80, 0xFFF0, 0x10000]);
  343. var Font = function FontClosure() {
  344. function Font(name, file, properties) {
  345. var _this = this;
  346. var charCode, glyphName, unicode;
  347. this.name = name;
  348. this.loadedName = properties.loadedName;
  349. this.isType3Font = properties.isType3Font;
  350. this.sizes = [];
  351. this.missingFile = false;
  352. this.glyphCache = Object.create(null);
  353. this.isSerifFont = !!(properties.flags & FontFlags.Serif);
  354. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  355. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  356. var type = properties.type;
  357. var subtype = properties.subtype;
  358. this.type = type;
  359. this.fallbackName = this.isMonospace ? 'monospace' : this.isSerifFont ? 'serif' : 'sans-serif';
  360. this.differences = properties.differences;
  361. this.widths = properties.widths;
  362. this.defaultWidth = properties.defaultWidth;
  363. this.composite = properties.composite;
  364. this.wideChars = properties.wideChars;
  365. this.cMap = properties.cMap;
  366. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  367. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  368. this.fontMatrix = properties.fontMatrix;
  369. this.bbox = properties.bbox;
  370. this.toUnicode = properties.toUnicode;
  371. this.toFontChar = [];
  372. if (properties.type === 'Type3') {
  373. for (charCode = 0; charCode < 256; charCode++) {
  374. this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
  375. }
  376. this.fontType = FontType.TYPE3;
  377. return;
  378. }
  379. this.cidEncoding = properties.cidEncoding;
  380. this.vertical = properties.vertical;
  381. if (this.vertical) {
  382. this.vmetrics = properties.vmetrics;
  383. this.defaultVMetrics = properties.defaultVMetrics;
  384. }
  385. var glyphsUnicodeMap;
  386. if (!file || file.isEmpty) {
  387. if (file) {
  388. warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
  389. }
  390. this.missingFile = true;
  391. var fontName = name.replace(/[,_]/g, '-');
  392. var stdFontMap = getStdFontMap(),
  393. nonStdFontMap = getNonStdFontMap();
  394. var isStandardFont = !!stdFontMap[fontName] || !!(nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]);
  395. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  396. this.bold = fontName.search(/bold/gi) !== -1;
  397. this.italic = fontName.search(/oblique/gi) !== -1 || fontName.search(/italic/gi) !== -1;
  398. this.black = name.search(/Black/g) !== -1;
  399. this.remeasure = Object.keys(this.widths).length > 0;
  400. if (isStandardFont && type === 'CIDFontType2' && properties.cidEncoding.indexOf('Identity-') === 0) {
  401. var GlyphMapForStandardFonts = getGlyphMapForStandardFonts();
  402. var map = [];
  403. for (charCode in GlyphMapForStandardFonts) {
  404. map[+charCode] = GlyphMapForStandardFonts[charCode];
  405. }
  406. if (/Arial-?Black/i.test(name)) {
  407. var SupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBlack();
  408. for (charCode in SupplementalGlyphMapForArialBlack) {
  409. map[+charCode] = SupplementalGlyphMapForArialBlack[charCode];
  410. }
  411. }
  412. var isIdentityUnicode = this.toUnicode instanceof IdentityToUnicodeMap;
  413. if (!isIdentityUnicode) {
  414. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  415. map[+charCode] = unicodeCharCode;
  416. });
  417. }
  418. this.toFontChar = map;
  419. this.toUnicode = new ToUnicodeMap(map);
  420. } else if (/Symbol/i.test(fontName)) {
  421. this.toFontChar = buildToFontChar(SymbolSetEncoding, getGlyphsUnicode(), properties.differences);
  422. } else if (/Dingbats/i.test(fontName)) {
  423. if (/Wingdings/i.test(name)) {
  424. warn('Non-embedded Wingdings font, falling back to ZapfDingbats.');
  425. }
  426. this.toFontChar = buildToFontChar(ZapfDingbatsEncoding, getDingbatsGlyphsUnicode(), properties.differences);
  427. } else if (isStandardFont) {
  428. this.toFontChar = buildToFontChar(properties.defaultEncoding, getGlyphsUnicode(), properties.differences);
  429. } else {
  430. glyphsUnicodeMap = getGlyphsUnicode();
  431. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  432. if (!_this.composite) {
  433. glyphName = properties.differences[charCode] || properties.defaultEncoding[charCode];
  434. unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  435. if (unicode !== -1) {
  436. unicodeCharCode = unicode;
  437. }
  438. }
  439. _this.toFontChar[charCode] = unicodeCharCode;
  440. });
  441. }
  442. this.loadedName = fontName.split('-')[0];
  443. this.loading = false;
  444. this.fontType = getFontType(type, subtype);
  445. return;
  446. }
  447. if (subtype === 'Type1C') {
  448. if (type !== 'Type1' && type !== 'MMType1') {
  449. if (isTrueTypeFile(file)) {
  450. subtype = 'TrueType';
  451. } else {
  452. type = 'Type1';
  453. }
  454. } else if (isOpenTypeFile(file)) {
  455. type = subtype = 'OpenType';
  456. }
  457. }
  458. if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
  459. type = 'CIDFontType0';
  460. }
  461. if (subtype === 'OpenType') {
  462. type = 'OpenType';
  463. }
  464. if (type === 'CIDFontType0') {
  465. if (isType1File(file)) {
  466. subtype = 'CIDFontType0';
  467. } else if (isOpenTypeFile(file)) {
  468. type = subtype = 'OpenType';
  469. } else {
  470. subtype = 'CIDFontType0C';
  471. }
  472. }
  473. var data;
  474. switch (type) {
  475. case 'MMType1':
  476. info('MMType1 font (' + name + '), falling back to Type1.');
  477. case 'Type1':
  478. case 'CIDFontType0':
  479. this.mimetype = 'font/opentype';
  480. var cff = subtype === 'Type1C' || subtype === 'CIDFontType0C' ? new CFFFont(file, properties) : new Type1Font(name, file, properties);
  481. adjustWidths(properties);
  482. data = this.convert(name, cff, properties);
  483. break;
  484. case 'OpenType':
  485. case 'TrueType':
  486. case 'CIDFontType2':
  487. this.mimetype = 'font/opentype';
  488. data = this.checkAndRepair(name, file, properties);
  489. if (this.isOpenType) {
  490. adjustWidths(properties);
  491. type = 'OpenType';
  492. }
  493. break;
  494. default:
  495. error('Font ' + type + ' is not supported');
  496. break;
  497. }
  498. this.data = data;
  499. this.fontType = getFontType(type, subtype);
  500. this.fontMatrix = properties.fontMatrix;
  501. this.widths = properties.widths;
  502. this.defaultWidth = properties.defaultWidth;
  503. this.toUnicode = properties.toUnicode;
  504. this.encoding = properties.baseEncoding;
  505. this.seacMap = properties.seacMap;
  506. this.loading = true;
  507. }
  508. Font.getFontID = function () {
  509. var ID = 1;
  510. return function Font_getFontID() {
  511. return String(ID++);
  512. };
  513. }();
  514. function int16(b0, b1) {
  515. return (b0 << 8) + b1;
  516. }
  517. function signedInt16(b0, b1) {
  518. var value = (b0 << 8) + b1;
  519. return value & 1 << 15 ? value - 0x10000 : value;
  520. }
  521. function int32(b0, b1, b2, b3) {
  522. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  523. }
  524. function string16(value) {
  525. return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
  526. }
  527. function safeString16(value) {
  528. value = value > 0x7FFF ? 0x7FFF : value < -0x8000 ? -0x8000 : value;
  529. return String.fromCharCode(value >> 8 & 0xff, value & 0xff);
  530. }
  531. function isTrueTypeFile(file) {
  532. var header = file.peekBytes(4);
  533. return readUint32(header, 0) === 0x00010000;
  534. }
  535. function isOpenTypeFile(file) {
  536. var header = file.peekBytes(4);
  537. return bytesToString(header) === 'OTTO';
  538. }
  539. function isType1File(file) {
  540. var header = file.peekBytes(2);
  541. if (header[0] === 0x25 && header[1] === 0x21) {
  542. return true;
  543. }
  544. if (header[0] === 0x80 && header[1] === 0x01) {
  545. return true;
  546. }
  547. return false;
  548. }
  549. function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
  550. var toFontChar = [],
  551. unicode;
  552. for (var i = 0, ii = encoding.length; i < ii; i++) {
  553. unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
  554. if (unicode !== -1) {
  555. toFontChar[i] = unicode;
  556. }
  557. }
  558. for (var charCode in differences) {
  559. unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
  560. if (unicode !== -1) {
  561. toFontChar[+charCode] = unicode;
  562. }
  563. }
  564. return toFontChar;
  565. }
  566. function isProblematicUnicodeLocation(code) {
  567. var i = 0,
  568. j = ProblematicCharRanges.length - 1;
  569. while (i < j) {
  570. var c = i + j + 1 >> 1;
  571. if (code < ProblematicCharRanges[c]) {
  572. j = c - 1;
  573. } else {
  574. i = c;
  575. }
  576. }
  577. return !(i & 1);
  578. }
  579. function adjustMapping(charCodeToGlyphId, properties) {
  580. var toUnicode = properties.toUnicode;
  581. var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
  582. var isIdentityUnicode = properties.toUnicode instanceof IdentityToUnicodeMap;
  583. var newMap = Object.create(null);
  584. var toFontChar = [];
  585. var usedFontCharCodes = [];
  586. var nextAvailableFontCharCode = PRIVATE_USE_OFFSET_START;
  587. for (var originalCharCode in charCodeToGlyphId) {
  588. originalCharCode |= 0;
  589. var glyphId = charCodeToGlyphId[originalCharCode];
  590. var fontCharCode = originalCharCode;
  591. var hasUnicodeValue = false;
  592. if (!isIdentityUnicode && toUnicode.has(originalCharCode)) {
  593. hasUnicodeValue = true;
  594. var unicode = toUnicode.get(fontCharCode);
  595. if (unicode.length === 1) {
  596. fontCharCode = unicode.charCodeAt(0);
  597. }
  598. }
  599. if ((usedFontCharCodes[fontCharCode] !== undefined || isProblematicUnicodeLocation(fontCharCode) || isSymbolic && !hasUnicodeValue) && nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END) {
  600. do {
  601. fontCharCode = nextAvailableFontCharCode++;
  602. if (SKIP_PRIVATE_USE_RANGE_F000_TO_F01F && fontCharCode === 0xF000) {
  603. fontCharCode = 0xF020;
  604. nextAvailableFontCharCode = fontCharCode + 1;
  605. }
  606. } while (usedFontCharCodes[fontCharCode] !== undefined && nextAvailableFontCharCode <= PRIVATE_USE_OFFSET_END);
  607. }
  608. newMap[fontCharCode] = glyphId;
  609. toFontChar[originalCharCode] = fontCharCode;
  610. usedFontCharCodes[fontCharCode] = true;
  611. }
  612. return {
  613. toFontChar: toFontChar,
  614. charCodeToGlyphId: newMap,
  615. nextAvailableFontCharCode: nextAvailableFontCharCode
  616. };
  617. }
  618. function getRanges(glyphs, numGlyphs) {
  619. var codes = [];
  620. for (var charCode in glyphs) {
  621. if (glyphs[charCode] >= numGlyphs) {
  622. continue;
  623. }
  624. codes.push({
  625. fontCharCode: charCode | 0,
  626. glyphId: glyphs[charCode]
  627. });
  628. }
  629. codes.sort(function fontGetRangesSort(a, b) {
  630. return a.fontCharCode - b.fontCharCode;
  631. });
  632. var ranges = [];
  633. var length = codes.length;
  634. for (var n = 0; n < length;) {
  635. var start = codes[n].fontCharCode;
  636. var codeIndices = [codes[n].glyphId];
  637. ++n;
  638. var end = start;
  639. while (n < length && end + 1 === codes[n].fontCharCode) {
  640. codeIndices.push(codes[n].glyphId);
  641. ++end;
  642. ++n;
  643. if (end === 0xFFFF) {
  644. break;
  645. }
  646. }
  647. ranges.push([start, end, codeIndices]);
  648. }
  649. return ranges;
  650. }
  651. function createCmapTable(glyphs, numGlyphs) {
  652. var ranges = getRanges(glyphs, numGlyphs);
  653. var numTables = ranges[ranges.length - 1][1] > 0xFFFF ? 2 : 1;
  654. var cmap = '\x00\x00' + string16(numTables) + '\x00\x03' + '\x00\x01' + string32(4 + numTables * 8);
  655. var i, ii, j, jj;
  656. for (i = ranges.length - 1; i >= 0; --i) {
  657. if (ranges[i][0] <= 0xFFFF) {
  658. break;
  659. }
  660. }
  661. var bmpLength = i + 1;
  662. if (ranges[i][0] < 0xFFFF && ranges[i][1] === 0xFFFF) {
  663. ranges[i][1] = 0xFFFE;
  664. }
  665. var trailingRangesCount = ranges[i][1] < 0xFFFF ? 1 : 0;
  666. var segCount = bmpLength + trailingRangesCount;
  667. var searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  668. var startCount = '';
  669. var endCount = '';
  670. var idDeltas = '';
  671. var idRangeOffsets = '';
  672. var glyphsIds = '';
  673. var bias = 0;
  674. var range, start, end, codes;
  675. for (i = 0, ii = bmpLength; i < ii; i++) {
  676. range = ranges[i];
  677. start = range[0];
  678. end = range[1];
  679. startCount += string16(start);
  680. endCount += string16(end);
  681. codes = range[2];
  682. var contiguous = true;
  683. for (j = 1, jj = codes.length; j < jj; ++j) {
  684. if (codes[j] !== codes[j - 1] + 1) {
  685. contiguous = false;
  686. break;
  687. }
  688. }
  689. if (!contiguous) {
  690. var offset = (segCount - i) * 2 + bias * 2;
  691. bias += end - start + 1;
  692. idDeltas += string16(0);
  693. idRangeOffsets += string16(offset);
  694. for (j = 0, jj = codes.length; j < jj; ++j) {
  695. glyphsIds += string16(codes[j]);
  696. }
  697. } else {
  698. var startCode = codes[0];
  699. idDeltas += string16(startCode - start & 0xFFFF);
  700. idRangeOffsets += string16(0);
  701. }
  702. }
  703. if (trailingRangesCount > 0) {
  704. endCount += '\xFF\xFF';
  705. startCount += '\xFF\xFF';
  706. idDeltas += '\x00\x01';
  707. idRangeOffsets += '\x00\x00';
  708. }
  709. var format314 = '\x00\x00' + string16(2 * segCount) + string16(searchParams.range) + string16(searchParams.entry) + string16(searchParams.rangeShift) + endCount + '\x00\x00' + startCount + idDeltas + idRangeOffsets + glyphsIds;
  710. var format31012 = '';
  711. var header31012 = '';
  712. if (numTables > 1) {
  713. cmap += '\x00\x03' + '\x00\x0A' + string32(4 + numTables * 8 + 4 + format314.length);
  714. format31012 = '';
  715. for (i = 0, ii = ranges.length; i < ii; i++) {
  716. range = ranges[i];
  717. start = range[0];
  718. codes = range[2];
  719. var code = codes[0];
  720. for (j = 1, jj = codes.length; j < jj; ++j) {
  721. if (codes[j] !== codes[j - 1] + 1) {
  722. end = range[0] + j - 1;
  723. format31012 += string32(start) + string32(end) + string32(code);
  724. start = end + 1;
  725. code = codes[j];
  726. }
  727. }
  728. format31012 += string32(start) + string32(range[1]) + string32(code);
  729. }
  730. header31012 = '\x00\x0C' + '\x00\x00' + string32(format31012.length + 16) + '\x00\x00\x00\x00' + string32(format31012.length / 12);
  731. }
  732. return cmap + '\x00\x04' + string16(format314.length + 4) + format314 + header31012 + format31012;
  733. }
  734. function validateOS2Table(os2) {
  735. var stream = new Stream(os2.data);
  736. var version = stream.getUint16();
  737. stream.getBytes(60);
  738. var selection = stream.getUint16();
  739. if (version < 4 && selection & 0x0300) {
  740. return false;
  741. }
  742. var firstChar = stream.getUint16();
  743. var lastChar = stream.getUint16();
  744. if (firstChar > lastChar) {
  745. return false;
  746. }
  747. stream.getBytes(6);
  748. var usWinAscent = stream.getUint16();
  749. if (usWinAscent === 0) {
  750. return false;
  751. }
  752. os2.data[8] = os2.data[9] = 0;
  753. return true;
  754. }
  755. function createOS2Table(properties, charstrings, override) {
  756. override = override || {
  757. unitsPerEm: 0,
  758. yMax: 0,
  759. yMin: 0,
  760. ascent: 0,
  761. descent: 0
  762. };
  763. var ulUnicodeRange1 = 0;
  764. var ulUnicodeRange2 = 0;
  765. var ulUnicodeRange3 = 0;
  766. var ulUnicodeRange4 = 0;
  767. var firstCharIndex = null;
  768. var lastCharIndex = 0;
  769. if (charstrings) {
  770. for (var code in charstrings) {
  771. code |= 0;
  772. if (firstCharIndex > code || !firstCharIndex) {
  773. firstCharIndex = code;
  774. }
  775. if (lastCharIndex < code) {
  776. lastCharIndex = code;
  777. }
  778. var position = getUnicodeRangeFor(code);
  779. if (position < 32) {
  780. ulUnicodeRange1 |= 1 << position;
  781. } else if (position < 64) {
  782. ulUnicodeRange2 |= 1 << position - 32;
  783. } else if (position < 96) {
  784. ulUnicodeRange3 |= 1 << position - 64;
  785. } else if (position < 123) {
  786. ulUnicodeRange4 |= 1 << position - 96;
  787. } else {
  788. error('Unicode ranges Bits > 123 are reserved for internal usage');
  789. }
  790. }
  791. } else {
  792. firstCharIndex = 0;
  793. lastCharIndex = 255;
  794. }
  795. var bbox = properties.bbox || [0, 0, 0, 0];
  796. var unitsPerEm = override.unitsPerEm || 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  797. var scale = properties.ascentScaled ? 1.0 : unitsPerEm / PDF_GLYPH_SPACE_UNITS;
  798. var typoAscent = override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
  799. var typoDescent = override.descent || Math.round(scale * (properties.descent || bbox[1]));
  800. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  801. typoDescent = -typoDescent;
  802. }
  803. var winAscent = override.yMax || typoAscent;
  804. var winDescent = -override.yMin || -typoDescent;
  805. return '\x00\x03' + '\x02\x24' + '\x01\xF4' + '\x00\x05' + '\x00\x00' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x00\x8C' + '\x02\x8A' + '\x02\xBB' + '\x00\x00' + '\x01\xDF' + '\x00\x31' + '\x01\x02' + '\x00\x00' + '\x00\x00\x06' + String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) + '\x00\x00\x00\x00\x00\x00' + string32(ulUnicodeRange1) + string32(ulUnicodeRange2) + string32(ulUnicodeRange3) + string32(ulUnicodeRange4) + '\x2A\x32\x31\x2A' + string16(properties.italicAngle ? 1 : 0) + string16(firstCharIndex || properties.firstChar) + string16(lastCharIndex || properties.lastChar) + string16(typoAscent) + string16(typoDescent) + '\x00\x64' + string16(winAscent) + string16(winDescent) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + string16(properties.xHeight) + string16(properties.capHeight) + string16(0) + string16(firstCharIndex || properties.firstChar) + '\x00\x03';
  806. }
  807. function createPostTable(properties) {
  808. var angle = Math.floor(properties.italicAngle * Math.pow(2, 16));
  809. return '\x00\x03\x00\x00' + string32(angle) + '\x00\x00' + '\x00\x00' + string32(properties.fixedPitch) + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00' + '\x00\x00\x00\x00';
  810. }
  811. function createNameTable(name, proto) {
  812. if (!proto) {
  813. proto = [[], []];
  814. }
  815. var strings = [proto[0][0] || 'Original licence', proto[0][1] || name, proto[0][2] || 'Unknown', proto[0][3] || 'uniqueID', proto[0][4] || name, proto[0][5] || 'Version 0.11', proto[0][6] || '', proto[0][7] || 'Unknown', proto[0][8] || 'Unknown', proto[0][9] || 'Unknown'];
  816. var stringsUnicode = [];
  817. var i, ii, j, jj, str;
  818. for (i = 0, ii = strings.length; i < ii; i++) {
  819. str = proto[1][i] || strings[i];
  820. var strBufUnicode = [];
  821. for (j = 0, jj = str.length; j < jj; j++) {
  822. strBufUnicode.push(string16(str.charCodeAt(j)));
  823. }
  824. stringsUnicode.push(strBufUnicode.join(''));
  825. }
  826. var names = [strings, stringsUnicode];
  827. var platforms = ['\x00\x01', '\x00\x03'];
  828. var encodings = ['\x00\x00', '\x00\x01'];
  829. var languages = ['\x00\x00', '\x04\x09'];
  830. var namesRecordCount = strings.length * platforms.length;
  831. var nameTable = '\x00\x00' + string16(namesRecordCount) + string16(namesRecordCount * 12 + 6);
  832. var strOffset = 0;
  833. for (i = 0, ii = platforms.length; i < ii; i++) {
  834. var strs = names[i];
  835. for (j = 0, jj = strs.length; j < jj; j++) {
  836. str = strs[j];
  837. var nameRecord = platforms[i] + encodings[i] + languages[i] + string16(j) + string16(str.length) + string16(strOffset);
  838. nameTable += nameRecord;
  839. strOffset += str.length;
  840. }
  841. }
  842. nameTable += strings.join('') + stringsUnicode.join('');
  843. return nameTable;
  844. }
  845. Font.prototype = {
  846. name: null,
  847. font: null,
  848. mimetype: null,
  849. encoding: null,
  850. get renderer() {
  851. var renderer = FontRendererFactory.create(this, SEAC_ANALYSIS_ENABLED);
  852. return shadow(this, 'renderer', renderer);
  853. },
  854. exportData: function Font_exportData() {
  855. var data = {};
  856. for (var i in this) {
  857. if (this.hasOwnProperty(i)) {
  858. data[i] = this[i];
  859. }
  860. }
  861. return data;
  862. },
  863. checkAndRepair: function Font_checkAndRepair(name, font, properties) {
  864. function readTableEntry(file) {
  865. var tag = bytesToString(file.getBytes(4));
  866. var checksum = file.getInt32() >>> 0;
  867. var offset = file.getInt32() >>> 0;
  868. var length = file.getInt32() >>> 0;
  869. var previousPosition = file.pos;
  870. file.pos = file.start ? file.start : 0;
  871. file.skip(offset);
  872. var data = file.getBytes(length);
  873. file.pos = previousPosition;
  874. if (tag === 'head') {
  875. data[8] = data[9] = data[10] = data[11] = 0;
  876. data[17] |= 0x20;
  877. }
  878. return {
  879. tag: tag,
  880. checksum: checksum,
  881. length: length,
  882. offset: offset,
  883. data: data
  884. };
  885. }
  886. function readOpenTypeHeader(ttf) {
  887. return {
  888. version: bytesToString(ttf.getBytes(4)),
  889. numTables: ttf.getUint16(),
  890. searchRange: ttf.getUint16(),
  891. entrySelector: ttf.getUint16(),
  892. rangeShift: ttf.getUint16()
  893. };
  894. }
  895. function readCmapTable(cmap, font, isSymbolicFont, hasEncoding) {
  896. if (!cmap) {
  897. warn('No cmap table available.');
  898. return {
  899. platformId: -1,
  900. encodingId: -1,
  901. mappings: [],
  902. hasShortCmap: false
  903. };
  904. }
  905. var segment;
  906. var start = (font.start ? font.start : 0) + cmap.offset;
  907. font.pos = start;
  908. font.getUint16();
  909. var numTables = font.getUint16();
  910. var potentialTable;
  911. var canBreak = false;
  912. for (var i = 0; i < numTables; i++) {
  913. var platformId = font.getUint16();
  914. var encodingId = font.getUint16();
  915. var offset = font.getInt32() >>> 0;
  916. var useTable = false;
  917. if (platformId === 0 && encodingId === 0) {
  918. useTable = true;
  919. } else if (platformId === 1 && encodingId === 0) {
  920. useTable = true;
  921. } else if (platformId === 3 && encodingId === 1 && (hasEncoding || !potentialTable)) {
  922. useTable = true;
  923. if (!isSymbolicFont) {
  924. canBreak = true;
  925. }
  926. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  927. useTable = true;
  928. canBreak = true;
  929. }
  930. if (useTable) {
  931. potentialTable = {
  932. platformId: platformId,
  933. encodingId: encodingId,
  934. offset: offset
  935. };
  936. }
  937. if (canBreak) {
  938. break;
  939. }
  940. }
  941. if (potentialTable) {
  942. font.pos = start + potentialTable.offset;
  943. }
  944. if (!potentialTable || font.peekByte() === -1) {
  945. warn('Could not find a preferred cmap table.');
  946. return {
  947. platformId: -1,
  948. encodingId: -1,
  949. mappings: [],
  950. hasShortCmap: false
  951. };
  952. }
  953. var format = font.getUint16();
  954. font.getUint16();
  955. font.getUint16();
  956. var hasShortCmap = false;
  957. var mappings = [];
  958. var j, glyphId;
  959. if (format === 0) {
  960. for (j = 0; j < 256; j++) {
  961. var index = font.getByte();
  962. if (!index) {
  963. continue;
  964. }
  965. mappings.push({
  966. charCode: j,
  967. glyphId: index
  968. });
  969. }
  970. hasShortCmap = true;
  971. } else if (format === 4) {
  972. var segCount = font.getUint16() >> 1;
  973. font.getBytes(6);
  974. var segIndex,
  975. segments = [];
  976. for (segIndex = 0; segIndex < segCount; segIndex++) {
  977. segments.push({ end: font.getUint16() });
  978. }
  979. font.getUint16();
  980. for (segIndex = 0; segIndex < segCount; segIndex++) {
  981. segments[segIndex].start = font.getUint16();
  982. }
  983. for (segIndex = 0; segIndex < segCount; segIndex++) {
  984. segments[segIndex].delta = font.getUint16();
  985. }
  986. var offsetsCount = 0;
  987. for (segIndex = 0; segIndex < segCount; segIndex++) {
  988. segment = segments[segIndex];
  989. var rangeOffset = font.getUint16();
  990. if (!rangeOffset) {
  991. segment.offsetIndex = -1;
  992. continue;
  993. }
  994. var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  995. segment.offsetIndex = offsetIndex;
  996. offsetsCount = Math.max(offsetsCount, offsetIndex + segment.end - segment.start + 1);
  997. }
  998. var offsets = [];
  999. for (j = 0; j < offsetsCount; j++) {
  1000. offsets.push(font.getUint16());
  1001. }
  1002. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1003. segment = segments[segIndex];
  1004. start = segment.start;
  1005. var end = segment.end;
  1006. var delta = segment.delta;
  1007. offsetIndex = segment.offsetIndex;
  1008. for (j = start; j <= end; j++) {
  1009. if (j === 0xFFFF) {
  1010. continue;
  1011. }
  1012. glyphId = offsetIndex < 0 ? j : offsets[offsetIndex + j - start];
  1013. glyphId = glyphId + delta & 0xFFFF;
  1014. mappings.push({
  1015. charCode: j,
  1016. glyphId: glyphId
  1017. });
  1018. }
  1019. }
  1020. } else if (format === 6) {
  1021. var firstCode = font.getUint16();
  1022. var entryCount = font.getUint16();
  1023. for (j = 0; j < entryCount; j++) {
  1024. glyphId = font.getUint16();
  1025. var charCode = firstCode + j;
  1026. mappings.push({
  1027. charCode: charCode,
  1028. glyphId: glyphId
  1029. });
  1030. }
  1031. } else {
  1032. warn('cmap table has unsupported format: ' + format);
  1033. return {
  1034. platformId: -1,
  1035. encodingId: -1,
  1036. mappings: [],
  1037. hasShortCmap: false
  1038. };
  1039. }
  1040. mappings.sort(function (a, b) {
  1041. return a.charCode - b.charCode;
  1042. });
  1043. for (i = 1; i < mappings.length; i++) {
  1044. if (mappings[i - 1].charCode === mappings[i].charCode) {
  1045. mappings.splice(i, 1);
  1046. i--;
  1047. }
  1048. }
  1049. return {
  1050. platformId: potentialTable.platformId,
  1051. encodingId: potentialTable.encodingId,
  1052. mappings: mappings,
  1053. hasShortCmap: hasShortCmap
  1054. };
  1055. }
  1056. function sanitizeMetrics(font, header, metrics, numGlyphs) {
  1057. if (!header) {
  1058. if (metrics) {
  1059. metrics.data = null;
  1060. }
  1061. return;
  1062. }
  1063. font.pos = (font.start ? font.start : 0) + header.offset;
  1064. font.pos += header.length - 2;
  1065. var numOfMetrics = font.getUint16();
  1066. if (numOfMetrics > numGlyphs) {
  1067. info('The numOfMetrics (' + numOfMetrics + ') should not be ' + 'greater than the numGlyphs (' + numGlyphs + ')');
  1068. numOfMetrics = numGlyphs;
  1069. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  1070. header.data[35] = numOfMetrics & 0x00ff;
  1071. }
  1072. var numOfSidebearings = numGlyphs - numOfMetrics;
  1073. var numMissing = numOfSidebearings - (metrics.length - numOfMetrics * 4 >> 1);
  1074. if (numMissing > 0) {
  1075. var entries = new Uint8Array(metrics.length + numMissing * 2);
  1076. entries.set(metrics.data);
  1077. metrics.data = entries;
  1078. }
  1079. }
  1080. function sanitizeGlyph(source, sourceStart, sourceEnd, dest, destStart, hintsValid) {
  1081. if (sourceEnd - sourceStart <= 12) {
  1082. return 0;
  1083. }
  1084. var glyf = source.subarray(sourceStart, sourceEnd);
  1085. var contoursCount = glyf[0] << 8 | glyf[1];
  1086. if (contoursCount & 0x8000) {
  1087. dest.set(glyf, destStart);
  1088. return glyf.length;
  1089. }
  1090. var i,
  1091. j = 10,
  1092. flagsCount = 0;
  1093. for (i = 0; i < contoursCount; i++) {
  1094. var endPoint = glyf[j] << 8 | glyf[j + 1];
  1095. flagsCount = endPoint + 1;
  1096. j += 2;
  1097. }
  1098. var instructionsStart = j;
  1099. var instructionsLength = glyf[j] << 8 | glyf[j + 1];
  1100. j += 2 + instructionsLength;
  1101. var instructionsEnd = j;
  1102. var coordinatesLength = 0;
  1103. for (i = 0; i < flagsCount; i++) {
  1104. var flag = glyf[j++];
  1105. if (flag & 0xC0) {
  1106. glyf[j - 1] = flag & 0x3F;
  1107. }
  1108. var xyLength = (flag & 2 ? 1 : flag & 16 ? 0 : 2) + (flag & 4 ? 1 : flag & 32 ? 0 : 2);
  1109. coordinatesLength += xyLength;
  1110. if (flag & 8) {
  1111. var repeat = glyf[j++];
  1112. i += repeat;
  1113. coordinatesLength += repeat * xyLength;
  1114. }
  1115. }
  1116. if (coordinatesLength === 0) {
  1117. return 0;
  1118. }
  1119. var glyphDataLength = j + coordinatesLength;
  1120. if (glyphDataLength > glyf.length) {
  1121. return 0;
  1122. }
  1123. if (!hintsValid && instructionsLength > 0) {
  1124. dest.set(glyf.subarray(0, instructionsStart), destStart);
  1125. dest.set([0, 0], destStart + instructionsStart);
  1126. dest.set(glyf.subarray(instructionsEnd, glyphDataLength), destStart + instructionsStart + 2);
  1127. glyphDataLength -= instructionsLength;
  1128. if (glyf.length - glyphDataLength > 3) {
  1129. glyphDataLength = glyphDataLength + 3 & ~3;
  1130. }
  1131. return glyphDataLength;
  1132. }
  1133. if (glyf.length - glyphDataLength > 3) {
  1134. glyphDataLength = glyphDataLength + 3 & ~3;
  1135. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  1136. return glyphDataLength;
  1137. }
  1138. dest.set(glyf, destStart);
  1139. return glyf.length;
  1140. }
  1141. function sanitizeHead(head, numGlyphs, locaLength) {
  1142. var data = head.data;
  1143. var version = int32(data[0], data[1], data[2], data[3]);
  1144. if (version >> 16 !== 1) {
  1145. info('Attempting to fix invalid version in head table: ' + version);
  1146. data[0] = 0;
  1147. data[1] = 1;
  1148. data[2] = 0;
  1149. data[3] = 0;
  1150. }
  1151. var indexToLocFormat = int16(data[50], data[51]);
  1152. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  1153. info('Attempting to fix invalid indexToLocFormat in head table: ' + indexToLocFormat);
  1154. var numGlyphsPlusOne = numGlyphs + 1;
  1155. if (locaLength === numGlyphsPlusOne << 1) {
  1156. data[50] = 0;
  1157. data[51] = 0;
  1158. } else if (locaLength === numGlyphsPlusOne << 2) {
  1159. data[50] = 0;
  1160. data[51] = 1;
  1161. } else {
  1162. warn('Could not fix indexToLocFormat: ' + indexToLocFormat);
  1163. }
  1164. }
  1165. }
  1166. function sanitizeGlyphLocations(loca, glyf, numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry) {
  1167. var itemSize, itemDecode, itemEncode;
  1168. if (isGlyphLocationsLong) {
  1169. itemSize = 4;
  1170. itemDecode = function fontItemDecodeLong(data, offset) {
  1171. return data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
  1172. };
  1173. itemEncode = function fontItemEncodeLong(data, offset, value) {
  1174. data[offset] = value >>> 24 & 0xFF;
  1175. data[offset + 1] = value >> 16 & 0xFF;
  1176. data[offset + 2] = value >> 8 & 0xFF;
  1177. data[offset + 3] = value & 0xFF;
  1178. };
  1179. } else {
  1180. itemSize = 2;
  1181. itemDecode = function fontItemDecode(data, offset) {
  1182. return data[offset] << 9 | data[offset + 1] << 1;
  1183. };
  1184. itemEncode = function fontItemEncode(data, offset, value) {
  1185. data[offset] = value >> 9 & 0xFF;
  1186. data[offset + 1] = value >> 1 & 0xFF;
  1187. };
  1188. }
  1189. var locaData = loca.data;
  1190. var locaDataSize = itemSize * (1 + numGlyphs);
  1191. if (locaData.length !== locaDataSize) {
  1192. locaData = new Uint8Array(locaDataSize);
  1193. locaData.set(loca.data.subarray(0, locaDataSize));
  1194. loca.data = locaData;
  1195. }
  1196. var oldGlyfData = glyf.data;
  1197. var oldGlyfDataLength = oldGlyfData.length;
  1198. var newGlyfData = new Uint8Array(oldGlyfDataLength);
  1199. var startOffset = itemDecode(locaData, 0);
  1200. var writeOffset = 0;
  1201. var missingGlyphData = Object.create(null);
  1202. itemEncode(locaData, 0, writeOffset);
  1203. var i, j;
  1204. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  1205. var endOffset = itemDecode(locaData, j);
  1206. if (endOffset > oldGlyfDataLength && (oldGlyfDataLength + 3 & ~3) === endOffset) {
  1207. endOffset = oldGlyfDataLength;
  1208. }
  1209. if (endOffset > oldGlyfDataLength) {
  1210. itemEncode(locaData, j, writeOffset);
  1211. startOffset = endOffset;
  1212. continue;
  1213. }
  1214. if (startOffset === endOffset) {
  1215. missingGlyphData[i] = true;
  1216. }
  1217. var newLength = sanitizeGlyph(oldGlyfData, startOffset, endOffset, newGlyfData, writeOffset, hintsValid);
  1218. writeOffset += newLength;
  1219. itemEncode(locaData, j, writeOffset);
  1220. startOffset = endOffset;
  1221. }
  1222. if (writeOffset === 0) {
  1223. var simpleGlyph = new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
  1224. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  1225. itemEncode(locaData, j, simpleGlyph.length);
  1226. }
  1227. glyf.data = simpleGlyph;
  1228. return missingGlyphData;
  1229. }
  1230. if (dupFirstEntry) {
  1231. var firstEntryLength = itemDecode(locaData, itemSize);
  1232. if (newGlyfData.length > firstEntryLength + writeOffset) {
  1233. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  1234. } else {
  1235. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  1236. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  1237. }
  1238. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  1239. itemEncode(loca.data, locaData.length - itemSize, writeOffset + firstEntryLength);
  1240. } else {
  1241. glyf.data = newGlyfData.subarray(0, writeOffset);
  1242. }
  1243. return missingGlyphData;
  1244. }
  1245. function readPostScriptTable(post, properties, maxpNumGlyphs) {
  1246. var start = (font.start ? font.start : 0) + post.offset;
  1247. font.pos = start;
  1248. var length = post.length,
  1249. end = start + length;
  1250. var version = font.getInt32();
  1251. font.getBytes(28);
  1252. var glyphNames;
  1253. var valid = true;
  1254. var i;
  1255. switch (version) {
  1256. case 0x00010000:
  1257. glyphNames = MacStandardGlyphOrdering;
  1258. break;
  1259. case 0x00020000:
  1260. var numGlyphs = font.getUint16();
  1261. if (numGlyphs !== maxpNumGlyphs) {
  1262. valid = false;
  1263. break;
  1264. }
  1265. var glyphNameIndexes = [];
  1266. for (i = 0; i < numGlyphs; ++i) {
  1267. var index = font.getUint16();
  1268. if (index >= 32768) {
  1269. valid = false;
  1270. break;
  1271. }
  1272. glyphNameIndexes.push(index);
  1273. }
  1274. if (!valid) {
  1275. break;
  1276. }
  1277. var customNames = [];
  1278. var strBuf = [];
  1279. while (font.pos < end) {
  1280. var stringLength = font.getByte();
  1281. strBuf.length = stringLength;
  1282. for (i = 0; i < stringLength; ++i) {
  1283. strBuf[i] = String.fromCharCode(font.getByte());
  1284. }
  1285. customNames.push(strBuf.join(''));
  1286. }
  1287. glyphNames = [];
  1288. for (i = 0; i < numGlyphs; ++i) {
  1289. var j = glyphNameIndexes[i];
  1290. if (j < 258) {
  1291. glyphNames.push(MacStandardGlyphOrdering[j]);
  1292. continue;
  1293. }
  1294. glyphNames.push(customNames[j - 258]);
  1295. }
  1296. break;
  1297. case 0x00030000:
  1298. break;
  1299. default:
  1300. warn('Unknown/unsupported post table version ' + version);
  1301. valid = false;
  1302. if (properties.defaultEncoding) {
  1303. glyphNames = properties.defaultEncoding;
  1304. }
  1305. break;
  1306. }
  1307. properties.glyphNames = glyphNames;
  1308. return valid;
  1309. }
  1310. function readNameTable(nameTable) {
  1311. var start = (font.start ? font.start : 0) + nameTable.offset;
  1312. font.pos = start;
  1313. var names = [[], []];
  1314. var length = nameTable.length,
  1315. end = start + length;
  1316. var format = font.getUint16();
  1317. var FORMAT_0_HEADER_LENGTH = 6;
  1318. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  1319. return names;
  1320. }
  1321. var numRecords = font.getUint16();
  1322. var stringsStart = font.getUint16();
  1323. var records = [];
  1324. var NAME_RECORD_LENGTH = 12;
  1325. var i, ii;
  1326. for (i = 0; i < numRecords && font.pos + NAME_RECORD_LENGTH <= end; i++) {
  1327. var r = {
  1328. platform: font.getUint16(),
  1329. encoding: font.getUint16(),
  1330. language: font.getUint16(),
  1331. name: font.getUint16(),
  1332. length: font.getUint16(),
  1333. offset: font.getUint16()
  1334. };
  1335. if (r.platform === 1 && r.encoding === 0 && r.language === 0 || r.platform === 3 && r.encoding === 1 && r.language === 0x409) {
  1336. records.push(r);
  1337. }
  1338. }
  1339. for (i = 0, ii = records.length; i < ii; i++) {
  1340. var record = records[i];
  1341. if (record.length <= 0) {
  1342. continue;
  1343. }
  1344. var pos = start + stringsStart + record.offset;
  1345. if (pos + record.length > end) {
  1346. continue;
  1347. }
  1348. font.pos = pos;
  1349. var nameIndex = record.name;
  1350. if (record.encoding) {
  1351. var str = '';
  1352. for (var j = 0, jj = record.length; j < jj; j += 2) {
  1353. str += String.fromCharCode(font.getUint16());
  1354. }
  1355. names[1][nameIndex] = str;
  1356. } else {
  1357. names[0][nameIndex] = bytesToString(font.getBytes(record.length));
  1358. }
  1359. }
  1360. return names;
  1361. }
  1362. var TTOpsStackDeltas = [0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1, 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1, 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2, 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1, -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  1363. function sanitizeTTProgram(table, ttContext) {
  1364. var data = table.data;
  1365. var i = 0,
  1366. j,
  1367. n,
  1368. b,
  1369. funcId,
  1370. pc,
  1371. lastEndf = 0,
  1372. lastDeff = 0;
  1373. var stack = [];
  1374. var callstack = [];
  1375. var functionsCalled = [];
  1376. var tooComplexToFollowFunctions = ttContext.tooComplexToFollowFunctions;
  1377. var inFDEF = false,
  1378. ifLevel = 0,
  1379. inELSE = 0;
  1380. for (var ii = data.length; i < ii;) {
  1381. var op = data[i++];
  1382. if (op === 0x40) {
  1383. n = data[i++];
  1384. if (inFDEF || inELSE) {
  1385. i += n;
  1386. } else {
  1387. for (j = 0; j < n; j++) {
  1388. stack.push(data[i++]);
  1389. }
  1390. }
  1391. } else if (op === 0x41) {
  1392. n = data[i++];
  1393. if (inFDEF || inELSE) {
  1394. i += n * 2;
  1395. } else {
  1396. for (j = 0; j < n; j++) {
  1397. b = data[i++];
  1398. stack.push(b << 8 | data[i++]);
  1399. }
  1400. }
  1401. } else if ((op & 0xF8) === 0xB0) {
  1402. n = op - 0xB0 + 1;
  1403. if (inFDEF || inELSE) {
  1404. i += n;
  1405. } else {
  1406. for (j = 0; j < n; j++) {
  1407. stack.push(data[i++]);
  1408. }
  1409. }
  1410. } else if ((op & 0xF8) === 0xB8) {
  1411. n = op - 0xB8 + 1;
  1412. if (inFDEF || inELSE) {
  1413. i += n * 2;
  1414. } else {
  1415. for (j = 0; j < n; j++) {
  1416. b = data[i++];
  1417. stack.push(b << 8 | data[i++]);
  1418. }
  1419. }
  1420. } else if (op === 0x2B && !tooComplexToFollowFunctions) {
  1421. if (!inFDEF && !inELSE) {
  1422. funcId = stack[stack.length - 1];
  1423. ttContext.functionsUsed[funcId] = true;
  1424. if (funcId in ttContext.functionsStackDeltas) {
  1425. stack.length += ttContext.functionsStackDeltas[funcId];
  1426. } else if (funcId in ttContext.functionsDefined && functionsCalled.indexOf(funcId) < 0) {
  1427. callstack.push({
  1428. data: data,
  1429. i: i,
  1430. stackTop: stack.length - 1
  1431. });
  1432. functionsCalled.push(funcId);
  1433. pc = ttContext.functionsDefined[funcId];
  1434. if (!pc) {
  1435. warn('TT: CALL non-existent function');
  1436. ttContext.hintsValid = false;
  1437. return;
  1438. }
  1439. data = pc.data;
  1440. i = pc.i;
  1441. }
  1442. }
  1443. } else if (op === 0x2C && !tooComplexToFollowFunctions) {
  1444. if (inFDEF || inELSE) {
  1445. warn('TT: nested FDEFs not allowed');
  1446. tooComplexToFollowFunctions = true;
  1447. }
  1448. inFDEF = true;
  1449. lastDeff = i;
  1450. funcId = stack.pop();
  1451. ttContext.functionsDefined[funcId] = {
  1452. data: data,
  1453. i: i
  1454. };
  1455. } else if (op === 0x2D) {
  1456. if (inFDEF) {
  1457. inFDEF = false;
  1458. lastEndf = i;
  1459. } else {
  1460. pc = callstack.pop();
  1461. if (!pc) {
  1462. warn('TT: ENDF bad stack');
  1463. ttContext.hintsValid = false;
  1464. return;
  1465. }
  1466. funcId = functionsCalled.pop();
  1467. data = pc.data;
  1468. i = pc.i;
  1469. ttContext.functionsStackDeltas[funcId] = stack.length - pc.stackTop;
  1470. }
  1471. } else if (op === 0x89) {
  1472. if (inFDEF || inELSE) {
  1473. warn('TT: nested IDEFs not allowed');
  1474. tooComplexToFollowFunctions = true;
  1475. }
  1476. inFDEF = true;
  1477. lastDeff = i;
  1478. } else if (op === 0x58) {
  1479. ++ifLevel;
  1480. } else if (op === 0x1B) {
  1481. inELSE = ifLevel;
  1482. } else if (op === 0x59) {
  1483. if (inELSE === ifLevel) {
  1484. inELSE = 0;
  1485. }
  1486. --ifLevel;
  1487. } else if (op === 0x1C) {
  1488. if (!inFDEF && !inELSE) {
  1489. var offset = stack[stack.length - 1];
  1490. if (offset > 0) {
  1491. i += offset - 1;
  1492. }
  1493. }
  1494. }
  1495. if (!inFDEF && !inELSE) {
  1496. var stackDelta = op <= 0x8E ? TTOpsStackDeltas[op] : op >= 0xC0 && op <= 0xDF ? -1 : op >= 0xE0 ? -2 : 0;
  1497. if (op >= 0x71 && op <= 0x75) {
  1498. n = stack.pop();
  1499. if (!isNaN(n)) {
  1500. stackDelta = -n * 2;
  1501. }
  1502. }
  1503. while (stackDelta < 0 && stack.length > 0) {
  1504. stack.pop();
  1505. stackDelta++;
  1506. }
  1507. while (stackDelta > 0) {
  1508. stack.push(NaN);
  1509. stackDelta--;
  1510. }
  1511. }
  1512. }
  1513. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  1514. var content = [data];
  1515. if (i > data.length) {
  1516. content.push(new Uint8Array(i - data.length));
  1517. }
  1518. if (lastDeff > lastEndf) {
  1519. warn('TT: complementing a missing function tail');
  1520. content.push(new Uint8Array([0x22, 0x2D]));
  1521. }
  1522. foldTTTable(table, content);
  1523. }
  1524. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  1525. if (ttContext.tooComplexToFollowFunctions) {
  1526. return;
  1527. }
  1528. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  1529. warn('TT: more functions defined than expected');
  1530. ttContext.hintsValid = false;
  1531. return;
  1532. }
  1533. for (var j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  1534. if (j > maxFunctionDefs) {
  1535. warn('TT: invalid function id: ' + j);
  1536. ttContext.hintsValid = false;
  1537. return;
  1538. }
  1539. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  1540. warn('TT: undefined function: ' + j);
  1541. ttContext.hintsValid = false;
  1542. return;
  1543. }
  1544. }
  1545. }
  1546. function foldTTTable(table, content) {
  1547. if (content.length > 1) {
  1548. var newLength = 0;
  1549. var j, jj;
  1550. for (j = 0, jj = content.length; j < jj; j++) {
  1551. newLength += content[j].length;
  1552. }
  1553. newLength = newLength + 3 & ~3;
  1554. var result = new Uint8Array(newLength);
  1555. var pos = 0;
  1556. for (j = 0, jj = content.length; j < jj; j++) {
  1557. result.set(content[j], pos);
  1558. pos += content[j].length;
  1559. }
  1560. table.data = result;
  1561. table.length = newLength;
  1562. }
  1563. }
  1564. function sanitizeTTPrograms(fpgm, prep, cvt, maxFunctionDefs) {
  1565. var ttContext = {
  1566. functionsDefined: [],
  1567. functionsUsed: [],
  1568. functionsStackDeltas: [],
  1569. tooComplexToFollowFunctions: false,
  1570. hintsValid: true
  1571. };
  1572. if (fpgm) {
  1573. sanitizeTTProgram(fpgm, ttContext);
  1574. }
  1575. if (prep) {
  1576. sanitizeTTProgram(prep, ttContext);
  1577. }
  1578. if (fpgm) {
  1579. checkInvalidFunctions(ttContext, maxFunctionDefs);
  1580. }
  1581. if (cvt && cvt.length & 1) {
  1582. var cvtData = new Uint8Array(cvt.length + 1);
  1583. cvtData.set(cvt.data);
  1584. cvt.data = cvtData;
  1585. }
  1586. return ttContext.hintsValid;
  1587. }
  1588. font = new Stream(new Uint8Array(font.getBytes()));
  1589. var VALID_TABLES = ['OS/2', 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'post', 'loca', 'glyf', 'fpgm', 'prep', 'cvt ', 'CFF '];
  1590. var header = readOpenTypeHeader(font);
  1591. var numTables = header.numTables;
  1592. var cff, cffFile;
  1593. var tables = Object.create(null);
  1594. tables['OS/2'] = null;
  1595. tables['cmap'] = null;
  1596. tables['head'] = null;
  1597. tables['hhea'] = null;
  1598. tables['hmtx'] = null;
  1599. tables['maxp'] = null;
  1600. tables['name'] = null;
  1601. tables['post'] = null;
  1602. var table;
  1603. for (var i = 0; i < numTables; i++) {
  1604. table = readTableEntry(font);
  1605. if (VALID_TABLES.indexOf(table.tag) < 0) {
  1606. continue;
  1607. }
  1608. if (table.length === 0) {
  1609. continue;
  1610. }
  1611. tables[table.tag] = table;
  1612. }
  1613. var isTrueType = !tables['CFF '];
  1614. if (!isTrueType) {
  1615. if (header.version === 'OTTO' && !properties.composite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
  1616. cffFile = new Stream(tables['CFF '].data);
  1617. cff = new CFFFont(cffFile, properties);
  1618. adjustWidths(properties);
  1619. return this.convert(name, cff, properties);
  1620. }
  1621. delete tables['glyf'];
  1622. delete tables['loca'];
  1623. delete tables['fpgm'];
  1624. delete tables['prep'];
  1625. delete tables['cvt '];
  1626. this.isOpenType = true;
  1627. } else {
  1628. if (!tables['loca']) {
  1629. error('Required "loca" table is not found');
  1630. }
  1631. if (!tables['glyf']) {
  1632. warn('Required "glyf" table is not found -- trying to recover.');
  1633. tables['glyf'] = {
  1634. tag: 'glyf',
  1635. data: new Uint8Array(0)
  1636. };
  1637. }
  1638. this.isOpenType = false;
  1639. }
  1640. if (!tables['maxp']) {
  1641. error('Required "maxp" table is not found');
  1642. }
  1643. font.pos = (font.start || 0) + tables['maxp'].offset;
  1644. var version = font.getInt32();
  1645. var numGlyphs = font.getUint16();
  1646. var maxFunctionDefs = 0;
  1647. if (version >= 0x00010000 && tables['maxp'].length >= 22) {
  1648. font.pos += 8;
  1649. var maxZones = font.getUint16();
  1650. if (maxZones > 2) {
  1651. tables['maxp'].data[14] = 0;
  1652. tables['maxp'].data[15] = 2;
  1653. }
  1654. font.pos += 4;
  1655. maxFunctionDefs = font.getUint16();
  1656. }
  1657. var dupFirstEntry = false;
  1658. if (properties.type === 'CIDFontType2' && properties.toUnicode && properties.toUnicode.get(0) > '\0') {
  1659. dupFirstEntry = true;
  1660. numGlyphs++;
  1661. tables['maxp'].data[4] = numGlyphs >> 8;
  1662. tables['maxp'].data[5] = numGlyphs & 255;
  1663. }
  1664. var hintsValid = sanitizeTTPrograms(tables['fpgm'], tables['prep'], tables['cvt '], maxFunctionDefs);
  1665. if (!hintsValid) {
  1666. delete tables['fpgm'];
  1667. delete tables['prep'];
  1668. delete tables['cvt '];
  1669. }
  1670. sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphs);
  1671. if (!tables['head']) {
  1672. error('Required "head" table is not found');
  1673. }
  1674. sanitizeHead(tables['head'], numGlyphs, isTrueType ? tables['loca'].length : 0);
  1675. var missingGlyphs = Object.create(null);
  1676. if (isTrueType) {
  1677. var isGlyphLocationsLong = int16(tables['head'].data[50], tables['head'].data[51]);
  1678. missingGlyphs = sanitizeGlyphLocations(tables['loca'], tables['glyf'], numGlyphs, isGlyphLocationsLong, hintsValid, dupFirstEntry);
  1679. }
  1680. if (!tables['hhea']) {
  1681. error('Required "hhea" table is not found');
  1682. }
  1683. if (tables['hhea'].data[10] === 0 && tables['hhea'].data[11] === 0) {
  1684. tables['hhea'].data[10] = 0xFF;
  1685. tables['hhea'].data[11] = 0xFF;
  1686. }
  1687. var metricsOverride = {
  1688. unitsPerEm: int16(tables['head'].data[18], tables['head'].data[19]),
  1689. yMax: int16(tables['head'].data[42], tables['head'].data[43]),
  1690. yMin: signedInt16(tables['head'].data[38], tables['head'].data[39]),
  1691. ascent: int16(tables['hhea'].data[4], tables['hhea'].data[5]),
  1692. descent: signedInt16(tables['hhea'].data[6], tables['hhea'].data[7])
  1693. };
  1694. this.ascent = metricsOverride.ascent / metricsOverride.unitsPerEm;
  1695. this.descent = metricsOverride.descent / metricsOverride.unitsPerEm;
  1696. if (tables['post']) {
  1697. var valid = readPostScriptTable(tables['post'], properties, numGlyphs);
  1698. if (!valid) {
  1699. tables['post'] = null;
  1700. }
  1701. }
  1702. var charCodeToGlyphId = [],
  1703. charCode;
  1704. var toUnicode = properties.toUnicode,
  1705. widths = properties.widths;
  1706. var skipToUnicode = toUnicode instanceof IdentityToUnicodeMap || toUnicode.length === 0x10000;
  1707. function hasGlyph(glyphId, charCode, widthCode) {
  1708. if (!missingGlyphs[glyphId]) {
  1709. return true;
  1710. }
  1711. if (!skipToUnicode && charCode >= 0 && toUnicode.has(charCode)) {
  1712. return true;
  1713. }
  1714. if (widths && widthCode >= 0 && isNum(widths[widthCode])) {
  1715. return true;
  1716. }
  1717. return false;
  1718. }
  1719. if (properties.composite) {
  1720. var cidToGidMap = properties.cidToGidMap || [];
  1721. var isCidToGidMapEmpty = cidToGidMap.length === 0;
  1722. properties.cMap.forEach(function (charCode, cid) {
  1723. assert(cid <= 0xffff, 'Max size of CID is 65,535');
  1724. var glyphId = -1;
  1725. if (isCidToGidMapEmpty) {
  1726. glyphId = cid;
  1727. } else if (cidToGidMap[cid] !== undefined) {
  1728. glyphId = cidToGidMap[cid];
  1729. }
  1730. if (glyphId >= 0 && glyphId < numGlyphs && hasGlyph(glyphId, charCode, cid)) {
  1731. charCodeToGlyphId[charCode] = glyphId;
  1732. }
  1733. });
  1734. if (dupFirstEntry && (isCidToGidMapEmpty || !charCodeToGlyphId[0])) {
  1735. charCodeToGlyphId[0] = numGlyphs - 1;
  1736. }
  1737. } else {
  1738. var cmapTable = readCmapTable(tables['cmap'], font, this.isSymbolicFont, properties.hasEncoding);
  1739. var cmapPlatformId = cmapTable.platformId;
  1740. var cmapEncodingId = cmapTable.encodingId;
  1741. var cmapMappings = cmapTable.mappings;
  1742. var cmapMappingsLength = cmapMappings.length;
  1743. if (properties.hasEncoding && (cmapPlatformId === 3 && cmapEncodingId === 1 || cmapPlatformId === 1 && cmapEncodingId === 0) || cmapPlatformId === -1 && cmapEncodingId === -1 && !!getEncoding(properties.baseEncodingName)) {
  1744. var baseEncoding = [];
  1745. if (properties.baseEncodingName === 'MacRomanEncoding' || properties.baseEncodingName === 'WinAnsiEncoding') {
  1746. baseEncoding = getEncoding(properties.baseEncodingName);
  1747. }
  1748. var glyphsUnicodeMap = getGlyphsUnicode();
  1749. for (charCode = 0; charCode < 256; charCode++) {
  1750. var glyphName, standardGlyphName;
  1751. if (this.differences && charCode in this.differences) {
  1752. glyphName = this.differences[charCode];
  1753. } else if (charCode in baseEncoding && baseEncoding[charCode] !== '') {
  1754. glyphName = baseEncoding[charCode];
  1755. } else {
  1756. glyphName = StandardEncoding[charCode];
  1757. }
  1758. if (!glyphName) {
  1759. continue;
  1760. }
  1761. standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
  1762. var unicodeOrCharCode,
  1763. isUnicode = false;
  1764. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  1765. unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName];
  1766. isUnicode = true;
  1767. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  1768. unicodeOrCharCode = MacRomanEncoding.indexOf(standardGlyphName);
  1769. }
  1770. var found = false;
  1771. for (i = 0; i < cmapMappingsLength; ++i) {
  1772. if (cmapMappings[i].charCode !== unicodeOrCharCode) {
  1773. continue;
  1774. }
  1775. var code = isUnicode ? charCode : unicodeOrCharCode;
  1776. if (hasGlyph(cmapMappings[i].glyphId, code, -1)) {
  1777. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  1778. found = true;
  1779. break;
  1780. }
  1781. }
  1782. if (!found && properties.glyphNames) {
  1783. var glyphId = properties.glyphNames.indexOf(glyphName);
  1784. if (glyphId === -1 && standardGlyphName !== glyphName) {
  1785. glyphId = properties.glyphNames.indexOf(standardGlyphName);
  1786. }
  1787. if (glyphId > 0 && hasGlyph(glyphId, -1, -1)) {
  1788. charCodeToGlyphId[charCode] = glyphId;
  1789. found = true;
  1790. }
  1791. }
  1792. if (!found) {
  1793. charCodeToGlyphId[charCode] = 0;
  1794. }
  1795. }
  1796. } else if (cmapPlatformId === 0 && cmapEncodingId === 0) {
  1797. for (i = 0; i < cmapMappingsLength; ++i) {
  1798. charCodeToGlyphId[cmapMappings[i].charCode] = cmapMappings[i].glyphId;
  1799. }
  1800. } else {
  1801. for (i = 0; i < cmapMappingsLength; ++i) {
  1802. charCode = cmapMappings[i].charCode & 0xFF;
  1803. charCodeToGlyphId[charCode] = cmapMappings[i].glyphId;
  1804. }
  1805. }
  1806. }
  1807. if (charCodeToGlyphId.length === 0) {
  1808. charCodeToGlyphId[0] = 0;
  1809. }
  1810. var newMapping = adjustMapping(charCodeToGlyphId, properties);
  1811. this.toFontChar = newMapping.toFontChar;
  1812. tables['cmap'] = {
  1813. tag: 'cmap',
  1814. data: createCmapTable(newMapping.charCodeToGlyphId, numGlyphs)
  1815. };
  1816. if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'])) {
  1817. tables['OS/2'] = {
  1818. tag: 'OS/2',
  1819. data: createOS2Table(properties, newMapping.charCodeToGlyphId, metricsOverride)
  1820. };
  1821. }
  1822. if (!tables['post']) {
  1823. tables['post'] = {
  1824. tag: 'post',
  1825. data: createPostTable(properties)
  1826. };
  1827. }
  1828. if (!isTrueType) {
  1829. try {
  1830. cffFile = new Stream(tables['CFF '].data);
  1831. var parser = new CFFParser(cffFile, properties, SEAC_ANALYSIS_ENABLED);
  1832. cff = parser.parse();
  1833. var compiler = new CFFCompiler(cff);
  1834. tables['CFF '].data = compiler.compile();
  1835. } catch (e) {
  1836. warn('Failed to compile font ' + properties.loadedName);
  1837. }
  1838. }
  1839. if (!tables['name']) {
  1840. tables['name'] = {
  1841. tag: 'name',
  1842. data: createNameTable(this.name)
  1843. };
  1844. } else {
  1845. var namePrototype = readNameTable(tables['name']);
  1846. tables['name'].data = createNameTable(name, namePrototype);
  1847. }
  1848. var builder = new OpenTypeFileBuilder(header.version);
  1849. for (var tableTag in tables) {
  1850. builder.addTable(tableTag, tables[tableTag].data);
  1851. }
  1852. return builder.toArray();
  1853. },
  1854. convert: function Font_convert(fontName, font, properties) {
  1855. properties.fixedPitch = false;
  1856. if (properties.builtInEncoding) {
  1857. adjustToUnicode(properties, properties.builtInEncoding);
  1858. }
  1859. var mapping = font.getGlyphMapping(properties);
  1860. var newMapping = adjustMapping(mapping, properties);
  1861. this.toFontChar = newMapping.toFontChar;
  1862. var numGlyphs = font.numGlyphs;
  1863. function getCharCodes(charCodeToGlyphId, glyphId) {
  1864. var charCodes = null;
  1865. for (var charCode in charCodeToGlyphId) {
  1866. if (glyphId === charCodeToGlyphId[charCode]) {
  1867. if (!charCodes) {
  1868. charCodes = [];
  1869. }
  1870. charCodes.push(charCode | 0);
  1871. }
  1872. }
  1873. return charCodes;
  1874. }
  1875. function createCharCode(charCodeToGlyphId, glyphId) {
  1876. for (var charCode in charCodeToGlyphId) {
  1877. if (glyphId === charCodeToGlyphId[charCode]) {
  1878. return charCode | 0;
  1879. }
  1880. }
  1881. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] = glyphId;
  1882. return newMapping.nextAvailableFontCharCode++;
  1883. }
  1884. var seacs = font.seacs;
  1885. if (SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  1886. var matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  1887. var charset = font.getCharset();
  1888. var seacMap = Object.create(null);
  1889. for (var glyphId in seacs) {
  1890. glyphId |= 0;
  1891. var seac = seacs[glyphId];
  1892. var baseGlyphName = StandardEncoding[seac[2]];
  1893. var accentGlyphName = StandardEncoding[seac[3]];
  1894. var baseGlyphId = charset.indexOf(baseGlyphName);
  1895. var accentGlyphId = charset.indexOf(accentGlyphName);
  1896. if (baseGlyphId < 0 || accentGlyphId < 0) {
  1897. continue;
  1898. }
  1899. var accentOffset = {
  1900. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  1901. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5]
  1902. };
  1903. var charCodes = getCharCodes(mapping, glyphId);
  1904. if (!charCodes) {
  1905. continue;
  1906. }
  1907. for (var i = 0, ii = charCodes.length; i < ii; i++) {
  1908. var charCode = charCodes[i];
  1909. var charCodeToGlyphId = newMapping.charCodeToGlyphId;
  1910. var baseFontCharCode = createCharCode(charCodeToGlyphId, baseGlyphId);
  1911. var accentFontCharCode = createCharCode(charCodeToGlyphId, accentGlyphId);
  1912. seacMap[charCode] = {
  1913. baseFontCharCode: baseFontCharCode,
  1914. accentFontCharCode: accentFontCharCode,
  1915. accentOffset: accentOffset
  1916. };
  1917. }
  1918. }
  1919. properties.seacMap = seacMap;
  1920. }
  1921. var unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  1922. var builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
  1923. builder.addTable('CFF ', font.data);
  1924. builder.addTable('OS/2', createOS2Table(properties, newMapping.charCodeToGlyphId));
  1925. builder.addTable('cmap', createCmapTable(newMapping.charCodeToGlyphId, numGlyphs));
  1926. builder.addTable('head', '\x00\x01\x00\x00' + '\x00\x00\x10\x00' + '\x00\x00\x00\x00' + '\x5F\x0F\x3C\xF5' + '\x00\x00' + safeString16(unitsPerEm) + '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + '\x00\x00\x00\x00\x9e\x0b\x7e\x27' + '\x00\x00' + safeString16(properties.descent) + '\x0F\xFF' + safeString16(properties.ascent) + string16(properties.italicAngle ? 2 : 0) + '\x00\x11' + '\x00\x00' + '\x00\x00' + '\x00\x00');
  1927. builder.addTable('hhea', '\x00\x01\x00\x00' + safeString16(properties.ascent) + safeString16(properties.descent) + '\x00\x00' + '\xFF\xFF' + '\x00\x00' + '\x00\x00' + '\x00\x00' + safeString16(properties.capHeight) + safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + '\x00\x00' + string16(numGlyphs));
  1928. builder.addTable('hmtx', function fontFieldsHmtx() {
  1929. var charstrings = font.charstrings;
  1930. var cffWidths = font.cff ? font.cff.widths : null;
  1931. var hmtx = '\x00\x00\x00\x00';
  1932. for (var i = 1, ii = numGlyphs; i < ii; i++) {
  1933. var width = 0;
  1934. if (charstrings) {
  1935. var charstring = charstrings[i - 1];
  1936. width = 'width' in charstring ? charstring.width : 0;
  1937. } else if (cffWidths) {
  1938. width = Math.ceil(cffWidths[i] || 0);
  1939. }
  1940. hmtx += string16(width) + string16(0);
  1941. }
  1942. return hmtx;
  1943. }());
  1944. builder.addTable('maxp', '\x00\x00\x50\x00' + string16(numGlyphs));
  1945. builder.addTable('name', createNameTable(fontName));
  1946. builder.addTable('post', createPostTable(properties));
  1947. return builder.toArray();
  1948. },
  1949. get spaceWidth() {
  1950. if ('_shadowWidth' in this) {
  1951. return this._shadowWidth;
  1952. }
  1953. var possibleSpaceReplacements = ['space', 'minus', 'one', 'i', 'I'];
  1954. var width;
  1955. for (var i = 0, ii = possibleSpaceReplacements.length; i < ii; i++) {
  1956. var glyphName = possibleSpaceReplacements[i];
  1957. if (glyphName in this.widths) {
  1958. width = this.widths[glyphName];
  1959. break;
  1960. }
  1961. var glyphsUnicodeMap = getGlyphsUnicode();
  1962. var glyphUnicode = glyphsUnicodeMap[glyphName];
  1963. var charcode = 0;
  1964. if (this.composite) {
  1965. if (this.cMap.contains(glyphUnicode)) {
  1966. charcode = this.cMap.lookup(glyphUnicode);
  1967. }
  1968. }
  1969. if (!charcode && this.toUnicode) {
  1970. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  1971. }
  1972. if (charcode <= 0) {
  1973. charcode = glyphUnicode;
  1974. }
  1975. width = this.widths[charcode];
  1976. if (width) {
  1977. break;
  1978. }
  1979. }
  1980. width = width || this.defaultWidth;
  1981. this._shadowWidth = width;
  1982. return width;
  1983. },
  1984. charToGlyph: function Font_charToGlyph(charcode, isSpace) {
  1985. var fontCharCode, width, operatorListId;
  1986. var widthCode = charcode;
  1987. if (this.cMap && this.cMap.contains(charcode)) {
  1988. widthCode = this.cMap.lookup(charcode);
  1989. }
  1990. width = this.widths[widthCode];
  1991. width = isNum(width) ? width : this.defaultWidth;
  1992. var vmetric = this.vmetrics && this.vmetrics[widthCode];
  1993. var unicode = this.toUnicode.get(charcode) || charcode;
  1994. if (typeof unicode === 'number') {
  1995. unicode = String.fromCharCode(unicode);
  1996. }
  1997. var isInFont = charcode in this.toFontChar;
  1998. fontCharCode = this.toFontChar[charcode] || charcode;
  1999. if (this.missingFile) {
  2000. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  2001. }
  2002. if (this.isType3Font) {
  2003. operatorListId = fontCharCode;
  2004. }
  2005. var accent = null;
  2006. if (this.seacMap && this.seacMap[charcode]) {
  2007. isInFont = true;
  2008. var seac = this.seacMap[charcode];
  2009. fontCharCode = seac.baseFontCharCode;
  2010. accent = {
  2011. fontChar: String.fromCharCode(seac.accentFontCharCode),
  2012. offset: seac.accentOffset
  2013. };
  2014. }
  2015. var fontChar = String.fromCharCode(fontCharCode);
  2016. var glyph = this.glyphCache[charcode];
  2017. if (!glyph || !glyph.matchesForCache(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont)) {
  2018. glyph = new Glyph(fontChar, unicode, accent, width, vmetric, operatorListId, isSpace, isInFont);
  2019. this.glyphCache[charcode] = glyph;
  2020. }
  2021. return glyph;
  2022. },
  2023. charsToGlyphs: function Font_charsToGlyphs(chars) {
  2024. var charsCache = this.charsCache;
  2025. var glyphs, glyph, charcode;
  2026. if (charsCache) {
  2027. glyphs = charsCache[chars];
  2028. if (glyphs) {
  2029. return glyphs;
  2030. }
  2031. }
  2032. if (!charsCache) {
  2033. charsCache = this.charsCache = Object.create(null);
  2034. }
  2035. glyphs = [];
  2036. var charsCacheKey = chars;
  2037. var i = 0,
  2038. ii;
  2039. if (this.cMap) {
  2040. var c = Object.create(null);
  2041. while (i < chars.length) {
  2042. this.cMap.readCharCode(chars, i, c);
  2043. charcode = c.charcode;
  2044. var length = c.length;
  2045. i += length;
  2046. var isSpace = length === 1 && chars.charCodeAt(i - 1) === 0x20;
  2047. glyph = this.charToGlyph(charcode, isSpace);
  2048. glyphs.push(glyph);
  2049. }
  2050. } else {
  2051. for (i = 0, ii = chars.length; i < ii; ++i) {
  2052. charcode = chars.charCodeAt(i);
  2053. glyph = this.charToGlyph(charcode, charcode === 0x20);
  2054. glyphs.push(glyph);
  2055. }
  2056. }
  2057. return charsCache[charsCacheKey] = glyphs;
  2058. }
  2059. };
  2060. return Font;
  2061. }();
  2062. var ErrorFont = function ErrorFontClosure() {
  2063. function ErrorFont(error) {
  2064. this.error = error;
  2065. this.loadedName = 'g_font_error';
  2066. this.loading = false;
  2067. }
  2068. ErrorFont.prototype = {
  2069. charsToGlyphs: function ErrorFont_charsToGlyphs() {
  2070. return [];
  2071. },
  2072. exportData: function ErrorFont_exportData() {
  2073. return { error: this.error };
  2074. }
  2075. };
  2076. return ErrorFont;
  2077. }();
  2078. function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) {
  2079. var charCodeToGlyphId = Object.create(null);
  2080. var glyphId, charCode, baseEncoding;
  2081. var isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  2082. if (properties.baseEncodingName) {
  2083. baseEncoding = getEncoding(properties.baseEncodingName);
  2084. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  2085. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  2086. if (glyphId >= 0) {
  2087. charCodeToGlyphId[charCode] = glyphId;
  2088. } else {
  2089. charCodeToGlyphId[charCode] = 0;
  2090. }
  2091. }
  2092. } else if (isSymbolicFont) {
  2093. for (charCode in builtInEncoding) {
  2094. charCodeToGlyphId[charCode] = builtInEncoding[charCode];
  2095. }
  2096. } else {
  2097. baseEncoding = StandardEncoding;
  2098. for (charCode = 0; charCode < baseEncoding.length; charCode++) {
  2099. glyphId = glyphNames.indexOf(baseEncoding[charCode]);
  2100. if (glyphId >= 0) {
  2101. charCodeToGlyphId[charCode] = glyphId;
  2102. } else {
  2103. charCodeToGlyphId[charCode] = 0;
  2104. }
  2105. }
  2106. }
  2107. var differences = properties.differences,
  2108. glyphsUnicodeMap;
  2109. if (differences) {
  2110. for (charCode in differences) {
  2111. var glyphName = differences[charCode];
  2112. glyphId = glyphNames.indexOf(glyphName);
  2113. if (glyphId === -1) {
  2114. if (!glyphsUnicodeMap) {
  2115. glyphsUnicodeMap = getGlyphsUnicode();
  2116. }
  2117. var standardGlyphName = recoverGlyphName(glyphName, glyphsUnicodeMap);
  2118. if (standardGlyphName !== glyphName) {
  2119. glyphId = glyphNames.indexOf(standardGlyphName);
  2120. }
  2121. }
  2122. if (glyphId >= 0) {
  2123. charCodeToGlyphId[charCode] = glyphId;
  2124. } else {
  2125. charCodeToGlyphId[charCode] = 0;
  2126. }
  2127. }
  2128. }
  2129. return charCodeToGlyphId;
  2130. }
  2131. var Type1Font = function Type1FontClosure() {
  2132. function findBlock(streamBytes, signature, startIndex) {
  2133. var streamBytesLength = streamBytes.length;
  2134. var signatureLength = signature.length;
  2135. var scanLength = streamBytesLength - signatureLength;
  2136. var i = startIndex,
  2137. j,
  2138. found = false;
  2139. while (i < scanLength) {
  2140. j = 0;
  2141. while (j < signatureLength && streamBytes[i + j] === signature[j]) {
  2142. j++;
  2143. }
  2144. if (j >= signatureLength) {
  2145. i += j;
  2146. while (i < streamBytesLength && isSpace(streamBytes[i])) {
  2147. i++;
  2148. }
  2149. found = true;
  2150. break;
  2151. }
  2152. i++;
  2153. }
  2154. return {
  2155. found: found,
  2156. length: i
  2157. };
  2158. }
  2159. function getHeaderBlock(stream, suggestedLength) {
  2160. var EEXEC_SIGNATURE = [0x65, 0x65, 0x78, 0x65, 0x63];
  2161. var streamStartPos = stream.pos;
  2162. var headerBytes, headerBytesLength, block;
  2163. try {
  2164. headerBytes = stream.getBytes(suggestedLength);
  2165. headerBytesLength = headerBytes.length;
  2166. } catch (ex) {
  2167. if (ex instanceof MissingDataException) {
  2168. throw ex;
  2169. }
  2170. }
  2171. if (headerBytesLength === suggestedLength) {
  2172. block = findBlock(headerBytes, EEXEC_SIGNATURE, suggestedLength - 2 * EEXEC_SIGNATURE.length);
  2173. if (block.found && block.length === suggestedLength) {
  2174. return {
  2175. stream: new Stream(headerBytes),
  2176. length: suggestedLength
  2177. };
  2178. }
  2179. }
  2180. warn('Invalid "Length1" property in Type1 font -- trying to recover.');
  2181. stream.pos = streamStartPos;
  2182. var SCAN_BLOCK_LENGTH = 2048;
  2183. var actualLength;
  2184. while (true) {
  2185. var scanBytes = stream.peekBytes(SCAN_BLOCK_LENGTH);
  2186. block = findBlock(scanBytes, EEXEC_SIGNATURE, 0);
  2187. if (block.length === 0) {
  2188. break;
  2189. }
  2190. stream.pos += block.length;
  2191. if (block.found) {
  2192. actualLength = stream.pos - streamStartPos;
  2193. break;
  2194. }
  2195. }
  2196. stream.pos = streamStartPos;
  2197. if (actualLength) {
  2198. return {
  2199. stream: new Stream(stream.getBytes(actualLength)),
  2200. length: actualLength
  2201. };
  2202. }
  2203. warn('Unable to recover "Length1" property in Type1 font -- using as is.');
  2204. return {
  2205. stream: new Stream(stream.getBytes(suggestedLength)),
  2206. length: suggestedLength
  2207. };
  2208. }
  2209. function getEexecBlock(stream, suggestedLength) {
  2210. var eexecBytes = stream.getBytes();
  2211. return {
  2212. stream: new Stream(eexecBytes),
  2213. length: eexecBytes.length
  2214. };
  2215. }
  2216. function Type1Font(name, file, properties) {
  2217. var PFB_HEADER_SIZE = 6;
  2218. var headerBlockLength = properties.length1;
  2219. var eexecBlockLength = properties.length2;
  2220. var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  2221. var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  2222. if (pfbHeaderPresent) {
  2223. file.skip(PFB_HEADER_SIZE);
  2224. headerBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
  2225. }
  2226. var headerBlock = getHeaderBlock(file, headerBlockLength);
  2227. headerBlockLength = headerBlock.length;
  2228. var headerBlockParser = new Type1Parser(headerBlock.stream, false, SEAC_ANALYSIS_ENABLED);
  2229. headerBlockParser.extractFontHeader(properties);
  2230. if (pfbHeaderPresent) {
  2231. pfbHeader = file.getBytes(PFB_HEADER_SIZE);
  2232. eexecBlockLength = pfbHeader[5] << 24 | pfbHeader[4] << 16 | pfbHeader[3] << 8 | pfbHeader[2];
  2233. }
  2234. var eexecBlock = getEexecBlock(file, eexecBlockLength);
  2235. eexecBlockLength = eexecBlock.length;
  2236. var eexecBlockParser = new Type1Parser(eexecBlock.stream, true, SEAC_ANALYSIS_ENABLED);
  2237. var data = eexecBlockParser.extractFontProgram();
  2238. for (var info in data.properties) {
  2239. properties[info] = data.properties[info];
  2240. }
  2241. var charstrings = data.charstrings;
  2242. var type2Charstrings = this.getType2Charstrings(charstrings);
  2243. var subrs = this.getType2Subrs(data.subrs);
  2244. this.charstrings = charstrings;
  2245. this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties);
  2246. this.seacs = this.getSeacs(data.charstrings);
  2247. }
  2248. Type1Font.prototype = {
  2249. get numGlyphs() {
  2250. return this.charstrings.length + 1;
  2251. },
  2252. getCharset: function Type1Font_getCharset() {
  2253. var charset = ['.notdef'];
  2254. var charstrings = this.charstrings;
  2255. for (var glyphId = 0; glyphId < charstrings.length; glyphId++) {
  2256. charset.push(charstrings[glyphId].glyphName);
  2257. }
  2258. return charset;
  2259. },
  2260. getGlyphMapping: function Type1Font_getGlyphMapping(properties) {
  2261. var charstrings = this.charstrings;
  2262. var glyphNames = ['.notdef'],
  2263. glyphId;
  2264. for (glyphId = 0; glyphId < charstrings.length; glyphId++) {
  2265. glyphNames.push(charstrings[glyphId].glyphName);
  2266. }
  2267. var encoding = properties.builtInEncoding;
  2268. if (encoding) {
  2269. var builtInEncoding = Object.create(null);
  2270. for (var charCode in encoding) {
  2271. glyphId = glyphNames.indexOf(encoding[charCode]);
  2272. if (glyphId >= 0) {
  2273. builtInEncoding[charCode] = glyphId;
  2274. }
  2275. }
  2276. }
  2277. return type1FontGlyphMapping(properties, builtInEncoding, glyphNames);
  2278. },
  2279. getSeacs: function Type1Font_getSeacs(charstrings) {
  2280. var i, ii;
  2281. var seacMap = [];
  2282. for (i = 0, ii = charstrings.length; i < ii; i++) {
  2283. var charstring = charstrings[i];
  2284. if (charstring.seac) {
  2285. seacMap[i + 1] = charstring.seac;
  2286. }
  2287. }
  2288. return seacMap;
  2289. },
  2290. getType2Charstrings: function Type1Font_getType2Charstrings(type1Charstrings) {
  2291. var type2Charstrings = [];
  2292. for (var i = 0, ii = type1Charstrings.length; i < ii; i++) {
  2293. type2Charstrings.push(type1Charstrings[i].charstring);
  2294. }
  2295. return type2Charstrings;
  2296. },
  2297. getType2Subrs: function Type1Font_getType2Subrs(type1Subrs) {
  2298. var bias = 0;
  2299. var count = type1Subrs.length;
  2300. if (count < 1133) {
  2301. bias = 107;
  2302. } else if (count < 33769) {
  2303. bias = 1131;
  2304. } else {
  2305. bias = 32768;
  2306. }
  2307. var type2Subrs = [];
  2308. var i;
  2309. for (i = 0; i < bias; i++) {
  2310. type2Subrs.push([0x0B]);
  2311. }
  2312. for (i = 0; i < count; i++) {
  2313. type2Subrs.push(type1Subrs[i]);
  2314. }
  2315. return type2Subrs;
  2316. },
  2317. wrap: function Type1Font_wrap(name, glyphs, charstrings, subrs, properties) {
  2318. var cff = new CFF();
  2319. cff.header = new CFFHeader(1, 0, 4, 4);
  2320. cff.names = [name];
  2321. var topDict = new CFFTopDict();
  2322. topDict.setByName('version', 391);
  2323. topDict.setByName('Notice', 392);
  2324. topDict.setByName('FullName', 393);
  2325. topDict.setByName('FamilyName', 394);
  2326. topDict.setByName('Weight', 395);
  2327. topDict.setByName('Encoding', null);
  2328. topDict.setByName('FontMatrix', properties.fontMatrix);
  2329. topDict.setByName('FontBBox', properties.bbox);
  2330. topDict.setByName('charset', null);
  2331. topDict.setByName('CharStrings', null);
  2332. topDict.setByName('Private', null);
  2333. cff.topDict = topDict;
  2334. var strings = new CFFStrings();
  2335. strings.add('Version 0.11');
  2336. strings.add('See original notice');
  2337. strings.add(name);
  2338. strings.add(name);
  2339. strings.add('Medium');
  2340. cff.strings = strings;
  2341. cff.globalSubrIndex = new CFFIndex();
  2342. var count = glyphs.length;
  2343. var charsetArray = [0];
  2344. var i, ii;
  2345. for (i = 0; i < count; i++) {
  2346. var index = CFFStandardStrings.indexOf(charstrings[i].glyphName);
  2347. if (index === -1) {
  2348. index = 0;
  2349. }
  2350. charsetArray.push(index >> 8 & 0xff, index & 0xff);
  2351. }
  2352. cff.charset = new CFFCharset(false, 0, [], charsetArray);
  2353. var charStringsIndex = new CFFIndex();
  2354. charStringsIndex.add([0x8B, 0x0E]);
  2355. for (i = 0; i < count; i++) {
  2356. var glyph = glyphs[i];
  2357. if (glyph.length === 0) {
  2358. charStringsIndex.add([0x8B, 0x0E]);
  2359. continue;
  2360. }
  2361. charStringsIndex.add(glyph);
  2362. }
  2363. cff.charStrings = charStringsIndex;
  2364. var privateDict = new CFFPrivateDict();
  2365. privateDict.setByName('Subrs', null);
  2366. var fields = ['BlueValues', 'OtherBlues', 'FamilyBlues', 'FamilyOtherBlues', 'StemSnapH', 'StemSnapV', 'BlueShift', 'BlueFuzz', 'BlueScale', 'LanguageGroup', 'ExpansionFactor', 'ForceBold', 'StdHW', 'StdVW'];
  2367. for (i = 0, ii = fields.length; i < ii; i++) {
  2368. var field = fields[i];
  2369. if (!(field in properties.privateData)) {
  2370. continue;
  2371. }
  2372. var value = properties.privateData[field];
  2373. if (isArray(value)) {
  2374. for (var j = value.length - 1; j > 0; j--) {
  2375. value[j] -= value[j - 1];
  2376. }
  2377. }
  2378. privateDict.setByName(field, value);
  2379. }
  2380. cff.topDict.privateDict = privateDict;
  2381. var subrIndex = new CFFIndex();
  2382. for (i = 0, ii = subrs.length; i < ii; i++) {
  2383. subrIndex.add(subrs[i]);
  2384. }
  2385. privateDict.subrsIndex = subrIndex;
  2386. var compiler = new CFFCompiler(cff);
  2387. return compiler.compile();
  2388. }
  2389. };
  2390. return Type1Font;
  2391. }();
  2392. var CFFFont = function CFFFontClosure() {
  2393. function CFFFont(file, properties) {
  2394. this.properties = properties;
  2395. var parser = new CFFParser(file, properties, SEAC_ANALYSIS_ENABLED);
  2396. this.cff = parser.parse();
  2397. var compiler = new CFFCompiler(this.cff);
  2398. this.seacs = this.cff.seacs;
  2399. try {
  2400. this.data = compiler.compile();
  2401. } catch (e) {
  2402. warn('Failed to compile font ' + properties.loadedName);
  2403. this.data = file;
  2404. }
  2405. }
  2406. CFFFont.prototype = {
  2407. get numGlyphs() {
  2408. return this.cff.charStrings.count;
  2409. },
  2410. getCharset: function CFFFont_getCharset() {
  2411. return this.cff.charset.charset;
  2412. },
  2413. getGlyphMapping: function CFFFont_getGlyphMapping() {
  2414. var cff = this.cff;
  2415. var properties = this.properties;
  2416. var charsets = cff.charset.charset;
  2417. var charCodeToGlyphId;
  2418. var glyphId;
  2419. if (properties.composite) {
  2420. charCodeToGlyphId = Object.create(null);
  2421. if (cff.isCIDFont) {
  2422. for (glyphId = 0; glyphId < charsets.length; glyphId++) {
  2423. var cid = charsets[glyphId];
  2424. var charCode = properties.cMap.charCodeOf(cid);
  2425. charCodeToGlyphId[charCode] = glyphId;
  2426. }
  2427. } else {
  2428. for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
  2429. charCodeToGlyphId[glyphId] = glyphId;
  2430. }
  2431. }
  2432. return charCodeToGlyphId;
  2433. }
  2434. var encoding = cff.encoding ? cff.encoding.encoding : null;
  2435. charCodeToGlyphId = type1FontGlyphMapping(properties, encoding, charsets);
  2436. return charCodeToGlyphId;
  2437. }
  2438. };
  2439. return CFFFont;
  2440. }();
  2441. (function checkSeacSupport() {
  2442. if (typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent)) {
  2443. SEAC_ANALYSIS_ENABLED = true;
  2444. }
  2445. })();
  2446. (function checkChromeWindows() {
  2447. if (typeof navigator !== 'undefined' && /Windows.*Chrome/.test(navigator.userAgent)) {
  2448. SKIP_PRIVATE_USE_RANGE_F000_TO_F01F = true;
  2449. }
  2450. })();
  2451. exports.SEAC_ANALYSIS_ENABLED = SEAC_ANALYSIS_ENABLED;
  2452. exports.PRIVATE_USE_OFFSET_START = PRIVATE_USE_OFFSET_START;
  2453. exports.PRIVATE_USE_OFFSET_END = PRIVATE_USE_OFFSET_END;
  2454. exports.ErrorFont = ErrorFont;
  2455. exports.Font = Font;
  2456. exports.FontFlags = FontFlags;
  2457. exports.IdentityToUnicodeMap = IdentityToUnicodeMap;
  2458. exports.ProblematicCharRanges = ProblematicCharRanges;
  2459. exports.ToUnicodeMap = ToUnicodeMap;
  2460. exports.getFontType = getFontType;