2
0

fonts.js 99 KB

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