PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

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

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