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.

CharacterSetBuilder.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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.afp.fonts;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.net.MalformedURLException;
  22. import java.net.URI;
  23. import java.net.URISyntaxException;
  24. import java.util.ArrayList;
  25. import java.util.Collections;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.WeakHashMap;
  30. import org.apache.commons.logging.Log;
  31. import org.apache.commons.logging.LogFactory;
  32. import org.apache.xmlgraphics.image.loader.util.SoftMapCache;
  33. import org.apache.fop.afp.AFPConstants;
  34. import org.apache.fop.afp.AFPEventProducer;
  35. import org.apache.fop.afp.util.AFPResourceAccessor;
  36. import org.apache.fop.afp.util.StructuredFieldReader;
  37. import org.apache.fop.fonts.Typeface;
  38. /**
  39. * The CharacterSetBuilder is responsible building the a CharacterSet instance that holds
  40. * the font metric data. The data is either read from disk and passed to a CharacterSet (*)
  41. * or a FopCharacterSet is instantiated that is composed of a Typeface instance configured
  42. * with this data.<p/>
  43. * -*- For referenced fonts CharacterSetBuilder is responsible for reading the font attributes
  44. * from binary code page files and the character set metric files. In IBM font structure, a
  45. * code page maps each character of text to the characters in a character set.
  46. * Each character is translated into a code point. When the character is
  47. * printed, each code point is matched to a character ID on the code page
  48. * specified. The character ID is then matched to the image (raster pattern or
  49. * outline pattern) of the character in the character set specified. The image
  50. * in the character set is the image that is printed in the document. To be a
  51. * valid code page for a particular character set, all character IDs in the code
  52. * page must be included in that character set. <p/>This class will read the
  53. * font information from the binary code page files and character set metric
  54. * files in order to determine the correct metrics to use when rendering the
  55. * formatted object. <p/>
  56. *
  57. */
  58. public abstract class CharacterSetBuilder {
  59. /**
  60. * Static logging instance
  61. */
  62. protected static final Log LOG = LogFactory.getLog(CharacterSetBuilder.class);
  63. /**
  64. * Template used to convert lists to arrays.
  65. */
  66. private static final CharacterSetOrientation[] EMPTY_CSO_ARRAY = new CharacterSetOrientation[0];
  67. /** Codepage MO:DCA structured field. */
  68. private static final byte[] CODEPAGE_SF = new byte[] {
  69. (byte) 0xD3, (byte) 0xA8, (byte) 0x87};
  70. /** Character table MO:DCA structured field. */
  71. private static final byte[] CHARACTER_TABLE_SF = new byte[] {
  72. (byte) 0xD3, (byte) 0x8C, (byte) 0x87};
  73. /** Font descriptor MO:DCA structured field. */
  74. private static final byte[] FONT_DESCRIPTOR_SF = new byte[] {
  75. (byte) 0xD3, (byte) 0xA6, (byte) 0x89 };
  76. /** Font control MO:DCA structured field. */
  77. private static final byte[] FONT_CONTROL_SF = new byte[] {
  78. (byte) 0xD3, (byte) 0xA7, (byte) 0x89 };
  79. /** Font orientation MO:DCA structured field. */
  80. private static final byte[] FONT_ORIENTATION_SF = new byte[] {
  81. (byte) 0xD3, (byte) 0xAE, (byte) 0x89 };
  82. /** Font position MO:DCA structured field. */
  83. private static final byte[] FONT_POSITION_SF = new byte[] {
  84. (byte) 0xD3, (byte) 0xAC, (byte) 0x89 };
  85. /** Font index MO:DCA structured field. */
  86. private static final byte[] FONT_INDEX_SF = new byte[] {
  87. (byte) 0xD3, (byte) 0x8C, (byte) 0x89 };
  88. /**
  89. * The collection of code pages
  90. */
  91. private final Map<String, Map<String, String>> codePagesCache
  92. = Collections.synchronizedMap(new WeakHashMap<String, Map<String, String>>());
  93. /**
  94. * Cache of charactersets
  95. */
  96. private final SoftMapCache characterSetsCache = new SoftMapCache(true);
  97. /** Default constructor. */
  98. private CharacterSetBuilder() {
  99. }
  100. /**
  101. * Factory method for the single-byte implementation of AFPFontReader.
  102. * @return AFPFontReader
  103. */
  104. public static CharacterSetBuilder getSingleByteInstance() {
  105. return SingleByteLoader.getInstance();
  106. }
  107. /**
  108. * Factory method for the double-byte (CID Keyed font (Type 0)) implementation of AFPFontReader.
  109. * @return AFPFontReader
  110. */
  111. public static CharacterSetBuilder getDoubleByteInstance() {
  112. return DoubleByteLoader.getInstance();
  113. }
  114. /**
  115. * Returns an InputStream to a given file path and filename
  116. *
  117. * * @param accessor the resource accessor
  118. * @param uriStr the URI
  119. * @param eventProducer for handling AFP related events
  120. * @return an inputStream
  121. * @throws IOException in the event that an I/O exception of some sort has occurred
  122. */
  123. protected InputStream openInputStream(AFPResourceAccessor accessor, String uriStr,
  124. AFPEventProducer eventProducer)
  125. throws IOException {
  126. URI uri;
  127. try {
  128. uri = new URI(uriStr.trim());
  129. } catch (URISyntaxException e) {
  130. throw new MalformedURLException("Invalid uri: " + uriStr + " (" + e.getMessage() + ")");
  131. }
  132. if (LOG.isDebugEnabled()) {
  133. LOG.debug("Opening " + uri);
  134. }
  135. return accessor.createInputStream(uri);
  136. }
  137. /**
  138. * Closes the inputstream
  139. *
  140. * @param inputStream the inputstream to close
  141. */
  142. protected void closeInputStream(InputStream inputStream) {
  143. try {
  144. if (inputStream != null) {
  145. inputStream.close();
  146. }
  147. } catch (Exception ex) {
  148. // Lets log at least!
  149. LOG.error(ex.getMessage());
  150. }
  151. }
  152. /**
  153. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  154. * actual afp code page and character set files to load the object with the necessary metrics.
  155. *
  156. * @param characterSetName name of the characterset
  157. * @param codePageName name of the code page file
  158. * @param encoding encoding name
  159. * @param accessor used to load codepage and characterset
  160. * @param eventProducer for handling AFP related events
  161. * @return CharacterSet object
  162. * @throws IOException if an I/O error occurs
  163. */
  164. public CharacterSet buildSBCS(String characterSetName, String codePageName, String encoding,
  165. AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
  166. return processFont(characterSetName, codePageName, encoding, CharacterSetType.SINGLE_BYTE,
  167. accessor, eventProducer);
  168. }
  169. /**
  170. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  171. * actual afp code page and character set files to load the object with the necessary metrics.
  172. * This method is to be used for double byte character sets (DBCS).
  173. *
  174. * @param characterSetName name of the characterset
  175. * @param codePageName name of the code page file
  176. * @param encoding encoding name
  177. * @param charsetType the characterset type
  178. * @param accessor used to load codepage and characterset
  179. * @param eventProducer for handling AFP related events
  180. * @return CharacterSet object
  181. * @throws IOException if an I/O error occurs
  182. */
  183. public CharacterSet buildDBCS(String characterSetName, String codePageName, String encoding,
  184. CharacterSetType charsetType, AFPResourceAccessor accessor, AFPEventProducer eventProducer)
  185. throws IOException {
  186. return processFont(characterSetName, codePageName, encoding, charsetType, accessor,
  187. eventProducer);
  188. }
  189. /**
  190. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  191. * actual afp code page and character set files to load the object with the necessary metrics.
  192. *
  193. * @param characterSetName the CharacterSetMetric object to populate
  194. * @param codePageName the name of the code page to use
  195. * @param encoding name of the encoding in use
  196. * @param typeface base14 font name
  197. * @param eventProducer for handling AFP related events
  198. * @return CharacterSet object
  199. * @throws IOException if an I/O error occurs
  200. */
  201. public CharacterSet build(String characterSetName, String codePageName, String encoding,
  202. Typeface typeface, AFPEventProducer eventProducer) throws IOException {
  203. return new FopCharacterSet(codePageName, encoding, characterSetName, typeface,
  204. eventProducer);
  205. }
  206. private CharacterSet processFont(String characterSetName, String codePageName, String encoding,
  207. CharacterSetType charsetType, AFPResourceAccessor accessor, AFPEventProducer eventProducer)
  208. throws IOException {
  209. // check for cached version of the characterset
  210. String descriptor = characterSetName + "_" + encoding + "_" + codePageName;
  211. CharacterSet characterSet = (CharacterSet) characterSetsCache.get(descriptor);
  212. if (characterSet != null) {
  213. return characterSet;
  214. }
  215. // characterset not in the cache, so recreating
  216. characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName,
  217. accessor, eventProducer);
  218. InputStream inputStream = null;
  219. try {
  220. /**
  221. * Get the code page which contains the character mapping
  222. * information to map the unicode character id to the graphic
  223. * chracter global identifier.
  224. */
  225. Map<String, String> codePage;
  226. synchronized (codePagesCache) {
  227. codePage = codePagesCache.get(codePageName);
  228. if (codePage == null) {
  229. codePage = loadCodePage(codePageName, encoding, accessor, eventProducer);
  230. codePagesCache.put(codePageName, codePage);
  231. }
  232. }
  233. inputStream = openInputStream(accessor, characterSetName, eventProducer);
  234. StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream);
  235. // Process D3A689 Font Descriptor
  236. FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader);
  237. characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints());
  238. // Process D3A789 Font Control
  239. FontControl fontControl = processFontControl(structuredFieldReader);
  240. if (fontControl != null) {
  241. //process D3AE89 Font Orientation
  242. CharacterSetOrientation[] characterSetOrientations
  243. = processFontOrientation(structuredFieldReader);
  244. double metricNormalizationFactor;
  245. if (fontControl.isRelative()) {
  246. metricNormalizationFactor = 1;
  247. } else {
  248. int dpi = fontControl.getDpi();
  249. metricNormalizationFactor = 1000.0d * 72000.0d
  250. / fontDescriptor.getNominalFontSizeInMillipoints() / dpi;
  251. }
  252. //process D3AC89 Font Position
  253. processFontPosition(structuredFieldReader, characterSetOrientations,
  254. metricNormalizationFactor);
  255. //process D38C89 Font Index (per orientation)
  256. for (int i = 0; i < characterSetOrientations.length; i++) {
  257. processFontIndex(structuredFieldReader,
  258. characterSetOrientations[i], codePage, metricNormalizationFactor);
  259. characterSet.addCharacterSetOrientation(characterSetOrientations[i]);
  260. }
  261. } else {
  262. throw new IOException("Missing D3AE89 Font Control structured field.");
  263. }
  264. } finally {
  265. closeInputStream(inputStream);
  266. }
  267. characterSetsCache.put(descriptor, characterSet);
  268. return characterSet;
  269. }
  270. /**
  271. * Load the code page information from the appropriate file. The file name
  272. * to load is determined by the code page name and the file extension 'CDP'.
  273. *
  274. * @param codePage
  275. * the code page identifier
  276. * @param encoding
  277. * the encoding to use for the character decoding
  278. * @param accessor the resource accessor
  279. * @param eventProducer for handling AFP related events
  280. * @return a code page mapping (key: GCGID, value: Unicode character)
  281. * @throws IOException if an I/O exception of some sort has occurred.
  282. */
  283. protected Map<String, String> loadCodePage(String codePage, String encoding,
  284. AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
  285. // Create the HashMap to store code page information
  286. Map<String, String> codePages = new HashMap<String, String>();
  287. InputStream inputStream = null;
  288. try {
  289. inputStream = openInputStream(accessor, codePage.trim(), eventProducer);
  290. } catch (IOException e) {
  291. eventProducer.codePageNotFound(this, e);
  292. throw e;
  293. }
  294. try {
  295. StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream);
  296. byte[] data = structuredFieldReader.getNext(CHARACTER_TABLE_SF);
  297. int position = 0;
  298. byte[] gcgiBytes = new byte[8];
  299. byte[] charBytes = new byte[1];
  300. // Read data, ignoring bytes 0 - 2
  301. for (int index = 3; index < data.length; index++) {
  302. if (position < 8) {
  303. // Build the graphic character global identifier key
  304. gcgiBytes[position] = data[index];
  305. position++;
  306. } else if (position == 9) {
  307. position = 0;
  308. // Set the character
  309. charBytes[0] = data[index];
  310. String gcgiString = new String(gcgiBytes,
  311. AFPConstants.EBCIDIC_ENCODING);
  312. //Use the 8-bit char index to find the Unicode character using the Java encoding
  313. //given in the configuration. If the code page and the Java encoding don't
  314. //match, a wrong Unicode character will be associated with the AFP GCGID.
  315. //Idea: we could use IBM's GCGID to Unicode map and build code pages ourselves.
  316. String charString = new String(charBytes, encoding);
  317. codePages.put(gcgiString, charString);
  318. } else {
  319. position++;
  320. }
  321. }
  322. } finally {
  323. closeInputStream(inputStream);
  324. }
  325. return codePages;
  326. }
  327. /**
  328. * Process the font descriptor details using the structured field reader.
  329. *
  330. * @param structuredFieldReader the structured field reader
  331. * @return a class representing the font descriptor
  332. * @throws IOException if an I/O exception of some sort has occurred.
  333. */
  334. protected static FontDescriptor processFontDescriptor(
  335. StructuredFieldReader structuredFieldReader)
  336. throws IOException {
  337. byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF);
  338. return new FontDescriptor(fndData);
  339. }
  340. /**
  341. * Process the font control details using the structured field reader.
  342. *
  343. * @param structuredFieldReader
  344. * the structured field reader
  345. * @return the FontControl
  346. * @throws IOException if an I/O exception of some sort has occurred.
  347. */
  348. protected FontControl processFontControl(StructuredFieldReader structuredFieldReader)
  349. throws IOException {
  350. byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF);
  351. FontControl fontControl = null;
  352. if (fncData != null) {
  353. fontControl = new FontControl();
  354. if (fncData[7] == (byte) 0x02) {
  355. fontControl.setRelative(true);
  356. }
  357. int metricResolution = getUBIN(fncData, 9);
  358. if (metricResolution == 1000) {
  359. //Special case: 1000 units per em (rather than dpi)
  360. fontControl.setUnitsPerEm(1000);
  361. } else {
  362. fontControl.setDpi(metricResolution / 10);
  363. }
  364. }
  365. return fontControl;
  366. }
  367. /**
  368. * Process the font orientation details from using the structured field
  369. * reader.
  370. *
  371. * @param structuredFieldReader
  372. * the structured field reader
  373. * @return CharacterSetOrientation array
  374. * @throws IOException if an I/O exception of some sort has occurred.
  375. */
  376. protected CharacterSetOrientation[] processFontOrientation(
  377. StructuredFieldReader structuredFieldReader) throws IOException {
  378. byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF);
  379. int position = 0;
  380. byte[] fnoData = new byte[26];
  381. List<CharacterSetOrientation> orientations = new ArrayList<CharacterSetOrientation>();
  382. // Read data, ignoring bytes 0 - 2
  383. for (int index = 3; index < data.length; index++) {
  384. // Build the font orientation record
  385. fnoData[position] = data[index];
  386. position++;
  387. if (position == 26) {
  388. position = 0;
  389. int orientation = determineOrientation(fnoData[2]);
  390. // Space Increment
  391. int space = ((fnoData[8] & 0xFF ) << 8) + (fnoData[9] & 0xFF);
  392. // Em-Space Increment
  393. int em = ((fnoData[14] & 0xFF ) << 8) + (fnoData[15] & 0xFF);
  394. CharacterSetOrientation cso = new CharacterSetOrientation(orientation);
  395. cso.setSpaceIncrement(space);
  396. cso.setEmSpaceIncrement(em);
  397. orientations.add(cso);
  398. }
  399. }
  400. return orientations.toArray(EMPTY_CSO_ARRAY);
  401. }
  402. /**
  403. * Populate the CharacterSetOrientation object in the suplied array with the
  404. * font position details using the supplied structured field reader.
  405. *
  406. * @param structuredFieldReader
  407. * the structured field reader
  408. * @param characterSetOrientations
  409. * the array of CharacterSetOrientation objects
  410. * @param metricNormalizationFactor factor to apply to the metrics to get normalized
  411. * font metric values
  412. * @throws IOException if an I/O exception of some sort has occurred.
  413. */
  414. protected void processFontPosition(StructuredFieldReader structuredFieldReader,
  415. CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor)
  416. throws IOException {
  417. byte[] data = structuredFieldReader.getNext(FONT_POSITION_SF);
  418. int position = 0;
  419. byte[] fpData = new byte[26];
  420. int characterSetOrientationIndex = 0;
  421. // Read data, ignoring bytes 0 - 2
  422. for (int index = 3; index < data.length; index++) {
  423. if (position < 22) {
  424. // Build the font orientation record
  425. fpData[position] = data[index];
  426. if (position == 9) {
  427. CharacterSetOrientation characterSetOrientation
  428. = characterSetOrientations[characterSetOrientationIndex];
  429. int xHeight = getSBIN(fpData, 2);
  430. int capHeight = getSBIN(fpData, 4);
  431. int ascHeight = getSBIN(fpData, 6);
  432. int dscHeight = getSBIN(fpData, 8);
  433. dscHeight = dscHeight * -1;
  434. characterSetOrientation.setXHeight(
  435. (int)Math.round(xHeight * metricNormalizationFactor));
  436. characterSetOrientation.setCapHeight(
  437. (int)Math.round(capHeight * metricNormalizationFactor));
  438. characterSetOrientation.setAscender(
  439. (int)Math.round(ascHeight * metricNormalizationFactor));
  440. characterSetOrientation.setDescender(
  441. (int)Math.round(dscHeight * metricNormalizationFactor));
  442. }
  443. } else if (position == 22) {
  444. position = 0;
  445. characterSetOrientationIndex++;
  446. fpData[position] = data[index];
  447. }
  448. position++;
  449. }
  450. }
  451. /**
  452. * Process the font index details for the character set orientation.
  453. *
  454. * @param structuredFieldReader the structured field reader
  455. * @param cso the CharacterSetOrientation object to populate
  456. * @param codepage the map of code pages
  457. * @param metricNormalizationFactor factor to apply to the metrics to get normalized
  458. * font metric values
  459. * @throws IOException if an I/O exception of some sort has occurred.
  460. */
  461. protected void processFontIndex(StructuredFieldReader structuredFieldReader,
  462. CharacterSetOrientation cso, Map<String, String> codepage,
  463. double metricNormalizationFactor)
  464. throws IOException {
  465. byte[] data = structuredFieldReader.getNext(FONT_INDEX_SF);
  466. int position = 0;
  467. byte[] gcgid = new byte[8];
  468. byte[] fiData = new byte[20];
  469. char lowest = 255;
  470. char highest = 0;
  471. String firstABCMismatch = null;
  472. // Read data, ignoring bytes 0 - 2
  473. for (int index = 3; index < data.length; index++) {
  474. if (position < 8) {
  475. gcgid[position] = data[index];
  476. position++;
  477. } else if (position < 27) {
  478. fiData[position - 8] = data[index];
  479. position++;
  480. } else if (position == 27) {
  481. fiData[position - 8] = data[index];
  482. position = 0;
  483. String gcgiString = new String(gcgid, AFPConstants.EBCIDIC_ENCODING);
  484. String idx = codepage.get(gcgiString);
  485. if (idx != null) {
  486. char cidx = idx.charAt(0);
  487. int width = getUBIN(fiData, 0);
  488. int a = getSBIN(fiData, 10);
  489. int b = getUBIN(fiData, 12);
  490. int c = getSBIN(fiData, 14);
  491. int abc = a + b + c;
  492. int diff = Math.abs(abc - width);
  493. if (diff != 0 && width != 0) {
  494. double diffPercent = 100 * diff / (double)width;
  495. if (diffPercent > 2) {
  496. if (LOG.isTraceEnabled()) {
  497. LOG.trace(gcgiString + ": "
  498. + a + " + " + b + " + " + c + " = " + (a + b + c)
  499. + " but found: " + width);
  500. }
  501. if (firstABCMismatch == null) {
  502. firstABCMismatch = gcgiString;
  503. }
  504. }
  505. }
  506. if (cidx < lowest) {
  507. lowest = cidx;
  508. }
  509. if (cidx > highest) {
  510. highest = cidx;
  511. }
  512. int normalizedWidth = (int)Math.round(width * metricNormalizationFactor);
  513. cso.setWidth(cidx, normalizedWidth);
  514. }
  515. }
  516. }
  517. cso.setFirstChar(lowest);
  518. cso.setLastChar(highest);
  519. if (LOG.isDebugEnabled() && firstABCMismatch != null) {
  520. //Debug level because it usually is no problem.
  521. LOG.debug("Font has metrics inconsitencies where A+B+C doesn't equal the"
  522. + " character increment. The first such character found: "
  523. + firstABCMismatch);
  524. }
  525. }
  526. private static int getUBIN(byte[] data, int start) {
  527. return ((data[start] & 0xFF) << 8) + (data[start + 1] & 0xFF);
  528. }
  529. private static int getSBIN(byte[] data, int start) {
  530. int ubin = ((data[start] & 0xFF) << 8) + (data[start + 1] & 0xFF);
  531. if ((ubin & 0x8000) != 0) {
  532. //extend sign
  533. return ubin | 0xFFFF0000;
  534. } else {
  535. return ubin;
  536. }
  537. }
  538. private class FontControl {
  539. private int dpi;
  540. private int unitsPerEm;
  541. private boolean isRelative = false;
  542. public int getDpi() {
  543. return dpi;
  544. }
  545. public void setDpi(int i) {
  546. dpi = i;
  547. }
  548. public int getUnitsPerEm() {
  549. return this.unitsPerEm;
  550. }
  551. public void setUnitsPerEm(int value) {
  552. this.unitsPerEm = value;
  553. }
  554. public boolean isRelative() {
  555. return isRelative;
  556. }
  557. public void setRelative(boolean b) {
  558. isRelative = b;
  559. }
  560. }
  561. private static class FontDescriptor {
  562. private byte[] data;
  563. public FontDescriptor(byte[] data) {
  564. this.data = data;
  565. }
  566. public int getNominalFontSizeInMillipoints() {
  567. int nominalFontSize = 100 * getUBIN(data, 39);
  568. return nominalFontSize;
  569. }
  570. }
  571. private static final class SingleByteLoader extends CharacterSetBuilder {
  572. private static final SingleByteLoader INSTANCE = new SingleByteLoader();
  573. private SingleByteLoader() {
  574. super();
  575. }
  576. private static SingleByteLoader getInstance() {
  577. return INSTANCE;
  578. }
  579. }
  580. /**
  581. * Double-byte (CID Keyed font (Type 0)) implementation of AFPFontReader.
  582. */
  583. private static final class DoubleByteLoader extends CharacterSetBuilder {
  584. private static final DoubleByteLoader INSTANCE = new DoubleByteLoader();
  585. private DoubleByteLoader() {
  586. }
  587. static DoubleByteLoader getInstance() {
  588. return INSTANCE;
  589. }
  590. protected Map<String, String> loadCodePage(String codePage, String encoding,
  591. AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
  592. // Create the HashMap to store code page information
  593. Map<String, String> codePages = new HashMap<String, String>();
  594. InputStream inputStream = null;
  595. try {
  596. inputStream = openInputStream(accessor, codePage.trim(), eventProducer);
  597. } catch (IOException e) {
  598. eventProducer.codePageNotFound(this, e);
  599. throw e;
  600. }
  601. try {
  602. StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream);
  603. byte[] data;
  604. while ((data = structuredFieldReader.getNext(CHARACTER_TABLE_SF)) != null) {
  605. int position = 0;
  606. byte[] gcgiBytes = new byte[8];
  607. byte[] charBytes = new byte[2];
  608. // Read data, ignoring bytes 0 - 2
  609. for (int index = 3; index < data.length; index++) {
  610. if (position < 8) {
  611. // Build the graphic character global identifier key
  612. gcgiBytes[position] = data[index];
  613. position++;
  614. } else if (position == 9) {
  615. // Set the character
  616. charBytes[0] = data[index];
  617. position++;
  618. } else if (position == 10) {
  619. position = 0;
  620. // Set the character
  621. charBytes[1] = data[index];
  622. String gcgiString = new String(gcgiBytes,
  623. AFPConstants.EBCIDIC_ENCODING);
  624. String charString = new String(charBytes, encoding);
  625. codePages.put(gcgiString, charString);
  626. } else {
  627. position++;
  628. }
  629. }
  630. }
  631. } finally {
  632. closeInputStream(inputStream);
  633. }
  634. return codePages;
  635. }
  636. }
  637. private static int determineOrientation(byte orientation) {
  638. int degrees = 0;
  639. switch (orientation) {
  640. case 0x00:
  641. degrees = 0;
  642. break;
  643. case 0x2D:
  644. degrees = 90;
  645. break;
  646. case 0x5A:
  647. degrees = 180;
  648. break;
  649. case (byte) 0x87:
  650. degrees = 270;
  651. break;
  652. default:
  653. throw new IllegalStateException("Invalid orientation: " + orientation);
  654. }
  655. return degrees;
  656. }
  657. }