fonts.js 91 KB

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