PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

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

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