fonts.js 92 KB

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