2
0

fonts.js 98 KB

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