2
0

fonts.js 93 KB

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