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.

SingleByteFont.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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;
  19. import java.awt.Rectangle;
  20. import java.util.ArrayList;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import java.util.TreeSet;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.apache.xmlgraphics.fonts.Glyphs;
  29. import org.apache.fop.apps.io.InternalResourceResolver;
  30. import org.apache.fop.fonts.truetype.OpenFont.PostScriptVersion;
  31. /**
  32. * Generic SingleByte font
  33. */
  34. public class SingleByteFont extends CustomFont {
  35. /** logger */
  36. private static Log log = LogFactory.getLog(SingleByteFont.class);
  37. private SingleByteEncoding mapping;
  38. private boolean useNativeEncoding = false;
  39. private int[] width = null;
  40. private Rectangle[] boundingBoxes;
  41. private Map<Character, UnencodedCharacter> unencodedCharacters;
  42. private List<SimpleSingleByteEncoding> additionalEncodings;
  43. private Map<Character, Character> alternativeCodes;
  44. private PostScriptVersion ttPostScriptVersion;
  45. /**
  46. * @param resourceResolver the URI resolver for controlling file access
  47. */
  48. public SingleByteFont(InternalResourceResolver resourceResolver) {
  49. super(resourceResolver);
  50. setEncoding(CodePointMapping.WIN_ANSI_ENCODING);
  51. }
  52. /** {@inheritDoc} */
  53. public boolean isEmbeddable() {
  54. return (!(getEmbedFileURI() == null
  55. && getEmbedResourceName() == null));
  56. }
  57. /** {@inheritDoc} */
  58. public boolean isSubsetEmbedded() {
  59. return false;
  60. }
  61. /** {@inheritDoc} */
  62. public String getEncodingName() {
  63. return this.mapping.getName();
  64. }
  65. /**
  66. * Returns the code point mapping (encoding) of this font.
  67. * @return the code point mapping
  68. */
  69. public SingleByteEncoding getEncoding() {
  70. return this.mapping;
  71. }
  72. /** {@inheritDoc} */
  73. public int getWidth(int i, int size) {
  74. if (i < 256) {
  75. int idx = i - getFirstChar();
  76. if (idx >= 0 && idx < width.length) {
  77. return size * width[idx];
  78. }
  79. } else if (this.additionalEncodings != null) {
  80. int encodingIndex = (i / 256) - 1;
  81. SimpleSingleByteEncoding encoding = getAdditionalEncoding(encodingIndex);
  82. int codePoint = i % 256;
  83. NamedCharacter nc = encoding.getCharacterForIndex(codePoint);
  84. UnencodedCharacter uc
  85. = this.unencodedCharacters.get(Character.valueOf(nc.getSingleUnicodeValue()));
  86. return size * uc.getWidth();
  87. }
  88. return 0;
  89. }
  90. /** {@inheritDoc} */
  91. public int[] getWidths() {
  92. int[] arr = new int[width.length];
  93. System.arraycopy(width, 0, arr, 0, width.length);
  94. return arr;
  95. }
  96. public Rectangle getBoundingBox(int glyphIndex, int size) {
  97. Rectangle bbox = null;
  98. if (glyphIndex < 256) {
  99. int idx = glyphIndex - getFirstChar();
  100. if (idx >= 0 && idx < boundingBoxes.length) {
  101. bbox = boundingBoxes[idx];
  102. }
  103. } else if (this.additionalEncodings != null) {
  104. int encodingIndex = (glyphIndex / 256) - 1;
  105. SimpleSingleByteEncoding encoding = getAdditionalEncoding(encodingIndex);
  106. int codePoint = glyphIndex % 256;
  107. NamedCharacter nc = encoding.getCharacterForIndex(codePoint);
  108. UnencodedCharacter uc = this.unencodedCharacters.get(Character.valueOf(nc.getSingleUnicodeValue()));
  109. bbox = uc.getBBox();
  110. }
  111. return bbox == null ? null : new Rectangle(bbox.x * size, bbox.y * size, bbox.width * size, bbox.height * size);
  112. }
  113. /**
  114. * Lookup a character using its alternative names. If found, cache it so we
  115. * can speed up lookups.
  116. * @param c the character
  117. * @return the suggested alternative character present in the font
  118. */
  119. private char findAlternative(char c) {
  120. char d;
  121. if (alternativeCodes == null) {
  122. alternativeCodes = new java.util.HashMap<Character, Character>();
  123. } else {
  124. Character alternative = alternativeCodes.get(c);
  125. if (alternative != null) {
  126. return alternative;
  127. }
  128. }
  129. String charName = Glyphs.charToGlyphName(c);
  130. String[] charNameAlternatives = Glyphs.getCharNameAlternativesFor(charName);
  131. if (charNameAlternatives != null && charNameAlternatives.length > 0) {
  132. for (int i = 0; i < charNameAlternatives.length; i++) {
  133. if (log.isDebugEnabled()) {
  134. log.debug("Checking alternative for char " + c + " (charname="
  135. + charName + "): " + charNameAlternatives[i]);
  136. }
  137. String s = Glyphs.getUnicodeSequenceForGlyphName(charNameAlternatives[i]);
  138. if (s != null) {
  139. d = lookupChar(s.charAt(0));
  140. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  141. alternativeCodes.put(c, d);
  142. return d;
  143. }
  144. }
  145. }
  146. }
  147. return SingleByteEncoding.NOT_FOUND_CODE_POINT;
  148. }
  149. private char lookupChar(char c) {
  150. char d = mapping.mapChar(c);
  151. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  152. return d;
  153. }
  154. // Check unencoded characters which are available in the font by
  155. // character name
  156. d = mapUnencodedChar(c);
  157. return d;
  158. }
  159. /** {@inheritDoc} */
  160. @Override
  161. public char mapChar(char c) {
  162. notifyMapOperation();
  163. char d = lookupChar(c);
  164. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  165. return d;
  166. } else {
  167. // Check for alternative
  168. d = findAlternative(c);
  169. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  170. return d;
  171. }
  172. }
  173. this.warnMissingGlyph(c);
  174. return Typeface.NOT_FOUND;
  175. }
  176. private char mapUnencodedChar(char ch) {
  177. if (this.unencodedCharacters != null) {
  178. UnencodedCharacter unencoded = this.unencodedCharacters.get(Character.valueOf(ch));
  179. if (unencoded != null) {
  180. if (this.additionalEncodings == null) {
  181. this.additionalEncodings = new ArrayList<SimpleSingleByteEncoding>();
  182. }
  183. SimpleSingleByteEncoding encoding = null;
  184. char mappedStart = 0;
  185. int additionalsCount = this.additionalEncodings.size();
  186. for (int i = 0; i < additionalsCount; i++) {
  187. mappedStart += 256;
  188. encoding = getAdditionalEncoding(i);
  189. char alt = encoding.mapChar(ch);
  190. if (alt != 0) {
  191. return (char)(mappedStart + alt);
  192. }
  193. }
  194. if (encoding != null && encoding.isFull()) {
  195. encoding = null;
  196. }
  197. if (encoding == null) {
  198. encoding = new SimpleSingleByteEncoding(
  199. getFontName() + "EncodingSupp" + (additionalsCount + 1));
  200. this.additionalEncodings.add(encoding);
  201. mappedStart += 256;
  202. }
  203. return (char)(mappedStart + encoding.addCharacter(unencoded.getCharacter()));
  204. }
  205. }
  206. return 0;
  207. }
  208. /** {@inheritDoc} */
  209. @Override
  210. public boolean hasChar(char c) {
  211. char d = mapping.mapChar(c);
  212. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  213. return true;
  214. }
  215. //Check unencoded characters which are available in the font by character name
  216. d = mapUnencodedChar(c);
  217. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  218. return true;
  219. }
  220. // Check if an alternative exists
  221. d = findAlternative(c);
  222. if (d != SingleByteEncoding.NOT_FOUND_CODE_POINT) {
  223. return true;
  224. }
  225. return false;
  226. }
  227. /* ---- single byte font specific setters --- */
  228. /**
  229. * Updates the mapping variable based on the encoding.
  230. * @param encoding the name of the encoding
  231. */
  232. protected void updateMapping(String encoding) {
  233. try {
  234. this.mapping = CodePointMapping.getMapping(encoding);
  235. } catch (UnsupportedOperationException e) {
  236. log.error("Font '" + super.getFontName() + "': " + e.getMessage());
  237. }
  238. }
  239. /**
  240. * Sets the encoding of the font.
  241. * @param encoding the encoding (ex. "WinAnsiEncoding" or "SymbolEncoding")
  242. */
  243. public void setEncoding(String encoding) {
  244. updateMapping(encoding);
  245. }
  246. /**
  247. * Sets the encoding of the font.
  248. * @param encoding the encoding information
  249. */
  250. public void setEncoding(CodePointMapping encoding) {
  251. this.mapping = encoding;
  252. }
  253. /**
  254. * Controls whether the font is configured to use its native encoding or if it
  255. * may need to be re-encoded for the target format.
  256. * @param value true indicates that the configured encoding is the font's native encoding
  257. */
  258. public void setUseNativeEncoding(boolean value) {
  259. this.useNativeEncoding = value;
  260. }
  261. /**
  262. * Indicates whether this font is configured to use its native encoding. This
  263. * method is used to determine whether the font needs to be re-encoded.
  264. * @return true if the font uses its native encoding.
  265. */
  266. public boolean isUsingNativeEncoding() {
  267. return this.useNativeEncoding;
  268. }
  269. /**
  270. * Sets a width for a character.
  271. * @param index index of the character
  272. * @param w the width of the character
  273. */
  274. public void setWidth(int index, int w) {
  275. if (this.width == null) {
  276. this.width = new int[getLastChar() - getFirstChar() + 1];
  277. }
  278. this.width[index - getFirstChar()] = w;
  279. }
  280. public void setBoundingBox(int index, Rectangle bbox) {
  281. if (this.boundingBoxes == null) {
  282. this.boundingBoxes = new Rectangle[getLastChar() - getFirstChar() + 1];
  283. }
  284. this.boundingBoxes[index - getFirstChar()] = bbox;
  285. }
  286. /**
  287. * Adds an unencoded character (one that is not supported by the primary encoding).
  288. * @param ch the named character
  289. * @param width the width of the character
  290. */
  291. public void addUnencodedCharacter(NamedCharacter ch, int width, Rectangle bbox) {
  292. if (this.unencodedCharacters == null) {
  293. this.unencodedCharacters = new HashMap<Character, UnencodedCharacter>();
  294. }
  295. if (ch.hasSingleUnicodeValue()) {
  296. UnencodedCharacter uc = new UnencodedCharacter(ch, width, bbox);
  297. this.unencodedCharacters.put(Character.valueOf(ch.getSingleUnicodeValue()), uc);
  298. } else {
  299. //Cannot deal with unicode sequences, so ignore this character
  300. }
  301. }
  302. /**
  303. * Makes all unencoded characters available through additional encodings. This method
  304. * is used in cases where the fonts need to be encoded in the target format before
  305. * all text of the document is processed (for example in PostScript when resource optimization
  306. * is disabled).
  307. */
  308. public void encodeAllUnencodedCharacters() {
  309. if (this.unencodedCharacters != null) {
  310. Set<Character> sortedKeys = new TreeSet<Character>(this.unencodedCharacters.keySet());
  311. for (Character ch : sortedKeys) {
  312. char mapped = mapChar(ch.charValue());
  313. assert mapped != Typeface.NOT_FOUND;
  314. }
  315. }
  316. }
  317. /**
  318. * Indicates whether the encoding has additional encodings besides the primary encoding.
  319. * @return true if there are additional encodings.
  320. */
  321. public boolean hasAdditionalEncodings() {
  322. return (this.additionalEncodings != null) && (this.additionalEncodings.size() > 0);
  323. }
  324. /**
  325. * Returns the number of additional encodings this single-byte font maintains.
  326. * @return the number of additional encodings
  327. */
  328. public int getAdditionalEncodingCount() {
  329. if (hasAdditionalEncodings()) {
  330. return this.additionalEncodings.size();
  331. } else {
  332. return 0;
  333. }
  334. }
  335. /**
  336. * Returns an additional encoding.
  337. * @param index the index of the additional encoding
  338. * @return the additional encoding
  339. * @throws IndexOutOfBoundsException if the index is out of bounds
  340. */
  341. public SimpleSingleByteEncoding getAdditionalEncoding(int index)
  342. throws IndexOutOfBoundsException {
  343. if (hasAdditionalEncodings()) {
  344. return this.additionalEncodings.get(index);
  345. } else {
  346. throw new IndexOutOfBoundsException("No additional encodings available");
  347. }
  348. }
  349. /**
  350. * Returns an array with the widths for an additional encoding.
  351. * @param index the index of the additional encoding
  352. * @return the width array
  353. */
  354. public int[] getAdditionalWidths(int index) {
  355. SimpleSingleByteEncoding enc = getAdditionalEncoding(index);
  356. int[] arr = new int[enc.getLastChar() - enc.getFirstChar() + 1];
  357. for (int i = 0, c = arr.length; i < c; i++) {
  358. NamedCharacter nc = enc.getCharacterForIndex(enc.getFirstChar() + i);
  359. UnencodedCharacter uc = this.unencodedCharacters.get(
  360. Character.valueOf(nc.getSingleUnicodeValue()));
  361. arr[i] = uc.getWidth();
  362. }
  363. return arr;
  364. }
  365. private static final class UnencodedCharacter {
  366. private final NamedCharacter character;
  367. private final int width;
  368. private final Rectangle bbox;
  369. public UnencodedCharacter(NamedCharacter character, int width, Rectangle bbox) {
  370. this.character = character;
  371. this.width = width;
  372. this.bbox = bbox;
  373. }
  374. public NamedCharacter getCharacter() {
  375. return this.character;
  376. }
  377. public int getWidth() {
  378. return this.width;
  379. }
  380. public Rectangle getBBox() {
  381. return bbox;
  382. }
  383. /** {@inheritDoc} */
  384. @Override
  385. public String toString() {
  386. return getCharacter().toString();
  387. }
  388. }
  389. /**
  390. * Sets the version of the PostScript table stored in the TrueType font represented by
  391. * this instance.
  392. *
  393. * @param version version of the <q>post</q> table
  394. */
  395. public void setTrueTypePostScriptVersion(PostScriptVersion version) {
  396. ttPostScriptVersion = version;
  397. }
  398. /**
  399. * Returns the version of the PostScript table stored in the TrueType font represented by
  400. * this instance.
  401. *
  402. * @return the version of the <q>post</q> table
  403. */
  404. public PostScriptVersion getTrueTypePostScriptVersion() {
  405. assert getFontType() == FontType.TRUETYPE;
  406. return ttPostScriptVersion;
  407. }
  408. }