2
0

fonts.js 93 KB

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