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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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.<br>
  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.<br>
  55. * This class will read the font information from the binary code page files and character
  56. * set metric files in order to determine the correct metrics to use when rendering the
  57. * formatted object.
  58. */
  59. public abstract class CharacterSetBuilder {
  60. /**
  61. * Static logging instance
  62. */
  63. protected static final Log LOG = LogFactory.getLog(CharacterSetBuilder.class);
  64. /**
  65. * Template used to convert lists to arrays.
  66. */
  67. private static final CharacterSetOrientation[] EMPTY_CSO_ARRAY = new CharacterSetOrientation[0];
  68. /** Codepage MO:DCA structured field. */
  69. private static final byte[] CODEPAGE_SF = new byte[] {
  70. (byte) 0xD3, (byte) 0xA8, (byte) 0x87};
  71. /** Character table MO:DCA structured field. */
  72. private static final byte[] CHARACTER_TABLE_SF = new byte[] {
  73. (byte) 0xD3, (byte) 0x8C, (byte) 0x87};
  74. /** Font descriptor MO:DCA structured field. */
  75. private static final byte[] FONT_DESCRIPTOR_SF = new byte[] {
  76. (byte) 0xD3, (byte) 0xA6, (byte) 0x89 };
  77. /** Font control MO:DCA structured field. */
  78. private static final byte[] FONT_CONTROL_SF = new byte[] {
  79. (byte) 0xD3, (byte) 0xA7, (byte) 0x89 };
  80. /** Font orientation MO:DCA structured field. */
  81. private static final byte[] FONT_ORIENTATION_SF = new byte[] {
  82. (byte) 0xD3, (byte) 0xAE, (byte) 0x89 };
  83. /** Font position MO:DCA structured field. */
  84. private static final byte[] FONT_POSITION_SF = new byte[] {
  85. (byte) 0xD3, (byte) 0xAC, (byte) 0x89 };
  86. /** Font index MO:DCA structured field. */
  87. private static final byte[] FONT_INDEX_SF = new byte[] {
  88. (byte) 0xD3, (byte) 0x8C, (byte) 0x89 };
  89. /**
  90. * The collection of code pages
  91. */
  92. private final Map<String, Map<String, String>> codePagesCache
  93. = Collections.synchronizedMap(new WeakHashMap<String, Map<String, String>>());
  94. /**
  95. * Cache of charactersets
  96. */
  97. private final SoftMapCache characterSetsCache = new SoftMapCache(true);
  98. /** Default constructor. */
  99. private CharacterSetBuilder() {
  100. }
  101. /**
  102. * Factory method for the single-byte implementation of AFPFontReader.
  103. * @return AFPFontReader
  104. */
  105. public static CharacterSetBuilder getSingleByteInstance() {
  106. return SingleByteLoader.getInstance();
  107. }
  108. /**
  109. * Factory method for the double-byte (CID Keyed font (Type 0)) implementation of AFPFontReader.
  110. * @return AFPFontReader
  111. */
  112. public static CharacterSetBuilder getDoubleByteInstance() {
  113. return DoubleByteLoader.getInstance();
  114. }
  115. /**
  116. * Returns an InputStream to a given file path and filename
  117. *
  118. * @param accessor the resource accessor
  119. * @param uriStr the URI
  120. * @param eventProducer for handling AFP related events
  121. * @return an inputStream
  122. * @throws IOException in the event that an I/O exception of some sort has occurred
  123. */
  124. private InputStream openInputStream(AFPResourceAccessor accessor, String uriStr,
  125. AFPEventProducer eventProducer)
  126. throws IOException {
  127. URI uri;
  128. try {
  129. uri = InternalResourceResolver.cleanURI(uriStr.trim());
  130. } catch (URISyntaxException e) {
  131. throw new MalformedURLException("Invalid uri: " + uriStr + " (" + e.getMessage() + ")");
  132. }
  133. if (LOG.isDebugEnabled()) {
  134. LOG.debug("Opening " + uri);
  135. }
  136. return accessor.createInputStream(uri);
  137. }
  138. /**
  139. * Closes the inputstream
  140. *
  141. * @param inputStream the inputstream to close
  142. */
  143. private void closeInputStream(InputStream inputStream) {
  144. try {
  145. if (inputStream != null) {
  146. inputStream.close();
  147. }
  148. } catch (Exception ex) {
  149. // Lets log at least!
  150. LOG.error(ex.getMessage());
  151. }
  152. }
  153. /**
  154. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  155. * actual afp code page and character set files to load the object with the necessary metrics.
  156. *
  157. * @param characterSetName name of the characterset
  158. * @param codePageName name of the code page file
  159. * @param encoding encoding name
  160. * @param accessor used to load codepage and characterset
  161. * @param eventProducer for handling AFP related events
  162. * @return CharacterSet object
  163. * @throws IOException if an I/O error occurs
  164. */
  165. public CharacterSet buildSBCS(String characterSetName, String codePageName, String encoding,
  166. AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
  167. return processFont(characterSetName, codePageName, encoding, CharacterSetType.SINGLE_BYTE,
  168. accessor, eventProducer);
  169. }
  170. /**
  171. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  172. * actual afp code page and character set files to load the object with the necessary metrics.
  173. * This method is to be used for double byte character sets (DBCS).
  174. *
  175. * @param characterSetName name of the characterset
  176. * @param codePageName name of the code page file
  177. * @param encoding encoding name
  178. * @param charsetType the characterset type
  179. * @param accessor used to load codepage and characterset
  180. * @param eventProducer for handling AFP related events
  181. * @return CharacterSet object
  182. * @throws IOException if an I/O error occurs
  183. */
  184. public CharacterSet buildDBCS(String characterSetName, String codePageName, String encoding,
  185. CharacterSetType charsetType, AFPResourceAccessor accessor, AFPEventProducer eventProducer)
  186. throws IOException {
  187. return processFont(characterSetName, codePageName, encoding, charsetType, accessor,
  188. eventProducer);
  189. }
  190. /**
  191. * Load the font details and metrics into the CharacterSetMetric object, this will use the
  192. * actual afp code page and character set files to load the object with the necessary metrics.
  193. *
  194. * @param characterSetName the CharacterSetMetric object to populate
  195. * @param codePageName the name of the code page to use
  196. * @param encoding name of the encoding in use
  197. * @param typeface base14 font name
  198. * @param eventProducer for handling AFP related events
  199. * @return CharacterSet object
  200. * @throws IOException if an I/O error occurs
  201. */
  202. public CharacterSet build(String characterSetName, String codePageName, String encoding,
  203. Typeface typeface, AFPEventProducer eventProducer) throws IOException {
  204. return new FopCharacterSet(codePageName, encoding, characterSetName, typeface,
  205. eventProducer);
  206. }
  207. public CharacterSet build(String characterSetName, String codePageName, String encoding,
  208. Typeface typeface, AFPResourceAccessor accessor, AFPEventProducer eventProducer)
  209. throws IOException {
  210. return new FopCharacterSet(codePageName, encoding, characterSetName, typeface, accessor, eventProducer);
  211. }
  212. private CharacterSet processFont(String characterSetName, String codePageName, String encoding,
  213. CharacterSetType charsetType, AFPResourceAccessor accessor, AFPEventProducer eventProducer)
  214. throws IOException {
  215. // check for cached version of the characterset
  216. URI charSetURI = accessor.resolveURI(characterSetName);
  217. String cacheKey = charSetURI.toASCIIString() + "_" + characterSetName + "_" + codePageName;
  218. CharacterSet characterSet = (CharacterSet) characterSetsCache.get(cacheKey);
  219. if (characterSet != null) {
  220. return characterSet;
  221. }
  222. // characterset not in the cache, so recreating
  223. characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName,
  224. accessor, eventProducer);
  225. InputStream inputStream = null;
  226. try {
  227. /**
  228. * Get the code page which contains the character mapping
  229. * information to map the unicode character id to the graphic
  230. * chracter global identifier.
  231. */
  232. Map<String, String> codePage;
  233. // TODO: This could have performance implications if several threads want to use the
  234. // codePagesCache to retrieve different codepages.
  235. synchronized (codePagesCache) {
  236. codePage = codePagesCache.get(codePageName);
  237. if (codePage == null) {
  238. codePage = loadCodePage(codePageName, encoding, accessor, eventProducer);
  239. codePagesCache.put(codePageName, codePage);
  240. }
  241. }
  242. inputStream = openInputStream(accessor, characterSetName, eventProducer);
  243. StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream);
  244. // Process D3A689 Font Descriptor
  245. FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader);
  246. characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints());
  247. // Process D3A789 Font Control
  248. FontControl fontControl = processFontControl(structuredFieldReader);
  249. if (fontControl != null) {
  250. //process D3AE89 Font Orientation
  251. CharacterSetOrientation[] characterSetOrientations
  252. = processFontOrientation(structuredFieldReader);
  253. double metricNormalizationFactor;
  254. if (fontControl.isRelative()) {
  255. metricNormalizationFactor = 1;
  256. } else {
  257. int dpi = fontControl.getDpi();
  258. metricNormalizationFactor = 1000.0d * 72000.0d
  259. / fontDescriptor.getNominalFontSizeInMillipoints() / dpi;
  260. }
  261. ValueNormalizer normalizer = new ValueNormalizer(metricNormalizationFactor);
  262. //process D3AC89 Font Position
  263. processFontPosition(structuredFieldReader, characterSetOrientations, normalizer);
  264. //process D38C89 Font Index (per orientation)
  265. for (int i = 0; i < characterSetOrientations.length; i++) {
  266. CharacterSetOrientation characterSetOrientation = characterSetOrientations[i];
  267. processFontIndex(structuredFieldReader, characterSetOrientation, codePage, normalizer);
  268. characterSet.addCharacterSetOrientation(characterSetOrientation);
  269. }
  270. } else {
  271. throw new IOException("Missing D3AE89 Font Control structured field.");
  272. }
  273. } finally {
  274. closeInputStream(inputStream);
  275. }
  276. characterSetsCache.put(cacheKey, characterSet);
  277. return characterSet;
  278. }
  279. private static class ValueNormalizer {
  280. private final double factor;
  281. public ValueNormalizer(double factor) {
  282. this.factor = factor;
  283. }
  284. public int normalize(int value) {
  285. return (int) Math.round(value * factor);
  286. }
  287. }
  288. /**
  289. * Load the code page information from the appropriate file. The file name
  290. * to load is determined by the code page name and the file extension 'CDP'.
  291. *
  292. * @param codePage
  293. * the code page identifier
  294. * @param encoding
  295. * the encoding to use for the character decoding
  296. * @param accessor the resource accessor
  297. * @param eventProducer for handling AFP related events
  298. * @return a code page mapping (key: GCGID, value: Unicode character)
  299. * @throws IOException if an I/O exception of some sort has occurred.
  300. */
  301. protected Map<String, String> loadCodePage(String codePage, String encoding,
  302. AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
  303. // Create the HashMap to store code page information
  304. Map<String, String> codePages = new HashMap<String, String>();
  305. InputStream inputStream = null;
  306. try {
  307. inputStream = openInputStream(accessor, codePage.trim(), eventProducer);
  308. } catch (IOException e) {
  309. eventProducer.codePageNotFound(this, e);
  310. throw e;
  311. }
  312. try {
  313. StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream);
  314. byte[] data = structuredFieldReader.getNext(CHARACTER_TABLE_SF);
  315. int position = 0;
  316. byte[] gcgiBytes = new byte[8];
  317. byte[] charBytes = new byte[1];
  318. // Read data, ignoring bytes 0 - 2
  319. for (int index = 3; index < data.length; index++) {
  320. if (position < 8) {
  321. // Build the graphic character global identifier key
  322. gcgiBytes[position] = data[index];
  323. position++;
  324. } else if (position == 9) {
  325. position = 0;
  326. // Set the character
  327. charBytes[0] = data[index];
  328. String gcgiString = new String(gcgiBytes,
  329. AFPConstants.EBCIDIC_ENCODING);
  330. //Use the 8-bit char index to find the Unicode character using the Java encoding
  331. //given in the configuration. If the code page and the Java encoding don't
  332. //match, a wrong Unicode character will be associated with the AFP GCGID.
  333. //Idea: we could use IBM's GCGID to Unicode map and build code pages ourselves.
  334. String charString = new String(charBytes, encoding);
  335. codePages.put(gcgiString, charString);
  336. } else {
  337. position++;
  338. }
  339. }
  340. } finally {
  341. closeInputStream(inputStream);
  342. }
  343. return codePages;
  344. }
  345. /**
  346. * Process the font descriptor details using the structured field reader.
  347. *
  348. * @param structuredFieldReader the structured field reader
  349. * @return a class representing the font descriptor
  350. * @throws IOException if an I/O exception of some sort has occurred.
  351. */
  352. private static FontDescriptor processFontDescriptor(
  353. StructuredFieldReader structuredFieldReader) throws IOException {
  354. byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF);
  355. return new FontDescriptor(fndData);
  356. }
  357. /**
  358. * Process the font control details using the structured field reader.
  359. *
  360. * @param structuredFieldReader
  361. * the structured field reader
  362. * @return the FontControl
  363. * @throws IOException if an I/O exception of some sort has occurred.
  364. */
  365. private FontControl processFontControl(StructuredFieldReader structuredFieldReader)
  366. throws IOException {
  367. byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF);
  368. FontControl fontControl = null;
  369. if (fncData != null) {
  370. fontControl = new FontControl();
  371. if (fncData[7] == (byte) 0x02) {
  372. fontControl.setRelative(true);
  373. }
  374. int metricResolution = getUBIN(fncData, 9);
  375. if (metricResolution == 1000) {
  376. //Special case: 1000 units per em (rather than dpi)
  377. fontControl.setUnitsPerEm(1000);
  378. } else {
  379. fontControl.setDpi(metricResolution / 10);
  380. }
  381. }
  382. return fontControl;
  383. }
  384. /**
  385. * Process the font orientation details from using the structured field
  386. * reader.
  387. *
  388. * @param structuredFieldReader
  389. * the structured field reader
  390. * @return CharacterSetOrientation array
  391. * @throws IOException if an I/O exception of some sort has occurred.
  392. */
  393. private CharacterSetOrientation[] processFontOrientation(
  394. StructuredFieldReader structuredFieldReader) throws IOException {
  395. byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF);
  396. int position = 0;
  397. byte[] fnoData = new byte[26];
  398. List<CharacterSetOrientation> orientations = new ArrayList<CharacterSetOrientation>();
  399. // Read data, ignoring bytes 0 - 2
  400. for (int index = 3; index < data.length; index++) {
  401. // Build the font orientation record
  402. fnoData[position] = data[index];
  403. position++;
  404. if (position == 26) {
  405. position = 0;
  406. int orientation = determineOrientation(fnoData[2]);
  407. int spaceIncrement = getUBIN(fnoData, 8);
  408. int emIncrement = getUBIN(fnoData, 14);
  409. int nominalCharacterIncrement = getUBIN(fnoData, 20);
  410. orientations.add(new CharacterSetOrientation(orientation, spaceIncrement,
  411. emIncrement, nominalCharacterIncrement));
  412. }
  413. }
  414. return orientations.toArray(EMPTY_CSO_ARRAY);
  415. }
  416. /**
  417. * Populate the CharacterSetOrientation object in the suplied array with the
  418. * font position details using the supplied structured field reader.
  419. *
  420. * @param structuredFieldReader
  421. * the structured field reader
  422. * @param characterSetOrientations
  423. * the array of CharacterSetOrientation objects
  424. * @param metricNormalizationFactor factor to apply to the metrics to get normalized
  425. * font metric values
  426. * @throws IOException if an I/O exception of some sort has occurred.
  427. */
  428. private void processFontPosition(StructuredFieldReader structuredFieldReader,
  429. CharacterSetOrientation[] characterSetOrientations, ValueNormalizer normalizer)
  430. throws IOException {
  431. byte[] data = structuredFieldReader.getNext(FONT_POSITION_SF);
  432. int position = 0;
  433. byte[] fpData = new byte[26];
  434. int characterSetOrientationIndex = 0;
  435. // Read data, ignoring bytes 0 - 2
  436. for (int index = 3; index < data.length; index++) {
  437. if (position < 22) {
  438. // Build the font orientation record
  439. fpData[position] = data[index];
  440. if (position == 9) {
  441. CharacterSetOrientation characterSetOrientation
  442. = characterSetOrientations[characterSetOrientationIndex];
  443. int xHeight = getSBIN(fpData, 2);
  444. int capHeight = getSBIN(fpData, 4);
  445. int ascHeight = getSBIN(fpData, 6);
  446. int dscHeight = getSBIN(fpData, 8);
  447. dscHeight = dscHeight * -1;
  448. int underscoreWidth = getUBIN(fpData, 17);
  449. int underscorePosition = getSBIN(fpData, 20);
  450. characterSetOrientation.setXHeight(normalizer.normalize(xHeight));
  451. characterSetOrientation.setCapHeight(normalizer.normalize(capHeight));
  452. characterSetOrientation.setAscender(normalizer.normalize(ascHeight));
  453. characterSetOrientation.setDescender(normalizer.normalize(dscHeight));
  454. characterSetOrientation.setUnderscoreWidth(normalizer.normalize(underscoreWidth));
  455. characterSetOrientation.setUnderscorePosition(normalizer.normalize(underscorePosition));
  456. }
  457. } else if (position == 22) {
  458. position = 0;
  459. characterSetOrientationIndex++;
  460. fpData[position] = data[index];
  461. }
  462. position++;
  463. }
  464. }
  465. private void processFontIndex(StructuredFieldReader structuredFieldReader, CharacterSetOrientation cso,
  466. Map<String, String> codepage, ValueNormalizer normalizer)
  467. throws IOException {
  468. byte[] data = structuredFieldReader.getNext(FONT_INDEX_SF);
  469. int position = 0;
  470. byte[] gcgid = new byte[8];
  471. byte[] fiData = new byte[20];
  472. String firstABCMismatch = null;
  473. // Read data, ignoring bytes 0 - 2
  474. for (int index = 3; index < data.length; index++) {
  475. if (position < 8) {
  476. gcgid[position] = data[index];
  477. position++;
  478. } else if (position < 27) {
  479. fiData[position - 8] = data[index];
  480. position++;
  481. } else if (position == 27) {
  482. fiData[position - 8] = data[index];
  483. position = 0;
  484. String gcgiString = new String(gcgid, AFPConstants.EBCIDIC_ENCODING);
  485. String idx = codepage.get(gcgiString);
  486. if (idx != null) {
  487. char cidx = idx.charAt(0);
  488. int width = getUBIN(fiData, 0);
  489. int ascendHt = getSBIN(fiData, 2);
  490. int descendDp = getSBIN(fiData, 4);
  491. int a = getSBIN(fiData, 10);
  492. int b = getUBIN(fiData, 12);
  493. int c = getSBIN(fiData, 14);
  494. int abc = a + b + c;
  495. int diff = Math.abs(abc - width);
  496. if (diff != 0 && width != 0) {
  497. double diffPercent = 100 * diff / (double) width;
  498. if (diffPercent > 2) {
  499. if (LOG.isTraceEnabled()) {
  500. LOG.trace(gcgiString + ": "
  501. + a + " + " + b + " + " + c + " = " + (a + b + c)
  502. + " but found: " + width);
  503. }
  504. if (firstABCMismatch == null) {
  505. firstABCMismatch = gcgiString;
  506. }
  507. }
  508. }
  509. int normalizedWidth = normalizer.normalize(width);
  510. int x0 = normalizer.normalize(a);
  511. int y0 = normalizer.normalize(-descendDp);
  512. int dx = normalizer.normalize(b);
  513. int dy = normalizer.normalize(ascendHt + descendDp);
  514. cso.setCharacterMetrics(cidx, normalizedWidth, new Rectangle(x0, y0, dx, dy));
  515. }
  516. }
  517. }
  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;
  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. }