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