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 47KB

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