You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OTFSubSetFile.java 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.fonts.truetype;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.Comparator;
  27. import java.util.HashMap;
  28. import java.util.LinkedHashMap;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Map.Entry;
  32. import org.apache.commons.logging.Log;
  33. import org.apache.commons.logging.LogFactory;
  34. import org.apache.fontbox.cff.CFFStandardString;
  35. import org.apache.fop.fonts.MultiByteFont;
  36. import org.apache.fop.fonts.cff.CFFDataReader;
  37. import org.apache.fop.fonts.cff.CFFDataReader.CFFIndexData;
  38. import org.apache.fop.fonts.cff.CFFDataReader.DICTEntry;
  39. import org.apache.fop.fonts.cff.CFFDataReader.FDSelect;
  40. import org.apache.fop.fonts.cff.CFFDataReader.FontDict;
  41. import org.apache.fop.fonts.cff.CFFDataReader.Format0FDSelect;
  42. import org.apache.fop.fonts.cff.CFFDataReader.Format3FDSelect;
  43. /**
  44. * Reads an OpenType CFF file and generates a subset
  45. * The OpenType specification can be found at the Microsoft
  46. * Typography site: http://www.microsoft.com/typography/otspec/
  47. */
  48. public class OTFSubSetFile extends OTFSubSetWriter {
  49. /** A map containing each glyph to be included in the subset
  50. * with their existing and new GID's **/
  51. protected Map<Integer, Integer> subsetGlyphs = new LinkedHashMap<Integer, Integer>();
  52. /** A map of the new GID to SID used to construct the charset table **/
  53. protected Map<Integer, Integer> gidToSID;
  54. protected CFFIndexData localIndexSubr;
  55. protected CFFIndexData globalIndexSubr;
  56. /** List of subroutines to write to the local / global indexes in the subset font **/
  57. protected List<byte[]> subsetLocalIndexSubr;
  58. protected List<byte[]> subsetGlobalIndexSubr;
  59. /** For fonts which have an FDSelect or ROS flag in Top Dict, this is used to store the
  60. * local subroutine indexes for each group as opposed to the above subsetLocalIndexSubr */
  61. protected List<List<byte[]>> fdSubrs;
  62. /** The subset FD Select table used to store the mappings between glyphs and their
  63. * associated FDFont object which point to a private dict and local subroutines. */
  64. private Map<Integer, FDIndexReference> subsetFDSelect;
  65. /** A list of unique subroutines from the global / local subroutine indexes */
  66. protected List<Integer> localUniques;
  67. protected List<Integer> globalUniques;
  68. /** A store of the number of subroutines each global / local subroutine will store **/
  69. protected int subsetLocalSubrCount;
  70. protected int subsetGlobalSubrCount;
  71. /** A list of char string data for each glyph to be stored in the subset font **/
  72. protected List<byte[]> subsetCharStringsIndex;
  73. /** The embedded name to change in the name table **/
  74. protected String embeddedName;
  75. /** An array used to hold the string index data for the subset font **/
  76. protected List<byte[]> stringIndexData = new ArrayList<byte[]>();
  77. /** The CFF reader object used to read data and offsets from the original font file */
  78. protected CFFDataReader cffReader;
  79. /** The class used to represent this font **/
  80. private MultiByteFont mbFont;
  81. /** The number of standard strings in CFF **/
  82. public static final int NUM_STANDARD_STRINGS = 391;
  83. /** The operator used to identify a local subroutine reference */
  84. private static final int LOCAL_SUBROUTINE = 10;
  85. /** The operator used to identify a global subroutine reference */
  86. private static final int GLOBAL_SUBROUTINE = 29;
  87. /** The parser used to parse type2 charstring */
  88. private Type2Parser type2Parser;
  89. public OTFSubSetFile() throws IOException {
  90. super();
  91. }
  92. public void readFont(FontFileReader in, String embeddedName, MultiByteFont mbFont) throws IOException {
  93. readFont(in, embeddedName, mbFont, mbFont.getUsedGlyphs());
  94. }
  95. /**
  96. * Reads and creates a subset of the font.
  97. *
  98. * @param in FontFileReader to read from
  99. * @param embeddedName Name to be checked for in the font file
  100. * @param usedGlyphs Map of glyphs (glyphs has old index as (Integer) key and
  101. * new index as (Integer) value)
  102. * @throws IOException in case of an I/O problem
  103. */
  104. void readFont(FontFileReader in, String embeddedName, MultiByteFont mbFont,
  105. Map<Integer, Integer> usedGlyphs) throws IOException {
  106. this.mbFont = mbFont;
  107. fontFile = in;
  108. this.embeddedName = embeddedName;
  109. //Sort by the new GID and store in a LinkedHashMap
  110. subsetGlyphs = sortByValue(usedGlyphs);
  111. initializeFont(in);
  112. cffReader = new CFFDataReader(fontFile);
  113. //Create the CIDFontType0C data
  114. createCFF();
  115. }
  116. private Map<Integer, Integer> sortByValue(Map<Integer, Integer> map) {
  117. List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(map.entrySet());
  118. Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
  119. public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
  120. return ((Comparable<Integer>) o1.getValue()).compareTo(o2.getValue());
  121. }
  122. });
  123. Map<Integer, Integer> result = new LinkedHashMap<Integer, Integer>();
  124. for (Entry<Integer, Integer> entry : list) {
  125. result.put(entry.getKey(), entry.getValue());
  126. }
  127. return result;
  128. }
  129. protected void createCFF() throws IOException {
  130. //Header
  131. writeBytes(cffReader.getHeader());
  132. //Name Index
  133. writeIndex(Arrays.asList(embedFontName.getBytes("UTF-8")));
  134. Offsets offsets = new Offsets();
  135. //Top DICT Index and Data
  136. offsets.topDictData = currentPos + writeTopDICT();
  137. boolean hasFDSelect = cffReader.getFDSelect() != null;
  138. //Create the char string index data and related local / global subroutines
  139. if (hasFDSelect) {
  140. createCharStringDataCID();
  141. } else {
  142. createCharStringData();
  143. }
  144. //If it is a CID-Keyed font, store each FD font and add each SID
  145. List<Integer> fontNameSIDs = null;
  146. List<Integer> subsetFDFonts = null;
  147. if (hasFDSelect) {
  148. subsetFDFonts = getUsedFDFonts();
  149. fontNameSIDs = storeFDStrings(subsetFDFonts);
  150. }
  151. //String index
  152. writeStringIndex();
  153. //Global subroutine index
  154. writeIndex(subsetGlobalIndexSubr);
  155. //Encoding
  156. offsets.encoding = currentPos;
  157. //Charset table
  158. offsets.charset = currentPos;
  159. writeCharsetTable(hasFDSelect);
  160. //FDSelect table
  161. offsets.fdSelect = currentPos;
  162. if (hasFDSelect) {
  163. writeFDSelect();
  164. if (!isCharStringBeforeFD()) {
  165. offsets.fdArray = writeFDArray(subsetFDFonts, fontNameSIDs);
  166. }
  167. }
  168. //Char Strings Index
  169. offsets.charString = currentPos;
  170. writeIndex(subsetCharStringsIndex);
  171. if (hasFDSelect) {
  172. if (isCharStringBeforeFD()) {
  173. offsets.fdArray = writeFDArray(subsetFDFonts, fontNameSIDs);
  174. }
  175. updateCIDOffsets(offsets);
  176. } else {
  177. //Keep offset to modify later with the local subroutine index offset
  178. offsets.privateDict = currentPos;
  179. writePrivateDict();
  180. //Local subroutine index
  181. offsets.localIndex = currentPos;
  182. writeIndex(subsetLocalIndexSubr);
  183. //Update the offsets
  184. updateOffsets(offsets);
  185. }
  186. }
  187. static class Offsets {
  188. Integer topDictData;
  189. Integer encoding;
  190. Integer charset;
  191. Integer fdSelect;
  192. Integer charString;
  193. Integer fdArray;
  194. Integer privateDict;
  195. Integer localIndex;
  196. }
  197. private int writeFDArray(List<Integer> subsetFDFonts, List<Integer> fontNameSIDs) throws IOException {
  198. List<Integer> privateDictOffsets = writeCIDDictsAndSubrs(subsetFDFonts);
  199. return writeFDArray(subsetFDFonts, privateDictOffsets, fontNameSIDs);
  200. }
  201. private boolean isCharStringBeforeFD() {
  202. LinkedHashMap<String, DICTEntry> entries = cffReader.getTopDictEntries();
  203. int len = entries.get("CharStrings").getOperandLength();
  204. if (entries.containsKey("FDArray")) {
  205. int len2 = entries.get("FDArray").getOperandLength();
  206. return len < len2;
  207. }
  208. return true;
  209. }
  210. protected List<Integer> storeFDStrings(List<Integer> uniqueNewRefs) throws IOException {
  211. List<Integer> fontNameSIDs = new ArrayList<Integer>();
  212. List<FontDict> fdFonts = cffReader.getFDFonts();
  213. for (int uniqueNewRef : uniqueNewRefs) {
  214. FontDict fdFont = fdFonts.get(uniqueNewRef);
  215. byte[] fdFontByteData = fdFont.getByteData();
  216. Map<String, DICTEntry> fdFontDict = cffReader.parseDictData(fdFontByteData);
  217. fontNameSIDs.add(stringIndexData.size() + NUM_STANDARD_STRINGS);
  218. stringIndexData.add(cffReader.getStringIndex().getValue(fdFontDict.get("FontName")
  219. .getOperands().get(0).intValue() - NUM_STANDARD_STRINGS));
  220. }
  221. return fontNameSIDs;
  222. }
  223. protected int writeTopDICT() throws IOException {
  224. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  225. List<String> topDictStringEntries = Arrays.asList("version", "Notice", "Copyright",
  226. "FullName", "FamilyName", "Weight", "PostScript");
  227. ByteArrayOutputStream dict = new ByteArrayOutputStream();
  228. int offsetExtra = 0;
  229. for (Map.Entry<String, DICTEntry> dictEntry : topDICT.entrySet()) {
  230. String dictKey = dictEntry.getKey();
  231. DICTEntry entry = dictEntry.getValue();
  232. //If the value is an SID, update the reference but keep the size the same
  233. entry.setOffset(entry.getOffset() + offsetExtra);
  234. if (dictKey.equals("CharStrings") && entry.getOperandLength() < 5) {
  235. byte[] extra = new byte[5 - entry.getOperandLength()];
  236. offsetExtra += extra.length;
  237. dict.write(extra);
  238. dict.write(entry.getByteData());
  239. entry.setOperandLength(5);
  240. } else if (dictKey.equals("ROS")) {
  241. dict.write(writeROSEntry(entry));
  242. } else if (dictKey.equals("CIDCount")) {
  243. dict.write(writeCIDCount(entry));
  244. } else if (topDictStringEntries.contains(dictKey)) {
  245. if (entry.getOperandLength() < 2) {
  246. entry.setOperandLength(2);
  247. offsetExtra++;
  248. }
  249. dict.write(writeTopDictStringEntry(entry));
  250. } else {
  251. dict.write(entry.getByteData());
  252. }
  253. }
  254. byte[] topDictIndex = cffReader.getTopDictIndex().getByteData();
  255. int offSize = topDictIndex[2];
  256. return writeIndex(Arrays.asList(dict.toByteArray()), offSize) - dict.size();
  257. }
  258. private byte[] writeROSEntry(DICTEntry dictEntry) throws IOException {
  259. int sidA = dictEntry.getOperands().get(0).intValue();
  260. if (sidA > 390) {
  261. stringIndexData.add(cffReader.getStringIndex().getValue(sidA - NUM_STANDARD_STRINGS));
  262. }
  263. int sidAStringIndex = stringIndexData.size() + 390;
  264. int sidB = dictEntry.getOperands().get(1).intValue();
  265. if (sidB > 390) {
  266. stringIndexData.add("Identity".getBytes("UTF-8"));
  267. }
  268. int sidBStringIndex = stringIndexData.size() + 390;
  269. byte[] cidEntryByteData = dictEntry.getByteData();
  270. updateOffset(cidEntryByteData, 0, dictEntry.getOperandLengths().get(0),
  271. sidAStringIndex);
  272. updateOffset(cidEntryByteData, dictEntry.getOperandLengths().get(0),
  273. dictEntry.getOperandLengths().get(1), sidBStringIndex);
  274. updateOffset(cidEntryByteData, dictEntry.getOperandLengths().get(0)
  275. + dictEntry.getOperandLengths().get(1), dictEntry.getOperandLengths().get(2), 0);
  276. return cidEntryByteData;
  277. }
  278. protected byte[] writeCIDCount(DICTEntry dictEntry) throws IOException {
  279. byte[] cidCountByteData = dictEntry.getByteData();
  280. updateOffset(cidCountByteData, 0, dictEntry.getOperandLengths().get(0),
  281. subsetGlyphs.size());
  282. return cidCountByteData;
  283. }
  284. private byte[] writeTopDictStringEntry(DICTEntry dictEntry) throws IOException {
  285. int sid = dictEntry.getOperands().get(0).intValue();
  286. if (sid > 391) {
  287. stringIndexData.add(cffReader.getStringIndex().getValue(sid - 391));
  288. }
  289. byte[] newDictEntry = createNewRef(stringIndexData.size() + 390, dictEntry.getOperator(),
  290. dictEntry.getOperandLength(), true);
  291. return newDictEntry;
  292. }
  293. private void writeStringIndex() throws IOException {
  294. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  295. int charsetOffset = topDICT.get("charset").getOperands().get(0).intValue();
  296. gidToSID = new LinkedHashMap<Integer, Integer>();
  297. for (Entry<Integer, Integer> subsetGlyph : subsetGlyphs.entrySet()) {
  298. int gid = subsetGlyph.getKey();
  299. int v = subsetGlyph.getValue();
  300. int sid = cffReader.getSIDFromGID(charsetOffset, gid);
  301. //Check whether the SID falls into the standard string set
  302. if (sid < NUM_STANDARD_STRINGS) {
  303. gidToSID.put(v, sid);
  304. if (mbFont != null) {
  305. mbFont.mapUsedGlyphName(v, CFFStandardString.getName(sid));
  306. }
  307. } else {
  308. int index = sid - NUM_STANDARD_STRINGS;
  309. //index is 0 based, should use < not <=
  310. if (index < cffReader.getStringIndex().getNumObjects()) {
  311. byte[] value = cffReader.getStringIndex().getValue(index);
  312. if (mbFont != null) {
  313. mbFont.mapUsedGlyphName(v, new String(value, "UTF-8"));
  314. }
  315. gidToSID.put(v, stringIndexData.size() + 391);
  316. stringIndexData.add(value);
  317. } else {
  318. if (mbFont != null) {
  319. mbFont.mapUsedGlyphName(v, ".notdef");
  320. }
  321. gidToSID.put(v, index);
  322. }
  323. }
  324. }
  325. //Write the String Index
  326. writeIndex(stringIndexData);
  327. }
  328. protected void createCharStringDataCID() throws IOException {
  329. CFFIndexData charStringsIndex = cffReader.getCharStringIndex();
  330. FDSelect fontDictionary = cffReader.getFDSelect();
  331. if (fontDictionary instanceof Format0FDSelect) {
  332. throw new UnsupportedOperationException("OTF CFF CID Format0 currently not implemented");
  333. } else if (fontDictionary instanceof Format3FDSelect) {
  334. Format3FDSelect fdSelect = (Format3FDSelect)fontDictionary;
  335. Map<Integer, Integer> subsetGroups = new HashMap<Integer, Integer>();
  336. List<Integer> uniqueGroups = new ArrayList<Integer>();
  337. Map<Integer, Integer> rangeMap = fdSelect.getRanges();
  338. Integer[] ranges = rangeMap.keySet().toArray(new Integer[rangeMap.size()]);
  339. for (int gid : subsetGlyphs.keySet()) {
  340. int i = 0;
  341. for (Entry<Integer, Integer> entry : rangeMap.entrySet()) {
  342. int nextRange;
  343. if (i < ranges.length - 1) {
  344. nextRange = ranges[i + 1];
  345. } else {
  346. nextRange = fdSelect.getSentinelGID();
  347. }
  348. if (gid >= entry.getKey() && gid < nextRange) {
  349. int r = entry.getValue();
  350. subsetGroups.put(gid, r);
  351. if (!uniqueGroups.contains(r)) {
  352. uniqueGroups.add(r);
  353. }
  354. }
  355. i++;
  356. }
  357. }
  358. //Prepare resources
  359. globalIndexSubr = cffReader.getGlobalIndexSubr();
  360. //Create the new char string index
  361. subsetCharStringsIndex = new ArrayList<byte[]>();
  362. globalUniques = new ArrayList<Integer>();
  363. subsetFDSelect = new LinkedHashMap<Integer, FDIndexReference>();
  364. List<List<Integer>> foundLocalUniques = new ArrayList<List<Integer>>();
  365. for (int u : uniqueGroups) {
  366. foundLocalUniques.add(new ArrayList<Integer>());
  367. }
  368. Map<Integer, Integer> gidHintMaskLengths = new HashMap<Integer, Integer>();
  369. for (Entry<Integer, Integer> subsetGlyph : subsetGlyphs.entrySet()) {
  370. int gid = subsetGlyph.getKey();
  371. int group = subsetGroups.get(gid);
  372. localIndexSubr = cffReader.getFDFonts().get(group).getLocalSubrData();
  373. localUniques = foundLocalUniques.get(uniqueGroups.indexOf(group));
  374. type2Parser = new Type2Parser();
  375. FDIndexReference newFDReference = new FDIndexReference(uniqueGroups.indexOf(group), group);
  376. subsetFDSelect.put(subsetGlyph.getValue(), newFDReference);
  377. byte[] data = charStringsIndex.getValue(gid);
  378. preScanForSubsetIndexSize(data);
  379. gidHintMaskLengths.put(gid, type2Parser.getMaskLength());
  380. }
  381. //Create the two lists which are to store the local and global subroutines
  382. subsetGlobalIndexSubr = new ArrayList<byte[]>();
  383. fdSubrs = new ArrayList<List<byte[]>>();
  384. subsetGlobalSubrCount = globalUniques.size();
  385. globalUniques.clear();
  386. localUniques = null;
  387. for (List<Integer> foundLocalUnique : foundLocalUniques) {
  388. fdSubrs.add(new ArrayList<byte[]>());
  389. }
  390. List<List<Integer>> foundLocalUniquesB = new ArrayList<List<Integer>>();
  391. for (int u : uniqueGroups) {
  392. foundLocalUniquesB.add(new ArrayList<Integer>());
  393. }
  394. for (Entry<Integer, Integer> subsetGlyph : subsetGlyphs.entrySet()) {
  395. int gid = subsetGlyph.getKey();
  396. int value = subsetGlyph.getValue();
  397. int group = subsetGroups.get(gid);
  398. localIndexSubr = cffReader.getFDFonts().get(group).getLocalSubrData();
  399. int newFDIndex = subsetFDSelect.get(value).getNewFDIndex();
  400. localUniques = foundLocalUniquesB.get(newFDIndex);
  401. byte[] data = charStringsIndex.getValue(gid);
  402. subsetLocalIndexSubr = fdSubrs.get(newFDIndex);
  403. subsetLocalSubrCount = foundLocalUniques.get(newFDIndex).size();
  404. type2Parser = new Type2Parser();
  405. type2Parser.setMaskLength(gidHintMaskLengths.get(gid));
  406. data = readCharStringData(data, subsetLocalSubrCount);
  407. subsetCharStringsIndex.add(data);
  408. }
  409. }
  410. }
  411. protected void writeFDSelect() {
  412. if (cffReader.getTopDictEntries().get("CharStrings").getOperandLength() == 2) {
  413. Map<Integer, Integer> indexs = getFormat3Index();
  414. writeByte(3); //Format
  415. writeCard16(indexs.size());
  416. int count = 0;
  417. for (Entry<Integer, Integer> x : indexs.entrySet()) {
  418. writeCard16(count);
  419. writeByte(x.getKey());
  420. count += x.getValue();
  421. }
  422. writeCard16(subsetFDSelect.size());
  423. } else {
  424. writeByte(0); //Format
  425. for (FDIndexReference e : subsetFDSelect.values()) {
  426. writeByte(e.getNewFDIndex());
  427. }
  428. }
  429. }
  430. private Map<Integer, Integer> getFormat3Index() {
  431. Map<Integer, Integer> indexs = new LinkedHashMap<Integer, Integer>();
  432. int last = -1;
  433. int count = 0;
  434. for (FDIndexReference e : subsetFDSelect.values()) {
  435. int i = e.getNewFDIndex();
  436. count++;
  437. if (i != last) {
  438. indexs.put(i, count);
  439. count = 1;
  440. }
  441. last = i;
  442. }
  443. indexs.put(last, count);
  444. return indexs;
  445. }
  446. protected List<Integer> getUsedFDFonts() {
  447. List<Integer> uniqueNewRefs = new ArrayList<Integer>();
  448. for (FDIndexReference e : subsetFDSelect.values()) {
  449. int fdIndex = e.getOldFDIndex();
  450. if (!uniqueNewRefs.contains(fdIndex)) {
  451. uniqueNewRefs.add(fdIndex);
  452. }
  453. }
  454. return uniqueNewRefs;
  455. }
  456. protected List<Integer> writeCIDDictsAndSubrs(List<Integer> uniqueNewRefs)
  457. throws IOException {
  458. List<Integer> privateDictOffsets = new ArrayList<Integer>();
  459. List<FontDict> fdFonts = cffReader.getFDFonts();
  460. int i = 0;
  461. for (int ref : uniqueNewRefs) {
  462. FontDict curFDFont = fdFonts.get(ref);
  463. byte[] fdPrivateDictByteData = curFDFont.getPrivateDictData();
  464. Map<String, DICTEntry> fdPrivateDict = cffReader.parseDictData(fdPrivateDictByteData);
  465. int privateDictOffset = currentPos;
  466. privateDictOffsets.add(privateDictOffset);
  467. DICTEntry subrs = fdPrivateDict.get("Subrs");
  468. if (subrs != null) {
  469. fdPrivateDictByteData = resizeToFitOpLen(fdPrivateDictByteData, subrs);
  470. updateOffset(fdPrivateDictByteData, subrs.getOffset(),
  471. subrs.getOperandLength(),
  472. fdPrivateDictByteData.length);
  473. }
  474. writeBytes(fdPrivateDictByteData);
  475. writeIndex(fdSubrs.get(i));
  476. i++;
  477. }
  478. return privateDictOffsets;
  479. }
  480. private byte[] resizeToFitOpLen(byte[] fdPrivateDictByteData, DICTEntry subrs) throws IOException {
  481. if (subrs.getOperandLength() == 2 && fdPrivateDictByteData.length < 108) {
  482. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  483. bos.write(fdPrivateDictByteData);
  484. bos.write(new byte[108 - fdPrivateDictByteData.length]);
  485. fdPrivateDictByteData = bos.toByteArray();
  486. }
  487. return fdPrivateDictByteData;
  488. }
  489. protected int writeFDArray(List<Integer> uniqueNewRefs, List<Integer> privateDictOffsets,
  490. List<Integer> fontNameSIDs)
  491. throws IOException {
  492. int offset = currentPos;
  493. List<FontDict> fdFonts = cffReader.getFDFonts();
  494. List<byte[]> index = new ArrayList<byte[]>();
  495. int i = 0;
  496. for (int ref : uniqueNewRefs) {
  497. FontDict fdFont = fdFonts.get(ref);
  498. byte[] fdFontByteData = fdFont.getByteData();
  499. Map<String, DICTEntry> fdFontDict = cffReader.parseDictData(fdFontByteData);
  500. //Update the SID to the FontName
  501. updateOffset(fdFontByteData, fdFontDict.get("FontName").getOffset() - 1,
  502. fdFontDict.get("FontName").getOperandLengths().get(0),
  503. fontNameSIDs.get(i));
  504. //Update the Private dict reference
  505. updateOffset(fdFontByteData, fdFontDict.get("Private").getOffset()
  506. + fdFontDict.get("Private").getOperandLengths().get(0),
  507. fdFontDict.get("Private").getOperandLengths().get(1),
  508. privateDictOffsets.get(i));
  509. index.add(fdFontByteData);
  510. i++;
  511. }
  512. writeIndex(index);
  513. return offset;
  514. }
  515. private static class FDIndexReference {
  516. private int newFDIndex;
  517. private int oldFDIndex;
  518. public FDIndexReference(int newFDIndex, int oldFDIndex) {
  519. this.newFDIndex = newFDIndex;
  520. this.oldFDIndex = oldFDIndex;
  521. }
  522. public int getNewFDIndex() {
  523. return newFDIndex;
  524. }
  525. public int getOldFDIndex() {
  526. return oldFDIndex;
  527. }
  528. }
  529. private void createCharStringData() throws IOException {
  530. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  531. CFFIndexData charStringsIndex = cffReader.getCharStringIndex();
  532. DICTEntry privateEntry = topDICT.get("Private");
  533. if (privateEntry != null) {
  534. int privateOffset = privateEntry.getOperands().get(1).intValue();
  535. Map<String, DICTEntry> privateDICT = cffReader.getPrivateDict(privateEntry);
  536. if (privateDICT.get("Subrs") != null) {
  537. int localSubrOffset = privateOffset + privateDICT.get("Subrs").getOperands().get(0).intValue();
  538. localIndexSubr = cffReader.readIndex(localSubrOffset);
  539. } else {
  540. localIndexSubr = cffReader.readIndex(null);
  541. }
  542. }
  543. globalIndexSubr = cffReader.getGlobalIndexSubr();
  544. //Create the two lists which are to store the local and global subroutines
  545. subsetLocalIndexSubr = new ArrayList<byte[]>();
  546. subsetGlobalIndexSubr = new ArrayList<byte[]>();
  547. //Create the new char string index
  548. subsetCharStringsIndex = new ArrayList<byte[]>();
  549. localUniques = new ArrayList<Integer>();
  550. globalUniques = new ArrayList<Integer>();
  551. Map<Integer, Integer> gidHintMaskLengths = new HashMap<Integer, Integer>();
  552. for (int gid : subsetGlyphs.keySet()) {
  553. type2Parser = new Type2Parser();
  554. byte[] data = charStringsIndex.getValue(gid);
  555. preScanForSubsetIndexSize(data);
  556. gidHintMaskLengths.put(gid, type2Parser.getMaskLength());
  557. }
  558. //Store the size of each subset index and clear the unique arrays
  559. subsetLocalSubrCount = localUniques.size();
  560. subsetGlobalSubrCount = globalUniques.size();
  561. localUniques.clear();
  562. globalUniques.clear();
  563. for (int gid : subsetGlyphs.keySet()) {
  564. byte[] data = charStringsIndex.getValue(gid);
  565. type2Parser = new Type2Parser();
  566. //Retrieve modified char string data and fill local / global subroutine arrays
  567. type2Parser.setMaskLength(gidHintMaskLengths.get(gid));
  568. data = readCharStringData(data, subsetLocalSubrCount);
  569. subsetCharStringsIndex.add(data);
  570. }
  571. }
  572. static class Type2Parser {
  573. /**
  574. * logging instance
  575. */
  576. protected Log log = LogFactory.getLog(Type2Parser.class);
  577. private List<BytesNumber> stack = new ArrayList<BytesNumber>();
  578. private int hstemCount;
  579. private int vstemCount;
  580. private int lastOp = -1;
  581. private int maskLength = -1;
  582. public void pushOperand(BytesNumber v) {
  583. stack.add(v);
  584. }
  585. public BytesNumber popOperand() {
  586. return stack.remove(stack.size() - 1);
  587. }
  588. public void clearStack() {
  589. stack.clear();
  590. }
  591. public int[] getOperands(int numbers) {
  592. int[] ret = new int[numbers];
  593. while (numbers > 0) {
  594. numbers--;
  595. ret[numbers] = this.popOperand().getNumber();
  596. }
  597. return ret;
  598. }
  599. public void setMaskLength(int maskLength) {
  600. this.maskLength = maskLength;
  601. }
  602. public int getMaskLength() {
  603. // The number of data bytes for mask is exactly the number needed, one
  604. // bit per hint, to reference the number of stem hints declared
  605. // at the beginning of the charstring program.
  606. if (maskLength > 0) {
  607. return maskLength;
  608. }
  609. return 1 + (hstemCount + vstemCount - 1) / 8;
  610. }
  611. private int exec(int b0, byte[] input, int curPos) throws IOException {
  612. ByteArrayInputStream bis = new ByteArrayInputStream(input);
  613. bis.skip(curPos + 1);
  614. return exec(b0, bis);
  615. }
  616. public int exec(int b0, InputStream data) throws IOException {
  617. int posDelta = 0;
  618. if ((b0 >= 0 && b0 <= 27) || (b0 >= 29 && b0 <= 31)) {
  619. if (b0 == 12) {
  620. log.warn("May not guess the operand count correctly.");
  621. posDelta = 1;
  622. } else if (b0 == 1 || b0 == 18) {
  623. // hstem(hm) operator
  624. hstemCount += stack.size() / 2;
  625. clearStack();
  626. } else if (b0 == 19 || b0 == 20) {
  627. if (lastOp == 1 || lastOp == 18) {
  628. //If hstem and vstem hints are both declared at the beginning of
  629. //a charstring, and this sequence is followed directly by the
  630. //hintmask or cntrmask operators, the vstem hint operator need
  631. //not be included.
  632. vstemCount += stack.size() / 2;
  633. }
  634. clearStack();
  635. posDelta = getMaskLength();
  636. } else if (b0 == 3 || b0 == 23) {
  637. // vstem(hm) operator
  638. vstemCount += stack.size() / 2;
  639. clearStack();
  640. }
  641. if (b0 != 11 && b0 != 12) {
  642. lastOp = b0;
  643. }
  644. } else if (b0 == 28 || (b0 >= 32 && b0 <= 255)) {
  645. BytesNumber operand = readNumber(b0, data);
  646. pushOperand(operand);
  647. posDelta = operand.getNumBytes() - 1;
  648. } else {
  649. throw new UnsupportedOperationException("Operator:" + b0 + " is not supported");
  650. }
  651. return posDelta;
  652. }
  653. private BytesNumber readNumber(int b0, InputStream input) throws IOException {
  654. if (b0 == 28) {
  655. int b1 = input.read();
  656. int b2 = input.read();
  657. return new BytesNumber((int) (short) (b1 << 8 | b2), 3);
  658. } else if (b0 >= 32 && b0 <= 246) {
  659. return new BytesNumber(b0 - 139, 1);
  660. } else if (b0 >= 247 && b0 <= 250) {
  661. int b1 = input.read();
  662. return new BytesNumber((b0 - 247) * 256 + b1 + 108, 2);
  663. } else if (b0 >= 251 && b0 <= 254) {
  664. int b1 = input.read();
  665. return new BytesNumber(-(b0 - 251) * 256 - b1 - 108, 2);
  666. } else if (b0 == 255) {
  667. int b1 = input.read();
  668. int b2 = input.read();
  669. int b3 = input.read();
  670. int b4 = input.read();
  671. return new BytesNumber((b1 << 24 | b2 << 16 | b3 << 8 | b4), 5);
  672. } else {
  673. throw new IllegalArgumentException();
  674. }
  675. }
  676. }
  677. private void preScanForSubsetIndexSize(byte[] data) throws IOException {
  678. boolean hasLocalSubroutines = localIndexSubr != null && localIndexSubr.getNumObjects() > 0;
  679. boolean hasGlobalSubroutines = globalIndexSubr != null && globalIndexSubr.getNumObjects() > 0;
  680. for (int dataPos = 0; dataPos < data.length; dataPos++) {
  681. int b0 = data[dataPos] & 0xff;
  682. if (b0 == LOCAL_SUBROUTINE && hasLocalSubroutines) {
  683. preScanForSubsetIndexSize(localIndexSubr, localUniques);
  684. } else if (b0 == GLOBAL_SUBROUTINE && hasGlobalSubroutines) {
  685. preScanForSubsetIndexSize(globalIndexSubr, globalUniques);
  686. } else {
  687. dataPos += type2Parser.exec(b0, data, dataPos);
  688. }
  689. }
  690. }
  691. private void preScanForSubsetIndexSize(CFFIndexData indexSubr, List<Integer> uniques) throws IOException {
  692. int subrNumber = getSubrNumber(indexSubr.getNumObjects(), type2Parser.popOperand().getNumber());
  693. if (!uniques.contains(subrNumber) && subrNumber < indexSubr.getNumObjects()) {
  694. uniques.add(subrNumber);
  695. }
  696. if (subrNumber < indexSubr.getNumObjects()) {
  697. byte[] subr = indexSubr.getValue(subrNumber);
  698. preScanForSubsetIndexSize(subr);
  699. } else {
  700. throw new IllegalArgumentException("callgsubr out of range");
  701. }
  702. }
  703. private int getSubrNumber(int numSubroutines, int operand) {
  704. int bias = getBias(numSubroutines);
  705. return bias + operand;
  706. }
  707. private byte[] readCharStringData(byte[] data, int subsetLocalSubrCount) throws IOException {
  708. boolean hasLocalSubroutines = localIndexSubr != null && localIndexSubr.getNumObjects() > 0;
  709. boolean hasGlobalSubroutines = globalIndexSubr != null && globalIndexSubr.getNumObjects() > 0;
  710. for (int dataPos = 0; dataPos < data.length; dataPos++) {
  711. int b0 = data[dataPos] & 0xff;
  712. if (b0 == 10 && hasLocalSubroutines) {
  713. BytesNumber operand = type2Parser.popOperand();
  714. int subrNumber = getSubrNumber(localIndexSubr.getNumObjects(), operand.getNumber());
  715. int newRef = getNewRefForReference(subrNumber, localUniques, localIndexSubr, subsetLocalIndexSubr,
  716. subsetLocalSubrCount);
  717. if (newRef != -1) {
  718. byte[] newData = constructNewRefData(dataPos, data, operand, subsetLocalSubrCount,
  719. newRef, new int[] {10});
  720. dataPos -= data.length - newData.length;
  721. data = newData;
  722. }
  723. } else if (b0 == 29 && hasGlobalSubroutines) {
  724. BytesNumber operand = type2Parser.popOperand();
  725. int subrNumber = getSubrNumber(globalIndexSubr.getNumObjects(), operand.getNumber());
  726. int newRef = getNewRefForReference(subrNumber, globalUniques, globalIndexSubr, subsetGlobalIndexSubr,
  727. subsetGlobalSubrCount);
  728. if (newRef != -1) {
  729. byte[] newData = constructNewRefData(dataPos, data, operand, subsetGlobalSubrCount,
  730. newRef, new int[] {29});
  731. dataPos -= data.length - newData.length;
  732. data = newData;
  733. }
  734. } else {
  735. dataPos += type2Parser.exec(b0, data, dataPos);
  736. }
  737. }
  738. //Return the data with the modified references to our arrays
  739. return data;
  740. }
  741. private int getNewRefForReference(int subrNumber, List<Integer> uniquesArray,
  742. CFFIndexData indexSubr, List<byte[]> subsetIndexSubr, int subrCount) throws IOException {
  743. int newRef;
  744. if (!uniquesArray.contains(subrNumber)) {
  745. if (subrNumber < indexSubr.getNumObjects()) {
  746. byte[] subr = indexSubr.getValue(subrNumber);
  747. subr = readCharStringData(subr, subrCount);
  748. uniquesArray.add(subrNumber);
  749. subsetIndexSubr.add(subr);
  750. newRef = subsetIndexSubr.size() - 1;
  751. } else {
  752. throw new IllegalArgumentException("subrNumber out of range");
  753. }
  754. } else {
  755. newRef = uniquesArray.indexOf(subrNumber);
  756. }
  757. return newRef;
  758. }
  759. private int getBias(int subrCount) {
  760. if (subrCount < 1240) {
  761. return 107;
  762. } else if (subrCount < 33900) {
  763. return 1131;
  764. } else {
  765. return 32768;
  766. }
  767. }
  768. private byte[] constructNewRefData(int curDataPos, byte[] currentData, BytesNumber operand,
  769. int fullSubsetIndexSize, int curSubsetIndexSize, int[] operatorCode) throws IOException {
  770. //Create the new array with the modified reference
  771. ByteArrayOutputStream newData = new ByteArrayOutputStream();
  772. int startRef = curDataPos - operand.getNumBytes();
  773. int length = operand.getNumBytes() + 1;
  774. int newBias = getBias(fullSubsetIndexSize);
  775. int newRef = curSubsetIndexSize - newBias;
  776. byte[] newRefBytes = createNewRef(newRef, operatorCode, -1, false);
  777. newData.write(currentData, 0, startRef);
  778. newData.write(newRefBytes);
  779. newData.write(currentData, startRef + length, currentData.length - (startRef + length));
  780. return newData.toByteArray();
  781. }
  782. public static byte[] createNewRef(int newRef, int[] operatorCode, int forceLength, boolean isDict) {
  783. ByteArrayOutputStream newRefBytes = new ByteArrayOutputStream();
  784. if ((forceLength == -1 && newRef >= -107 && newRef <= 107) || forceLength == 1) {
  785. //The index values are 0 indexed
  786. newRefBytes.write(newRef + 139);
  787. } else if ((forceLength == -1 && newRef >= -1131 && newRef <= 1131) || forceLength == 2) {
  788. if (newRef <= -876) {
  789. newRefBytes.write(254);
  790. } else if (newRef <= -620) {
  791. newRefBytes.write(253);
  792. } else if (newRef <= -364) {
  793. newRefBytes.write(252);
  794. } else if (newRef <= -108) {
  795. newRefBytes.write(251);
  796. } else if (newRef <= 363) {
  797. newRefBytes.write(247);
  798. } else if (newRef <= 619) {
  799. newRefBytes.write(248);
  800. } else if (newRef <= 875) {
  801. newRefBytes.write(249);
  802. } else {
  803. newRefBytes.write(250);
  804. }
  805. if (newRef > 0) {
  806. newRefBytes.write(newRef - 108);
  807. } else {
  808. newRefBytes.write(-newRef - 108);
  809. }
  810. } else if ((forceLength == -1 && newRef >= -32768 && newRef <= 32767) || forceLength == 3) {
  811. newRefBytes.write(28);
  812. newRefBytes.write(newRef >> 8);
  813. newRefBytes.write(newRef);
  814. } else {
  815. if (isDict) {
  816. newRefBytes.write(29);
  817. } else {
  818. newRefBytes.write(255);
  819. }
  820. newRefBytes.write(newRef >> 24);
  821. newRefBytes.write(newRef >> 16);
  822. newRefBytes.write(newRef >> 8);
  823. newRefBytes.write(newRef);
  824. }
  825. for (int i : operatorCode) {
  826. newRefBytes.write(i);
  827. }
  828. return newRefBytes.toByteArray();
  829. }
  830. protected int writeIndex(List<byte[]> dataArray) {
  831. int totLength = 1;
  832. for (byte[] data : dataArray) {
  833. totLength += data.length;
  834. }
  835. int offSize = getOffSize(totLength);
  836. return writeIndex(dataArray, offSize);
  837. }
  838. protected int writeIndex(List<byte[]> dataArray, int offSize) {
  839. int hdrTotal = 3;
  840. //2 byte number of items
  841. this.writeCard16(dataArray.size());
  842. //Offset Size: 1 byte = 256, 2 bytes = 65536 etc.
  843. //Offsets in the offset array are relative to the byte that precedes the object data.
  844. //Therefore the first element of the offset array is always 1.
  845. this.writeByte(offSize);
  846. //Count the first offset 1
  847. hdrTotal += offSize;
  848. int total = 0;
  849. int i = 0;
  850. for (byte[] data : dataArray) {
  851. hdrTotal += offSize;
  852. int length = data.length;
  853. switch (offSize) {
  854. case 1:
  855. if (i == 0) {
  856. writeByte(1);
  857. }
  858. total += length;
  859. writeByte(total + 1);
  860. break;
  861. case 2:
  862. if (i == 0) {
  863. writeCard16(1);
  864. }
  865. total += length;
  866. writeCard16(total + 1);
  867. break;
  868. case 3:
  869. if (i == 0) {
  870. writeThreeByteNumber(1);
  871. }
  872. total += length;
  873. writeThreeByteNumber(total + 1);
  874. break;
  875. case 4:
  876. if (i == 0) {
  877. writeULong(1);
  878. }
  879. total += length;
  880. writeULong(total + 1);
  881. break;
  882. default:
  883. throw new AssertionError("Offset Size was not an expected value.");
  884. }
  885. i++;
  886. }
  887. for (byte[] aDataArray : dataArray) {
  888. writeBytes(aDataArray);
  889. }
  890. return hdrTotal + total;
  891. }
  892. private int getOffSize(int totLength) {
  893. int offSize = 1;
  894. if (totLength < (1 << 8)) {
  895. offSize = 1;
  896. } else if (totLength < (1 << 16)) {
  897. offSize = 2;
  898. } else if (totLength < (1 << 24)) {
  899. offSize = 3;
  900. } else {
  901. offSize = 4;
  902. }
  903. return offSize;
  904. }
  905. /**
  906. * A class used to store the last number operand and also it's size in bytes
  907. */
  908. static class BytesNumber {
  909. private int number;
  910. private int numBytes;
  911. public BytesNumber(int number, int numBytes) {
  912. this.number = number;
  913. this.numBytes = numBytes;
  914. }
  915. public int getNumber() {
  916. return this.number;
  917. }
  918. public int getNumBytes() {
  919. return this.numBytes;
  920. }
  921. public void clearNumber() {
  922. this.number = -1;
  923. this.numBytes = -1;
  924. }
  925. public String toString() {
  926. return Integer.toString(number);
  927. }
  928. @Override
  929. public boolean equals(Object entry) {
  930. assert entry instanceof BytesNumber;
  931. BytesNumber bnEntry = (BytesNumber)entry;
  932. return this.number == bnEntry.getNumber()
  933. && this.numBytes == bnEntry.getNumBytes();
  934. }
  935. @Override
  936. public int hashCode() {
  937. int hash = 1;
  938. hash = hash * 17 + number;
  939. hash = hash * 31 + numBytes;
  940. return hash;
  941. }
  942. }
  943. private void writeCharsetTable(boolean cidFont) throws IOException {
  944. if (cidFont) {
  945. writeByte(2);
  946. for (int entry : gidToSID.keySet()) {
  947. if (entry == 0) {
  948. continue;
  949. }
  950. writeCard16(entry);
  951. writeCard16(gidToSID.size() - 1);
  952. break;
  953. }
  954. } else {
  955. writeByte(0);
  956. for (int entry : gidToSID.values()) {
  957. if (entry == 0) {
  958. continue;
  959. }
  960. writeCard16(entry);
  961. }
  962. }
  963. }
  964. protected void writePrivateDict() throws IOException {
  965. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  966. DICTEntry privateEntry = topDICT.get("Private");
  967. if (privateEntry != null) {
  968. writeBytes(cffReader.getPrivateDictBytes(privateEntry));
  969. }
  970. }
  971. protected void updateOffsets(Offsets offsets) throws IOException {
  972. Map<String, DICTEntry> topDICT = cffReader.getTopDictEntries();
  973. Map<String, DICTEntry> privateDICT = null;
  974. DICTEntry privateEntry = topDICT.get("Private");
  975. if (privateEntry != null) {
  976. privateDICT = cffReader.getPrivateDict(privateEntry);
  977. }
  978. updateFixedOffsets(topDICT, offsets);
  979. if (privateDICT != null) {
  980. //Private index offset in the top dict
  981. int oldPrivateOffset = offsets.topDictData + privateEntry.getOffset();
  982. updateOffset(oldPrivateOffset + privateEntry.getOperandLengths().get(0),
  983. privateEntry.getOperandLengths().get(1), offsets.privateDict);
  984. //Update the local subroutine index offset in the private dict
  985. DICTEntry subroutines = privateDICT.get("Subrs");
  986. if (subroutines != null) {
  987. int oldLocalSubrOffset = offsets.privateDict + subroutines.getOffset();
  988. updateOffset(oldLocalSubrOffset, subroutines.getOperandLength(),
  989. (offsets.localIndex - offsets.privateDict));
  990. }
  991. }
  992. }
  993. protected void updateFixedOffsets(Map<String, DICTEntry> topDICT, Offsets offsets) throws IOException {
  994. //Charset offset in the top dict
  995. DICTEntry charset = topDICT.get("charset");
  996. int oldCharsetOffset = offsets.topDictData + charset.getOffset();
  997. updateOffset(oldCharsetOffset, charset.getOperandLength(), offsets.charset);
  998. //Char string index offset in the private dict
  999. DICTEntry charString = topDICT.get("CharStrings");
  1000. int oldCharStringOffset = offsets.topDictData + charString.getOffset();
  1001. updateOffset(oldCharStringOffset, charString.getOperandLength(), offsets.charString);
  1002. DICTEntry encodingEntry = topDICT.get("Encoding");
  1003. if (encodingEntry != null && encodingEntry.getOperands().get(0).intValue() != 0
  1004. && encodingEntry.getOperands().get(0).intValue() != 1) {
  1005. int oldEncodingOffset = offsets.topDictData + encodingEntry.getOffset();
  1006. updateOffset(oldEncodingOffset, encodingEntry.getOperandLength(), offsets.encoding);
  1007. }
  1008. }
  1009. protected void updateCIDOffsets(Offsets offsets) throws IOException {
  1010. Map<String, DICTEntry> topDict = cffReader.getTopDictEntries();
  1011. DICTEntry fdArrayEntry = topDict.get("FDArray");
  1012. if (fdArrayEntry != null) {
  1013. updateOffset(offsets.topDictData + fdArrayEntry.getOffset() - 1,
  1014. fdArrayEntry.getOperandLength(), offsets.fdArray);
  1015. }
  1016. DICTEntry fdSelect = topDict.get("FDSelect");
  1017. if (fdSelect != null) {
  1018. updateOffset(offsets.topDictData + fdSelect.getOffset() - 1,
  1019. fdSelect.getOperandLength(), offsets.fdSelect);
  1020. }
  1021. updateFixedOffsets(topDict, offsets);
  1022. }
  1023. private void updateOffset(int position, int length, int replacement) throws IOException {
  1024. byte[] outBytes = output.toByteArray();
  1025. updateOffset(outBytes, position, length, replacement);
  1026. output.reset();
  1027. output.write(outBytes);
  1028. }
  1029. private void updateOffset(byte[] out, int position, int length, int replacement) {
  1030. switch (length) {
  1031. case 1:
  1032. out[position] = (byte)(replacement + 139);
  1033. break;
  1034. case 2:
  1035. assert replacement <= 1131;
  1036. if (replacement <= -876) {
  1037. out[position] = (byte)254;
  1038. } else if (replacement <= -620) {
  1039. out[position] = (byte)253;
  1040. } else if (replacement <= -364) {
  1041. out[position] = (byte)252;
  1042. } else if (replacement <= -108) {
  1043. out[position] = (byte)251;
  1044. } else if (replacement <= 363) {
  1045. out[position] = (byte)247;
  1046. } else if (replacement <= 619) {
  1047. out[position] = (byte)248;
  1048. } else if (replacement <= 875) {
  1049. out[position] = (byte)249;
  1050. } else {
  1051. out[position] = (byte)250;
  1052. }
  1053. if (replacement > 0) {
  1054. out[position + 1] = (byte)(replacement - 108);
  1055. } else {
  1056. out[position + 1] = (byte)(-replacement - 108);
  1057. }
  1058. break;
  1059. case 3:
  1060. assert replacement <= 32767;
  1061. out[position] = (byte)28;
  1062. out[position + 1] = (byte)((replacement >> 8) & 0xFF);
  1063. out[position + 2] = (byte)(replacement & 0xFF);
  1064. break;
  1065. case 5:
  1066. out[position] = (byte)29;
  1067. out[position + 1] = (byte)((replacement >> 24) & 0xFF);
  1068. out[position + 2] = (byte)((replacement >> 16) & 0xFF);
  1069. out[position + 3] = (byte)((replacement >> 8) & 0xFF);
  1070. out[position + 4] = (byte)(replacement & 0xFF);
  1071. break;
  1072. default:
  1073. }
  1074. }
  1075. /**
  1076. * Returns the parsed CFF data for the original font.
  1077. * @return The CFFDataReader contaiing the parsed data
  1078. */
  1079. public CFFDataReader getCFFReader() {
  1080. return cffReader;
  1081. }
  1082. }