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

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