fonts.js 91 KB

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