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. private 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. private 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. private static FontDescriptor processFontDescriptor(
  335. StructuredFieldReader structuredFieldReader) throws IOException {
  336. byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF);
  337. return new FontDescriptor(fndData);
  338. }
  339. /**
  340. * Process the font control details using the structured field reader.
  341. *
  342. * @param structuredFieldReader
  343. * the structured field reader
  344. * @return the FontControl
  345. * @throws IOException if an I/O exception of some sort has occurred.
  346. */
  347. private FontControl processFontControl(StructuredFieldReader structuredFieldReader)
  348. throws IOException {
  349. byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF);
  350. FontControl fontControl = null;
  351. if (fncData != null) {
  352. fontControl = new FontControl();
  353. if (fncData[7] == (byte) 0x02) {
  354. fontControl.setRelative(true);
  355. }
  356. int metricResolution = getUBIN(fncData, 9);
  357. if (metricResolution == 1000) {
  358. //Special case: 1000 units per em (rather than dpi)
  359. fontControl.setUnitsPerEm(1000);
  360. } else {
  361. fontControl.setDpi(metricResolution / 10);
  362. }
  363. }
  364. return fontControl;
  365. }
  366. /**
  367. * Process the font orientation details from using the structured field
  368. * reader.
  369. *
  370. * @param structuredFieldReader
  371. * the structured field reader
  372. * @return CharacterSetOrientation array
  373. * @throws IOException if an I/O exception of some sort has occurred.
  374. */
  375. private CharacterSetOrientation[] processFontOrientation(
  376. StructuredFieldReader structuredFieldReader) throws IOException {
  377. byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF);
  378. int position = 0;
  379. byte[] fnoData = new byte[26];
  380. List<CharacterSetOrientation> orientations = new ArrayList<CharacterSetOrientation>();
  381. // Read data, ignoring bytes 0 - 2
  382. for (int index = 3; index < data.length; index++) {
  383. // Build the font orientation record
  384. fnoData[position] = data[index];
  385. position++;
  386. if (position == 26) {
  387. position = 0;
  388. int orientation = determineOrientation(fnoData[2]);
  389. // Space Increment
  390. int space = ((fnoData[8] & 0xFF ) << 8) + (fnoData[9] & 0xFF);
  391. // Em-Space Increment
  392. int em = ((fnoData[14] & 0xFF ) << 8) + (fnoData[15] & 0xFF);
  393. CharacterSetOrientation cso = new CharacterSetOrientation(orientation);
  394. cso.setSpaceIncrement(space);
  395. cso.setEmSpaceIncrement(em);
  396. orientations.add(cso);
  397. }
  398. }
  399. return orientations.toArray(EMPTY_CSO_ARRAY);
  400. }
  401. /**
  402. * Populate the CharacterSetOrientation object in the suplied array with the
  403. * font position details using the supplied structured field reader.
  404. *
  405. * @param structuredFieldReader
  406. * the structured field reader
  407. * @param characterSetOrientations
  408. * the array of CharacterSetOrientation objects
  409. * @param metricNormalizationFactor factor to apply to the metrics to get normalized
  410. * font metric values
  411. * @throws IOException if an I/O exception of some sort has occurred.
  412. */
  413. private void processFontPosition(StructuredFieldReader structuredFieldReader,
  414. CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor)
  415. throws IOException {
  416. byte[] data = structuredFieldReader.getNext(FONT_POSITION_SF);
  417. int position = 0;
  418. byte[] fpData = new byte[26];
  419. int characterSetOrientationIndex = 0;
  420. // Read data, ignoring bytes 0 - 2
  421. for (int index = 3; index < data.length; index++) {
  422. if (position < 22) {
  423. // Build the font orientation record
  424. fpData[position] = data[index];
  425. if (position == 9) {
  426. CharacterSetOrientation characterSetOrientation
  427. = characterSetOrientations[characterSetOrientationIndex];
  428. int xHeight = getSBIN(fpData, 2);
  429. int capHeight = getSBIN(fpData, 4);
  430. int ascHeight = getSBIN(fpData, 6);
  431. int dscHeight = getSBIN(fpData, 8);
  432. dscHeight = dscHeight * -1;
  433. characterSetOrientation.setXHeight(
  434. (int)Math.round(xHeight * metricNormalizationFactor));
  435. characterSetOrientation.setCapHeight(
  436. (int)Math.round(capHeight * metricNormalizationFactor));
  437. characterSetOrientation.setAscender(
  438. (int)Math.round(ascHeight * metricNormalizationFactor));
  439. characterSetOrientation.setDescender(
  440. (int)Math.round(dscHeight * metricNormalizationFactor));
  441. }
  442. } else if (position == 22) {
  443. position = 0;
  444. characterSetOrientationIndex++;
  445. fpData[position] = data[index];
  446. }
  447. position++;
  448. }
  449. }
  450. /**
  451. * Process the font index details for the character set orientation.
  452. *
  453. * @param structuredFieldReader the structured field reader
  454. * @param cso the CharacterSetOrientation object to populate
  455. * @param codepage the map of code pages
  456. * @param metricNormalizationFactor factor to apply to the metrics to get normalized
  457. * font metric values
  458. * @throws IOException if an I/O exception of some sort has occurred.
  459. */
  460. private void processFontIndex(StructuredFieldReader structuredFieldReader,
  461. CharacterSetOrientation cso, Map<String, String> codepage,
  462. double metricNormalizationFactor)
  463. throws IOException {
  464. byte[] data = structuredFieldReader.getNext(FONT_INDEX_SF);
  465. int position = 0;
  466. byte[] gcgid = new byte[8];
  467. byte[] fiData = new byte[20];
  468. char lowest = 255;
  469. char highest = 0;
  470. String firstABCMismatch = null;
  471. // Read data, ignoring bytes 0 - 2
  472. for (int index = 3; index < data.length; index++) {
  473. if (position < 8) {
  474. gcgid[position] = data[index];
  475. position++;
  476. } else if (position < 27) {
  477. fiData[position - 8] = data[index];
  478. position++;
  479. } else if (position == 27) {
  480. fiData[position - 8] = data[index];
  481. position = 0;
  482. String gcgiString = new String(gcgid, AFPConstants.EBCIDIC_ENCODING);
  483. String idx = codepage.get(gcgiString);
  484. if (idx != null) {
  485. char cidx = idx.charAt(0);
  486. int width = getUBIN(fiData, 0);
  487. int a = getSBIN(fiData, 10);
  488. int b = getUBIN(fiData, 12);
  489. int c = getSBIN(fiData, 14);
  490. int abc = a + b + c;
  491. int diff = Math.abs(abc - width);
  492. if (diff != 0 && width != 0) {
  493. double diffPercent = 100 * diff / (double)width;
  494. if (diffPercent > 2) {
  495. if (LOG.isTraceEnabled()) {
  496. LOG.trace(gcgiString + ": "
  497. + a + " + " + b + " + " + c + " = " + (a + b + c)
  498. + " but found: " + width);
  499. }
  500. if (firstABCMismatch == null) {
  501. firstABCMismatch = gcgiString;
  502. }
  503. }
  504. }
  505. if (cidx < lowest) {
  506. lowest = cidx;
  507. }
  508. if (cidx > highest) {
  509. highest = cidx;
  510. }
  511. int normalizedWidth = (int)Math.round(width * metricNormalizationFactor);
  512. cso.setWidth(cidx, normalizedWidth);
  513. }
  514. }
  515. }
  516. cso.setFirstChar(lowest);
  517. cso.setLastChar(highest);
  518. if (LOG.isDebugEnabled() && firstABCMismatch != null) {
  519. //Debug level because it usually is no problem.
  520. LOG.debug("Font has metrics inconsitencies where A+B+C doesn't equal the"
  521. + " character increment. The first such character found: "
  522. + firstABCMismatch);
  523. }
  524. }
  525. private static int getUBIN(byte[] data, int start) {
  526. return ((data[start] & 0xFF) << 8) + (data[start + 1] & 0xFF);
  527. }
  528. private static int getSBIN(byte[] data, int start) {
  529. int ubin = ((data[start] & 0xFF) << 8) + (data[start + 1] & 0xFF);
  530. if ((ubin & 0x8000) != 0) {
  531. //extend sign
  532. return ubin | 0xFFFF0000;
  533. } else {
  534. return ubin;
  535. }
  536. }
  537. private class FontControl {
  538. private int dpi;
  539. private int unitsPerEm;
  540. private boolean isRelative = false;
  541. public int getDpi() {
  542. return dpi;
  543. }
  544. public void setDpi(int i) {
  545. dpi = i;
  546. }
  547. public int getUnitsPerEm() {
  548. return this.unitsPerEm;
  549. }
  550. public void setUnitsPerEm(int value) {
  551. this.unitsPerEm = value;
  552. }
  553. public boolean isRelative() {
  554. return isRelative;
  555. }
  556. public void setRelative(boolean b) {
  557. isRelative = b;
  558. }
  559. }
  560. private static class FontDescriptor {
  561. private byte[] data;
  562. public FontDescriptor(byte[] data) {
  563. this.data = data;
  564. }
  565. public int getNominalFontSizeInMillipoints() {
  566. int nominalFontSize = 100 * getUBIN(data, 39);
  567. return nominalFontSize;
  568. }
  569. }
  570. private static final class SingleByteLoader extends CharacterSetBuilder {
  571. private static final SingleByteLoader INSTANCE = new SingleByteLoader();
  572. private SingleByteLoader() {
  573. super();
  574. }
  575. private static SingleByteLoader getInstance() {
  576. return INSTANCE;
  577. }
  578. }
  579. /**
  580. * Double-byte (CID Keyed font (Type 0)) implementation of AFPFontReader.
  581. */
  582. private static final class DoubleByteLoader extends CharacterSetBuilder {
  583. private static final DoubleByteLoader INSTANCE = new DoubleByteLoader();
  584. private DoubleByteLoader() {
  585. }
  586. static DoubleByteLoader getInstance() {
  587. return INSTANCE;
  588. }
  589. @Override
  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 = super.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. super.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. }