PageRenderTime 72ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 1ms

/openjdk7/jdk/src/share/classes/sun/font/FontUtilities.java

https://github.com/Helbrass/openjdk-fontfix
Java | 512 lines | 252 code | 52 blank | 208 comment | 73 complexity | 3aca5b901f62fdc0f62139ffee3ad094 MD5 | raw file
  1. /*
  2. * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package sun.font;
  26. import java.awt.Font;
  27. import java.io.BufferedReader;
  28. import java.io.File;
  29. import java.io.FileInputStream;
  30. import java.io.InputStreamReader;
  31. import java.lang.ref.SoftReference;
  32. import java.util.concurrent.ConcurrentHashMap;
  33. import java.security.AccessController;
  34. import java.security.PrivilegedAction;
  35. import javax.swing.plaf.FontUIResource;
  36. import sun.util.logging.PlatformLogger;
  37. /**
  38. * A collection of utility methods.
  39. */
  40. public final class FontUtilities {
  41. public static boolean isSolaris;
  42. public static boolean isLinux;
  43. public static boolean isSolaris8;
  44. public static boolean isSolaris9;
  45. public static boolean isOpenSolaris;
  46. public static boolean useT2K;
  47. public static boolean isWindows;
  48. public static boolean isOpenJDK;
  49. static final String LUCIDA_FILE_NAME = "LucidaSansRegular.ttf";
  50. private static boolean debugFonts = false;
  51. private static PlatformLogger logger = null;
  52. private static boolean logging;
  53. // This static initializer block figures out the OS constants.
  54. static {
  55. AccessController.doPrivileged(new PrivilegedAction () {
  56. public Object run() {
  57. String osName = System.getProperty("os.name", "unknownOS");
  58. isSolaris = osName.startsWith("SunOS");
  59. isLinux = osName.startsWith("Linux");
  60. String t2kStr = System.getProperty("sun.java2d.font.scaler");
  61. if (t2kStr != null) {
  62. useT2K = "t2k".equals(t2kStr);
  63. } else {
  64. useT2K = false;
  65. }
  66. if (isSolaris) {
  67. String version = System.getProperty("os.version", "0.0");
  68. isSolaris8 = version.startsWith("5.8");
  69. isSolaris9 = version.startsWith("5.9");
  70. float ver = Float.parseFloat(version);
  71. if (ver > 5.10f) {
  72. File f = new File("/etc/release");
  73. String line = null;
  74. try {
  75. FileInputStream fis = new FileInputStream(f);
  76. InputStreamReader isr = new InputStreamReader(
  77. fis, "ISO-8859-1");
  78. BufferedReader br = new BufferedReader(isr);
  79. line = br.readLine();
  80. fis.close();
  81. } catch (Exception ex) {
  82. // Nothing to do here.
  83. }
  84. if (line != null && line.indexOf("OpenSolaris") >= 0) {
  85. isOpenSolaris = true;
  86. } else {
  87. isOpenSolaris = false;
  88. }
  89. } else {
  90. isOpenSolaris = false;
  91. }
  92. } else {
  93. isSolaris8 = false;
  94. isSolaris9 = false;
  95. isOpenSolaris = false;
  96. }
  97. isWindows = osName.startsWith("Windows");
  98. String jreLibDirName = System.getProperty("java.home", "")
  99. + File.separator + "lib";
  100. String jreFontDirName =
  101. jreLibDirName + File.separator + "fonts";
  102. File lucidaFile = new File(jreFontDirName + File.separator
  103. + LUCIDA_FILE_NAME);
  104. isOpenJDK = !lucidaFile.exists();
  105. String debugLevel =
  106. System.getProperty("sun.java2d.debugfonts");
  107. if (debugLevel != null && !debugLevel.equals("false")) {
  108. debugFonts = true;
  109. logger = PlatformLogger.getLogger("sun.java2d");
  110. if (debugLevel.equals("warning")) {
  111. logger.setLevel(PlatformLogger.WARNING);
  112. } else if (debugLevel.equals("severe")) {
  113. logger.setLevel(PlatformLogger.SEVERE);
  114. }
  115. }
  116. if (debugFonts) {
  117. logger = PlatformLogger.getLogger("sun.java2d");
  118. logging = logger.isEnabled();
  119. }
  120. return null;
  121. }
  122. });
  123. }
  124. /**
  125. * Referenced by code in the JDK which wants to test for the
  126. * minimum char code for which layout may be required.
  127. * Note that even basic latin text can benefit from ligatures,
  128. * eg "ffi" but we presently apply those only if explicitly
  129. * requested with TextAttribute.LIGATURES_ON.
  130. * The value here indicates the lowest char code for which failing
  131. * to invoke layout would prevent acceptable rendering.
  132. */
  133. public static final int MIN_LAYOUT_CHARCODE = 0x0300;
  134. /**
  135. * Referenced by code in the JDK which wants to test for the
  136. * maximum char code for which layout may be required.
  137. * Note this does not account for supplementary characters
  138. * where the caller interprets 'layout' to mean any case where
  139. * one 'char' (ie the java type char) does not map to one glyph
  140. */
  141. public static final int MAX_LAYOUT_CHARCODE = 0x206F;
  142. /**
  143. * Calls the private getFont2D() method in java.awt.Font objects.
  144. *
  145. * @param font the font object to call
  146. *
  147. * @return the Font2D object returned by Font.getFont2D()
  148. */
  149. public static Font2D getFont2D(Font font) {
  150. return FontAccess.getFontAccess().getFont2D(font);
  151. }
  152. /**
  153. * If there is anything in the text which triggers a case
  154. * where char->glyph does not map 1:1 in straightforward
  155. * left->right ordering, then this method returns true.
  156. * Scripts which might require it but are not treated as such
  157. * due to JDK implementations will not return true.
  158. * ie a 'true' return is an indication of the treatment by
  159. * the implementation.
  160. * Whether supplementary characters should be considered is dependent
  161. * on the needs of the caller. Since this method accepts the 'char' type
  162. * then such chars are always represented by a pair. From a rendering
  163. * perspective these will all (in the cases I know of) still be one
  164. * unicode character -> one glyph. But if a caller is using this to
  165. * discover any case where it cannot make naive assumptions about
  166. * the number of chars, and how to index through them, then it may
  167. * need the option to have a 'true' return in such a case.
  168. */
  169. public static boolean isComplexText(char [] chs, int start, int limit) {
  170. for (int i = start; i < limit; i++) {
  171. if (chs[i] < MIN_LAYOUT_CHARCODE) {
  172. continue;
  173. }
  174. else if (isNonSimpleChar(chs[i])) {
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. /* This is almost the same as the method above, except it takes a
  181. * char which means it may include undecoded surrogate pairs.
  182. * The distinction is made so that code which needs to identify all
  183. * cases in which we do not have a simple mapping from
  184. * char->unicode character->glyph can be be identified.
  185. * For example measurement cannot simply sum advances of 'chars',
  186. * the caret in editable text cannot advance one 'char' at a time, etc.
  187. * These callers really are asking for more than whether 'layout'
  188. * needs to be run, they need to know if they can assume 1->1
  189. * char->glyph mapping.
  190. */
  191. public static boolean isNonSimpleChar(char ch) {
  192. return
  193. isComplexCharCode(ch) ||
  194. (ch >= CharToGlyphMapper.HI_SURROGATE_START &&
  195. ch <= CharToGlyphMapper.LO_SURROGATE_END);
  196. }
  197. /* If the character code falls into any of a number of unicode ranges
  198. * where we know that simple left->right layout mapping chars to glyphs
  199. * 1:1 and accumulating advances is going to produce incorrect results,
  200. * we want to know this so the caller can use a more intelligent layout
  201. * approach. A caller who cares about optimum performance may want to
  202. * check the first case and skip the method call if its in that range.
  203. * Although there's a lot of tests in here, knowing you can skip
  204. * CTL saves a great deal more. The rest of the checks are ordered
  205. * so that rather than checking explicitly if (>= start & <= end)
  206. * which would mean all ranges would need to be checked so be sure
  207. * CTL is not needed, the method returns as soon as it recognises
  208. * the code point is outside of a CTL ranges.
  209. * NOTE: Since this method accepts an 'int' it is asssumed to properly
  210. * represent a CHARACTER. ie it assumes the caller has already
  211. * converted surrogate pairs into supplementary characters, and so
  212. * can handle this case and doesn't need to be told such a case is
  213. * 'complex'.
  214. */
  215. public static boolean isComplexCharCode(int code) {
  216. if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {
  217. return false;
  218. }
  219. else if (code <= 0x036f) {
  220. // Trigger layout for combining diacriticals 0x0300->0x036f
  221. return true;
  222. }
  223. else if (code < 0x0590) {
  224. // No automatic layout for Greek, Cyrillic, Armenian.
  225. return false;
  226. }
  227. else if (code <= 0x06ff) {
  228. // Hebrew 0590 - 05ff
  229. // Arabic 0600 - 06ff
  230. return true;
  231. }
  232. else if (code < 0x0900) {
  233. return false; // Syriac and Thaana
  234. }
  235. else if (code <= 0x0e7f) {
  236. // if Indic, assume shaping for conjuncts, reordering:
  237. // 0900 - 097F Devanagari
  238. // 0980 - 09FF Bengali
  239. // 0A00 - 0A7F Gurmukhi
  240. // 0A80 - 0AFF Gujarati
  241. // 0B00 - 0B7F Oriya
  242. // 0B80 - 0BFF Tamil
  243. // 0C00 - 0C7F Telugu
  244. // 0C80 - 0CFF Kannada
  245. // 0D00 - 0D7F Malayalam
  246. // 0D80 - 0DFF Sinhala
  247. // 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks
  248. return true;
  249. }
  250. else if (code < 0x0f00) {
  251. return false;
  252. }
  253. else if (code <= 0x0fff) { // U+0F00 - U+0FFF Tibetan
  254. return true;
  255. }
  256. else if (code < 0x1100) {
  257. return false;
  258. }
  259. else if (code < 0x11ff) { // U+1100 - U+11FF Old Hangul
  260. return true;
  261. }
  262. else if (code < 0x1780) {
  263. return false;
  264. }
  265. else if (code <= 0x17ff) { // 1780 - 17FF Khmer
  266. return true;
  267. }
  268. else if (code < 0x200c) {
  269. return false;
  270. }
  271. else if (code <= 0x200d) { // zwj or zwnj
  272. return true;
  273. }
  274. else if (code >= 0x202a && code <= 0x202e) { // directional control
  275. return true;
  276. }
  277. else if (code >= 0x206a && code <= 0x206f) { // directional control
  278. return true;
  279. }
  280. return false;
  281. }
  282. public static PlatformLogger getLogger() {
  283. return logger;
  284. }
  285. public static boolean isLogging() {
  286. return logging;
  287. }
  288. public static boolean debugFonts() {
  289. return debugFonts;
  290. }
  291. // The following methods are used by Swing.
  292. /* Revise the implementation to in fact mean "font is a composite font.
  293. * This ensures that Swing components will always benefit from the
  294. * fall back fonts
  295. */
  296. public static boolean fontSupportsDefaultEncoding(Font font) {
  297. return getFont2D(font) instanceof CompositeFont;
  298. }
  299. /**
  300. * This method is provided for internal and exclusive use by Swing.
  301. *
  302. * It may be used in conjunction with fontSupportsDefaultEncoding(Font)
  303. * In the event that a desktop properties font doesn't directly
  304. * support the default encoding, (ie because the host OS supports
  305. * adding support for the current locale automatically for native apps),
  306. * then Swing calls this method to get a font which uses the specified
  307. * font for the code points it covers, but also supports this locale
  308. * just as the standard composite fonts do.
  309. * Note: this will over-ride any setting where an application
  310. * specifies it prefers locale specific composite fonts.
  311. * The logic for this, is that this method is used only where the user or
  312. * application has specified that the native L&F be used, and that
  313. * we should honour that request to use the same font as native apps use.
  314. *
  315. * The behaviour of this method is to construct a new composite
  316. * Font object that uses the specified physical font as its first
  317. * component, and adds all the components of "dialog" as fall back
  318. * components.
  319. * The method currently assumes that only the size and style attributes
  320. * are set on the specified font. It doesn't copy the font transform or
  321. * other attributes because they aren't set on a font created from
  322. * the desktop. This will need to be fixed if use is broadened.
  323. *
  324. * Operations such as Font.deriveFont will work properly on the
  325. * font returned by this method for deriving a different point size.
  326. * Additionally it tries to support a different style by calling
  327. * getNewComposite() below. That also supports replacing slot zero
  328. * with a different physical font but that is expected to be "rare".
  329. * Deriving with a different style is needed because its been shown
  330. * that some applications try to do this for Swing FontUIResources.
  331. * Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);
  332. * will NOT yield the same result, as the new underlying CompositeFont
  333. * cannot be "looked up" in the font registry.
  334. * This returns a FontUIResource as that is the Font sub-class needed
  335. * by Swing.
  336. * Suggested usage is something like :
  337. * FontUIResource fuir;
  338. * Font desktopFont = getDesktopFont(..);
  339. * // NOTE even if fontSupportsDefaultEncoding returns true because
  340. * // you get Tahoma and are running in an English locale, you may
  341. * // still want to just call getCompositeFontUIResource() anyway
  342. * // as only then will you get fallback fonts - eg for CJK.
  343. * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
  344. * fuir = new FontUIResource(..);
  345. * } else {
  346. * fuir = FontManager.getCompositeFontUIResource(desktopFont);
  347. * }
  348. * return fuir;
  349. */
  350. private static volatile
  351. SoftReference<ConcurrentHashMap<PhysicalFont, CompositeFont>>
  352. compMapRef = new SoftReference(null);
  353. public static FontUIResource getCompositeFontUIResource(Font font) {
  354. FontUIResource fuir = new FontUIResource(font);
  355. Font2D font2D = FontUtilities.getFont2D(font);
  356. if (!(font2D instanceof PhysicalFont)) {
  357. /* Swing should only be calling this when a font is obtained
  358. * from desktop properties, so should generally be a physical font,
  359. * an exception might be for names like "MS Serif" which are
  360. * automatically mapped to "Serif", so there's no need to do
  361. * anything special in that case. But note that suggested usage
  362. * is first to call fontSupportsDefaultEncoding(Font) and this
  363. * method should not be called if that were to return true.
  364. */
  365. return fuir;
  366. }
  367. FontManager fm = FontManagerFactory.getInstance();
  368. CompositeFont dialog2D =
  369. (CompositeFont) fm.findFont2D("dialog", font.getStyle(),
  370. FontManager.NO_FALLBACK);
  371. if (dialog2D == null) { /* shouldn't happen */
  372. return fuir;
  373. }
  374. PhysicalFont physicalFont = (PhysicalFont)font2D;
  375. ConcurrentHashMap<PhysicalFont, CompositeFont> compMap = compMapRef.get();
  376. if (compMap == null) { // Its been collected.
  377. compMap = new ConcurrentHashMap<PhysicalFont, CompositeFont>();
  378. compMapRef = new SoftReference(compMap);
  379. }
  380. CompositeFont compFont = compMap.get(physicalFont);
  381. if (compFont == null) {
  382. compFont = new CompositeFont(physicalFont, dialog2D);
  383. compMap.put(physicalFont, compFont);
  384. }
  385. FontAccess.getFontAccess().setFont2D(fuir, compFont.handle);
  386. /* marking this as a created font is needed as only created fonts
  387. * copy their creator's handles.
  388. */
  389. FontAccess.getFontAccess().setCreatedFont(fuir);
  390. return fuir;
  391. }
  392. /* A small "map" from GTK/fontconfig names to the equivalent JDK
  393. * logical font name.
  394. */
  395. private static final String[][] nameMap = {
  396. {"sans", "sansserif"},
  397. {"sans-serif", "sansserif"},
  398. {"serif", "serif"},
  399. {"monospace", "monospaced"}
  400. };
  401. public static String mapFcName(String name) {
  402. for (int i = 0; i < nameMap.length; i++) {
  403. if (name.equals(nameMap[i][0])) {
  404. return nameMap[i][1];
  405. }
  406. }
  407. return null;
  408. }
  409. /* This is called by Swing passing in a fontconfig family name
  410. * such as "sans". In return Swing gets a FontUIResource instance
  411. * that has queried fontconfig to resolve the font(s) used for this.
  412. * Fontconfig will if asked return a list of fonts to give the largest
  413. * possible code point coverage.
  414. * For now we use only the first font returned by fontconfig, and
  415. * back it up with the most closely matching JDK logical font.
  416. * Essentially this means pre-pending what we return now with fontconfig's
  417. * preferred physical font. This could lead to some duplication in cases,
  418. * if we already included that font later. We probably should remove such
  419. * duplicates, but it is not a significant problem. It can be addressed
  420. * later as part of creating a Composite which uses more of the
  421. * same fonts as fontconfig. At that time we also should pay more
  422. * attention to the special rendering instructions fontconfig returns,
  423. * such as whether we should prefer embedded bitmaps over antialiasing.
  424. * There's no way to express that via a Font at present.
  425. */
  426. public static FontUIResource getFontConfigFUIR(String fcFamily,
  427. int style, int size) {
  428. String mapped = mapFcName(fcFamily);
  429. if (mapped == null) {
  430. mapped = "sansserif";
  431. }
  432. FontUIResource fuir;
  433. FontManager fm = FontManagerFactory.getInstance();
  434. if (fm instanceof SunFontManager) {
  435. SunFontManager sfm = (SunFontManager) fm;
  436. fuir = sfm.getFontConfigFUIR(mapped, style, size);
  437. } else {
  438. fuir = new FontUIResource(mapped, style, size);
  439. }
  440. return fuir;
  441. }
  442. /**
  443. * Used by windows printing to assess if a font is likely to
  444. * be layout compatible with JDK
  445. * TrueType fonts should be, but if they have no GPOS table,
  446. * but do have a GSUB table, then they are probably older
  447. * fonts GDI handles differently.
  448. */
  449. public static boolean textLayoutIsCompatible(Font font) {
  450. Font2D font2D = getFont2D(font);
  451. if (font2D instanceof TrueTypeFont) {
  452. TrueTypeFont ttf = (TrueTypeFont) font2D;
  453. return
  454. ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
  455. ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
  456. } else {
  457. return false;
  458. }
  459. }
  460. }