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.

AFMParser.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.fonts.type1;
  19. import java.awt.Rectangle;
  20. import java.beans.Statement;
  21. import java.io.BufferedReader;
  22. import java.io.File;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.Reader;
  26. import java.util.Map;
  27. import java.util.Stack;
  28. import org.apache.commons.io.IOUtils;
  29. /**
  30. * Parses the contents of a Type 1 AFM font metrics file into an object structure ({@link AFMFile}).
  31. */
  32. public class AFMParser {
  33. private static final String START_FONT_METRICS = "StartFontMetrics";
  34. //private static final String END_FONT_METRICS = "EndFontMetrics";
  35. private static final String FONT_NAME = "FontName";
  36. private static final String FULL_NAME = "FullName";
  37. private static final String FAMILY_NAME = "FamilyName";
  38. private static final String WEIGHT = "Weight";
  39. private static final String FONT_BBOX = "FontBBox";
  40. private static final String ENCODING_SCHEME = "EncodingScheme";
  41. private static final String CHARACTER_SET = "CharacterSet";
  42. private static final String IS_BASE_FONT = "IsBaseFont";
  43. private static final String IS_CID_FONT = "IsCIDFont";
  44. private static final String CAP_HEIGHT = "CapHeight";
  45. private static final String X_HEIGHT = "XHeight";
  46. private static final String ASCENDER = "Ascender";
  47. private static final String DESCENDER = "Descender";
  48. private static final String STDHW = "StdHW";
  49. private static final String STDVW = "StdVW";
  50. private static final String UNDERLINE_POSITION = "UnderlinePosition";
  51. private static final String UNDERLINE_THICKNESS = "UnderlineThickness";
  52. private static final String ITALIC_ANGLE = "ItalicAngle";
  53. private static final String IS_FIXED_PITCH = "IsFixedPitch";
  54. private static final String START_DIRECTION = "StartDirection";
  55. private static final String END_DIRECTION = "EndDirection";
  56. private static final String START_CHAR_METRICS = "StartCharMetrics";
  57. private static final String END_CHAR_METRICS = "EndCharMetrics";
  58. private static final String C = "C";
  59. private static final String CH = "CH";
  60. private static final String WX = "WX";
  61. private static final String W0X = "W0X";
  62. private static final String W1X = "W1X";
  63. private static final String WY = "WY";
  64. private static final String W0Y = "W0Y";
  65. private static final String W1Y = "W1Y";
  66. private static final String W = "W";
  67. private static final String W0 = "W0";
  68. private static final String W1 = "W1";
  69. private static final String N = "N";
  70. private static final String START_TRACK_KERN = "StartTrackKern";
  71. private static final String END_TRACK_KERN = "EndTrackKern";
  72. //private static final String START_KERN_PAIRS = "StartKernPairs";
  73. //private static final String START_KERN_PAIRS0 = "StartKernPairs0";
  74. private static final String START_KERN_PAIRS1 = "StartKernPairs1";
  75. //private static final String END_KERN_PAIRS = "EndKernPairs";
  76. private static final String KP = "KP";
  77. private static final String KPH = "KPH";
  78. private static final String KPX = "KPX";
  79. private static final String KPY = "KPY";
  80. private static final int PARSE_NORMAL = 0;
  81. private static final int PARSE_CHAR_METRICS = 1;
  82. private static final Map VALUE_PARSERS;
  83. private static final Map PARSE_MODE_CHANGES;
  84. static {
  85. VALUE_PARSERS = new java.util.HashMap();
  86. VALUE_PARSERS.put(START_FONT_METRICS, new StartFontMetrics());
  87. VALUE_PARSERS.put(FONT_NAME, new StringSetter(FONT_NAME));
  88. VALUE_PARSERS.put(FULL_NAME, new StringSetter(FULL_NAME));
  89. VALUE_PARSERS.put(FAMILY_NAME, new StringSetter(FAMILY_NAME));
  90. VALUE_PARSERS.put(WEIGHT, new StringSetter(WEIGHT));
  91. VALUE_PARSERS.put(ENCODING_SCHEME, new StringSetter(ENCODING_SCHEME));
  92. VALUE_PARSERS.put(FONT_BBOX, new FontBBox());
  93. VALUE_PARSERS.put(CHARACTER_SET, new StringSetter(CHARACTER_SET));
  94. VALUE_PARSERS.put(IS_BASE_FONT, new IsBaseFont());
  95. VALUE_PARSERS.put(IS_CID_FONT, new IsCIDFont());
  96. VALUE_PARSERS.put(CAP_HEIGHT, new NumberSetter(CAP_HEIGHT));
  97. VALUE_PARSERS.put(X_HEIGHT, new NumberSetter(X_HEIGHT));
  98. VALUE_PARSERS.put(ASCENDER, new NumberSetter(ASCENDER));
  99. VALUE_PARSERS.put(DESCENDER, new NumberSetter(DESCENDER));
  100. VALUE_PARSERS.put(STDHW, new NumberSetter(STDHW));
  101. VALUE_PARSERS.put(STDVW, new NumberSetter(STDVW));
  102. VALUE_PARSERS.put(START_DIRECTION, new StartDirection());
  103. VALUE_PARSERS.put(END_DIRECTION, new EndDirection());
  104. VALUE_PARSERS.put(UNDERLINE_POSITION, new WritingDirNumberSetter(UNDERLINE_POSITION));
  105. VALUE_PARSERS.put(UNDERLINE_THICKNESS, new WritingDirNumberSetter(UNDERLINE_THICKNESS));
  106. VALUE_PARSERS.put(ITALIC_ANGLE, new WritingDirDoubleSetter(ITALIC_ANGLE));
  107. VALUE_PARSERS.put(IS_FIXED_PITCH, new WritingDirBooleanSetter(IS_FIXED_PITCH));
  108. VALUE_PARSERS.put(C, new IntegerSetter("CharCode"));
  109. VALUE_PARSERS.put(CH, new NotImplementedYet(CH));
  110. VALUE_PARSERS.put(WX, new DoubleSetter("WidthX"));
  111. VALUE_PARSERS.put(W0X, new DoubleSetter("WidthX"));
  112. VALUE_PARSERS.put(W1X, new NotImplementedYet(W1X));
  113. VALUE_PARSERS.put(WY, new DoubleSetter("WidthY"));
  114. VALUE_PARSERS.put(W0Y, new DoubleSetter("WidthY"));
  115. VALUE_PARSERS.put(W1Y, new NotImplementedYet(W1Y));
  116. VALUE_PARSERS.put(W, new NotImplementedYet(W));
  117. VALUE_PARSERS.put(W0, new NotImplementedYet(W0));
  118. VALUE_PARSERS.put(W1, new NotImplementedYet(W1));
  119. VALUE_PARSERS.put(N, new StringSetter("CharName"));
  120. VALUE_PARSERS.put(START_TRACK_KERN, new NotImplementedYet(START_TRACK_KERN));
  121. VALUE_PARSERS.put(END_TRACK_KERN, new NotImplementedYet(END_TRACK_KERN));
  122. VALUE_PARSERS.put(START_KERN_PAIRS1, new NotImplementedYet(START_KERN_PAIRS1));
  123. VALUE_PARSERS.put(KP, new NotImplementedYet(KP));
  124. VALUE_PARSERS.put(KPH, new NotImplementedYet(KPH));
  125. VALUE_PARSERS.put(KPX, new KPXHandler());
  126. VALUE_PARSERS.put(KPY, new NotImplementedYet(KPY));
  127. PARSE_MODE_CHANGES = new java.util.HashMap();
  128. PARSE_MODE_CHANGES.put(START_CHAR_METRICS, new Integer(PARSE_CHAR_METRICS));
  129. PARSE_MODE_CHANGES.put(END_CHAR_METRICS, new Integer(PARSE_NORMAL));
  130. }
  131. /**
  132. * Main constructor.
  133. */
  134. public AFMParser() {
  135. //nop
  136. }
  137. /**
  138. * Parses an AFM file from a local file.
  139. * @param afmFile the AFM file
  140. * @return the parsed AFM file
  141. * @throws IOException if an I/O error occurs
  142. */
  143. public AFMFile parse(File afmFile) throws IOException {
  144. InputStream in = new java.io.FileInputStream(afmFile);
  145. try {
  146. return parse(in);
  147. } finally {
  148. IOUtils.closeQuietly(in);
  149. }
  150. }
  151. /**
  152. * Parses an AFM file from a stream.
  153. * @param in the stream to read from
  154. * @return the parsed AFM file
  155. * @throws IOException if an I/O error occurs
  156. */
  157. public AFMFile parse(InputStream in) throws IOException {
  158. Reader reader = new java.io.InputStreamReader(in, "US-ASCII");
  159. try {
  160. return parse(new BufferedReader(reader));
  161. } finally {
  162. IOUtils.closeQuietly(reader);
  163. }
  164. }
  165. /**
  166. * Parses an AFM file from a BufferedReader.
  167. * @param reader the BufferedReader instance to read from
  168. * @return the parsed AFM file
  169. * @throws IOException if an I/O error occurs
  170. */
  171. public AFMFile parse(BufferedReader reader) throws IOException {
  172. Stack stack = new Stack();
  173. int parseMode = PARSE_NORMAL;
  174. while (true) {
  175. String line = reader.readLine();
  176. if (line == null) {
  177. break;
  178. }
  179. String key = null;
  180. switch (parseMode) {
  181. case PARSE_NORMAL:
  182. key = parseLine(line, stack);
  183. break;
  184. case PARSE_CHAR_METRICS:
  185. key = parseCharMetrics(line, stack);
  186. break;
  187. default:
  188. throw new IllegalStateException("Invalid parse mode");
  189. }
  190. Integer newParseMode = (Integer)PARSE_MODE_CHANGES.get(key);
  191. if (newParseMode != null) {
  192. parseMode = newParseMode.intValue();
  193. }
  194. }
  195. return (AFMFile)stack.pop();
  196. }
  197. private String parseLine(String line, Stack stack) throws IOException {
  198. int startpos = 0;
  199. //Find key
  200. startpos = skipToNonWhiteSpace(line, startpos);
  201. int endpos = skipToWhiteSpace(line, startpos);
  202. String key = line.substring(startpos, endpos);
  203. //Parse value
  204. startpos = skipToNonWhiteSpace(line, endpos);
  205. ValueHandler vp = (ValueHandler)VALUE_PARSERS.get(key);
  206. if (vp != null) {
  207. vp.parse(line, startpos, stack);
  208. }
  209. return key;
  210. }
  211. private String parseCharMetrics(String line, Stack stack) throws IOException {
  212. int startpos = 0;
  213. AFMCharMetrics chm = new AFMCharMetrics();
  214. stack.push(chm);
  215. while (true) {
  216. //Find key
  217. startpos = skipToNonWhiteSpace(line, startpos);
  218. int endpos = skipToWhiteSpace(line, startpos);
  219. String key = line.substring(startpos, endpos);
  220. if (END_CHAR_METRICS.equals(key)) {
  221. stack.pop(); //Pop and forget unused AFMCharMetrics instance
  222. return key;
  223. } else if (key.length() == 0) {
  224. //EOL: No more key so break
  225. break;
  226. }
  227. //Extract value
  228. startpos = skipToNonWhiteSpace(line, endpos);
  229. endpos = skipToSemicolon(line, startpos);
  230. String value = line.substring(startpos, endpos).trim();
  231. startpos = endpos + 1;
  232. //Parse value
  233. ValueHandler vp = (ValueHandler)VALUE_PARSERS.get(key);
  234. if (vp != null) {
  235. vp.parse(value, 0, stack);
  236. }
  237. if (false) {
  238. break;
  239. }
  240. }
  241. stack.pop();
  242. AFMFile afm = (AFMFile)stack.peek();
  243. afm.addCharMetrics(chm);
  244. return null;
  245. }
  246. private static int skipToNonWhiteSpace(String line, int startpos) {
  247. int pos = startpos;
  248. while (pos < line.length() && isWhitespace(line.charAt(pos))) {
  249. pos++;
  250. }
  251. return pos;
  252. }
  253. private static int skipToWhiteSpace(String line, int startpos) {
  254. int pos = startpos;
  255. while (pos < line.length() && !isWhitespace(line.charAt(pos))) {
  256. pos++;
  257. }
  258. return pos;
  259. }
  260. private static int skipToSemicolon(String line, int startpos) {
  261. int pos = startpos;
  262. while (pos < line.length() && ';' != line.charAt(pos)) {
  263. pos++;
  264. }
  265. return pos;
  266. }
  267. private static boolean isWhitespace(char ch) {
  268. return ch == ' '
  269. || ch == '\t';
  270. }
  271. // ---------------- Value Handlers ---------------------------
  272. private interface ValueHandler {
  273. void parse(String line, int startpos, Stack stack) throws IOException;
  274. }
  275. private abstract static class AbstractValueHandler implements ValueHandler {
  276. protected int findValue(String line, int startpos) {
  277. return skipToWhiteSpace(line, startpos);
  278. }
  279. protected String getStringValue(String line, int startpos) {
  280. return line.substring(startpos);
  281. }
  282. protected Number getNumberValue(String line, int startpos) {
  283. try {
  284. return new Integer(getIntegerValue(line, startpos));
  285. } catch (NumberFormatException nfe) {
  286. return new Double(getDoubleValue(line, startpos));
  287. }
  288. }
  289. protected int getIntegerValue(String line, int startpos) {
  290. int endpos = findValue(line, startpos);
  291. return Integer.parseInt(line.substring(startpos, endpos));
  292. }
  293. protected double getDoubleValue(String line, int startpos) {
  294. int endpos = findValue(line, startpos);
  295. return Double.parseDouble(line.substring(startpos, endpos));
  296. }
  297. protected Boolean getBooleanValue(String line, int startpos) {
  298. return Boolean.valueOf(getStringValue(line, startpos));
  299. }
  300. }
  301. private static class StartFontMetrics extends AbstractValueHandler {
  302. public void parse(String line, int startpos, Stack stack) throws IOException {
  303. int endpos = findValue(line, startpos);
  304. double version = Double.parseDouble(line.substring(startpos, endpos));
  305. if (version < 2) {
  306. throw new IOException(
  307. "AFM version must be at least 2.0 but it is " + version + "!");
  308. }
  309. AFMFile afm = new AFMFile();
  310. stack.push(afm);
  311. }
  312. }
  313. private abstract static class BeanSetter extends AbstractValueHandler {
  314. private String method;
  315. public BeanSetter(String variable) {
  316. this.method = "set" + variable;
  317. }
  318. protected void setValue(Object target, Object value) {
  319. //Uses Java Beans API
  320. Statement statement = new Statement(target, method, new Object[] {value});
  321. try {
  322. statement.execute();
  323. } catch (Exception e) {
  324. //Should never happen
  325. throw new RuntimeException("Bean error: " + e.getMessage());
  326. }
  327. }
  328. }
  329. private static class StringSetter extends BeanSetter {
  330. public StringSetter(String variable) {
  331. super(variable);
  332. }
  333. public void parse(String line, int startpos, Stack stack) throws IOException {
  334. String s = getStringValue(line, startpos);
  335. Object obj = stack.peek();
  336. setValue(obj, s);
  337. }
  338. }
  339. private static class NumberSetter extends BeanSetter {
  340. public NumberSetter(String variable) {
  341. super(variable);
  342. }
  343. protected Object getContextObject(Stack stack) {
  344. return stack.peek();
  345. }
  346. public void parse(String line, int startpos, Stack stack) throws IOException {
  347. Number num = getNumberValue(line, startpos);
  348. setValue(getContextObject(stack), num);
  349. }
  350. }
  351. private static class IntegerSetter extends NumberSetter {
  352. public IntegerSetter(String variable) {
  353. super(variable);
  354. }
  355. public void parse(String line, int startpos, Stack stack) throws IOException {
  356. int value = getIntegerValue(line, startpos);
  357. setValue(getContextObject(stack), new Integer(value));
  358. }
  359. }
  360. private static class DoubleSetter extends NumberSetter {
  361. public DoubleSetter(String variable) {
  362. super(variable);
  363. }
  364. public void parse(String line, int startpos, Stack stack) throws IOException {
  365. double value = getDoubleValue(line, startpos);
  366. setValue(getContextObject(stack), new Double(value));
  367. }
  368. }
  369. private static class WritingDirNumberSetter extends NumberSetter {
  370. public WritingDirNumberSetter(String variable) {
  371. super(variable);
  372. }
  373. protected Object getContextObject(Stack stack) {
  374. if (stack.peek() instanceof AFMWritingDirectionMetrics) {
  375. return (AFMWritingDirectionMetrics)stack.peek();
  376. } else {
  377. AFMFile afm = (AFMFile)stack.peek();
  378. AFMWritingDirectionMetrics wdm = afm.getWritingDirectionMetrics(0);
  379. if (wdm == null) {
  380. wdm = new AFMWritingDirectionMetrics();
  381. afm.setWritingDirectionMetrics(0, wdm);
  382. }
  383. return wdm;
  384. }
  385. }
  386. }
  387. private static class WritingDirDoubleSetter extends WritingDirNumberSetter {
  388. public WritingDirDoubleSetter(String variable) {
  389. super(variable);
  390. }
  391. public void parse(String line, int startpos, Stack stack) throws IOException {
  392. double value = getDoubleValue(line, startpos);
  393. setValue(getContextObject(stack), new Double(value));
  394. }
  395. }
  396. private static class BooleanSetter extends AbstractValueHandler {
  397. private String method;
  398. public BooleanSetter(String variable) {
  399. this.method = "set" + variable.substring(2); //Cut "Is" in front
  400. }
  401. protected Object getContextObject(Stack stack) {
  402. return (AFMFile)stack.peek();
  403. }
  404. public void parse(String line, int startpos, Stack stack) throws IOException {
  405. Boolean b = getBooleanValue(line, startpos);
  406. //Uses Java Beans API
  407. Statement statement = new Statement(getContextObject(stack),
  408. method, new Object[] {b});
  409. try {
  410. statement.execute();
  411. } catch (Exception e) {
  412. //Should never happen
  413. throw new RuntimeException("Bean error: " + e.getMessage());
  414. }
  415. }
  416. }
  417. private static class WritingDirBooleanSetter extends BooleanSetter {
  418. public WritingDirBooleanSetter(String variable) {
  419. super(variable);
  420. }
  421. protected Object getContextObject(Stack stack) {
  422. if (stack.peek() instanceof AFMWritingDirectionMetrics) {
  423. return (AFMWritingDirectionMetrics)stack.peek();
  424. } else {
  425. AFMFile afm = (AFMFile)stack.peek();
  426. AFMWritingDirectionMetrics wdm = afm.getWritingDirectionMetrics(0);
  427. if (wdm == null) {
  428. wdm = new AFMWritingDirectionMetrics();
  429. afm.setWritingDirectionMetrics(0, wdm);
  430. }
  431. return wdm;
  432. }
  433. }
  434. }
  435. private static class FontBBox extends AbstractValueHandler {
  436. public void parse(String line, int startpos, Stack stack) throws IOException {
  437. AFMFile afm = (AFMFile)stack.peek();
  438. Rectangle rect = new Rectangle();
  439. int endpos;
  440. endpos = findValue(line, startpos);
  441. rect.x = Integer.parseInt(line.substring(startpos, endpos));
  442. startpos = skipToNonWhiteSpace(line, endpos);
  443. endpos = findValue(line, startpos);
  444. rect.y = Integer.parseInt(line.substring(startpos, endpos));
  445. startpos = skipToNonWhiteSpace(line, endpos);
  446. endpos = findValue(line, startpos);
  447. int v = Integer.parseInt(line.substring(startpos, endpos));
  448. rect.width = v - rect.x;
  449. startpos = skipToNonWhiteSpace(line, endpos);
  450. endpos = findValue(line, startpos);
  451. v = Integer.parseInt(line.substring(startpos, endpos));
  452. rect.height = v - rect.y;
  453. startpos = skipToNonWhiteSpace(line, endpos);
  454. afm.setFontBBox(rect);
  455. }
  456. }
  457. private static class IsBaseFont extends AbstractValueHandler {
  458. public void parse(String line, int startpos, Stack stack) throws IOException {
  459. if (getBooleanValue(line, startpos).booleanValue()) {
  460. throw new IOException("Only base fonts are currently supported!");
  461. }
  462. }
  463. }
  464. private static class IsCIDFont extends AbstractValueHandler {
  465. public void parse(String line, int startpos, Stack stack) throws IOException {
  466. if (getBooleanValue(line, startpos).booleanValue()) {
  467. throw new IOException("CID fonts are currently not supported!");
  468. }
  469. }
  470. }
  471. private static class NotImplementedYet extends AbstractValueHandler {
  472. private String key;
  473. public NotImplementedYet(String key) {
  474. this.key = key;
  475. }
  476. public void parse(String line, int startpos, Stack stack) throws IOException {
  477. throw new IOException("Support for '" + key
  478. + "' has not been implemented, yet! Font is not supported.");
  479. }
  480. }
  481. private static class StartDirection extends AbstractValueHandler {
  482. public void parse(String line, int startpos, Stack stack) throws IOException {
  483. int index = getIntegerValue(line, startpos);
  484. AFMWritingDirectionMetrics wdm = new AFMWritingDirectionMetrics();
  485. AFMFile afm = (AFMFile)stack.peek();
  486. afm.setWritingDirectionMetrics(index, wdm);
  487. stack.push(wdm);
  488. }
  489. }
  490. private static class EndDirection extends AbstractValueHandler {
  491. public void parse(String line, int startpos, Stack stack) throws IOException {
  492. if (!(stack.pop() instanceof AFMWritingDirectionMetrics)) {
  493. throw new IOException("AFM format error: nesting incorrect");
  494. }
  495. }
  496. }
  497. private static class KPXHandler extends AbstractValueHandler {
  498. public void parse(String line, int startpos, Stack stack) throws IOException {
  499. AFMFile afm = (AFMFile)stack.peek();
  500. int endpos;
  501. endpos = findValue(line, startpos);
  502. String name1 = line.substring(startpos, endpos);
  503. startpos = skipToNonWhiteSpace(line, endpos);
  504. endpos = findValue(line, startpos);
  505. String name2 = line.substring(startpos, endpos);
  506. startpos = skipToNonWhiteSpace(line, endpos);
  507. endpos = findValue(line, startpos);
  508. double kx = Double.parseDouble(line.substring(startpos, endpos));
  509. startpos = skipToNonWhiteSpace(line, endpos);
  510. afm.addXKerning(name1, name2, kx);
  511. }
  512. }
  513. }