fonts.js 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494
  1. /* Copyright 2012 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. import {
  16. assert,
  17. bytesToString,
  18. FONT_IDENTITY_MATRIX,
  19. FontType,
  20. FormatError,
  21. info,
  22. shadow,
  23. string32,
  24. warn,
  25. } from "../shared/util.js";
  26. import { CFFCompiler, CFFParser } from "./cff_parser.js";
  27. import {
  28. FontFlags,
  29. getFontType,
  30. MacStandardGlyphOrdering,
  31. normalizeFontName,
  32. recoverGlyphName,
  33. SEAC_ANALYSIS_ENABLED,
  34. } from "./fonts_utils.js";
  35. import {
  36. getCharUnicodeCategory,
  37. getNormalizedUnicodes,
  38. getUnicodeForGlyph,
  39. getUnicodeRangeFor,
  40. mapSpecialUnicodeValues,
  41. reverseIfRtl,
  42. } from "./unicode.js";
  43. import { getDingbatsGlyphsUnicode, getGlyphsUnicode } from "./glyphlist.js";
  44. import {
  45. getEncoding,
  46. MacRomanEncoding,
  47. StandardEncoding,
  48. SymbolSetEncoding,
  49. ZapfDingbatsEncoding,
  50. } from "./encodings.js";
  51. import {
  52. getGlyphMapForStandardFonts,
  53. getNonStdFontMap,
  54. getSerifFonts,
  55. getStdFontMap,
  56. getSupplementalGlyphMapForArialBlack,
  57. getSupplementalGlyphMapForCalibri,
  58. } from "./standard_fonts.js";
  59. import { IdentityToUnicodeMap, ToUnicodeMap } from "./to_unicode_map.js";
  60. import { CFFFont } from "./cff_font.js";
  61. import { FontRendererFactory } from "./font_renderer.js";
  62. import { getFontBasicMetrics } from "./metrics.js";
  63. import { GlyfTable } from "./glyf.js";
  64. import { IdentityCMap } from "./cmap.js";
  65. import { OpenTypeFileBuilder } from "./opentype_file_builder.js";
  66. import { readUint32 } from "./core_utils.js";
  67. import { Stream } from "./stream.js";
  68. import { Type1Font } from "./type1_font.js";
  69. // Unicode Private Use Areas:
  70. const PRIVATE_USE_AREAS = [
  71. [0xe000, 0xf8ff], // BMP (0)
  72. [0x100000, 0x10fffd], // PUP (16)
  73. ];
  74. // PDF Glyph Space Units are one Thousandth of a TextSpace Unit
  75. // except for Type 3 fonts
  76. const PDF_GLYPH_SPACE_UNITS = 1000;
  77. const EXPORT_DATA_PROPERTIES = [
  78. "ascent",
  79. "bbox",
  80. "black",
  81. "bold",
  82. "charProcOperatorList",
  83. "composite",
  84. "cssFontInfo",
  85. "data",
  86. "defaultVMetrics",
  87. "defaultWidth",
  88. "descent",
  89. "fallbackName",
  90. "fontMatrix",
  91. "fontType",
  92. "isInvalidPDFjsFont",
  93. "isType3Font",
  94. "italic",
  95. "loadedName",
  96. "mimetype",
  97. "missingFile",
  98. "name",
  99. "remeasure",
  100. "subtype",
  101. "type",
  102. "vertical",
  103. ];
  104. const EXPORT_DATA_EXTRA_PROPERTIES = [
  105. "cMap",
  106. "defaultEncoding",
  107. "differences",
  108. "isMonospace",
  109. "isSerifFont",
  110. "isSymbolicFont",
  111. "seacMap",
  112. "toFontChar",
  113. "toUnicode",
  114. "vmetrics",
  115. "widths",
  116. ];
  117. function adjustWidths(properties) {
  118. if (!properties.fontMatrix) {
  119. return;
  120. }
  121. if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
  122. return;
  123. }
  124. // adjusting width to fontMatrix scale
  125. const scale = 0.001 / properties.fontMatrix[0];
  126. const glyphsWidths = properties.widths;
  127. for (const glyph in glyphsWidths) {
  128. glyphsWidths[glyph] *= scale;
  129. }
  130. properties.defaultWidth *= scale;
  131. }
  132. function adjustToUnicode(properties, builtInEncoding) {
  133. if (properties.isInternalFont) {
  134. return;
  135. }
  136. if (properties.hasIncludedToUnicodeMap) {
  137. return; // The font dictionary has a `ToUnicode` entry.
  138. }
  139. if (builtInEncoding === properties.defaultEncoding) {
  140. return; // No point in trying to adjust `toUnicode` if the encodings match.
  141. }
  142. if (properties.toUnicode instanceof IdentityToUnicodeMap) {
  143. return;
  144. }
  145. const toUnicode = [],
  146. glyphsUnicodeMap = getGlyphsUnicode();
  147. for (const charCode in builtInEncoding) {
  148. if (properties.hasEncoding) {
  149. if (
  150. properties.differences.length === 0 ||
  151. properties.differences[charCode] !== undefined
  152. ) {
  153. continue; // The font dictionary has an `Encoding`/`Differences` entry.
  154. }
  155. }
  156. const glyphName = builtInEncoding[charCode];
  157. const unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  158. if (unicode !== -1) {
  159. toUnicode[charCode] = String.fromCharCode(unicode);
  160. }
  161. }
  162. if (toUnicode.length > 0) {
  163. properties.toUnicode.amend(toUnicode);
  164. }
  165. }
  166. /**
  167. * NOTE: This function should only be called at the *end* of font-parsing,
  168. * after e.g. `adjustToUnicode` has run, to prevent any issues.
  169. */
  170. function amendFallbackToUnicode(properties) {
  171. if (!properties.fallbackToUnicode) {
  172. return;
  173. }
  174. if (properties.toUnicode instanceof IdentityToUnicodeMap) {
  175. return;
  176. }
  177. const toUnicode = [];
  178. for (const charCode in properties.fallbackToUnicode) {
  179. if (properties.toUnicode.has(charCode)) {
  180. continue; // The font dictionary has a `ToUnicode` entry.
  181. }
  182. toUnicode[charCode] = properties.fallbackToUnicode[charCode];
  183. }
  184. if (toUnicode.length > 0) {
  185. properties.toUnicode.amend(toUnicode);
  186. }
  187. }
  188. class Glyph {
  189. constructor(
  190. originalCharCode,
  191. fontChar,
  192. unicode,
  193. accent,
  194. width,
  195. vmetric,
  196. operatorListId,
  197. isSpace,
  198. isInFont
  199. ) {
  200. this.originalCharCode = originalCharCode;
  201. this.fontChar = fontChar;
  202. this.unicode = unicode;
  203. this.accent = accent;
  204. this.width = width;
  205. this.vmetric = vmetric;
  206. this.operatorListId = operatorListId;
  207. this.isSpace = isSpace;
  208. this.isInFont = isInFont;
  209. }
  210. /**
  211. * This property, which is only used by `PartialEvaluator.getTextContent`,
  212. * is purposely made non-serializable.
  213. * @type {Object}
  214. */
  215. get category() {
  216. return shadow(
  217. this,
  218. "category",
  219. getCharUnicodeCategory(this.unicode),
  220. /* nonSerializable = */ true
  221. );
  222. }
  223. /**
  224. * This property, which is only used by `PartialEvaluator.getTextContent`,
  225. * is purposely made non-serializable.
  226. * @type {string}
  227. */
  228. get normalizedUnicode() {
  229. return shadow(
  230. this,
  231. "normalizedUnicode",
  232. reverseIfRtl(Glyph._NormalizedUnicodes[this.unicode] || this.unicode),
  233. /* nonSerializable = */ true
  234. );
  235. }
  236. static get _NormalizedUnicodes() {
  237. return shadow(this, "_NormalizedUnicodes", getNormalizedUnicodes());
  238. }
  239. }
  240. function int16(b0, b1) {
  241. return (b0 << 8) + b1;
  242. }
  243. function writeSignedInt16(bytes, index, value) {
  244. bytes[index + 1] = value;
  245. bytes[index] = value >>> 8;
  246. }
  247. function signedInt16(b0, b1) {
  248. const value = (b0 << 8) + b1;
  249. return value & (1 << 15) ? value - 0x10000 : value;
  250. }
  251. function int32(b0, b1, b2, b3) {
  252. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  253. }
  254. function string16(value) {
  255. if (
  256. typeof PDFJSDev === "undefined" ||
  257. PDFJSDev.test("!PRODUCTION || TESTING")
  258. ) {
  259. assert(
  260. typeof value === "number" && Math.abs(value) < 2 ** 16,
  261. `string16: Unexpected input "${value}".`
  262. );
  263. }
  264. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  265. }
  266. function safeString16(value) {
  267. if (
  268. typeof PDFJSDev === "undefined" ||
  269. PDFJSDev.test("!PRODUCTION || TESTING")
  270. ) {
  271. assert(
  272. typeof value === "number" && !Number.isNaN(value),
  273. `safeString16: Unexpected input "${value}".`
  274. );
  275. }
  276. // clamp value to the 16-bit int range
  277. if (value > 0x7fff) {
  278. value = 0x7fff;
  279. } else if (value < -0x8000) {
  280. value = -0x8000;
  281. }
  282. return String.fromCharCode((value >> 8) & 0xff, value & 0xff);
  283. }
  284. function isTrueTypeFile(file) {
  285. const header = file.peekBytes(4);
  286. return (
  287. readUint32(header, 0) === 0x00010000 || bytesToString(header) === "true"
  288. );
  289. }
  290. function isTrueTypeCollectionFile(file) {
  291. const header = file.peekBytes(4);
  292. return bytesToString(header) === "ttcf";
  293. }
  294. function isOpenTypeFile(file) {
  295. const header = file.peekBytes(4);
  296. return bytesToString(header) === "OTTO";
  297. }
  298. function isType1File(file) {
  299. const header = file.peekBytes(2);
  300. // All Type1 font programs must begin with the comment '%!' (0x25 + 0x21).
  301. if (header[0] === 0x25 && header[1] === 0x21) {
  302. return true;
  303. }
  304. // ... obviously some fonts violate that part of the specification,
  305. // please refer to the comment in |Type1Font| below (pfb file header).
  306. if (header[0] === 0x80 && header[1] === 0x01) {
  307. return true;
  308. }
  309. return false;
  310. }
  311. /**
  312. * Compared to other font formats, the header in CFF files is not constant
  313. * but contains version numbers. To reduce the possibility of misclassifying
  314. * font files as CFF, it's recommended to check for other font formats first.
  315. */
  316. function isCFFFile(file) {
  317. const header = file.peekBytes(4);
  318. if (
  319. /* major version, [1, 255] */ header[0] >= 1 &&
  320. /* minor version, [0, 255]; header[1] */
  321. /* header size, [0, 255]; header[2] */
  322. /* offset(0) size, [1, 4] */ header[3] >= 1 &&
  323. header[3] <= 4
  324. ) {
  325. return true;
  326. }
  327. return false;
  328. }
  329. function getFontFileType(file, { type, subtype, composite }) {
  330. let fileType, fileSubtype;
  331. if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) {
  332. if (composite) {
  333. fileType = "CIDFontType2";
  334. } else {
  335. fileType = "TrueType";
  336. }
  337. } else if (isOpenTypeFile(file)) {
  338. if (composite) {
  339. fileType = "CIDFontType2";
  340. } else {
  341. fileType = "OpenType";
  342. }
  343. } else if (isType1File(file)) {
  344. if (composite) {
  345. fileType = "CIDFontType0";
  346. } else {
  347. fileType = type === "MMType1" ? "MMType1" : "Type1";
  348. }
  349. } else if (isCFFFile(file)) {
  350. if (composite) {
  351. fileType = "CIDFontType0";
  352. fileSubtype = "CIDFontType0C";
  353. } else {
  354. fileType = type === "MMType1" ? "MMType1" : "Type1";
  355. fileSubtype = "Type1C";
  356. }
  357. } else {
  358. warn("getFontFileType: Unable to detect correct font file Type/Subtype.");
  359. fileType = type;
  360. fileSubtype = subtype;
  361. }
  362. return [fileType, fileSubtype];
  363. }
  364. function applyStandardFontGlyphMap(map, glyphMap) {
  365. for (const charCode in glyphMap) {
  366. map[+charCode] = glyphMap[charCode];
  367. }
  368. }
  369. function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
  370. const toFontChar = [];
  371. let unicode;
  372. for (let i = 0, ii = encoding.length; i < ii; i++) {
  373. unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
  374. if (unicode !== -1) {
  375. toFontChar[i] = unicode;
  376. }
  377. }
  378. for (const charCode in differences) {
  379. unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
  380. if (unicode !== -1) {
  381. toFontChar[+charCode] = unicode;
  382. }
  383. }
  384. return toFontChar;
  385. }
  386. function convertCidString(charCode, cid, shouldThrow = false) {
  387. switch (cid.length) {
  388. case 1:
  389. return cid.charCodeAt(0);
  390. case 2:
  391. return (cid.charCodeAt(0) << 8) | cid.charCodeAt(1);
  392. }
  393. const msg = `Unsupported CID string (charCode ${charCode}): "${cid}".`;
  394. if (shouldThrow) {
  395. throw new FormatError(msg);
  396. }
  397. warn(msg);
  398. return cid;
  399. }
  400. /**
  401. * Rebuilds the char code to glyph ID map by moving all char codes to the
  402. * private use area. This is done to avoid issues with various problematic
  403. * unicode areas where either a glyph won't be drawn or is deformed by a
  404. * shaper.
  405. * @returns {Object} Two properties:
  406. * 'toFontChar' - maps original char codes(the value that will be read
  407. * from commands such as show text) to the char codes that will be used in the
  408. * font that we build
  409. * 'charCodeToGlyphId' - maps the new font char codes to glyph ids
  410. */
  411. function adjustMapping(charCodeToGlyphId, hasGlyph, newGlyphZeroId, toUnicode) {
  412. const newMap = Object.create(null);
  413. const toUnicodeExtraMap = new Map();
  414. const toFontChar = [];
  415. const usedGlyphIds = new Set();
  416. let privateUseAreaIndex = 0;
  417. const privateUseOffetStart = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
  418. let nextAvailableFontCharCode = privateUseOffetStart;
  419. let privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
  420. for (let originalCharCode in charCodeToGlyphId) {
  421. originalCharCode |= 0;
  422. let glyphId = charCodeToGlyphId[originalCharCode];
  423. // For missing glyphs don't create the mappings so the glyph isn't
  424. // drawn.
  425. if (!hasGlyph(glyphId)) {
  426. continue;
  427. }
  428. if (nextAvailableFontCharCode > privateUseOffetEnd) {
  429. privateUseAreaIndex++;
  430. if (privateUseAreaIndex >= PRIVATE_USE_AREAS.length) {
  431. warn("Ran out of space in font private use area.");
  432. break;
  433. }
  434. nextAvailableFontCharCode = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
  435. privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
  436. }
  437. const fontCharCode = nextAvailableFontCharCode++;
  438. if (glyphId === 0) {
  439. glyphId = newGlyphZeroId;
  440. }
  441. // Fix for bug 1778484:
  442. // The charcodes are moved into a private use area to fix some rendering
  443. // issues (https://github.com/mozilla/pdf.js/pull/9340) but when printing
  444. // to PDF the generated font will contain wrong chars. We can avoid that by
  445. // adding the unicode to the cmap and the print backend will then map the
  446. // glyph ids to the correct unicode.
  447. let unicode = toUnicode.get(originalCharCode);
  448. if (typeof unicode === "string") {
  449. unicode = unicode.codePointAt(0);
  450. }
  451. if (
  452. unicode &&
  453. unicode < privateUseOffetStart &&
  454. !usedGlyphIds.has(glyphId)
  455. ) {
  456. toUnicodeExtraMap.set(unicode, glyphId);
  457. usedGlyphIds.add(glyphId);
  458. }
  459. newMap[fontCharCode] = glyphId;
  460. toFontChar[originalCharCode] = fontCharCode;
  461. }
  462. return {
  463. toFontChar,
  464. charCodeToGlyphId: newMap,
  465. toUnicodeExtraMap,
  466. nextAvailableFontCharCode,
  467. };
  468. }
  469. function getRanges(glyphs, toUnicodeExtraMap, numGlyphs) {
  470. // Array.sort() sorts by characters, not numerically, so convert to an
  471. // array of characters.
  472. const codes = [];
  473. for (const charCode in glyphs) {
  474. // Remove an invalid glyph ID mappings to make OTS happy.
  475. if (glyphs[charCode] >= numGlyphs) {
  476. continue;
  477. }
  478. codes.push({ fontCharCode: charCode | 0, glyphId: glyphs[charCode] });
  479. }
  480. if (toUnicodeExtraMap) {
  481. for (const [unicode, glyphId] of toUnicodeExtraMap) {
  482. if (glyphId >= numGlyphs) {
  483. continue;
  484. }
  485. codes.push({ fontCharCode: unicode, glyphId });
  486. }
  487. }
  488. // Some fonts have zero glyphs and are used only for text selection, but
  489. // there needs to be at least one to build a valid cmap table.
  490. if (codes.length === 0) {
  491. codes.push({ fontCharCode: 0, glyphId: 0 });
  492. }
  493. codes.sort(function fontGetRangesSort(a, b) {
  494. return a.fontCharCode - b.fontCharCode;
  495. });
  496. // Split the sorted codes into ranges.
  497. const ranges = [];
  498. const length = codes.length;
  499. for (let n = 0; n < length; ) {
  500. const start = codes[n].fontCharCode;
  501. const codeIndices = [codes[n].glyphId];
  502. ++n;
  503. let end = start;
  504. while (n < length && end + 1 === codes[n].fontCharCode) {
  505. codeIndices.push(codes[n].glyphId);
  506. ++end;
  507. ++n;
  508. if (end === 0xffff) {
  509. break;
  510. }
  511. }
  512. ranges.push([start, end, codeIndices]);
  513. }
  514. return ranges;
  515. }
  516. function createCmapTable(glyphs, toUnicodeExtraMap, numGlyphs) {
  517. const ranges = getRanges(glyphs, toUnicodeExtraMap, numGlyphs);
  518. const numTables = ranges.at(-1)[1] > 0xffff ? 2 : 1;
  519. let cmap =
  520. "\x00\x00" + // version
  521. string16(numTables) + // numTables
  522. "\x00\x03" + // platformID
  523. "\x00\x01" + // encodingID
  524. string32(4 + numTables * 8); // start of the table record
  525. let i, ii, j, jj;
  526. for (i = ranges.length - 1; i >= 0; --i) {
  527. if (ranges[i][0] <= 0xffff) {
  528. break;
  529. }
  530. }
  531. const bmpLength = i + 1;
  532. if (ranges[i][0] < 0xffff && ranges[i][1] === 0xffff) {
  533. ranges[i][1] = 0xfffe;
  534. }
  535. const trailingRangesCount = ranges[i][1] < 0xffff ? 1 : 0;
  536. const segCount = bmpLength + trailingRangesCount;
  537. const searchParams = OpenTypeFileBuilder.getSearchParams(segCount, 2);
  538. // Fill up the 4 parallel arrays describing the segments.
  539. let startCount = "";
  540. let endCount = "";
  541. let idDeltas = "";
  542. let idRangeOffsets = "";
  543. let glyphsIds = "";
  544. let bias = 0;
  545. let range, start, end, codes;
  546. for (i = 0, ii = bmpLength; i < ii; i++) {
  547. range = ranges[i];
  548. start = range[0];
  549. end = range[1];
  550. startCount += string16(start);
  551. endCount += string16(end);
  552. codes = range[2];
  553. let contiguous = true;
  554. for (j = 1, jj = codes.length; j < jj; ++j) {
  555. if (codes[j] !== codes[j - 1] + 1) {
  556. contiguous = false;
  557. break;
  558. }
  559. }
  560. if (!contiguous) {
  561. const offset = (segCount - i) * 2 + bias * 2;
  562. bias += end - start + 1;
  563. idDeltas += string16(0);
  564. idRangeOffsets += string16(offset);
  565. for (j = 0, jj = codes.length; j < jj; ++j) {
  566. glyphsIds += string16(codes[j]);
  567. }
  568. } else {
  569. const startCode = codes[0];
  570. idDeltas += string16((startCode - start) & 0xffff);
  571. idRangeOffsets += string16(0);
  572. }
  573. }
  574. if (trailingRangesCount > 0) {
  575. endCount += "\xFF\xFF";
  576. startCount += "\xFF\xFF";
  577. idDeltas += "\x00\x01";
  578. idRangeOffsets += "\x00\x00";
  579. }
  580. const format314 =
  581. "\x00\x00" + // language
  582. string16(2 * segCount) +
  583. string16(searchParams.range) +
  584. string16(searchParams.entry) +
  585. string16(searchParams.rangeShift) +
  586. endCount +
  587. "\x00\x00" +
  588. startCount +
  589. idDeltas +
  590. idRangeOffsets +
  591. glyphsIds;
  592. let format31012 = "";
  593. let header31012 = "";
  594. if (numTables > 1) {
  595. cmap +=
  596. "\x00\x03" + // platformID
  597. "\x00\x0A" + // encodingID
  598. string32(4 + numTables * 8 + 4 + format314.length); // start of the table record
  599. format31012 = "";
  600. for (i = 0, ii = ranges.length; i < ii; i++) {
  601. range = ranges[i];
  602. start = range[0];
  603. codes = range[2];
  604. let code = codes[0];
  605. for (j = 1, jj = codes.length; j < jj; ++j) {
  606. if (codes[j] !== codes[j - 1] + 1) {
  607. end = range[0] + j - 1;
  608. format31012 +=
  609. string32(start) + // startCharCode
  610. string32(end) + // endCharCode
  611. string32(code); // startGlyphID
  612. start = end + 1;
  613. code = codes[j];
  614. }
  615. }
  616. format31012 +=
  617. string32(start) + // startCharCode
  618. string32(range[1]) + // endCharCode
  619. string32(code); // startGlyphID
  620. }
  621. header31012 =
  622. "\x00\x0C" + // format
  623. "\x00\x00" + // reserved
  624. string32(format31012.length + 16) + // length
  625. "\x00\x00\x00\x00" + // language
  626. string32(format31012.length / 12); // nGroups
  627. }
  628. return (
  629. cmap +
  630. "\x00\x04" + // format
  631. string16(format314.length + 4) + // length
  632. format314 +
  633. header31012 +
  634. format31012
  635. );
  636. }
  637. function validateOS2Table(os2, file) {
  638. file.pos = (file.start || 0) + os2.offset;
  639. const version = file.getUint16();
  640. // TODO verify all OS/2 tables fields, but currently we validate only those
  641. // that give us issues
  642. file.skip(60); // skipping type, misc sizes, panose, unicode ranges
  643. const selection = file.getUint16();
  644. if (version < 4 && selection & 0x0300) {
  645. return false;
  646. }
  647. const firstChar = file.getUint16();
  648. const lastChar = file.getUint16();
  649. if (firstChar > lastChar) {
  650. return false;
  651. }
  652. file.skip(6); // skipping sTypoAscender/Descender/LineGap
  653. const usWinAscent = file.getUint16();
  654. if (usWinAscent === 0) {
  655. // makes font unreadable by windows
  656. return false;
  657. }
  658. // OS/2 appears to be valid, resetting some fields
  659. os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
  660. return true;
  661. }
  662. function createOS2Table(properties, charstrings, override) {
  663. override = override || {
  664. unitsPerEm: 0,
  665. yMax: 0,
  666. yMin: 0,
  667. ascent: 0,
  668. descent: 0,
  669. };
  670. let ulUnicodeRange1 = 0;
  671. let ulUnicodeRange2 = 0;
  672. let ulUnicodeRange3 = 0;
  673. let ulUnicodeRange4 = 0;
  674. let firstCharIndex = null;
  675. let lastCharIndex = 0;
  676. if (charstrings) {
  677. for (let code in charstrings) {
  678. code |= 0;
  679. if (firstCharIndex > code || !firstCharIndex) {
  680. firstCharIndex = code;
  681. }
  682. if (lastCharIndex < code) {
  683. lastCharIndex = code;
  684. }
  685. const position = getUnicodeRangeFor(code);
  686. if (position < 32) {
  687. ulUnicodeRange1 |= 1 << position;
  688. } else if (position < 64) {
  689. ulUnicodeRange2 |= 1 << (position - 32);
  690. } else if (position < 96) {
  691. ulUnicodeRange3 |= 1 << (position - 64);
  692. } else if (position < 123) {
  693. ulUnicodeRange4 |= 1 << (position - 96);
  694. } else {
  695. throw new FormatError(
  696. "Unicode ranges Bits > 123 are reserved for internal usage"
  697. );
  698. }
  699. }
  700. if (lastCharIndex > 0xffff) {
  701. // OS2 only supports a 16 bit int. The spec says if supplementary
  702. // characters are used the field should just be set to 0xFFFF.
  703. lastCharIndex = 0xffff;
  704. }
  705. } else {
  706. // TODO
  707. firstCharIndex = 0;
  708. lastCharIndex = 255;
  709. }
  710. const bbox = properties.bbox || [0, 0, 0, 0];
  711. const unitsPerEm =
  712. override.unitsPerEm ||
  713. 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  714. // if the font units differ to the PDF glyph space units
  715. // then scale up the values
  716. const scale = properties.ascentScaled
  717. ? 1.0
  718. : unitsPerEm / PDF_GLYPH_SPACE_UNITS;
  719. const typoAscent =
  720. override.ascent || Math.round(scale * (properties.ascent || bbox[3]));
  721. let typoDescent =
  722. override.descent || Math.round(scale * (properties.descent || bbox[1]));
  723. if (typoDescent > 0 && properties.descent > 0 && bbox[1] < 0) {
  724. typoDescent = -typoDescent; // fixing incorrect descent
  725. }
  726. const winAscent = override.yMax || typoAscent;
  727. const winDescent = -override.yMin || -typoDescent;
  728. return (
  729. "\x00\x03" + // version
  730. "\x02\x24" + // xAvgCharWidth
  731. "\x01\xF4" + // usWeightClass
  732. "\x00\x05" + // usWidthClass
  733. "\x00\x00" + // fstype (0 to let the font loads via font-face on IE)
  734. "\x02\x8A" + // ySubscriptXSize
  735. "\x02\xBB" + // ySubscriptYSize
  736. "\x00\x00" + // ySubscriptXOffset
  737. "\x00\x8C" + // ySubscriptYOffset
  738. "\x02\x8A" + // ySuperScriptXSize
  739. "\x02\xBB" + // ySuperScriptYSize
  740. "\x00\x00" + // ySuperScriptXOffset
  741. "\x01\xDF" + // ySuperScriptYOffset
  742. "\x00\x31" + // yStrikeOutSize
  743. "\x01\x02" + // yStrikeOutPosition
  744. "\x00\x00" + // sFamilyClass
  745. "\x00\x00\x06" +
  746. String.fromCharCode(properties.fixedPitch ? 0x09 : 0x00) +
  747. "\x00\x00\x00\x00\x00\x00" + // Panose
  748. string32(ulUnicodeRange1) + // ulUnicodeRange1 (Bits 0-31)
  749. string32(ulUnicodeRange2) + // ulUnicodeRange2 (Bits 32-63)
  750. string32(ulUnicodeRange3) + // ulUnicodeRange3 (Bits 64-95)
  751. string32(ulUnicodeRange4) + // ulUnicodeRange4 (Bits 96-127)
  752. "\x2A\x32\x31\x2A" + // achVendID
  753. string16(properties.italicAngle ? 1 : 0) + // fsSelection
  754. string16(firstCharIndex || properties.firstChar) + // usFirstCharIndex
  755. string16(lastCharIndex || properties.lastChar) + // usLastCharIndex
  756. string16(typoAscent) + // sTypoAscender
  757. string16(typoDescent) + // sTypoDescender
  758. "\x00\x64" + // sTypoLineGap (7%-10% of the unitsPerEM value)
  759. string16(winAscent) + // usWinAscent
  760. string16(winDescent) + // usWinDescent
  761. "\x00\x00\x00\x00" + // ulCodePageRange1 (Bits 0-31)
  762. "\x00\x00\x00\x00" + // ulCodePageRange2 (Bits 32-63)
  763. string16(properties.xHeight) + // sxHeight
  764. string16(properties.capHeight) + // sCapHeight
  765. string16(0) + // usDefaultChar
  766. string16(firstCharIndex || properties.firstChar) + // usBreakChar
  767. "\x00\x03"
  768. ); // usMaxContext
  769. }
  770. function createPostTable(properties) {
  771. const angle = Math.floor(properties.italicAngle * 2 ** 16);
  772. return (
  773. "\x00\x03\x00\x00" + // Version number
  774. string32(angle) + // italicAngle
  775. "\x00\x00" + // underlinePosition
  776. "\x00\x00" + // underlineThickness
  777. string32(properties.fixedPitch ? 1 : 0) + // isFixedPitch
  778. "\x00\x00\x00\x00" + // minMemType42
  779. "\x00\x00\x00\x00" + // maxMemType42
  780. "\x00\x00\x00\x00" + // minMemType1
  781. "\x00\x00\x00\x00"
  782. ); // maxMemType1
  783. }
  784. function createPostscriptName(name) {
  785. // See https://docs.microsoft.com/en-us/typography/opentype/spec/recom#name.
  786. return name.replace(/[^\x21-\x7E]|[[\](){}<>/%]/g, "").slice(0, 63);
  787. }
  788. function createNameTable(name, proto) {
  789. if (!proto) {
  790. proto = [[], []]; // no strings and unicode strings
  791. }
  792. const strings = [
  793. proto[0][0] || "Original licence", // 0.Copyright
  794. proto[0][1] || name, // 1.Font family
  795. proto[0][2] || "Unknown", // 2.Font subfamily (font weight)
  796. proto[0][3] || "uniqueID", // 3.Unique ID
  797. proto[0][4] || name, // 4.Full font name
  798. proto[0][5] || "Version 0.11", // 5.Version
  799. proto[0][6] || createPostscriptName(name), // 6.Postscript name
  800. proto[0][7] || "Unknown", // 7.Trademark
  801. proto[0][8] || "Unknown", // 8.Manufacturer
  802. proto[0][9] || "Unknown", // 9.Designer
  803. ];
  804. // Mac want 1-byte per character strings while Windows want
  805. // 2-bytes per character, so duplicate the names table
  806. const stringsUnicode = [];
  807. let i, ii, j, jj, str;
  808. for (i = 0, ii = strings.length; i < ii; i++) {
  809. str = proto[1][i] || strings[i];
  810. const strBufUnicode = [];
  811. for (j = 0, jj = str.length; j < jj; j++) {
  812. strBufUnicode.push(string16(str.charCodeAt(j)));
  813. }
  814. stringsUnicode.push(strBufUnicode.join(""));
  815. }
  816. const names = [strings, stringsUnicode];
  817. const platforms = ["\x00\x01", "\x00\x03"];
  818. const encodings = ["\x00\x00", "\x00\x01"];
  819. const languages = ["\x00\x00", "\x04\x09"];
  820. const namesRecordCount = strings.length * platforms.length;
  821. let nameTable =
  822. "\x00\x00" + // format
  823. string16(namesRecordCount) + // Number of names Record
  824. string16(namesRecordCount * 12 + 6); // Storage
  825. // Build the name records field
  826. let strOffset = 0;
  827. for (i = 0, ii = platforms.length; i < ii; i++) {
  828. const strs = names[i];
  829. for (j = 0, jj = strs.length; j < jj; j++) {
  830. str = strs[j];
  831. const nameRecord =
  832. platforms[i] + // platform ID
  833. encodings[i] + // encoding ID
  834. languages[i] + // language ID
  835. string16(j) + // name ID
  836. string16(str.length) +
  837. string16(strOffset);
  838. nameTable += nameRecord;
  839. strOffset += str.length;
  840. }
  841. }
  842. nameTable += strings.join("") + stringsUnicode.join("");
  843. return nameTable;
  844. }
  845. /**
  846. * 'Font' is the class the outside world should use, it encapsulate all the font
  847. * decoding logics whatever type it is (assuming the font type is supported).
  848. */
  849. class Font {
  850. constructor(name, file, properties) {
  851. this.name = name;
  852. this.psName = null;
  853. this.mimetype = null;
  854. this.disableFontFace = false;
  855. this.loadedName = properties.loadedName;
  856. this.isType3Font = properties.isType3Font;
  857. this.missingFile = false;
  858. this.cssFontInfo = properties.cssFontInfo;
  859. this._charsCache = Object.create(null);
  860. this._glyphCache = Object.create(null);
  861. let isSerifFont = !!(properties.flags & FontFlags.Serif);
  862. // Fallback to checking the font name, in order to improve text-selection,
  863. // since the /Flags-entry is often wrong (fixes issue13845.pdf).
  864. if (!isSerifFont && !properties.isSimulatedFlags) {
  865. const baseName = name.replace(/[,_]/g, "-").split("-")[0],
  866. serifFonts = getSerifFonts();
  867. for (const namePart of baseName.split("+")) {
  868. if (serifFonts[namePart]) {
  869. isSerifFont = true;
  870. break;
  871. }
  872. }
  873. }
  874. this.isSerifFont = isSerifFont;
  875. this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
  876. this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);
  877. let type = properties.type;
  878. let subtype = properties.subtype;
  879. this.type = type;
  880. this.subtype = subtype;
  881. const matches = name.match(/^InvalidPDFjsFont_(.*)_\d+$/);
  882. this.isInvalidPDFjsFont = !!matches;
  883. if (this.isInvalidPDFjsFont) {
  884. this.fallbackName = matches[1];
  885. } else if (this.isMonospace) {
  886. this.fallbackName = "monospace";
  887. } else if (this.isSerifFont) {
  888. this.fallbackName = "serif";
  889. } else {
  890. this.fallbackName = "sans-serif";
  891. }
  892. this.differences = properties.differences;
  893. this.widths = properties.widths;
  894. this.defaultWidth = properties.defaultWidth;
  895. this.composite = properties.composite;
  896. this.cMap = properties.cMap;
  897. this.capHeight = properties.capHeight / PDF_GLYPH_SPACE_UNITS;
  898. this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
  899. this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
  900. this.lineHeight = this.ascent - this.descent;
  901. this.fontMatrix = properties.fontMatrix;
  902. this.bbox = properties.bbox;
  903. this.defaultEncoding = properties.defaultEncoding;
  904. this.toUnicode = properties.toUnicode;
  905. this.toFontChar = [];
  906. if (properties.type === "Type3") {
  907. for (let charCode = 0; charCode < 256; charCode++) {
  908. this.toFontChar[charCode] =
  909. this.differences[charCode] || properties.defaultEncoding[charCode];
  910. }
  911. this.fontType = FontType.TYPE3;
  912. return;
  913. }
  914. this.cidEncoding = properties.cidEncoding || "";
  915. this.vertical = !!properties.vertical;
  916. if (this.vertical) {
  917. this.vmetrics = properties.vmetrics;
  918. this.defaultVMetrics = properties.defaultVMetrics;
  919. }
  920. if (!file || file.isEmpty) {
  921. if (file) {
  922. // Some bad PDF generators will include empty font files,
  923. // attempting to recover by assuming that no file exists.
  924. warn('Font file is empty in "' + name + '" (' + this.loadedName + ")");
  925. }
  926. this.fallbackToSystemFont(properties);
  927. return;
  928. }
  929. // Parse the font file to determine the correct type/subtype, rather than
  930. // relying on the (often incorrect) data in the font dictionary; (see e.g.
  931. // issue6782.pdf, issue7598.pdf, and issue9949.pdf).
  932. [type, subtype] = getFontFileType(file, properties);
  933. if (type !== this.type || subtype !== this.subtype) {
  934. info(
  935. "Inconsistent font file Type/SubType, expected: " +
  936. `${this.type}/${this.subtype} but found: ${type}/${subtype}.`
  937. );
  938. }
  939. let data;
  940. try {
  941. switch (type) {
  942. case "MMType1":
  943. info("MMType1 font (" + name + "), falling back to Type1.");
  944. /* falls through */
  945. case "Type1":
  946. case "CIDFontType0":
  947. this.mimetype = "font/opentype";
  948. const cff =
  949. subtype === "Type1C" || subtype === "CIDFontType0C"
  950. ? new CFFFont(file, properties)
  951. : new Type1Font(name, file, properties);
  952. adjustWidths(properties);
  953. // Wrap the CFF data inside an OTF font file
  954. data = this.convert(name, cff, properties);
  955. break;
  956. case "OpenType":
  957. case "TrueType":
  958. case "CIDFontType2":
  959. this.mimetype = "font/opentype";
  960. // Repair the TrueType file. It is can be damaged in the point of
  961. // view of the sanitizer
  962. data = this.checkAndRepair(name, file, properties);
  963. if (this.isOpenType) {
  964. adjustWidths(properties);
  965. type = "OpenType";
  966. }
  967. break;
  968. default:
  969. throw new FormatError(`Font ${type} is not supported`);
  970. }
  971. } catch (e) {
  972. warn(e);
  973. this.fallbackToSystemFont(properties);
  974. return;
  975. }
  976. amendFallbackToUnicode(properties);
  977. this.data = data;
  978. this.fontType = getFontType(type, subtype, properties.isStandardFont);
  979. // Transfer some properties again that could change during font conversion
  980. this.fontMatrix = properties.fontMatrix;
  981. this.widths = properties.widths;
  982. this.defaultWidth = properties.defaultWidth;
  983. this.toUnicode = properties.toUnicode;
  984. this.seacMap = properties.seacMap;
  985. }
  986. get renderer() {
  987. const renderer = FontRendererFactory.create(this, SEAC_ANALYSIS_ENABLED);
  988. return shadow(this, "renderer", renderer);
  989. }
  990. exportData(extraProperties = false) {
  991. const exportDataProperties = extraProperties
  992. ? [...EXPORT_DATA_PROPERTIES, ...EXPORT_DATA_EXTRA_PROPERTIES]
  993. : EXPORT_DATA_PROPERTIES;
  994. const data = Object.create(null);
  995. let property, value;
  996. for (property of exportDataProperties) {
  997. value = this[property];
  998. // Ignore properties that haven't been explicitly set.
  999. if (value !== undefined) {
  1000. data[property] = value;
  1001. }
  1002. }
  1003. return data;
  1004. }
  1005. fallbackToSystemFont(properties) {
  1006. this.missingFile = true;
  1007. // The file data is not specified. Trying to fix the font name
  1008. // to be used with the canvas.font.
  1009. const name = this.name;
  1010. const type = this.type;
  1011. const subtype = this.subtype;
  1012. let fontName = normalizeFontName(name);
  1013. const stdFontMap = getStdFontMap(),
  1014. nonStdFontMap = getNonStdFontMap();
  1015. const isStandardFont = !!stdFontMap[fontName];
  1016. const isMappedToStandardFont = !!(
  1017. nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]
  1018. );
  1019. fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
  1020. const fontBasicMetricsMap = getFontBasicMetrics();
  1021. const metrics = fontBasicMetricsMap[fontName];
  1022. if (metrics) {
  1023. if (isNaN(this.ascent)) {
  1024. this.ascent = metrics.ascent / PDF_GLYPH_SPACE_UNITS;
  1025. }
  1026. if (isNaN(this.descent)) {
  1027. this.descent = metrics.descent / PDF_GLYPH_SPACE_UNITS;
  1028. }
  1029. if (isNaN(this.capHeight)) {
  1030. this.capHeight = metrics.capHeight / PDF_GLYPH_SPACE_UNITS;
  1031. }
  1032. }
  1033. this.bold = /bold/gi.test(fontName);
  1034. this.italic = /oblique|italic/gi.test(fontName);
  1035. // Use 'name' instead of 'fontName' here because the original
  1036. // name ArialBlack for example will be replaced by Helvetica.
  1037. this.black = /Black/g.test(name);
  1038. // Use 'name' instead of 'fontName' here because the original
  1039. // name ArialNarrow for example will be replaced by Helvetica.
  1040. const isNarrow = /Narrow/g.test(name);
  1041. // if at least one width is present, remeasure all chars when exists
  1042. this.remeasure =
  1043. (!isStandardFont || isNarrow) && Object.keys(this.widths).length > 0;
  1044. if (
  1045. (isStandardFont || isMappedToStandardFont) &&
  1046. type === "CIDFontType2" &&
  1047. this.cidEncoding.startsWith("Identity-")
  1048. ) {
  1049. const cidToGidMap = properties.cidToGidMap;
  1050. // Standard fonts might be embedded as CID font without glyph mapping.
  1051. // Building one based on GlyphMapForStandardFonts.
  1052. const map = [];
  1053. applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts());
  1054. if (/Arial-?Black/i.test(name)) {
  1055. applyStandardFontGlyphMap(map, getSupplementalGlyphMapForArialBlack());
  1056. } else if (/Calibri/i.test(name)) {
  1057. applyStandardFontGlyphMap(map, getSupplementalGlyphMapForCalibri());
  1058. }
  1059. // Always update the glyph mapping with the `cidToGidMap` when it exists
  1060. // (fixes issue12418_reduced.pdf).
  1061. if (cidToGidMap) {
  1062. for (const charCode in map) {
  1063. const cid = map[charCode];
  1064. if (cidToGidMap[cid] !== undefined) {
  1065. map[+charCode] = cidToGidMap[cid];
  1066. }
  1067. }
  1068. // When the /CIDToGIDMap is "incomplete", fallback to the included
  1069. // /ToUnicode-map regardless of its encoding (fixes issue11915.pdf).
  1070. if (
  1071. cidToGidMap.length !== this.toUnicode.length &&
  1072. properties.hasIncludedToUnicodeMap &&
  1073. this.toUnicode instanceof IdentityToUnicodeMap
  1074. ) {
  1075. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  1076. const cid = map[charCode];
  1077. if (cidToGidMap[cid] === undefined) {
  1078. map[+charCode] = unicodeCharCode;
  1079. }
  1080. });
  1081. }
  1082. }
  1083. if (!(this.toUnicode instanceof IdentityToUnicodeMap)) {
  1084. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  1085. map[+charCode] = unicodeCharCode;
  1086. });
  1087. }
  1088. this.toFontChar = map;
  1089. this.toUnicode = new ToUnicodeMap(map);
  1090. } else if (/Symbol/i.test(fontName)) {
  1091. this.toFontChar = buildToFontChar(
  1092. SymbolSetEncoding,
  1093. getGlyphsUnicode(),
  1094. this.differences
  1095. );
  1096. } else if (/Dingbats/i.test(fontName)) {
  1097. if (/Wingdings/i.test(name)) {
  1098. warn("Non-embedded Wingdings font, falling back to ZapfDingbats.");
  1099. }
  1100. this.toFontChar = buildToFontChar(
  1101. ZapfDingbatsEncoding,
  1102. getDingbatsGlyphsUnicode(),
  1103. this.differences
  1104. );
  1105. } else if (isStandardFont) {
  1106. const map = buildToFontChar(
  1107. this.defaultEncoding,
  1108. getGlyphsUnicode(),
  1109. this.differences
  1110. );
  1111. if (
  1112. type === "CIDFontType2" &&
  1113. !this.cidEncoding.startsWith("Identity-") &&
  1114. !(this.toUnicode instanceof IdentityToUnicodeMap)
  1115. ) {
  1116. this.toUnicode.forEach(function (charCode, unicodeCharCode) {
  1117. map[+charCode] = unicodeCharCode;
  1118. });
  1119. }
  1120. this.toFontChar = map;
  1121. } else {
  1122. const glyphsUnicodeMap = getGlyphsUnicode();
  1123. const map = [];
  1124. this.toUnicode.forEach((charCode, unicodeCharCode) => {
  1125. if (!this.composite) {
  1126. const glyphName =
  1127. this.differences[charCode] || this.defaultEncoding[charCode];
  1128. const unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
  1129. if (unicode !== -1) {
  1130. unicodeCharCode = unicode;
  1131. }
  1132. }
  1133. map[+charCode] = unicodeCharCode;
  1134. });
  1135. // Attempt to improve the glyph mapping for (some) composite fonts that
  1136. // appear to lack meaningful ToUnicode data.
  1137. if (this.composite && this.toUnicode instanceof IdentityToUnicodeMap) {
  1138. if (/Tahoma|Verdana/i.test(name)) {
  1139. // Fixes issue15719.pdf and issue11242_reduced.pdf.
  1140. applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts());
  1141. }
  1142. }
  1143. this.toFontChar = map;
  1144. }
  1145. amendFallbackToUnicode(properties);
  1146. this.loadedName = fontName.split("-")[0];
  1147. this.fontType = getFontType(type, subtype, properties.isStandardFont);
  1148. }
  1149. checkAndRepair(name, font, properties) {
  1150. const VALID_TABLES = [
  1151. "OS/2",
  1152. "cmap",
  1153. "head",
  1154. "hhea",
  1155. "hmtx",
  1156. "maxp",
  1157. "name",
  1158. "post",
  1159. "loca",
  1160. "glyf",
  1161. "fpgm",
  1162. "prep",
  1163. "cvt ",
  1164. "CFF ",
  1165. ];
  1166. function readTables(file, numTables) {
  1167. const tables = Object.create(null);
  1168. tables["OS/2"] = null;
  1169. tables.cmap = null;
  1170. tables.head = null;
  1171. tables.hhea = null;
  1172. tables.hmtx = null;
  1173. tables.maxp = null;
  1174. tables.name = null;
  1175. tables.post = null;
  1176. for (let i = 0; i < numTables; i++) {
  1177. const table = readTableEntry(file);
  1178. if (!VALID_TABLES.includes(table.tag)) {
  1179. continue; // skipping table if it's not a required or optional table
  1180. }
  1181. if (table.length === 0) {
  1182. continue; // skipping empty tables
  1183. }
  1184. tables[table.tag] = table;
  1185. }
  1186. return tables;
  1187. }
  1188. function readTableEntry(file) {
  1189. const tag = file.getString(4);
  1190. const checksum = file.getInt32() >>> 0;
  1191. const offset = file.getInt32() >>> 0;
  1192. const length = file.getInt32() >>> 0;
  1193. // Read the table associated data
  1194. const previousPosition = file.pos;
  1195. file.pos = file.start || 0;
  1196. file.skip(offset);
  1197. const data = file.getBytes(length);
  1198. file.pos = previousPosition;
  1199. if (tag === "head") {
  1200. // clearing checksum adjustment
  1201. data[8] = data[9] = data[10] = data[11] = 0;
  1202. data[17] |= 0x20; // Set font optimized for cleartype flag.
  1203. }
  1204. return {
  1205. tag,
  1206. checksum,
  1207. length,
  1208. offset,
  1209. data,
  1210. };
  1211. }
  1212. function readOpenTypeHeader(ttf) {
  1213. return {
  1214. version: ttf.getString(4),
  1215. numTables: ttf.getUint16(),
  1216. searchRange: ttf.getUint16(),
  1217. entrySelector: ttf.getUint16(),
  1218. rangeShift: ttf.getUint16(),
  1219. };
  1220. }
  1221. function readTrueTypeCollectionHeader(ttc) {
  1222. const ttcTag = ttc.getString(4);
  1223. assert(ttcTag === "ttcf", "Must be a TrueType Collection font.");
  1224. const majorVersion = ttc.getUint16();
  1225. const minorVersion = ttc.getUint16();
  1226. const numFonts = ttc.getInt32() >>> 0;
  1227. const offsetTable = [];
  1228. for (let i = 0; i < numFonts; i++) {
  1229. offsetTable.push(ttc.getInt32() >>> 0);
  1230. }
  1231. const header = {
  1232. ttcTag,
  1233. majorVersion,
  1234. minorVersion,
  1235. numFonts,
  1236. offsetTable,
  1237. };
  1238. switch (majorVersion) {
  1239. case 1:
  1240. return header;
  1241. case 2:
  1242. header.dsigTag = ttc.getInt32() >>> 0;
  1243. header.dsigLength = ttc.getInt32() >>> 0;
  1244. header.dsigOffset = ttc.getInt32() >>> 0;
  1245. return header;
  1246. }
  1247. throw new FormatError(
  1248. `Invalid TrueType Collection majorVersion: ${majorVersion}.`
  1249. );
  1250. }
  1251. function readTrueTypeCollectionData(ttc, fontName) {
  1252. const { numFonts, offsetTable } = readTrueTypeCollectionHeader(ttc);
  1253. const fontNameParts = fontName.split("+");
  1254. let fallbackData;
  1255. for (let i = 0; i < numFonts; i++) {
  1256. ttc.pos = (ttc.start || 0) + offsetTable[i];
  1257. const potentialHeader = readOpenTypeHeader(ttc);
  1258. const potentialTables = readTables(ttc, potentialHeader.numTables);
  1259. if (!potentialTables.name) {
  1260. throw new FormatError(
  1261. 'TrueType Collection font must contain a "name" table.'
  1262. );
  1263. }
  1264. const nameTable = readNameTable(potentialTables.name);
  1265. for (let j = 0, jj = nameTable.length; j < jj; j++) {
  1266. for (let k = 0, kk = nameTable[j].length; k < kk; k++) {
  1267. const nameEntry =
  1268. nameTable[j][k] && nameTable[j][k].replace(/\s/g, "");
  1269. if (!nameEntry) {
  1270. continue;
  1271. }
  1272. if (nameEntry === fontName) {
  1273. return {
  1274. header: potentialHeader,
  1275. tables: potentialTables,
  1276. };
  1277. }
  1278. if (fontNameParts.length < 2) {
  1279. continue;
  1280. }
  1281. for (const part of fontNameParts) {
  1282. if (nameEntry === part) {
  1283. fallbackData = {
  1284. name: part,
  1285. header: potentialHeader,
  1286. tables: potentialTables,
  1287. };
  1288. }
  1289. }
  1290. }
  1291. }
  1292. }
  1293. if (fallbackData) {
  1294. warn(
  1295. `TrueType Collection does not contain "${fontName}" font, ` +
  1296. `falling back to "${fallbackData.name}" font instead.`
  1297. );
  1298. return {
  1299. header: fallbackData.header,
  1300. tables: fallbackData.tables,
  1301. };
  1302. }
  1303. throw new FormatError(
  1304. `TrueType Collection does not contain "${fontName}" font.`
  1305. );
  1306. }
  1307. /**
  1308. * Read the appropriate subtable from the cmap according to 9.6.6.4 from
  1309. * PDF spec
  1310. */
  1311. function readCmapTable(cmap, file, isSymbolicFont, hasEncoding) {
  1312. if (!cmap) {
  1313. warn("No cmap table available.");
  1314. return {
  1315. platformId: -1,
  1316. encodingId: -1,
  1317. mappings: [],
  1318. hasShortCmap: false,
  1319. };
  1320. }
  1321. let segment;
  1322. let start = (file.start || 0) + cmap.offset;
  1323. file.pos = start;
  1324. file.skip(2); // version
  1325. const numTables = file.getUint16();
  1326. let potentialTable;
  1327. let canBreak = false;
  1328. // There's an order of preference in terms of which cmap subtable to
  1329. // use:
  1330. // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
  1331. // - symbolic fonts the preference is a 3,0 table then a 1,0 table
  1332. // The following takes advantage of the fact that the tables are sorted
  1333. // to work.
  1334. for (let i = 0; i < numTables; i++) {
  1335. const platformId = file.getUint16();
  1336. const encodingId = file.getUint16();
  1337. const offset = file.getInt32() >>> 0;
  1338. let useTable = false;
  1339. // Sometimes there are multiple of the same type of table. Default
  1340. // to choosing the first table and skip the rest.
  1341. if (
  1342. potentialTable &&
  1343. potentialTable.platformId === platformId &&
  1344. potentialTable.encodingId === encodingId
  1345. ) {
  1346. continue;
  1347. }
  1348. if (
  1349. platformId === 0 &&
  1350. (encodingId === /* Unicode Default */ 0 ||
  1351. encodingId === /* Unicode 1.1 */ 1 ||
  1352. encodingId === /* Unicode BMP */ 3)
  1353. ) {
  1354. useTable = true;
  1355. // Continue the loop since there still may be a higher priority
  1356. // table.
  1357. } else if (platformId === 1 && encodingId === 0) {
  1358. useTable = true;
  1359. // Continue the loop since there still may be a higher priority
  1360. // table.
  1361. } else if (
  1362. platformId === 3 &&
  1363. encodingId === 1 &&
  1364. (hasEncoding || !potentialTable)
  1365. ) {
  1366. useTable = true;
  1367. if (!isSymbolicFont) {
  1368. canBreak = true;
  1369. }
  1370. } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
  1371. useTable = true;
  1372. let correctlySorted = true;
  1373. if (i < numTables - 1) {
  1374. const nextBytes = file.peekBytes(2),
  1375. nextPlatformId = int16(nextBytes[0], nextBytes[1]);
  1376. if (nextPlatformId < platformId) {
  1377. correctlySorted = false;
  1378. }
  1379. }
  1380. if (correctlySorted) {
  1381. canBreak = true;
  1382. }
  1383. }
  1384. if (useTable) {
  1385. potentialTable = {
  1386. platformId,
  1387. encodingId,
  1388. offset,
  1389. };
  1390. }
  1391. if (canBreak) {
  1392. break;
  1393. }
  1394. }
  1395. if (potentialTable) {
  1396. file.pos = start + potentialTable.offset;
  1397. }
  1398. if (!potentialTable || file.peekByte() === -1) {
  1399. warn("Could not find a preferred cmap table.");
  1400. return {
  1401. platformId: -1,
  1402. encodingId: -1,
  1403. mappings: [],
  1404. hasShortCmap: false,
  1405. };
  1406. }
  1407. const format = file.getUint16();
  1408. let hasShortCmap = false;
  1409. const mappings = [];
  1410. let j, glyphId;
  1411. // TODO(mack): refactor this cmap subtable reading logic out
  1412. if (format === 0) {
  1413. file.skip(2 + 2); // length + language
  1414. for (j = 0; j < 256; j++) {
  1415. const index = file.getByte();
  1416. if (!index) {
  1417. continue;
  1418. }
  1419. mappings.push({
  1420. charCode: j,
  1421. glyphId: index,
  1422. });
  1423. }
  1424. hasShortCmap = true;
  1425. } else if (format === 2) {
  1426. file.skip(2 + 2); // length + language
  1427. const subHeaderKeys = [];
  1428. let maxSubHeaderKey = 0;
  1429. // Read subHeaderKeys. If subHeaderKeys[i] === 0, then i is a
  1430. // single-byte character. Otherwise, i is the first byte of a
  1431. // multi-byte character, and the value is 8*index into
  1432. // subHeaders.
  1433. for (let i = 0; i < 256; i++) {
  1434. const subHeaderKey = file.getUint16() >> 3;
  1435. subHeaderKeys.push(subHeaderKey);
  1436. maxSubHeaderKey = Math.max(subHeaderKey, maxSubHeaderKey);
  1437. }
  1438. // Read subHeaders. The number of entries is determined
  1439. // dynamically based on the subHeaderKeys found above.
  1440. const subHeaders = [];
  1441. for (let i = 0; i <= maxSubHeaderKey; i++) {
  1442. subHeaders.push({
  1443. firstCode: file.getUint16(),
  1444. entryCount: file.getUint16(),
  1445. idDelta: signedInt16(file.getByte(), file.getByte()),
  1446. idRangePos: file.pos + file.getUint16(),
  1447. });
  1448. }
  1449. for (let i = 0; i < 256; i++) {
  1450. if (subHeaderKeys[i] === 0) {
  1451. // i is a single-byte code.
  1452. file.pos = subHeaders[0].idRangePos + 2 * i;
  1453. glyphId = file.getUint16();
  1454. mappings.push({
  1455. charCode: i,
  1456. glyphId,
  1457. });
  1458. } else {
  1459. // i is the first byte of a two-byte code.
  1460. const s = subHeaders[subHeaderKeys[i]];
  1461. for (j = 0; j < s.entryCount; j++) {
  1462. const charCode = (i << 8) + j + s.firstCode;
  1463. file.pos = s.idRangePos + 2 * j;
  1464. glyphId = file.getUint16();
  1465. if (glyphId !== 0) {
  1466. glyphId = (glyphId + s.idDelta) % 65536;
  1467. }
  1468. mappings.push({
  1469. charCode,
  1470. glyphId,
  1471. });
  1472. }
  1473. }
  1474. }
  1475. } else if (format === 4) {
  1476. file.skip(2 + 2); // length + language
  1477. // re-creating the table in format 4 since the encoding
  1478. // might be changed
  1479. const segCount = file.getUint16() >> 1;
  1480. file.skip(6); // skipping range fields
  1481. const segments = [];
  1482. let segIndex;
  1483. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1484. segments.push({ end: file.getUint16() });
  1485. }
  1486. file.skip(2);
  1487. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1488. segments[segIndex].start = file.getUint16();
  1489. }
  1490. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1491. segments[segIndex].delta = file.getUint16();
  1492. }
  1493. let offsetsCount = 0,
  1494. offsetIndex;
  1495. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1496. segment = segments[segIndex];
  1497. const rangeOffset = file.getUint16();
  1498. if (!rangeOffset) {
  1499. segment.offsetIndex = -1;
  1500. continue;
  1501. }
  1502. offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
  1503. segment.offsetIndex = offsetIndex;
  1504. offsetsCount = Math.max(
  1505. offsetsCount,
  1506. offsetIndex + segment.end - segment.start + 1
  1507. );
  1508. }
  1509. const offsets = [];
  1510. for (j = 0; j < offsetsCount; j++) {
  1511. offsets.push(file.getUint16());
  1512. }
  1513. for (segIndex = 0; segIndex < segCount; segIndex++) {
  1514. segment = segments[segIndex];
  1515. start = segment.start;
  1516. const end = segment.end;
  1517. const delta = segment.delta;
  1518. offsetIndex = segment.offsetIndex;
  1519. for (j = start; j <= end; j++) {
  1520. if (j === 0xffff) {
  1521. continue;
  1522. }
  1523. glyphId = offsetIndex < 0 ? j : offsets[offsetIndex + j - start];
  1524. glyphId = (glyphId + delta) & 0xffff;
  1525. mappings.push({
  1526. charCode: j,
  1527. glyphId,
  1528. });
  1529. }
  1530. }
  1531. } else if (format === 6) {
  1532. file.skip(2 + 2); // length + language
  1533. // Format 6 is a 2-bytes dense mapping, which means the font data
  1534. // lives glue together even if they are pretty far in the unicode
  1535. // table. (This looks weird, so I can have missed something), this
  1536. // works on Linux but seems to fails on Mac so let's rewrite the
  1537. // cmap table to a 3-1-4 style
  1538. const firstCode = file.getUint16();
  1539. const entryCount = file.getUint16();
  1540. for (j = 0; j < entryCount; j++) {
  1541. glyphId = file.getUint16();
  1542. const charCode = firstCode + j;
  1543. mappings.push({
  1544. charCode,
  1545. glyphId,
  1546. });
  1547. }
  1548. } else if (format === 12) {
  1549. file.skip(2 + 4 + 4); // reserved + length + language
  1550. const nGroups = file.getInt32() >>> 0;
  1551. for (j = 0; j < nGroups; j++) {
  1552. const startCharCode = file.getInt32() >>> 0;
  1553. const endCharCode = file.getInt32() >>> 0;
  1554. let glyphCode = file.getInt32() >>> 0;
  1555. for (
  1556. let charCode = startCharCode;
  1557. charCode <= endCharCode;
  1558. charCode++
  1559. ) {
  1560. mappings.push({
  1561. charCode,
  1562. glyphId: glyphCode++,
  1563. });
  1564. }
  1565. }
  1566. } else {
  1567. warn("cmap table has unsupported format: " + format);
  1568. return {
  1569. platformId: -1,
  1570. encodingId: -1,
  1571. mappings: [],
  1572. hasShortCmap: false,
  1573. };
  1574. }
  1575. // removing duplicate entries
  1576. mappings.sort(function (a, b) {
  1577. return a.charCode - b.charCode;
  1578. });
  1579. for (let i = 1; i < mappings.length; i++) {
  1580. if (mappings[i - 1].charCode === mappings[i].charCode) {
  1581. mappings.splice(i, 1);
  1582. i--;
  1583. }
  1584. }
  1585. return {
  1586. platformId: potentialTable.platformId,
  1587. encodingId: potentialTable.encodingId,
  1588. mappings,
  1589. hasShortCmap,
  1590. };
  1591. }
  1592. function sanitizeMetrics(
  1593. file,
  1594. header,
  1595. metrics,
  1596. headTable,
  1597. numGlyphs,
  1598. dupFirstEntry
  1599. ) {
  1600. if (!header) {
  1601. if (metrics) {
  1602. metrics.data = null;
  1603. }
  1604. return;
  1605. }
  1606. file.pos = (file.start || 0) + header.offset;
  1607. file.pos += 4; // version
  1608. file.pos += 2; // ascent
  1609. file.pos += 2; // descent
  1610. file.pos += 2; // linegap
  1611. file.pos += 2; // adv_width_max
  1612. file.pos += 2; // min_sb1
  1613. file.pos += 2; // min_sb2
  1614. file.pos += 2; // max_extent
  1615. file.pos += 2; // caret_slope_rise
  1616. file.pos += 2; // caret_slope_run
  1617. const caretOffset = file.getUint16();
  1618. file.pos += 8; // reserved
  1619. file.pos += 2; // format
  1620. let numOfMetrics = file.getUint16();
  1621. if (caretOffset !== 0) {
  1622. const macStyle = int16(headTable.data[44], headTable.data[45]);
  1623. if (!(macStyle & 2)) {
  1624. // Suppress OTS warnings about the `caretOffset` in the hhea-table.
  1625. header.data[22] = 0;
  1626. header.data[23] = 0;
  1627. }
  1628. }
  1629. if (numOfMetrics > numGlyphs) {
  1630. info(
  1631. `The numOfMetrics (${numOfMetrics}) should not be ` +
  1632. `greater than the numGlyphs (${numGlyphs}).`
  1633. );
  1634. // Reduce numOfMetrics if it is greater than numGlyphs
  1635. numOfMetrics = numGlyphs;
  1636. header.data[34] = (numOfMetrics & 0xff00) >> 8;
  1637. header.data[35] = numOfMetrics & 0x00ff;
  1638. }
  1639. const numOfSidebearings = numGlyphs - numOfMetrics;
  1640. const numMissing =
  1641. numOfSidebearings - ((metrics.length - numOfMetrics * 4) >> 1);
  1642. if (numMissing > 0) {
  1643. // For each missing glyph, we set both the width and lsb to 0 (zero).
  1644. // Since we need to add two properties for each glyph, this explains
  1645. // the use of |numMissing * 2| when initializing the typed array.
  1646. const entries = new Uint8Array(metrics.length + numMissing * 2);
  1647. entries.set(metrics.data);
  1648. if (dupFirstEntry) {
  1649. // Set the sidebearing value of the duplicated glyph.
  1650. entries[metrics.length] = metrics.data[2];
  1651. entries[metrics.length + 1] = metrics.data[3];
  1652. }
  1653. metrics.data = entries;
  1654. }
  1655. }
  1656. function sanitizeGlyph(
  1657. source,
  1658. sourceStart,
  1659. sourceEnd,
  1660. dest,
  1661. destStart,
  1662. hintsValid
  1663. ) {
  1664. const glyphProfile = {
  1665. length: 0,
  1666. sizeOfInstructions: 0,
  1667. };
  1668. if (sourceEnd - sourceStart <= 12) {
  1669. // glyph with data less than 12 is invalid one
  1670. return glyphProfile;
  1671. }
  1672. const glyf = source.subarray(sourceStart, sourceEnd);
  1673. let contoursCount = signedInt16(glyf[0], glyf[1]);
  1674. if (contoursCount < 0) {
  1675. // OTS doesn't like contour count to be less than -1.
  1676. contoursCount = -1;
  1677. writeSignedInt16(glyf, 0, contoursCount);
  1678. // complex glyph, writing as is
  1679. dest.set(glyf, destStart);
  1680. glyphProfile.length = glyf.length;
  1681. return glyphProfile;
  1682. }
  1683. let i,
  1684. j = 10,
  1685. flagsCount = 0;
  1686. for (i = 0; i < contoursCount; i++) {
  1687. const endPoint = (glyf[j] << 8) | glyf[j + 1];
  1688. flagsCount = endPoint + 1;
  1689. j += 2;
  1690. }
  1691. // skipping instructions
  1692. const instructionsStart = j;
  1693. const instructionsLength = (glyf[j] << 8) | glyf[j + 1];
  1694. glyphProfile.sizeOfInstructions = instructionsLength;
  1695. j += 2 + instructionsLength;
  1696. const instructionsEnd = j;
  1697. // validating flags
  1698. let coordinatesLength = 0;
  1699. for (i = 0; i < flagsCount; i++) {
  1700. const flag = glyf[j++];
  1701. if (flag & 0xc0) {
  1702. // reserved flags must be zero, cleaning up
  1703. glyf[j - 1] = flag & 0x3f;
  1704. }
  1705. let xLength = 2;
  1706. if (flag & 2) {
  1707. xLength = 1;
  1708. } else if (flag & 16) {
  1709. xLength = 0;
  1710. }
  1711. let yLength = 2;
  1712. if (flag & 4) {
  1713. yLength = 1;
  1714. } else if (flag & 32) {
  1715. yLength = 0;
  1716. }
  1717. const xyLength = xLength + yLength;
  1718. coordinatesLength += xyLength;
  1719. if (flag & 8) {
  1720. const repeat = glyf[j++];
  1721. i += repeat;
  1722. coordinatesLength += repeat * xyLength;
  1723. }
  1724. }
  1725. // glyph without coordinates will be rejected
  1726. if (coordinatesLength === 0) {
  1727. return glyphProfile;
  1728. }
  1729. let glyphDataLength = j + coordinatesLength;
  1730. if (glyphDataLength > glyf.length) {
  1731. // not enough data for coordinates
  1732. return glyphProfile;
  1733. }
  1734. if (!hintsValid && instructionsLength > 0) {
  1735. dest.set(glyf.subarray(0, instructionsStart), destStart);
  1736. dest.set([0, 0], destStart + instructionsStart);
  1737. dest.set(
  1738. glyf.subarray(instructionsEnd, glyphDataLength),
  1739. destStart + instructionsStart + 2
  1740. );
  1741. glyphDataLength -= instructionsLength;
  1742. if (glyf.length - glyphDataLength > 3) {
  1743. glyphDataLength = (glyphDataLength + 3) & ~3;
  1744. }
  1745. glyphProfile.length = glyphDataLength;
  1746. return glyphProfile;
  1747. }
  1748. if (glyf.length - glyphDataLength > 3) {
  1749. // truncating and aligning to 4 bytes the long glyph data
  1750. glyphDataLength = (glyphDataLength + 3) & ~3;
  1751. dest.set(glyf.subarray(0, glyphDataLength), destStart);
  1752. glyphProfile.length = glyphDataLength;
  1753. return glyphProfile;
  1754. }
  1755. // glyph data is fine
  1756. dest.set(glyf, destStart);
  1757. glyphProfile.length = glyf.length;
  1758. return glyphProfile;
  1759. }
  1760. function sanitizeHead(head, numGlyphs, locaLength) {
  1761. const data = head.data;
  1762. // Validate version:
  1763. // Should always be 0x00010000
  1764. const version = int32(data[0], data[1], data[2], data[3]);
  1765. if (version >> 16 !== 1) {
  1766. info("Attempting to fix invalid version in head table: " + version);
  1767. data[0] = 0;
  1768. data[1] = 1;
  1769. data[2] = 0;
  1770. data[3] = 0;
  1771. }
  1772. const indexToLocFormat = int16(data[50], data[51]);
  1773. if (indexToLocFormat < 0 || indexToLocFormat > 1) {
  1774. info(
  1775. "Attempting to fix invalid indexToLocFormat in head table: " +
  1776. indexToLocFormat
  1777. );
  1778. // The value of indexToLocFormat should be 0 if the loca table
  1779. // consists of short offsets, and should be 1 if the loca table
  1780. // consists of long offsets.
  1781. //
  1782. // The number of entries in the loca table should be numGlyphs + 1.
  1783. //
  1784. // Using this information, we can work backwards to deduce if the
  1785. // size of each offset in the loca table, and thus figure out the
  1786. // appropriate value for indexToLocFormat.
  1787. const numGlyphsPlusOne = numGlyphs + 1;
  1788. if (locaLength === numGlyphsPlusOne << 1) {
  1789. // 0x0000 indicates the loca table consists of short offsets
  1790. data[50] = 0;
  1791. data[51] = 0;
  1792. } else if (locaLength === numGlyphsPlusOne << 2) {
  1793. // 0x0001 indicates the loca table consists of long offsets
  1794. data[50] = 0;
  1795. data[51] = 1;
  1796. } else {
  1797. throw new FormatError(
  1798. "Could not fix indexToLocFormat: " + indexToLocFormat
  1799. );
  1800. }
  1801. }
  1802. }
  1803. function sanitizeGlyphLocations(
  1804. loca,
  1805. glyf,
  1806. numGlyphs,
  1807. isGlyphLocationsLong,
  1808. hintsValid,
  1809. dupFirstEntry,
  1810. maxSizeOfInstructions
  1811. ) {
  1812. let itemSize, itemDecode, itemEncode;
  1813. if (isGlyphLocationsLong) {
  1814. itemSize = 4;
  1815. itemDecode = function fontItemDecodeLong(data, offset) {
  1816. return (
  1817. (data[offset] << 24) |
  1818. (data[offset + 1] << 16) |
  1819. (data[offset + 2] << 8) |
  1820. data[offset + 3]
  1821. );
  1822. };
  1823. itemEncode = function fontItemEncodeLong(data, offset, value) {
  1824. data[offset] = (value >>> 24) & 0xff;
  1825. data[offset + 1] = (value >> 16) & 0xff;
  1826. data[offset + 2] = (value >> 8) & 0xff;
  1827. data[offset + 3] = value & 0xff;
  1828. };
  1829. } else {
  1830. itemSize = 2;
  1831. itemDecode = function fontItemDecode(data, offset) {
  1832. return (data[offset] << 9) | (data[offset + 1] << 1);
  1833. };
  1834. itemEncode = function fontItemEncode(data, offset, value) {
  1835. data[offset] = (value >> 9) & 0xff;
  1836. data[offset + 1] = (value >> 1) & 0xff;
  1837. };
  1838. }
  1839. // The first glyph is duplicated.
  1840. const numGlyphsOut = dupFirstEntry ? numGlyphs + 1 : numGlyphs;
  1841. const locaDataSize = itemSize * (1 + numGlyphsOut);
  1842. // Resize loca table to account for duplicated glyph.
  1843. const locaData = new Uint8Array(locaDataSize);
  1844. locaData.set(loca.data.subarray(0, locaDataSize));
  1845. loca.data = locaData;
  1846. // removing the invalid glyphs
  1847. const oldGlyfData = glyf.data;
  1848. const oldGlyfDataLength = oldGlyfData.length;
  1849. const newGlyfData = new Uint8Array(oldGlyfDataLength);
  1850. // The spec says the offsets should be in ascending order, however
  1851. // this is not true for some fonts or they use the offset of 0 to mark a
  1852. // glyph as missing. OTS requires the offsets to be in order and not to
  1853. // be zero, so we must sort and rebuild the loca table and potentially
  1854. // re-arrange the glyf data.
  1855. let i, j;
  1856. const locaEntries = [];
  1857. // There are numGlyphs + 1 loca table entries.
  1858. for (i = 0, j = 0; i < numGlyphs + 1; i++, j += itemSize) {
  1859. let offset = itemDecode(locaData, j);
  1860. if (offset > oldGlyfDataLength) {
  1861. offset = oldGlyfDataLength;
  1862. }
  1863. locaEntries.push({
  1864. index: i,
  1865. offset,
  1866. endOffset: 0,
  1867. });
  1868. }
  1869. locaEntries.sort((a, b) => {
  1870. return a.offset - b.offset;
  1871. });
  1872. // Now the offsets are sorted, calculate the end offset of each glyph.
  1873. // The last loca entry's endOffset is not calculated since it's the end
  1874. // of the data and will be stored on the previous entry's endOffset.
  1875. for (i = 0; i < numGlyphs; i++) {
  1876. locaEntries[i].endOffset = locaEntries[i + 1].offset;
  1877. }
  1878. // Re-sort so glyphs aren't out of order.
  1879. locaEntries.sort((a, b) => {
  1880. return a.index - b.index;
  1881. });
  1882. // Calculate the endOffset of the "first" glyph correctly when there are
  1883. // *multiple* empty ones at the start of the data (fixes issue14618.pdf).
  1884. for (i = 0; i < numGlyphs; i++) {
  1885. const { offset, endOffset } = locaEntries[i];
  1886. if (offset !== 0 || endOffset !== 0) {
  1887. break;
  1888. }
  1889. const nextOffset = locaEntries[i + 1].offset;
  1890. if (nextOffset === 0) {
  1891. continue;
  1892. }
  1893. locaEntries[i].endOffset = nextOffset;
  1894. break;
  1895. }
  1896. const missingGlyphs = Object.create(null);
  1897. let writeOffset = 0;
  1898. itemEncode(locaData, 0, writeOffset);
  1899. for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
  1900. const glyphProfile = sanitizeGlyph(
  1901. oldGlyfData,
  1902. locaEntries[i].offset,
  1903. locaEntries[i].endOffset,
  1904. newGlyfData,
  1905. writeOffset,
  1906. hintsValid
  1907. );
  1908. const newLength = glyphProfile.length;
  1909. if (newLength === 0) {
  1910. missingGlyphs[i] = true;
  1911. }
  1912. if (glyphProfile.sizeOfInstructions > maxSizeOfInstructions) {
  1913. maxSizeOfInstructions = glyphProfile.sizeOfInstructions;
  1914. }
  1915. writeOffset += newLength;
  1916. itemEncode(locaData, j, writeOffset);
  1917. }
  1918. if (writeOffset === 0) {
  1919. // glyf table cannot be empty -- redoing the glyf and loca tables
  1920. // to have single glyph with one point
  1921. const simpleGlyph = new Uint8Array([
  1922. 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0,
  1923. ]);
  1924. for (i = 0, j = itemSize; i < numGlyphsOut; i++, j += itemSize) {
  1925. itemEncode(locaData, j, simpleGlyph.length);
  1926. }
  1927. glyf.data = simpleGlyph;
  1928. } else if (dupFirstEntry) {
  1929. // Browsers will not display a glyph at position 0. Typically glyph 0
  1930. // is notdef, but a number of fonts put a valid glyph there so it must
  1931. // be duplicated and appended.
  1932. const firstEntryLength = itemDecode(locaData, itemSize);
  1933. if (newGlyfData.length > firstEntryLength + writeOffset) {
  1934. glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
  1935. } else {
  1936. glyf.data = new Uint8Array(firstEntryLength + writeOffset);
  1937. glyf.data.set(newGlyfData.subarray(0, writeOffset));
  1938. }
  1939. glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
  1940. itemEncode(
  1941. loca.data,
  1942. locaData.length - itemSize,
  1943. writeOffset + firstEntryLength
  1944. );
  1945. } else {
  1946. glyf.data = newGlyfData.subarray(0, writeOffset);
  1947. }
  1948. return {
  1949. missingGlyphs,
  1950. maxSizeOfInstructions,
  1951. };
  1952. }
  1953. function readPostScriptTable(post, propertiesObj, maxpNumGlyphs) {
  1954. const start = (font.start || 0) + post.offset;
  1955. font.pos = start;
  1956. const length = post.length,
  1957. end = start + length;
  1958. const version = font.getInt32();
  1959. // skip rest to the tables
  1960. font.skip(28);
  1961. let glyphNames;
  1962. let valid = true;
  1963. let i;
  1964. switch (version) {
  1965. case 0x00010000:
  1966. glyphNames = MacStandardGlyphOrdering;
  1967. break;
  1968. case 0x00020000:
  1969. const numGlyphs = font.getUint16();
  1970. if (numGlyphs !== maxpNumGlyphs) {
  1971. valid = false;
  1972. break;
  1973. }
  1974. const glyphNameIndexes = [];
  1975. for (i = 0; i < numGlyphs; ++i) {
  1976. const index = font.getUint16();
  1977. if (index >= 32768) {
  1978. valid = false;
  1979. break;
  1980. }
  1981. glyphNameIndexes.push(index);
  1982. }
  1983. if (!valid) {
  1984. break;
  1985. }
  1986. const customNames = [],
  1987. strBuf = [];
  1988. while (font.pos < end) {
  1989. const stringLength = font.getByte();
  1990. strBuf.length = stringLength;
  1991. for (i = 0; i < stringLength; ++i) {
  1992. strBuf[i] = String.fromCharCode(font.getByte());
  1993. }
  1994. customNames.push(strBuf.join(""));
  1995. }
  1996. glyphNames = [];
  1997. for (i = 0; i < numGlyphs; ++i) {
  1998. const j = glyphNameIndexes[i];
  1999. if (j < 258) {
  2000. glyphNames.push(MacStandardGlyphOrdering[j]);
  2001. continue;
  2002. }
  2003. glyphNames.push(customNames[j - 258]);
  2004. }
  2005. break;
  2006. case 0x00030000:
  2007. break;
  2008. default:
  2009. warn("Unknown/unsupported post table version " + version);
  2010. valid = false;
  2011. if (propertiesObj.defaultEncoding) {
  2012. glyphNames = propertiesObj.defaultEncoding;
  2013. }
  2014. break;
  2015. }
  2016. propertiesObj.glyphNames = glyphNames;
  2017. return valid;
  2018. }
  2019. function readNameTable(nameTable) {
  2020. const start = (font.start || 0) + nameTable.offset;
  2021. font.pos = start;
  2022. const names = [[], []];
  2023. const length = nameTable.length,
  2024. end = start + length;
  2025. const format = font.getUint16();
  2026. const FORMAT_0_HEADER_LENGTH = 6;
  2027. if (format !== 0 || length < FORMAT_0_HEADER_LENGTH) {
  2028. // unsupported name table format or table "too" small
  2029. return names;
  2030. }
  2031. const numRecords = font.getUint16();
  2032. const stringsStart = font.getUint16();
  2033. const records = [];
  2034. const NAME_RECORD_LENGTH = 12;
  2035. let i, ii;
  2036. for (i = 0; i < numRecords && font.pos + NAME_RECORD_LENGTH <= end; i++) {
  2037. const r = {
  2038. platform: font.getUint16(),
  2039. encoding: font.getUint16(),
  2040. language: font.getUint16(),
  2041. name: font.getUint16(),
  2042. length: font.getUint16(),
  2043. offset: font.getUint16(),
  2044. };
  2045. // using only Macintosh and Windows platform/encoding names
  2046. if (
  2047. (r.platform === 1 && r.encoding === 0 && r.language === 0) ||
  2048. (r.platform === 3 && r.encoding === 1 && r.language === 0x409)
  2049. ) {
  2050. records.push(r);
  2051. }
  2052. }
  2053. for (i = 0, ii = records.length; i < ii; i++) {
  2054. const record = records[i];
  2055. if (record.length <= 0) {
  2056. continue; // Nothing to process, ignoring.
  2057. }
  2058. const pos = start + stringsStart + record.offset;
  2059. if (pos + record.length > end) {
  2060. continue; // outside of name table, ignoring
  2061. }
  2062. font.pos = pos;
  2063. const nameIndex = record.name;
  2064. if (record.encoding) {
  2065. // unicode
  2066. let str = "";
  2067. for (let j = 0, jj = record.length; j < jj; j += 2) {
  2068. str += String.fromCharCode(font.getUint16());
  2069. }
  2070. names[1][nameIndex] = str;
  2071. } else {
  2072. names[0][nameIndex] = font.getString(record.length);
  2073. }
  2074. }
  2075. return names;
  2076. }
  2077. // prettier-ignore
  2078. const TTOpsStackDeltas = [
  2079. 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, 0, 0, -2, -5,
  2080. -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, -1, -1,
  2081. 1, -1, -999, 0, 1, 0, -1, -2, 0, -1, -2, -1, -1, 0, -1, -1,
  2082. 0, 0, -999, -999, -1, -1, -1, -1, -2, -999, -2, -2, -999, 0, -2, -2,
  2083. 0, 0, -2, 0, -2, 0, 0, 0, -2, -1, -1, 1, 1, 0, 0, -1,
  2084. -1, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, -1, 0, -999, -1, -1,
  2085. -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2086. -2, -999, -999, -999, -999, -999, -1, -1, -2, -2, 0, 0, 0, 0, -1, -1,
  2087. -999, -2, -2, 0, 0, -1, -2, -2, 0, 0, 0, -1, -1, -1, -2];
  2088. // 0xC0-DF == -1 and 0xE0-FF == -2
  2089. function sanitizeTTProgram(table, ttContext) {
  2090. let data = table.data;
  2091. let i = 0,
  2092. j,
  2093. n,
  2094. b,
  2095. funcId,
  2096. pc,
  2097. lastEndf = 0,
  2098. lastDeff = 0;
  2099. const stack = [];
  2100. const callstack = [];
  2101. const functionsCalled = [];
  2102. let tooComplexToFollowFunctions = ttContext.tooComplexToFollowFunctions;
  2103. let inFDEF = false,
  2104. ifLevel = 0,
  2105. inELSE = 0;
  2106. for (let ii = data.length; i < ii; ) {
  2107. const op = data[i++];
  2108. // The TrueType instruction set docs can be found at
  2109. // https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html
  2110. if (op === 0x40) {
  2111. // NPUSHB - pushes n bytes
  2112. n = data[i++];
  2113. if (inFDEF || inELSE) {
  2114. i += n;
  2115. } else {
  2116. for (j = 0; j < n; j++) {
  2117. stack.push(data[i++]);
  2118. }
  2119. }
  2120. } else if (op === 0x41) {
  2121. // NPUSHW - pushes n words
  2122. n = data[i++];
  2123. if (inFDEF || inELSE) {
  2124. i += n * 2;
  2125. } else {
  2126. for (j = 0; j < n; j++) {
  2127. b = data[i++];
  2128. stack.push((b << 8) | data[i++]);
  2129. }
  2130. }
  2131. } else if ((op & 0xf8) === 0xb0) {
  2132. // PUSHB - pushes bytes
  2133. n = op - 0xb0 + 1;
  2134. if (inFDEF || inELSE) {
  2135. i += n;
  2136. } else {
  2137. for (j = 0; j < n; j++) {
  2138. stack.push(data[i++]);
  2139. }
  2140. }
  2141. } else if ((op & 0xf8) === 0xb8) {
  2142. // PUSHW - pushes words
  2143. n = op - 0xb8 + 1;
  2144. if (inFDEF || inELSE) {
  2145. i += n * 2;
  2146. } else {
  2147. for (j = 0; j < n; j++) {
  2148. b = data[i++];
  2149. stack.push((b << 8) | data[i++]);
  2150. }
  2151. }
  2152. } else if (op === 0x2b && !tooComplexToFollowFunctions) {
  2153. // CALL
  2154. if (!inFDEF && !inELSE) {
  2155. // collecting information about which functions are used
  2156. funcId = stack.at(-1);
  2157. if (isNaN(funcId)) {
  2158. info("TT: CALL empty stack (or invalid entry).");
  2159. } else {
  2160. ttContext.functionsUsed[funcId] = true;
  2161. if (funcId in ttContext.functionsStackDeltas) {
  2162. const newStackLength =
  2163. stack.length + ttContext.functionsStackDeltas[funcId];
  2164. if (newStackLength < 0) {
  2165. warn("TT: CALL invalid functions stack delta.");
  2166. ttContext.hintsValid = false;
  2167. return;
  2168. }
  2169. stack.length = newStackLength;
  2170. } else if (
  2171. funcId in ttContext.functionsDefined &&
  2172. !functionsCalled.includes(funcId)
  2173. ) {
  2174. callstack.push({ data, i, stackTop: stack.length - 1 });
  2175. functionsCalled.push(funcId);
  2176. pc = ttContext.functionsDefined[funcId];
  2177. if (!pc) {
  2178. warn("TT: CALL non-existent function");
  2179. ttContext.hintsValid = false;
  2180. return;
  2181. }
  2182. data = pc.data;
  2183. i = pc.i;
  2184. }
  2185. }
  2186. }
  2187. } else if (op === 0x2c && !tooComplexToFollowFunctions) {
  2188. // FDEF
  2189. if (inFDEF || inELSE) {
  2190. warn("TT: nested FDEFs not allowed");
  2191. tooComplexToFollowFunctions = true;
  2192. }
  2193. inFDEF = true;
  2194. // collecting information about which functions are defined
  2195. lastDeff = i;
  2196. funcId = stack.pop();
  2197. ttContext.functionsDefined[funcId] = { data, i };
  2198. } else if (op === 0x2d) {
  2199. // ENDF - end of function
  2200. if (inFDEF) {
  2201. inFDEF = false;
  2202. lastEndf = i;
  2203. } else {
  2204. pc = callstack.pop();
  2205. if (!pc) {
  2206. warn("TT: ENDF bad stack");
  2207. ttContext.hintsValid = false;
  2208. return;
  2209. }
  2210. funcId = functionsCalled.pop();
  2211. data = pc.data;
  2212. i = pc.i;
  2213. ttContext.functionsStackDeltas[funcId] = stack.length - pc.stackTop;
  2214. }
  2215. } else if (op === 0x89) {
  2216. // IDEF - instruction definition
  2217. if (inFDEF || inELSE) {
  2218. warn("TT: nested IDEFs not allowed");
  2219. tooComplexToFollowFunctions = true;
  2220. }
  2221. inFDEF = true;
  2222. // recording it as a function to track ENDF
  2223. lastDeff = i;
  2224. } else if (op === 0x58) {
  2225. // IF
  2226. ++ifLevel;
  2227. } else if (op === 0x1b) {
  2228. // ELSE
  2229. inELSE = ifLevel;
  2230. } else if (op === 0x59) {
  2231. // EIF
  2232. if (inELSE === ifLevel) {
  2233. inELSE = 0;
  2234. }
  2235. --ifLevel;
  2236. } else if (op === 0x1c) {
  2237. // JMPR
  2238. if (!inFDEF && !inELSE) {
  2239. const offset = stack.at(-1);
  2240. // only jumping forward to prevent infinite loop
  2241. if (offset > 0) {
  2242. i += offset - 1;
  2243. }
  2244. }
  2245. }
  2246. // Adjusting stack not extactly, but just enough to get function id
  2247. if (!inFDEF && !inELSE) {
  2248. let stackDelta = 0;
  2249. if (op <= 0x8e) {
  2250. stackDelta = TTOpsStackDeltas[op];
  2251. } else if (op >= 0xc0 && op <= 0xdf) {
  2252. stackDelta = -1;
  2253. } else if (op >= 0xe0) {
  2254. stackDelta = -2;
  2255. }
  2256. if (op >= 0x71 && op <= 0x75) {
  2257. n = stack.pop();
  2258. if (!isNaN(n)) {
  2259. stackDelta = -n * 2;
  2260. }
  2261. }
  2262. while (stackDelta < 0 && stack.length > 0) {
  2263. stack.pop();
  2264. stackDelta++;
  2265. }
  2266. while (stackDelta > 0) {
  2267. stack.push(NaN); // pushing any number into stack
  2268. stackDelta--;
  2269. }
  2270. }
  2271. }
  2272. ttContext.tooComplexToFollowFunctions = tooComplexToFollowFunctions;
  2273. const content = [data];
  2274. if (i > data.length) {
  2275. content.push(new Uint8Array(i - data.length));
  2276. }
  2277. if (lastDeff > lastEndf) {
  2278. warn("TT: complementing a missing function tail");
  2279. // new function definition started, but not finished
  2280. // complete function by [CLEAR, ENDF]
  2281. content.push(new Uint8Array([0x22, 0x2d]));
  2282. }
  2283. foldTTTable(table, content);
  2284. }
  2285. function checkInvalidFunctions(ttContext, maxFunctionDefs) {
  2286. if (ttContext.tooComplexToFollowFunctions) {
  2287. return;
  2288. }
  2289. if (ttContext.functionsDefined.length > maxFunctionDefs) {
  2290. warn("TT: more functions defined than expected");
  2291. ttContext.hintsValid = false;
  2292. return;
  2293. }
  2294. for (let j = 0, jj = ttContext.functionsUsed.length; j < jj; j++) {
  2295. if (j > maxFunctionDefs) {
  2296. warn("TT: invalid function id: " + j);
  2297. ttContext.hintsValid = false;
  2298. return;
  2299. }
  2300. if (ttContext.functionsUsed[j] && !ttContext.functionsDefined[j]) {
  2301. warn("TT: undefined function: " + j);
  2302. ttContext.hintsValid = false;
  2303. return;
  2304. }
  2305. }
  2306. }
  2307. function foldTTTable(table, content) {
  2308. if (content.length > 1) {
  2309. // concatenating the content items
  2310. let newLength = 0;
  2311. let j, jj;
  2312. for (j = 0, jj = content.length; j < jj; j++) {
  2313. newLength += content[j].length;
  2314. }
  2315. newLength = (newLength + 3) & ~3;
  2316. const result = new Uint8Array(newLength);
  2317. let pos = 0;
  2318. for (j = 0, jj = content.length; j < jj; j++) {
  2319. result.set(content[j], pos);
  2320. pos += content[j].length;
  2321. }
  2322. table.data = result;
  2323. table.length = newLength;
  2324. }
  2325. }
  2326. function sanitizeTTPrograms(fpgm, prep, cvt, maxFunctionDefs) {
  2327. const ttContext = {
  2328. functionsDefined: [],
  2329. functionsUsed: [],
  2330. functionsStackDeltas: [],
  2331. tooComplexToFollowFunctions: false,
  2332. hintsValid: true,
  2333. };
  2334. if (fpgm) {
  2335. sanitizeTTProgram(fpgm, ttContext);
  2336. }
  2337. if (prep) {
  2338. sanitizeTTProgram(prep, ttContext);
  2339. }
  2340. if (fpgm) {
  2341. checkInvalidFunctions(ttContext, maxFunctionDefs);
  2342. }
  2343. if (cvt && cvt.length & 1) {
  2344. const cvtData = new Uint8Array(cvt.length + 1);
  2345. cvtData.set(cvt.data);
  2346. cvt.data = cvtData;
  2347. }
  2348. return ttContext.hintsValid;
  2349. }
  2350. // The following steps modify the original font data, making copy
  2351. font = new Stream(new Uint8Array(font.getBytes()));
  2352. let header, tables;
  2353. if (isTrueTypeCollectionFile(font)) {
  2354. const ttcData = readTrueTypeCollectionData(font, this.name);
  2355. header = ttcData.header;
  2356. tables = ttcData.tables;
  2357. } else {
  2358. header = readOpenTypeHeader(font);
  2359. tables = readTables(font, header.numTables);
  2360. }
  2361. let cff, cffFile;
  2362. const isTrueType = !tables["CFF "];
  2363. if (!isTrueType) {
  2364. const isComposite =
  2365. properties.composite &&
  2366. ((properties.cidToGidMap || []).length > 0 ||
  2367. !(properties.cMap instanceof IdentityCMap));
  2368. // OpenType font (skip composite fonts with non-default glyph mapping).
  2369. if (
  2370. (header.version === "OTTO" && !isComposite) ||
  2371. !tables.head ||
  2372. !tables.hhea ||
  2373. !tables.maxp ||
  2374. !tables.post
  2375. ) {
  2376. // No major tables: throwing everything at `CFFFont`.
  2377. cffFile = new Stream(tables["CFF "].data);
  2378. cff = new CFFFont(cffFile, properties);
  2379. adjustWidths(properties);
  2380. return this.convert(name, cff, properties);
  2381. }
  2382. delete tables.glyf;
  2383. delete tables.loca;
  2384. delete tables.fpgm;
  2385. delete tables.prep;
  2386. delete tables["cvt "];
  2387. this.isOpenType = true;
  2388. } else {
  2389. if (!tables.loca) {
  2390. throw new FormatError('Required "loca" table is not found');
  2391. }
  2392. if (!tables.glyf) {
  2393. warn('Required "glyf" table is not found -- trying to recover.');
  2394. // Note: We use `sanitizeGlyphLocations` to add dummy glyf data below.
  2395. tables.glyf = {
  2396. tag: "glyf",
  2397. data: new Uint8Array(0),
  2398. };
  2399. }
  2400. this.isOpenType = false;
  2401. }
  2402. if (!tables.maxp) {
  2403. throw new FormatError('Required "maxp" table is not found');
  2404. }
  2405. font.pos = (font.start || 0) + tables.maxp.offset;
  2406. const version = font.getInt32();
  2407. const numGlyphs = font.getUint16();
  2408. if (
  2409. properties.scaleFactors &&
  2410. properties.scaleFactors.length === numGlyphs &&
  2411. isTrueType
  2412. ) {
  2413. const { scaleFactors } = properties;
  2414. const isGlyphLocationsLong = int16(
  2415. tables.head.data[50],
  2416. tables.head.data[51]
  2417. );
  2418. const glyphs = new GlyfTable({
  2419. glyfTable: tables.glyf.data,
  2420. isGlyphLocationsLong,
  2421. locaTable: tables.loca.data,
  2422. numGlyphs,
  2423. });
  2424. glyphs.scale(scaleFactors);
  2425. const { glyf, loca, isLocationLong } = glyphs.write();
  2426. tables.glyf.data = glyf;
  2427. tables.loca.data = loca;
  2428. if (isLocationLong !== !!isGlyphLocationsLong) {
  2429. tables.head.data[50] = 0;
  2430. tables.head.data[51] = isLocationLong ? 1 : 0;
  2431. }
  2432. const metrics = tables.hmtx.data;
  2433. for (let i = 0; i < numGlyphs; i++) {
  2434. const j = 4 * i;
  2435. const advanceWidth = Math.round(
  2436. scaleFactors[i] * int16(metrics[j], metrics[j + 1])
  2437. );
  2438. metrics[j] = (advanceWidth >> 8) & 0xff;
  2439. metrics[j + 1] = advanceWidth & 0xff;
  2440. const lsb = Math.round(
  2441. scaleFactors[i] * signedInt16(metrics[j + 2], metrics[j + 3])
  2442. );
  2443. writeSignedInt16(metrics, j + 2, lsb);
  2444. }
  2445. }
  2446. // Glyph 0 is duplicated and appended.
  2447. let numGlyphsOut = numGlyphs + 1;
  2448. let dupFirstEntry = true;
  2449. if (numGlyphsOut > 0xffff) {
  2450. dupFirstEntry = false;
  2451. numGlyphsOut = numGlyphs;
  2452. warn("Not enough space in glyfs to duplicate first glyph.");
  2453. }
  2454. let maxFunctionDefs = 0;
  2455. let maxSizeOfInstructions = 0;
  2456. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  2457. // maxZones can be invalid
  2458. font.pos += 8;
  2459. const maxZones = font.getUint16();
  2460. if (maxZones > 2) {
  2461. // reset to 2 if font has invalid maxZones
  2462. tables.maxp.data[14] = 0;
  2463. tables.maxp.data[15] = 2;
  2464. }
  2465. font.pos += 4;
  2466. maxFunctionDefs = font.getUint16();
  2467. font.pos += 4;
  2468. maxSizeOfInstructions = font.getUint16();
  2469. }
  2470. tables.maxp.data[4] = numGlyphsOut >> 8;
  2471. tables.maxp.data[5] = numGlyphsOut & 255;
  2472. const hintsValid = sanitizeTTPrograms(
  2473. tables.fpgm,
  2474. tables.prep,
  2475. tables["cvt "],
  2476. maxFunctionDefs
  2477. );
  2478. if (!hintsValid) {
  2479. delete tables.fpgm;
  2480. delete tables.prep;
  2481. delete tables["cvt "];
  2482. }
  2483. // Ensure the hmtx table contains the advance width and
  2484. // sidebearings information for numGlyphs in the maxp table
  2485. sanitizeMetrics(
  2486. font,
  2487. tables.hhea,
  2488. tables.hmtx,
  2489. tables.head,
  2490. numGlyphsOut,
  2491. dupFirstEntry
  2492. );
  2493. if (!tables.head) {
  2494. throw new FormatError('Required "head" table is not found');
  2495. }
  2496. sanitizeHead(tables.head, numGlyphs, isTrueType ? tables.loca.length : 0);
  2497. let missingGlyphs = Object.create(null);
  2498. if (isTrueType) {
  2499. const isGlyphLocationsLong = int16(
  2500. tables.head.data[50],
  2501. tables.head.data[51]
  2502. );
  2503. const glyphsInfo = sanitizeGlyphLocations(
  2504. tables.loca,
  2505. tables.glyf,
  2506. numGlyphs,
  2507. isGlyphLocationsLong,
  2508. hintsValid,
  2509. dupFirstEntry,
  2510. maxSizeOfInstructions
  2511. );
  2512. missingGlyphs = glyphsInfo.missingGlyphs;
  2513. // Some fonts have incorrect maxSizeOfInstructions values, so we use
  2514. // the computed value instead.
  2515. if (version >= 0x00010000 && tables.maxp.length >= 22) {
  2516. tables.maxp.data[26] = glyphsInfo.maxSizeOfInstructions >> 8;
  2517. tables.maxp.data[27] = glyphsInfo.maxSizeOfInstructions & 255;
  2518. }
  2519. }
  2520. if (!tables.hhea) {
  2521. throw new FormatError('Required "hhea" table is not found');
  2522. }
  2523. // Sanitizer reduces the glyph advanceWidth to the maxAdvanceWidth
  2524. // Sometimes it's 0. That needs to be fixed
  2525. if (tables.hhea.data[10] === 0 && tables.hhea.data[11] === 0) {
  2526. tables.hhea.data[10] = 0xff;
  2527. tables.hhea.data[11] = 0xff;
  2528. }
  2529. // Extract some more font properties from the OpenType head and
  2530. // hhea tables; yMin and descent value are always negative.
  2531. const metricsOverride = {
  2532. unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
  2533. yMax: int16(tables.head.data[42], tables.head.data[43]),
  2534. yMin: signedInt16(tables.head.data[38], tables.head.data[39]),
  2535. ascent: signedInt16(tables.hhea.data[4], tables.hhea.data[5]),
  2536. descent: signedInt16(tables.hhea.data[6], tables.hhea.data[7]),
  2537. lineGap: signedInt16(tables.hhea.data[8], tables.hhea.data[9]),
  2538. };
  2539. // PDF FontDescriptor metrics lie -- using data from actual font.
  2540. this.ascent = metricsOverride.ascent / metricsOverride.unitsPerEm;
  2541. this.descent = metricsOverride.descent / metricsOverride.unitsPerEm;
  2542. this.lineGap = metricsOverride.lineGap / metricsOverride.unitsPerEm;
  2543. if (this.cssFontInfo && this.cssFontInfo.lineHeight) {
  2544. this.lineHeight = this.cssFontInfo.metrics.lineHeight;
  2545. this.lineGap = this.cssFontInfo.metrics.lineGap;
  2546. } else {
  2547. this.lineHeight = this.ascent - this.descent + this.lineGap;
  2548. }
  2549. // The 'post' table has glyphs names.
  2550. if (tables.post) {
  2551. readPostScriptTable(tables.post, properties, numGlyphs);
  2552. }
  2553. // The original 'post' table is not needed, replace it.
  2554. tables.post = {
  2555. tag: "post",
  2556. data: createPostTable(properties),
  2557. };
  2558. const charCodeToGlyphId = [];
  2559. // Helper function to try to skip mapping of empty glyphs.
  2560. function hasGlyph(glyphId) {
  2561. return !missingGlyphs[glyphId];
  2562. }
  2563. if (properties.composite) {
  2564. const cidToGidMap = properties.cidToGidMap || [];
  2565. const isCidToGidMapEmpty = cidToGidMap.length === 0;
  2566. properties.cMap.forEach(function (charCode, cid) {
  2567. if (typeof cid === "string") {
  2568. cid = convertCidString(charCode, cid, /* shouldThrow = */ true);
  2569. }
  2570. if (cid > 0xffff) {
  2571. throw new FormatError("Max size of CID is 65,535");
  2572. }
  2573. let glyphId = -1;
  2574. if (isCidToGidMapEmpty) {
  2575. glyphId = cid;
  2576. } else if (cidToGidMap[cid] !== undefined) {
  2577. glyphId = cidToGidMap[cid];
  2578. }
  2579. if (glyphId >= 0 && glyphId < numGlyphs && hasGlyph(glyphId)) {
  2580. charCodeToGlyphId[charCode] = glyphId;
  2581. }
  2582. });
  2583. } else {
  2584. // Most of the following logic in this code branch is based on the
  2585. // 9.6.6.4 of the PDF spec.
  2586. const cmapTable = readCmapTable(
  2587. tables.cmap,
  2588. font,
  2589. this.isSymbolicFont,
  2590. properties.hasEncoding
  2591. );
  2592. const cmapPlatformId = cmapTable.platformId;
  2593. const cmapEncodingId = cmapTable.encodingId;
  2594. const cmapMappings = cmapTable.mappings;
  2595. let baseEncoding = [],
  2596. forcePostTable = false;
  2597. if (
  2598. properties.hasEncoding &&
  2599. (properties.baseEncodingName === "MacRomanEncoding" ||
  2600. properties.baseEncodingName === "WinAnsiEncoding")
  2601. ) {
  2602. baseEncoding = getEncoding(properties.baseEncodingName);
  2603. }
  2604. // If the font has an encoding and is not symbolic then follow the rules
  2605. // in section 9.6.6.4 of the spec on how to map 3,1 and 1,0 cmaps.
  2606. if (
  2607. properties.hasEncoding &&
  2608. !this.isSymbolicFont &&
  2609. ((cmapPlatformId === 3 && cmapEncodingId === 1) ||
  2610. (cmapPlatformId === 1 && cmapEncodingId === 0))
  2611. ) {
  2612. const glyphsUnicodeMap = getGlyphsUnicode();
  2613. for (let charCode = 0; charCode < 256; charCode++) {
  2614. let glyphName;
  2615. if (this.differences[charCode] !== undefined) {
  2616. glyphName = this.differences[charCode];
  2617. } else if (baseEncoding.length && baseEncoding[charCode] !== "") {
  2618. glyphName = baseEncoding[charCode];
  2619. } else {
  2620. glyphName = StandardEncoding[charCode];
  2621. }
  2622. if (!glyphName) {
  2623. continue;
  2624. }
  2625. // Ensure that non-standard glyph names are resolved to valid ones.
  2626. const standardGlyphName = recoverGlyphName(
  2627. glyphName,
  2628. glyphsUnicodeMap
  2629. );
  2630. let unicodeOrCharCode;
  2631. if (cmapPlatformId === 3 && cmapEncodingId === 1) {
  2632. unicodeOrCharCode = glyphsUnicodeMap[standardGlyphName];
  2633. } else if (cmapPlatformId === 1 && cmapEncodingId === 0) {
  2634. // TODO: the encoding needs to be updated with mac os table.
  2635. unicodeOrCharCode = MacRomanEncoding.indexOf(standardGlyphName);
  2636. }
  2637. if (unicodeOrCharCode === undefined) {
  2638. // Not a valid glyph name, fallback to using the /ToUnicode map
  2639. // when no post-table exists (fixes issue13316_reduced.pdf).
  2640. if (
  2641. !properties.glyphNames &&
  2642. properties.hasIncludedToUnicodeMap &&
  2643. !(this.toUnicode instanceof IdentityToUnicodeMap)
  2644. ) {
  2645. const unicode = this.toUnicode.get(charCode);
  2646. if (unicode) {
  2647. unicodeOrCharCode = unicode.codePointAt(0);
  2648. }
  2649. }
  2650. if (unicodeOrCharCode === undefined) {
  2651. continue; // No valid glyph mapping found.
  2652. }
  2653. }
  2654. for (const mapping of cmapMappings) {
  2655. if (mapping.charCode !== unicodeOrCharCode) {
  2656. continue;
  2657. }
  2658. charCodeToGlyphId[charCode] = mapping.glyphId;
  2659. break;
  2660. }
  2661. }
  2662. } else if (cmapPlatformId === 0) {
  2663. // Default Unicode semantics, use the charcodes as is.
  2664. for (const mapping of cmapMappings) {
  2665. charCodeToGlyphId[mapping.charCode] = mapping.glyphId;
  2666. }
  2667. // Always prefer the BaseEncoding/Differences arrays, when they exist
  2668. // (fixes issue13433.pdf).
  2669. forcePostTable = true;
  2670. } else {
  2671. // When there is only a (1, 0) cmap table, the char code is a single
  2672. // byte and it is used directly as the char code.
  2673. // When a (3, 0) cmap table is present, it is used instead but the
  2674. // spec has special rules for char codes in the range of 0xF000 to
  2675. // 0xF0FF and it says the (3, 0) table should map the values from
  2676. // the (1, 0) table by prepending 0xF0 to the char codes. To reverse
  2677. // this, the upper bits of the char code are cleared, but only for the
  2678. // special range since some PDFs have char codes outside of this range
  2679. // (e.g. 0x2013) which when masked would overwrite other values in the
  2680. // cmap.
  2681. for (const mapping of cmapMappings) {
  2682. let charCode = mapping.charCode;
  2683. if (
  2684. cmapPlatformId === 3 &&
  2685. charCode >= 0xf000 &&
  2686. charCode <= 0xf0ff
  2687. ) {
  2688. charCode &= 0xff;
  2689. }
  2690. charCodeToGlyphId[charCode] = mapping.glyphId;
  2691. }
  2692. }
  2693. // Last, try to map any missing charcodes using the post table.
  2694. if (
  2695. properties.glyphNames &&
  2696. (baseEncoding.length || this.differences.length)
  2697. ) {
  2698. for (let i = 0; i < 256; ++i) {
  2699. if (!forcePostTable && charCodeToGlyphId[i] !== undefined) {
  2700. continue;
  2701. }
  2702. const glyphName = this.differences[i] || baseEncoding[i];
  2703. if (!glyphName) {
  2704. continue;
  2705. }
  2706. const glyphId = properties.glyphNames.indexOf(glyphName);
  2707. if (glyphId > 0 && hasGlyph(glyphId)) {
  2708. charCodeToGlyphId[i] = glyphId;
  2709. }
  2710. }
  2711. }
  2712. }
  2713. if (charCodeToGlyphId.length === 0) {
  2714. // defines at least one glyph
  2715. charCodeToGlyphId[0] = 0;
  2716. }
  2717. // Typically glyph 0 is duplicated and the mapping must be updated, but if
  2718. // there isn't enough room to duplicate, the glyph id is left the same. In
  2719. // this case, glyph 0 may not work correctly, but that is better than
  2720. // having the whole font fail.
  2721. let glyphZeroId = numGlyphsOut - 1;
  2722. if (!dupFirstEntry) {
  2723. glyphZeroId = 0;
  2724. }
  2725. // When `cssFontInfo` is set, the font is used to render text in the HTML
  2726. // view (e.g. with Xfa) so nothing must be moved in the private use area.
  2727. if (!properties.cssFontInfo) {
  2728. // Converting glyphs and ids into font's cmap table
  2729. const newMapping = adjustMapping(
  2730. charCodeToGlyphId,
  2731. hasGlyph,
  2732. glyphZeroId,
  2733. this.toUnicode
  2734. );
  2735. this.toFontChar = newMapping.toFontChar;
  2736. tables.cmap = {
  2737. tag: "cmap",
  2738. data: createCmapTable(
  2739. newMapping.charCodeToGlyphId,
  2740. newMapping.toUnicodeExtraMap,
  2741. numGlyphsOut
  2742. ),
  2743. };
  2744. if (!tables["OS/2"] || !validateOS2Table(tables["OS/2"], font)) {
  2745. tables["OS/2"] = {
  2746. tag: "OS/2",
  2747. data: createOS2Table(
  2748. properties,
  2749. newMapping.charCodeToGlyphId,
  2750. metricsOverride
  2751. ),
  2752. };
  2753. }
  2754. }
  2755. if (!isTrueType) {
  2756. try {
  2757. // Trying to repair CFF file
  2758. cffFile = new Stream(tables["CFF "].data);
  2759. const parser = new CFFParser(
  2760. cffFile,
  2761. properties,
  2762. SEAC_ANALYSIS_ENABLED
  2763. );
  2764. cff = parser.parse();
  2765. cff.duplicateFirstGlyph();
  2766. const compiler = new CFFCompiler(cff);
  2767. tables["CFF "].data = compiler.compile();
  2768. } catch (e) {
  2769. warn("Failed to compile font " + properties.loadedName);
  2770. }
  2771. }
  2772. // Re-creating 'name' table
  2773. if (!tables.name) {
  2774. tables.name = {
  2775. tag: "name",
  2776. data: createNameTable(this.name),
  2777. };
  2778. } else {
  2779. // ... using existing 'name' table as prototype
  2780. const namePrototype = readNameTable(tables.name);
  2781. tables.name.data = createNameTable(name, namePrototype);
  2782. this.psName = namePrototype[0][6] || null;
  2783. }
  2784. const builder = new OpenTypeFileBuilder(header.version);
  2785. for (const tableTag in tables) {
  2786. builder.addTable(tableTag, tables[tableTag].data);
  2787. }
  2788. return builder.toArray();
  2789. }
  2790. convert(fontName, font, properties) {
  2791. // TODO: Check the charstring widths to determine this.
  2792. properties.fixedPitch = false;
  2793. if (properties.builtInEncoding) {
  2794. // For Type1 fonts that do not include either `ToUnicode` or `Encoding`
  2795. // data, attempt to use the `builtInEncoding` to improve text selection.
  2796. adjustToUnicode(properties, properties.builtInEncoding);
  2797. }
  2798. // Type 1 fonts have a notdef inserted at the beginning, so glyph 0
  2799. // becomes glyph 1. In a CFF font glyph 0 is appended to the end of the
  2800. // char strings.
  2801. let glyphZeroId = 1;
  2802. if (font instanceof CFFFont) {
  2803. glyphZeroId = font.numGlyphs - 1;
  2804. }
  2805. const mapping = font.getGlyphMapping(properties);
  2806. let newMapping = null;
  2807. let newCharCodeToGlyphId = mapping;
  2808. let toUnicodeExtraMap = null;
  2809. // When `cssFontInfo` is set, the font is used to render text in the HTML
  2810. // view (e.g. with Xfa) so nothing must be moved in the private use area.
  2811. if (!properties.cssFontInfo) {
  2812. newMapping = adjustMapping(
  2813. mapping,
  2814. font.hasGlyphId.bind(font),
  2815. glyphZeroId,
  2816. this.toUnicode
  2817. );
  2818. this.toFontChar = newMapping.toFontChar;
  2819. newCharCodeToGlyphId = newMapping.charCodeToGlyphId;
  2820. toUnicodeExtraMap = newMapping.toUnicodeExtraMap;
  2821. }
  2822. const numGlyphs = font.numGlyphs;
  2823. function getCharCodes(charCodeToGlyphId, glyphId) {
  2824. let charCodes = null;
  2825. for (const charCode in charCodeToGlyphId) {
  2826. if (glyphId === charCodeToGlyphId[charCode]) {
  2827. if (!charCodes) {
  2828. charCodes = [];
  2829. }
  2830. charCodes.push(charCode | 0);
  2831. }
  2832. }
  2833. return charCodes;
  2834. }
  2835. function createCharCode(charCodeToGlyphId, glyphId) {
  2836. for (const charCode in charCodeToGlyphId) {
  2837. if (glyphId === charCodeToGlyphId[charCode]) {
  2838. return charCode | 0;
  2839. }
  2840. }
  2841. newMapping.charCodeToGlyphId[newMapping.nextAvailableFontCharCode] =
  2842. glyphId;
  2843. return newMapping.nextAvailableFontCharCode++;
  2844. }
  2845. const seacs = font.seacs;
  2846. if (newMapping && SEAC_ANALYSIS_ENABLED && seacs && seacs.length) {
  2847. const matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
  2848. const charset = font.getCharset();
  2849. const seacMap = Object.create(null);
  2850. for (let glyphId in seacs) {
  2851. glyphId |= 0;
  2852. const seac = seacs[glyphId];
  2853. const baseGlyphName = StandardEncoding[seac[2]];
  2854. const accentGlyphName = StandardEncoding[seac[3]];
  2855. const baseGlyphId = charset.indexOf(baseGlyphName);
  2856. const accentGlyphId = charset.indexOf(accentGlyphName);
  2857. if (baseGlyphId < 0 || accentGlyphId < 0) {
  2858. continue;
  2859. }
  2860. const accentOffset = {
  2861. x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
  2862. y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5],
  2863. };
  2864. const charCodes = getCharCodes(mapping, glyphId);
  2865. if (!charCodes) {
  2866. // There's no point in mapping it if the char code was never mapped
  2867. // to begin with.
  2868. continue;
  2869. }
  2870. for (const charCode of charCodes) {
  2871. // Find a fontCharCode that maps to the base and accent glyphs.
  2872. // If one doesn't exists, create it.
  2873. const charCodeToGlyphId = newMapping.charCodeToGlyphId;
  2874. const baseFontCharCode = createCharCode(
  2875. charCodeToGlyphId,
  2876. baseGlyphId
  2877. );
  2878. const accentFontCharCode = createCharCode(
  2879. charCodeToGlyphId,
  2880. accentGlyphId
  2881. );
  2882. seacMap[charCode] = {
  2883. baseFontCharCode,
  2884. accentFontCharCode,
  2885. accentOffset,
  2886. };
  2887. }
  2888. }
  2889. properties.seacMap = seacMap;
  2890. }
  2891. const unitsPerEm = 1 / (properties.fontMatrix || FONT_IDENTITY_MATRIX)[0];
  2892. const builder = new OpenTypeFileBuilder("\x4F\x54\x54\x4F");
  2893. // PostScript Font Program
  2894. builder.addTable("CFF ", font.data);
  2895. // OS/2 and Windows Specific metrics
  2896. builder.addTable("OS/2", createOS2Table(properties, newCharCodeToGlyphId));
  2897. // Character to glyphs mapping
  2898. builder.addTable(
  2899. "cmap",
  2900. createCmapTable(newCharCodeToGlyphId, toUnicodeExtraMap, numGlyphs)
  2901. );
  2902. // Font header
  2903. builder.addTable(
  2904. "head",
  2905. "\x00\x01\x00\x00" + // Version number
  2906. "\x00\x00\x10\x00" + // fontRevision
  2907. "\x00\x00\x00\x00" + // checksumAdjustement
  2908. "\x5F\x0F\x3C\xF5" + // magicNumber
  2909. "\x00\x00" + // Flags
  2910. safeString16(unitsPerEm) + // unitsPerEM
  2911. "\x00\x00\x00\x00\x9e\x0b\x7e\x27" + // creation date
  2912. "\x00\x00\x00\x00\x9e\x0b\x7e\x27" + // modifification date
  2913. "\x00\x00" + // xMin
  2914. safeString16(properties.descent) + // yMin
  2915. "\x0F\xFF" + // xMax
  2916. safeString16(properties.ascent) + // yMax
  2917. string16(properties.italicAngle ? 2 : 0) + // macStyle
  2918. "\x00\x11" + // lowestRecPPEM
  2919. "\x00\x00" + // fontDirectionHint
  2920. "\x00\x00" + // indexToLocFormat
  2921. "\x00\x00"
  2922. ); // glyphDataFormat
  2923. // Horizontal header
  2924. builder.addTable(
  2925. "hhea",
  2926. "\x00\x01\x00\x00" + // Version number
  2927. safeString16(properties.ascent) + // Typographic Ascent
  2928. safeString16(properties.descent) + // Typographic Descent
  2929. "\x00\x00" + // Line Gap
  2930. "\xFF\xFF" + // advanceWidthMax
  2931. "\x00\x00" + // minLeftSidebearing
  2932. "\x00\x00" + // minRightSidebearing
  2933. "\x00\x00" + // xMaxExtent
  2934. safeString16(properties.capHeight) + // caretSlopeRise
  2935. safeString16(Math.tan(properties.italicAngle) * properties.xHeight) + // caretSlopeRun
  2936. "\x00\x00" + // caretOffset
  2937. "\x00\x00" + // -reserved-
  2938. "\x00\x00" + // -reserved-
  2939. "\x00\x00" + // -reserved-
  2940. "\x00\x00" + // -reserved-
  2941. "\x00\x00" + // metricDataFormat
  2942. string16(numGlyphs)
  2943. ); // Number of HMetrics
  2944. // Horizontal metrics
  2945. builder.addTable(
  2946. "hmtx",
  2947. (function fontFieldsHmtx() {
  2948. const charstrings = font.charstrings;
  2949. const cffWidths = font.cff ? font.cff.widths : null;
  2950. let hmtx = "\x00\x00\x00\x00"; // Fake .notdef
  2951. for (let i = 1, ii = numGlyphs; i < ii; i++) {
  2952. let width = 0;
  2953. if (charstrings) {
  2954. const charstring = charstrings[i - 1];
  2955. width = "width" in charstring ? charstring.width : 0;
  2956. } else if (cffWidths) {
  2957. width = Math.ceil(cffWidths[i] || 0);
  2958. }
  2959. hmtx += string16(width) + string16(0);
  2960. }
  2961. return hmtx;
  2962. })()
  2963. );
  2964. // Maximum profile
  2965. builder.addTable(
  2966. "maxp",
  2967. "\x00\x00\x50\x00" + string16(numGlyphs) // Version number
  2968. ); // Num of glyphs
  2969. // Naming tables
  2970. builder.addTable("name", createNameTable(fontName));
  2971. // PostScript information
  2972. builder.addTable("post", createPostTable(properties));
  2973. return builder.toArray();
  2974. }
  2975. get spaceWidth() {
  2976. // trying to estimate space character width
  2977. const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"];
  2978. let width;
  2979. for (const glyphName of possibleSpaceReplacements) {
  2980. // if possible, getting width by glyph name
  2981. if (glyphName in this.widths) {
  2982. width = this.widths[glyphName];
  2983. break;
  2984. }
  2985. const glyphsUnicodeMap = getGlyphsUnicode();
  2986. const glyphUnicode = glyphsUnicodeMap[glyphName];
  2987. // finding the charcode via unicodeToCID map
  2988. let charcode = 0;
  2989. if (this.composite && this.cMap.contains(glyphUnicode)) {
  2990. charcode = this.cMap.lookup(glyphUnicode);
  2991. if (typeof charcode === "string") {
  2992. charcode = convertCidString(glyphUnicode, charcode);
  2993. }
  2994. }
  2995. // ... via toUnicode map
  2996. if (!charcode && this.toUnicode) {
  2997. charcode = this.toUnicode.charCodeOf(glyphUnicode);
  2998. }
  2999. // setting it to unicode if negative or undefined
  3000. if (charcode <= 0) {
  3001. charcode = glyphUnicode;
  3002. }
  3003. // trying to get width via charcode
  3004. width = this.widths[charcode];
  3005. if (width) {
  3006. break; // the non-zero width found
  3007. }
  3008. }
  3009. width = width || this.defaultWidth;
  3010. return shadow(this, "spaceWidth", width);
  3011. }
  3012. /**
  3013. * @private
  3014. */
  3015. _charToGlyph(charcode, isSpace = false) {
  3016. let glyph = this._glyphCache[charcode];
  3017. // All `Glyph`-properties, except `isSpace` in multi-byte strings,
  3018. // depend indirectly on the `charcode`.
  3019. if (glyph && glyph.isSpace === isSpace) {
  3020. return glyph;
  3021. }
  3022. let fontCharCode, width, operatorListId;
  3023. let widthCode = charcode;
  3024. if (this.cMap && this.cMap.contains(charcode)) {
  3025. widthCode = this.cMap.lookup(charcode);
  3026. if (typeof widthCode === "string") {
  3027. widthCode = convertCidString(charcode, widthCode);
  3028. }
  3029. }
  3030. width = this.widths[widthCode];
  3031. if (typeof width !== "number") {
  3032. width = this.defaultWidth;
  3033. }
  3034. const vmetric = this.vmetrics && this.vmetrics[widthCode];
  3035. let unicode = this.toUnicode.get(charcode) || charcode;
  3036. if (typeof unicode === "number") {
  3037. unicode = String.fromCharCode(unicode);
  3038. }
  3039. let isInFont = this.toFontChar[charcode] !== undefined;
  3040. // First try the toFontChar map, if it's not there then try falling
  3041. // back to the char code.
  3042. fontCharCode = this.toFontChar[charcode] || charcode;
  3043. if (this.missingFile) {
  3044. const glyphName =
  3045. this.differences[charcode] || this.defaultEncoding[charcode];
  3046. if (
  3047. (glyphName === ".notdef" || glyphName === "") &&
  3048. this.type === "Type1"
  3049. ) {
  3050. // .notdef glyphs should be invisible in non-embedded Type1 fonts, so
  3051. // replace them with spaces.
  3052. fontCharCode = 0x20;
  3053. }
  3054. fontCharCode = mapSpecialUnicodeValues(fontCharCode);
  3055. }
  3056. if (this.isType3Font) {
  3057. // Font char code in this case is actually a glyph name.
  3058. operatorListId = fontCharCode;
  3059. }
  3060. let accent = null;
  3061. if (this.seacMap && this.seacMap[charcode]) {
  3062. isInFont = true;
  3063. const seac = this.seacMap[charcode];
  3064. fontCharCode = seac.baseFontCharCode;
  3065. accent = {
  3066. fontChar: String.fromCodePoint(seac.accentFontCharCode),
  3067. offset: seac.accentOffset,
  3068. };
  3069. }
  3070. let fontChar = "";
  3071. if (typeof fontCharCode === "number") {
  3072. if (fontCharCode <= 0x10ffff) {
  3073. fontChar = String.fromCodePoint(fontCharCode);
  3074. } else {
  3075. warn(`charToGlyph - invalid fontCharCode: ${fontCharCode}`);
  3076. }
  3077. }
  3078. glyph = new Glyph(
  3079. charcode,
  3080. fontChar,
  3081. unicode,
  3082. accent,
  3083. width,
  3084. vmetric,
  3085. operatorListId,
  3086. isSpace,
  3087. isInFont
  3088. );
  3089. return (this._glyphCache[charcode] = glyph);
  3090. }
  3091. charsToGlyphs(chars) {
  3092. // If we translated this string before, just grab it from the cache.
  3093. let glyphs = this._charsCache[chars];
  3094. if (glyphs) {
  3095. return glyphs;
  3096. }
  3097. glyphs = [];
  3098. if (this.cMap) {
  3099. // Composite fonts have multi-byte strings, convert the string from
  3100. // single-byte to multi-byte.
  3101. const c = Object.create(null),
  3102. ii = chars.length;
  3103. let i = 0;
  3104. while (i < ii) {
  3105. this.cMap.readCharCode(chars, i, c);
  3106. const { charcode, length } = c;
  3107. i += length;
  3108. // Space is char with code 0x20 and length 1 in multiple-byte codes.
  3109. const glyph = this._charToGlyph(
  3110. charcode,
  3111. length === 1 && chars.charCodeAt(i - 1) === 0x20
  3112. );
  3113. glyphs.push(glyph);
  3114. }
  3115. } else {
  3116. for (let i = 0, ii = chars.length; i < ii; ++i) {
  3117. const charcode = chars.charCodeAt(i);
  3118. const glyph = this._charToGlyph(charcode, charcode === 0x20);
  3119. glyphs.push(glyph);
  3120. }
  3121. }
  3122. // Enter the translated string into the cache.
  3123. return (this._charsCache[chars] = glyphs);
  3124. }
  3125. /**
  3126. * Chars can have different sizes (depends on the encoding).
  3127. * @param {String} a string encoded with font encoding.
  3128. * @returns {Array<Array<number>>} the positions of each char in the string.
  3129. */
  3130. getCharPositions(chars) {
  3131. // This function doesn't use a cache because
  3132. // it's called only when saving or printing.
  3133. const positions = [];
  3134. if (this.cMap) {
  3135. const c = Object.create(null);
  3136. let i = 0;
  3137. while (i < chars.length) {
  3138. this.cMap.readCharCode(chars, i, c);
  3139. const length = c.length;
  3140. positions.push([i, i + length]);
  3141. i += length;
  3142. }
  3143. } else {
  3144. for (let i = 0, ii = chars.length; i < ii; ++i) {
  3145. positions.push([i, i + 1]);
  3146. }
  3147. }
  3148. return positions;
  3149. }
  3150. get glyphCacheValues() {
  3151. return Object.values(this._glyphCache);
  3152. }
  3153. /**
  3154. * Encode a js string using font encoding.
  3155. * The resulting array contains an encoded string at even positions
  3156. * (can be empty) and a non-encoded one at odd positions.
  3157. * @param {String} a js string.
  3158. * @returns {Array<String>} an array of encoded strings or non-encoded ones.
  3159. */
  3160. encodeString(str) {
  3161. const buffers = [];
  3162. const currentBuf = [];
  3163. // buffers will contain: encoded, non-encoded, encoded, ...
  3164. // currentBuf is pushed in buffers each time there is a change.
  3165. // So when buffers.length is odd then the last string is an encoded one
  3166. // and currentBuf contains non-encoded chars.
  3167. const hasCurrentBufErrors = () => buffers.length % 2 === 1;
  3168. const getCharCode =
  3169. this.toUnicode instanceof IdentityToUnicodeMap
  3170. ? unicode => this.toUnicode.charCodeOf(unicode)
  3171. : unicode => this.toUnicode.charCodeOf(String.fromCodePoint(unicode));
  3172. for (let i = 0, ii = str.length; i < ii; i++) {
  3173. const unicode = str.codePointAt(i);
  3174. if (unicode > 0xd7ff && (unicode < 0xe000 || unicode > 0xfffd)) {
  3175. // unicode is represented by two uint16
  3176. i++;
  3177. }
  3178. if (this.toUnicode) {
  3179. const charCode = getCharCode(unicode);
  3180. if (charCode !== -1) {
  3181. if (hasCurrentBufErrors()) {
  3182. buffers.push(currentBuf.join(""));
  3183. currentBuf.length = 0;
  3184. }
  3185. const charCodeLength = this.cMap
  3186. ? this.cMap.getCharCodeLength(charCode)
  3187. : 1;
  3188. for (let j = charCodeLength - 1; j >= 0; j--) {
  3189. currentBuf.push(String.fromCharCode((charCode >> (8 * j)) & 0xff));
  3190. }
  3191. continue;
  3192. }
  3193. }
  3194. // unicode can't be encoded
  3195. if (!hasCurrentBufErrors()) {
  3196. buffers.push(currentBuf.join(""));
  3197. currentBuf.length = 0;
  3198. }
  3199. currentBuf.push(String.fromCodePoint(unicode));
  3200. }
  3201. buffers.push(currentBuf.join(""));
  3202. return buffers;
  3203. }
  3204. }
  3205. class ErrorFont {
  3206. constructor(error) {
  3207. this.error = error;
  3208. this.loadedName = "g_font_error";
  3209. this.missingFile = true;
  3210. }
  3211. charsToGlyphs() {
  3212. return [];
  3213. }
  3214. encodeString(chars) {
  3215. return [chars];
  3216. }
  3217. exportData(extraProperties = false) {
  3218. return { error: this.error };
  3219. }
  3220. }
  3221. export { ErrorFont, Font };