fonts.js 92 KB

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