PageRenderTime 79ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/MRI-J/jdk/src/share/classes/sun/font/FontManager.java

http://github.com/GregBowyer/ManagedRuntimeInitiative
Java | 3760 lines | 2342 code | 303 blank | 1115 comment | 617 complexity | 8c06dc7474fbbbebfb698d7074d32963 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-3.0
  1. /*
  2. * Copyright 2003-2008 Sun Microsystems, Inc. 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. Sun designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22. * CA 95054 USA or visit www.sun.com if you need additional information or
  23. * have any questions.
  24. */
  25. package sun.font;
  26. import java.awt.Font;
  27. import java.awt.GraphicsEnvironment;
  28. import java.awt.FontFormatException;
  29. import java.io.File;
  30. import java.io.FilenameFilter;
  31. import java.security.AccessController;
  32. import java.security.PrivilegedAction;
  33. import java.util.ArrayList;
  34. import java.util.HashMap;
  35. import java.util.HashSet;
  36. import java.util.Hashtable;
  37. import java.util.Iterator;
  38. import java.util.Locale;
  39. import java.util.Map;
  40. import java.util.NoSuchElementException;
  41. import java.util.StringTokenizer;
  42. import java.util.TreeMap;
  43. import java.util.Vector;
  44. import java.util.concurrent.ConcurrentHashMap;
  45. import java.util.logging.Level;
  46. import java.util.logging.Logger;
  47. import javax.swing.plaf.FontUIResource;
  48. import sun.awt.AppContext;
  49. import sun.awt.FontConfiguration;
  50. import sun.awt.SunHints;
  51. import sun.awt.SunToolkit;
  52. import sun.java2d.HeadlessGraphicsEnvironment;
  53. import sun.java2d.SunGraphicsEnvironment;
  54. import java.awt.geom.GeneralPath;
  55. import java.awt.geom.Point2D;
  56. import java.awt.geom.Rectangle2D;
  57. import java.lang.reflect.Constructor;
  58. import sun.java2d.Disposer;
  59. /*
  60. * Interface between Java Fonts (java.awt.Font) and the underlying
  61. * font files/native font resources and the Java and native font scalers.
  62. */
  63. public final class FontManager {
  64. public static final int FONTFORMAT_NONE = -1;
  65. public static final int FONTFORMAT_TRUETYPE = 0;
  66. public static final int FONTFORMAT_TYPE1 = 1;
  67. public static final int FONTFORMAT_T2K = 2;
  68. public static final int FONTFORMAT_TTC = 3;
  69. public static final int FONTFORMAT_COMPOSITE = 4;
  70. public static final int FONTFORMAT_NATIVE = 5;
  71. public static final int NO_FALLBACK = 0;
  72. public static final int PHYSICAL_FALLBACK = 1;
  73. public static final int LOGICAL_FALLBACK = 2;
  74. public static final int QUADPATHTYPE = 1;
  75. public static final int CUBICPATHTYPE = 2;
  76. /* Pool of 20 font file channels chosen because some UTF-8 locale
  77. * composite fonts can use up to 16 platform fonts (including the
  78. * Lucida fall back). This should prevent channel thrashing when
  79. * dealing with one of these fonts.
  80. * The pool array stores the fonts, rather than directly referencing
  81. * the channels, as the font needs to do the open/close work.
  82. */
  83. private static final int CHANNELPOOLSIZE = 20;
  84. private static int lastPoolIndex = 0;
  85. private static int poolSize = 0;
  86. private static FileFont fontFileCache[] = new FileFont[CHANNELPOOLSIZE];
  87. /* Need to implement a simple linked list scheme for fast
  88. * traversal and lookup.
  89. * Also want to "fast path" dialog so there's minimal overhead.
  90. */
  91. /* There are at exactly 20 composite fonts: 5 faces (but some are not
  92. * usually different), in 4 styles. The array may be auto-expanded
  93. * later if more are needed, eg for user-defined composites or locale
  94. * variants.
  95. */
  96. private static int maxCompFont = 0;
  97. private static CompositeFont [] compFonts = new CompositeFont[20];
  98. private static ConcurrentHashMap<String, CompositeFont>
  99. compositeFonts = new ConcurrentHashMap<String, CompositeFont>();
  100. private static ConcurrentHashMap<String, PhysicalFont>
  101. physicalFonts = new ConcurrentHashMap<String, PhysicalFont>();
  102. private static ConcurrentHashMap<String, PhysicalFont>
  103. registeredFontFiles = new ConcurrentHashMap<String, PhysicalFont>();
  104. /* given a full name find the Font. Remind: there's duplication
  105. * here in that this contains the content of compositeFonts +
  106. * physicalFonts.
  107. */
  108. private static ConcurrentHashMap<String, Font2D>
  109. fullNameToFont = new ConcurrentHashMap<String, Font2D>();
  110. /* TrueType fonts have localised names. Support searching all
  111. * of these before giving up on a name.
  112. */
  113. private static HashMap<String, TrueTypeFont> localeFullNamesToFont;
  114. private static PhysicalFont defaultPhysicalFont;
  115. /* deprecated, unsupported hack - actually invokes a bug! */
  116. private static boolean usePlatformFontMetrics = false;
  117. public static Logger logger = null;
  118. public static boolean logging;
  119. static boolean longAddresses;
  120. static String osName;
  121. static boolean useT2K;
  122. static boolean isWindows;
  123. static boolean isSolaris;
  124. public static boolean isSolaris8; // needed to check for JA wavedash fix.
  125. public static boolean isSolaris9; // needed to check for songti font usage.
  126. private static boolean loaded1dot0Fonts = false;
  127. static SunGraphicsEnvironment sgEnv;
  128. static boolean loadedAllFonts = false;
  129. static boolean loadedAllFontFiles = false;
  130. static TrueTypeFont eudcFont;
  131. static HashMap<String,String> jreFontMap;
  132. static HashSet<String> jreLucidaFontFiles;
  133. static String[] jreOtherFontFiles;
  134. static boolean noOtherJREFontFiles = false; // initial assumption.
  135. /* Used to indicate required return type from toArray(..); */
  136. private static String[] STR_ARRAY = new String[0];
  137. private static void initJREFontMap() {
  138. /* Key is familyname+style value as an int.
  139. * Value is filename containing the font.
  140. * If no mapping exists, it means there is no font file for the style
  141. * If the mapping exists but the file doesn't exist in the deferred
  142. * list then it means its not installed.
  143. * This looks like a lot of code and strings but if it saves even
  144. * a single file being opened at JRE start-up there's a big payoff.
  145. * Lucida Sans is probably the only important case as the others
  146. * are rarely used. Consider removing the other mappings if there's
  147. * no evidence they are useful in practice.
  148. */
  149. jreFontMap = new HashMap<String,String>();
  150. jreLucidaFontFiles = new HashSet<String>();
  151. if (SunGraphicsEnvironment.isOpenJDK()) {
  152. return;
  153. }
  154. /* Lucida Sans Family */
  155. jreFontMap.put("lucida sans0", "LucidaSansRegular.ttf");
  156. jreFontMap.put("lucida sans1", "LucidaSansDemiBold.ttf");
  157. /* Lucida Sans full names (map Bold and DemiBold to same file) */
  158. jreFontMap.put("lucida sans regular0", "LucidaSansRegular.ttf");
  159. jreFontMap.put("lucida sans regular1", "LucidaSansDemiBold.ttf");
  160. jreFontMap.put("lucida sans bold1", "LucidaSansDemiBold.ttf");
  161. jreFontMap.put("lucida sans demibold1", "LucidaSansDemiBold.ttf");
  162. /* Lucida Sans Typewriter Family */
  163. jreFontMap.put("lucida sans typewriter0",
  164. "LucidaTypewriterRegular.ttf");
  165. jreFontMap.put("lucida sans typewriter1", "LucidaTypewriterBold.ttf");
  166. /* Typewriter full names (map Bold and DemiBold to same file) */
  167. jreFontMap.put("lucida sans typewriter regular0",
  168. "LucidaTypewriter.ttf");
  169. jreFontMap.put("lucida sans typewriter regular1",
  170. "LucidaTypewriterBold.ttf");
  171. jreFontMap.put("lucida sans typewriter bold1",
  172. "LucidaTypewriterBold.ttf");
  173. jreFontMap.put("lucida sans typewriter demibold1",
  174. "LucidaTypewriterBold.ttf");
  175. /* Lucida Bright Family */
  176. jreFontMap.put("lucida bright0", "LucidaBrightRegular.ttf");
  177. jreFontMap.put("lucida bright1", "LucidaBrightDemiBold.ttf");
  178. jreFontMap.put("lucida bright2", "LucidaBrightItalic.ttf");
  179. jreFontMap.put("lucida bright3", "LucidaBrightDemiItalic.ttf");
  180. /* Lucida Bright full names (map Bold and DemiBold to same file) */
  181. jreFontMap.put("lucida bright regular0", "LucidaBrightRegular.ttf");
  182. jreFontMap.put("lucida bright regular1", "LucidaBrightDemiBold.ttf");
  183. jreFontMap.put("lucida bright regular2", "LucidaBrightItalic.ttf");
  184. jreFontMap.put("lucida bright regular3", "LucidaBrightDemiItalic.ttf");
  185. jreFontMap.put("lucida bright bold1", "LucidaBrightDemiBold.ttf");
  186. jreFontMap.put("lucida bright bold3", "LucidaBrightDemiItalic.ttf");
  187. jreFontMap.put("lucida bright demibold1", "LucidaBrightDemiBold.ttf");
  188. jreFontMap.put("lucida bright demibold3","LucidaBrightDemiItalic.ttf");
  189. jreFontMap.put("lucida bright italic2", "LucidaBrightItalic.ttf");
  190. jreFontMap.put("lucida bright italic3", "LucidaBrightDemiItalic.ttf");
  191. jreFontMap.put("lucida bright bold italic3",
  192. "LucidaBrightDemiItalic.ttf");
  193. jreFontMap.put("lucida bright demibold italic3",
  194. "LucidaBrightDemiItalic.ttf");
  195. for (String ffile : jreFontMap.values()) {
  196. jreLucidaFontFiles.add(ffile);
  197. }
  198. }
  199. static {
  200. if (SunGraphicsEnvironment.debugFonts) {
  201. logger = Logger.getLogger("sun.java2d", null);
  202. logging = logger.getLevel() != Level.OFF;
  203. }
  204. initJREFontMap();
  205. java.security.AccessController.doPrivileged(
  206. new java.security.PrivilegedAction() {
  207. public Object run() {
  208. FontManagerNativeLibrary.load();
  209. // JNI throws an exception if a class/method/field is not found,
  210. // so there's no need to do anything explicit here.
  211. initIDs();
  212. switch (StrikeCache.nativeAddressSize) {
  213. case 8: longAddresses = true; break;
  214. case 4: longAddresses = false; break;
  215. default: throw new RuntimeException("Unexpected address size");
  216. }
  217. osName = System.getProperty("os.name", "unknownOS");
  218. isSolaris = osName.startsWith("SunOS");
  219. if (isSolaris) {
  220. String t2kStr= System.getProperty("sun.java2d.font.scaler");
  221. useT2K = "t2k".equals(t2kStr);
  222. String version = System.getProperty("os.version", "unk");
  223. isSolaris8 = version.equals("5.8");
  224. isSolaris9 = version.equals("5.9");
  225. } else {
  226. isWindows = osName.startsWith("Windows");
  227. if (isWindows) {
  228. String eudcFile =
  229. SunGraphicsEnvironment.eudcFontFileName;
  230. if (eudcFile != null) {
  231. try {
  232. eudcFont = new TrueTypeFont(eudcFile, null, 0,
  233. true);
  234. } catch (FontFormatException e) {
  235. }
  236. }
  237. String prop =
  238. System.getProperty("java2d.font.usePlatformFont");
  239. if (("true".equals(prop) || getPlatformFontVar())) {
  240. usePlatformFontMetrics = true;
  241. System.out.println("Enabling platform font metrics for win32. This is an unsupported option.");
  242. System.out.println("This yields incorrect composite font metrics as reported by 1.1.x releases.");
  243. System.out.println("It is appropriate only for use by applications which do not use any Java 2");
  244. System.out.println("functionality. This property will be removed in a later release.");
  245. }
  246. }
  247. }
  248. return null;
  249. }
  250. });
  251. }
  252. /* Initialise ptrs used by JNI methods */
  253. private static native void initIDs();
  254. public static void addToPool(FileFont font) {
  255. boolean added = false;
  256. synchronized (fontFileCache) {
  257. /* use poolSize to quickly detect if there's any free slots.
  258. * This is a performance tweak based on the assumption that
  259. * if this is executed at all often, its because there are many
  260. * fonts being used and the pool will be full, and we will save
  261. * a fruitless iteration
  262. */
  263. if (poolSize < CHANNELPOOLSIZE) {
  264. for (int i=0; i<CHANNELPOOLSIZE; i++) {
  265. if (fontFileCache[i] == null) {
  266. fontFileCache[i] = font;
  267. poolSize++;
  268. added = true;
  269. break;
  270. }
  271. }
  272. assert added;
  273. } else {
  274. // is it possible for this to be the same font?
  275. assert fontFileCache[lastPoolIndex] != font;
  276. /* replace with new font, poolSize is unchanged. */
  277. fontFileCache[lastPoolIndex].close();
  278. fontFileCache[lastPoolIndex] = font;
  279. /* lastPoolIndex is updated so that the least recently opened
  280. * file will be closed next.
  281. */
  282. lastPoolIndex = (lastPoolIndex+1) % CHANNELPOOLSIZE;
  283. }
  284. }
  285. }
  286. /*
  287. * In the normal course of events, the pool of fonts can remain open
  288. * ready for quick access to their contents. The pool is sized so
  289. * that it is not an excessive consumer of system resources whilst
  290. * facilitating performance by providing ready access to the most
  291. * recently used set of font files.
  292. * The only reason to call removeFromPool(..) is for a Font that
  293. * you want to to have GC'd. Currently this would apply only to fonts
  294. * created with java.awt.Font.createFont(..).
  295. * In this case, the caller is expected to have arranged for the file
  296. * to be closed.
  297. * REMIND: consider how to know when a createFont created font should
  298. * be closed.
  299. */
  300. public static void removeFromPool(FileFont font) {
  301. synchronized (fontFileCache) {
  302. for (int i=0; i<CHANNELPOOLSIZE; i++) {
  303. if (fontFileCache[i] == font) {
  304. fontFileCache[i] = null;
  305. poolSize--;
  306. }
  307. }
  308. }
  309. }
  310. /**
  311. * This method is provided for internal and exclusive use by Swing.
  312. *
  313. * @param font representing a physical font.
  314. * @return true if the underlying font is a TrueType or OpenType font
  315. * that claims to support the Microsoft Windows encoding corresponding to
  316. * the default file.encoding property of this JRE instance.
  317. * This narrow value is useful for Swing to decide if the font is useful
  318. * for the the Windows Look and Feel, or, if a composite font should be
  319. * used instead.
  320. * The information used to make the decision is obtained from
  321. * the ulCodePageRange fields in the font.
  322. * A caller can use isLogicalFont(Font) in this class before calling
  323. * this method and would not need to call this method if that
  324. * returns true.
  325. */
  326. // static boolean fontSupportsDefaultEncoding(Font font) {
  327. // String encoding =
  328. // (String) java.security.AccessController.doPrivileged(
  329. // new sun.security.action.GetPropertyAction("file.encoding"));
  330. // if (encoding == null || font == null) {
  331. // return false;
  332. // }
  333. // encoding = encoding.toLowerCase(Locale.ENGLISH);
  334. // return FontManager.fontSupportsEncoding(font, encoding);
  335. // }
  336. /* Revise the implementation to in fact mean "font is a composite font.
  337. * This ensures that Swing components will always benefit from the
  338. * fall back fonts
  339. */
  340. public static boolean fontSupportsDefaultEncoding(Font font) {
  341. return getFont2D(font) instanceof CompositeFont;
  342. }
  343. /**
  344. * This method is provided for internal and exclusive use by Swing.
  345. *
  346. * It may be used in conjunction with fontSupportsDefaultEncoding(Font)
  347. * In the event that a desktop properties font doesn't directly
  348. * support the default encoding, (ie because the host OS supports
  349. * adding support for the current locale automatically for native apps),
  350. * then Swing calls this method to get a font which uses the specified
  351. * font for the code points it covers, but also supports this locale
  352. * just as the standard composite fonts do.
  353. * Note: this will over-ride any setting where an application
  354. * specifies it prefers locale specific composite fonts.
  355. * The logic for this, is that this method is used only where the user or
  356. * application has specified that the native L&F be used, and that
  357. * we should honour that request to use the same font as native apps use.
  358. *
  359. * The behaviour of this method is to construct a new composite
  360. * Font object that uses the specified physical font as its first
  361. * component, and adds all the components of "dialog" as fall back
  362. * components.
  363. * The method currently assumes that only the size and style attributes
  364. * are set on the specified font. It doesn't copy the font transform or
  365. * other attributes because they aren't set on a font created from
  366. * the desktop. This will need to be fixed if use is broadened.
  367. *
  368. * Operations such as Font.deriveFont will work properly on the
  369. * font returned by this method for deriving a different point size.
  370. * Additionally it tries to support a different style by calling
  371. * getNewComposite() below. That also supports replacing slot zero
  372. * with a different physical font but that is expected to be "rare".
  373. * Deriving with a different style is needed because its been shown
  374. * that some applications try to do this for Swing FontUIResources.
  375. * Also operations such as new Font(font.getFontName(..), Font.PLAIN, 14);
  376. * will NOT yield the same result, as the new underlying CompositeFont
  377. * cannot be "looked up" in the font registry.
  378. * This returns a FontUIResource as that is the Font sub-class needed
  379. * by Swing.
  380. * Suggested usage is something like :
  381. * FontUIResource fuir;
  382. * Font desktopFont = getDesktopFont(..);
  383. * // NOTE even if fontSupportsDefaultEncoding returns true because
  384. * // you get Tahoma and are running in an English locale, you may
  385. * // still want to just call getCompositeFontUIResource() anyway
  386. * // as only then will you get fallback fonts - eg for CJK.
  387. * if (FontManager.fontSupportsDefaultEncoding(desktopFont)) {
  388. * fuir = new FontUIResource(..);
  389. * } else {
  390. * fuir = FontManager.getCompositeFontUIResource(desktopFont);
  391. * }
  392. * return fuir;
  393. */
  394. public static FontUIResource getCompositeFontUIResource(Font font) {
  395. FontUIResource fuir =
  396. new FontUIResource(font.getName(),font.getStyle(),font.getSize());
  397. Font2D font2D = getFont2D(font);
  398. if (!(font2D instanceof PhysicalFont)) {
  399. /* Swing should only be calling this when a font is obtained
  400. * from desktop properties, so should generally be a physical font,
  401. * an exception might be for names like "MS Serif" which are
  402. * automatically mapped to "Serif", so there's no need to do
  403. * anything special in that case. But note that suggested usage
  404. * is first to call fontSupportsDefaultEncoding(Font) and this
  405. * method should not be called if that were to return true.
  406. */
  407. return fuir;
  408. }
  409. CompositeFont dialog2D =
  410. (CompositeFont)findFont2D("dialog", font.getStyle(), NO_FALLBACK);
  411. if (dialog2D == null) { /* shouldn't happen */
  412. return fuir;
  413. }
  414. PhysicalFont physicalFont = (PhysicalFont)font2D;
  415. CompositeFont compFont = new CompositeFont(physicalFont, dialog2D);
  416. setFont2D(fuir, compFont.handle);
  417. /* marking this as a created font is needed as only created fonts
  418. * copy their creator's handles.
  419. */
  420. setCreatedFont(fuir);
  421. return fuir;
  422. }
  423. public static Font2DHandle getNewComposite(String family, int style,
  424. Font2DHandle handle) {
  425. if (!(handle.font2D instanceof CompositeFont)) {
  426. return handle;
  427. }
  428. CompositeFont oldComp = (CompositeFont)handle.font2D;
  429. PhysicalFont oldFont = oldComp.getSlotFont(0);
  430. if (family == null) {
  431. family = oldFont.getFamilyName(null);
  432. }
  433. if (style == -1) {
  434. style = oldComp.getStyle();
  435. }
  436. Font2D newFont = findFont2D(family, style, NO_FALLBACK);
  437. if (!(newFont instanceof PhysicalFont)) {
  438. newFont = oldFont;
  439. }
  440. PhysicalFont physicalFont = (PhysicalFont)newFont;
  441. CompositeFont dialog2D =
  442. (CompositeFont)findFont2D("dialog", style, NO_FALLBACK);
  443. if (dialog2D == null) { /* shouldn't happen */
  444. return handle;
  445. }
  446. CompositeFont compFont = new CompositeFont(physicalFont, dialog2D);
  447. Font2DHandle newHandle = new Font2DHandle(compFont);
  448. return newHandle;
  449. }
  450. public static native void setFont2D(Font font, Font2DHandle font2DHandle);
  451. private static native boolean isCreatedFont(Font font);
  452. private static native void setCreatedFont(Font font);
  453. public static void registerCompositeFont(String compositeName,
  454. String[] componentFileNames,
  455. String[] componentNames,
  456. int numMetricsSlots,
  457. int[] exclusionRanges,
  458. int[] exclusionMaxIndex,
  459. boolean defer) {
  460. CompositeFont cf = new CompositeFont(compositeName,
  461. componentFileNames,
  462. componentNames,
  463. numMetricsSlots,
  464. exclusionRanges,
  465. exclusionMaxIndex, defer);
  466. addCompositeToFontList(cf, Font2D.FONT_CONFIG_RANK);
  467. synchronized (compFonts) {
  468. compFonts[maxCompFont++] = cf;
  469. }
  470. }
  471. /* This variant is used only when the application specifies
  472. * a variant of composite fonts which prefers locale specific or
  473. * proportional fonts.
  474. */
  475. public static void registerCompositeFont(String compositeName,
  476. String[] componentFileNames,
  477. String[] componentNames,
  478. int numMetricsSlots,
  479. int[] exclusionRanges,
  480. int[] exclusionMaxIndex,
  481. boolean defer,
  482. ConcurrentHashMap<String, Font2D>
  483. altNameCache) {
  484. CompositeFont cf = new CompositeFont(compositeName,
  485. componentFileNames,
  486. componentNames,
  487. numMetricsSlots,
  488. exclusionRanges,
  489. exclusionMaxIndex, defer);
  490. /* if the cache has an existing composite for this case, make
  491. * its handle point to this new font.
  492. * This ensures that when the altNameCache that is passed in
  493. * is the global mapNameCache - ie we are running as an application -
  494. * that any statically created java.awt.Font instances which already
  495. * have a Font2D instance will have that re-directed to the new Font
  496. * on subsequent uses. This is particularly important for "the"
  497. * default font instance, or similar cases where a UI toolkit (eg
  498. * Swing) has cached a java.awt.Font. Note that if Swing is using
  499. * a custom composite APIs which update the standard composites have
  500. * no effect - this is typically the case only when using the Windows
  501. * L&F where these APIs would conflict with that L&F anyway.
  502. */
  503. Font2D oldFont = (Font2D)
  504. altNameCache.get(compositeName.toLowerCase(Locale.ENGLISH));
  505. if (oldFont instanceof CompositeFont) {
  506. oldFont.handle.font2D = cf;
  507. }
  508. altNameCache.put(compositeName.toLowerCase(Locale.ENGLISH), cf);
  509. }
  510. private static void addCompositeToFontList(CompositeFont f, int rank) {
  511. if (logging) {
  512. logger.info("Add to Family "+ f.familyName +
  513. ", Font " + f.fullName + " rank="+rank);
  514. }
  515. f.setRank(rank);
  516. compositeFonts.put(f.fullName, f);
  517. fullNameToFont.put(f.fullName.toLowerCase(Locale.ENGLISH), f);
  518. FontFamily family = FontFamily.getFamily(f.familyName);
  519. if (family == null) {
  520. family = new FontFamily(f.familyName, true, rank);
  521. }
  522. family.setFont(f, f.style);
  523. }
  524. /*
  525. * Systems may have fonts with the same name.
  526. * We want to register only one of such fonts (at least until
  527. * such time as there might be APIs which can accommodate > 1).
  528. * Rank is 1) font configuration fonts, 2) JRE fonts, 3) OT/TT fonts,
  529. * 4) Type1 fonts, 5) native fonts.
  530. *
  531. * If the new font has the same name as the old font, the higher
  532. * ranked font gets added, replacing the lower ranked one.
  533. * If the fonts are of equal rank, then make a special case of
  534. * font configuration rank fonts, which are on closer inspection,
  535. * OT/TT fonts such that the larger font is registered. This is
  536. * a heuristic since a font may be "larger" in the sense of more
  537. * code points, or be a larger "file" because it has more bitmaps.
  538. * So it is possible that using filesize may lead to less glyphs, and
  539. * using glyphs may lead to lower quality display. Probably number
  540. * of glyphs is the ideal, but filesize is information we already
  541. * have and is good enough for the known cases.
  542. * Also don't want to register fonts that match JRE font families
  543. * but are coming from a source other than the JRE.
  544. * This will ensure that we will algorithmically style the JRE
  545. * plain font and get the same set of glyphs for all styles.
  546. *
  547. * Note that this method returns a value
  548. * if it returns the same object as its argument that means this
  549. * font was newly registered.
  550. * If it returns a different object it means this font already exists,
  551. * and you should use that one.
  552. * If it returns null means this font was not registered and none
  553. * in that name is registered. The caller must find a substitute
  554. */
  555. private static PhysicalFont addToFontList(PhysicalFont f, int rank) {
  556. String fontName = f.fullName;
  557. String familyName = f.familyName;
  558. if (fontName == null || "".equals(fontName)) {
  559. return null;
  560. }
  561. if (compositeFonts.containsKey(fontName)) {
  562. /* Don't register any font that has the same name as a composite */
  563. return null;
  564. }
  565. f.setRank(rank);
  566. if (!physicalFonts.containsKey(fontName)) {
  567. if (logging) {
  568. logger.info("Add to Family "+familyName +
  569. ", Font " + fontName + " rank="+rank);
  570. }
  571. physicalFonts.put(fontName, f);
  572. FontFamily family = FontFamily.getFamily(familyName);
  573. if (family == null) {
  574. family = new FontFamily(familyName, false, rank);
  575. family.setFont(f, f.style);
  576. } else if (family.getRank() >= rank) {
  577. family.setFont(f, f.style);
  578. }
  579. fullNameToFont.put(fontName.toLowerCase(Locale.ENGLISH), f);
  580. return f;
  581. } else {
  582. PhysicalFont newFont = f;
  583. PhysicalFont oldFont = physicalFonts.get(fontName);
  584. if (oldFont == null) {
  585. return null;
  586. }
  587. /* If the new font is of an equal or higher rank, it is a
  588. * candidate to replace the current one, subject to further tests.
  589. */
  590. if (oldFont.getRank() >= rank) {
  591. /* All fonts initialise their mapper when first
  592. * used. If the mapper is non-null then this font
  593. * has been accessed at least once. In that case
  594. * do not replace it. This may be overly stringent,
  595. * but its probably better not to replace a font that
  596. * someone is already using without a compelling reason.
  597. * Additionally the primary case where it is known
  598. * this behaviour is important is in certain composite
  599. * fonts, and since all the components of a given
  600. * composite are usually initialised together this
  601. * is unlikely. For this to be a problem, there would
  602. * have to be a case where two different composites used
  603. * different versions of the same-named font, and they
  604. * were initialised and used at separate times.
  605. * In that case we continue on and allow the new font to
  606. * be installed, but replaceFont will continue to allow
  607. * the original font to be used in Composite fonts.
  608. */
  609. if (oldFont.mapper != null && rank > Font2D.FONT_CONFIG_RANK) {
  610. return oldFont;
  611. }
  612. /* Normally we require a higher rank to replace a font,
  613. * but as a special case, if the two fonts are the same rank,
  614. * and are instances of TrueTypeFont we want the
  615. * more complete (larger) one.
  616. */
  617. if (oldFont.getRank() == rank) {
  618. if (oldFont instanceof TrueTypeFont &&
  619. newFont instanceof TrueTypeFont) {
  620. TrueTypeFont oldTTFont = (TrueTypeFont)oldFont;
  621. TrueTypeFont newTTFont = (TrueTypeFont)newFont;
  622. if (oldTTFont.fileSize >= newTTFont.fileSize) {
  623. return oldFont;
  624. }
  625. } else {
  626. return oldFont;
  627. }
  628. }
  629. /* Don't replace ever JRE fonts.
  630. * This test is in case a font configuration references
  631. * a Lucida font, which has been mapped to a Lucida
  632. * from the host O/S. The assumption here is that any
  633. * such font configuration file is probably incorrect, or
  634. * the host O/S version is for the use of AWT.
  635. * In other words if we reach here, there's a possible
  636. * problem with our choice of font configuration fonts.
  637. */
  638. if (oldFont.platName.startsWith(
  639. SunGraphicsEnvironment.jreFontDirName)) {
  640. if (logging) {
  641. logger.warning("Unexpected attempt to replace a JRE " +
  642. " font " + fontName + " from " +
  643. oldFont.platName +
  644. " with " + newFont.platName);
  645. }
  646. return oldFont;
  647. }
  648. if (logging) {
  649. logger.info("Replace in Family " + familyName +
  650. ",Font " + fontName + " new rank="+rank +
  651. " from " + oldFont.platName +
  652. " with " + newFont.platName);
  653. }
  654. replaceFont(oldFont, newFont);
  655. physicalFonts.put(fontName, newFont);
  656. fullNameToFont.put(fontName.toLowerCase(Locale.ENGLISH),
  657. newFont);
  658. FontFamily family = FontFamily.getFamily(familyName);
  659. if (family == null) {
  660. family = new FontFamily(familyName, false, rank);
  661. family.setFont(newFont, newFont.style);
  662. } else if (family.getRank() >= rank) {
  663. family.setFont(newFont, newFont.style);
  664. }
  665. return newFont;
  666. } else {
  667. return oldFont;
  668. }
  669. }
  670. }
  671. public static Font2D[] getRegisteredFonts() {
  672. PhysicalFont[] physFonts = getPhysicalFonts();
  673. int mcf = maxCompFont; /* for MT-safety */
  674. Font2D[] regFonts = new Font2D[physFonts.length+mcf];
  675. System.arraycopy(compFonts, 0, regFonts, 0, mcf);
  676. System.arraycopy(physFonts, 0, regFonts, mcf, physFonts.length);
  677. return regFonts;
  678. }
  679. public static PhysicalFont[] getPhysicalFonts() {
  680. return physicalFonts.values().toArray(new PhysicalFont[0]);
  681. }
  682. /* The class FontRegistrationInfo is used when a client says not
  683. * to register a font immediately. This mechanism is used to defer
  684. * initialisation of all the components of composite fonts at JRE
  685. * start-up. The CompositeFont class is "aware" of this and when it
  686. * is first used it asks for the registration of its components.
  687. * Also in the event that any physical font is requested the
  688. * deferred fonts are initialised before triggering a search of the
  689. * system.
  690. * Two maps are used. One to track the deferred fonts. The
  691. * other to track the fonts that have been initialised through this
  692. * mechanism.
  693. */
  694. private static final class FontRegistrationInfo {
  695. String fontFilePath;
  696. String[] nativeNames;
  697. int fontFormat;
  698. boolean javaRasterizer;
  699. int fontRank;
  700. FontRegistrationInfo(String fontPath, String[] names, int format,
  701. boolean useJavaRasterizer, int rank) {
  702. this.fontFilePath = fontPath;
  703. this.nativeNames = names;
  704. this.fontFormat = format;
  705. this.javaRasterizer = useJavaRasterizer;
  706. this.fontRank = rank;
  707. }
  708. }
  709. private static final ConcurrentHashMap<String, FontRegistrationInfo>
  710. deferredFontFiles =
  711. new ConcurrentHashMap<String, FontRegistrationInfo>();
  712. private static final ConcurrentHashMap<String, Font2DHandle>
  713. initialisedFonts = new ConcurrentHashMap<String, Font2DHandle>();
  714. /* Remind: possibly enhance initialiseDeferredFonts() to be
  715. * optionally given a name and a style and it could stop when it
  716. * finds that font - but this would be a problem if two of the
  717. * fonts reference the same font face name (cf the Solaris
  718. * euro fonts).
  719. */
  720. public static synchronized void initialiseDeferredFonts() {
  721. for (String fileName : deferredFontFiles.keySet()) {
  722. initialiseDeferredFont(fileName);
  723. }
  724. }
  725. public static synchronized void registerDeferredJREFonts(String jreDir) {
  726. for (FontRegistrationInfo info : deferredFontFiles.values()) {
  727. if (info.fontFilePath != null &&
  728. info.fontFilePath.startsWith(jreDir)) {
  729. initialiseDeferredFont(info.fontFilePath);
  730. }
  731. }
  732. }
  733. /* We keep a map of the files which contain the Lucida fonts so we
  734. * don't need to search for them.
  735. * But since we know what fonts these files contain, we can also avoid
  736. * opening them to look for a font name we don't recognise - see
  737. * findDeferredFont().
  738. * For typical cases where the font isn't a JRE one the overhead is
  739. * this method call, HashMap.get() and null reference test, then
  740. * a boolean test of noOtherJREFontFiles.
  741. */
  742. private static PhysicalFont findJREDeferredFont(String name, int style) {
  743. PhysicalFont physicalFont;
  744. String nameAndStyle = name.toLowerCase(Locale.ENGLISH) + style;
  745. String fileName = jreFontMap.get(nameAndStyle);
  746. if (fileName != null) {
  747. initSGEnv(); /* ensure jreFontDirName is initialised */
  748. fileName = SunGraphicsEnvironment.jreFontDirName +
  749. File.separator + fileName;
  750. if (deferredFontFiles.get(fileName) != null) {
  751. physicalFont = initialiseDeferredFont(fileName);
  752. if (physicalFont != null &&
  753. (physicalFont.getFontName(null).equalsIgnoreCase(name) ||
  754. physicalFont.getFamilyName(null).equalsIgnoreCase(name))
  755. && physicalFont.style == style) {
  756. return physicalFont;
  757. }
  758. }
  759. }
  760. /* Iterate over the deferred font files looking for any in the
  761. * jre directory that we didn't recognise, open each of these.
  762. * In almost all installations this will quickly fall through
  763. * because only the Lucidas will be present and jreOtherFontFiles
  764. * will be empty.
  765. * noOtherJREFontFiles is used so we can skip this block as soon
  766. * as its determined that its not needed - almost always after the
  767. * very first time through.
  768. */
  769. if (noOtherJREFontFiles) {
  770. return null;
  771. }
  772. synchronized (jreLucidaFontFiles) {
  773. if (jreOtherFontFiles == null) {
  774. HashSet<String> otherFontFiles = new HashSet<String>();
  775. for (String deferredFile : deferredFontFiles.keySet()) {
  776. File file = new File(deferredFile);
  777. String dir = file.getParent();
  778. String fname = file.getName();
  779. /* skip names which aren't absolute, aren't in the JRE
  780. * directory, or are known Lucida fonts.
  781. */
  782. if (dir == null ||
  783. !dir.equals(SunGraphicsEnvironment.jreFontDirName) ||
  784. jreLucidaFontFiles.contains(fname)) {
  785. continue;
  786. }
  787. otherFontFiles.add(deferredFile);
  788. }
  789. jreOtherFontFiles = otherFontFiles.toArray(STR_ARRAY);
  790. if (jreOtherFontFiles.length == 0) {
  791. noOtherJREFontFiles = true;
  792. }
  793. }
  794. for (int i=0; i<jreOtherFontFiles.length;i++) {
  795. fileName = jreOtherFontFiles[i];
  796. if (fileName == null) {
  797. continue;
  798. }
  799. jreOtherFontFiles[i] = null;
  800. physicalFont = initialiseDeferredFont(fileName);
  801. if (physicalFont != null &&
  802. (physicalFont.getFontName(null).equalsIgnoreCase(name) ||
  803. physicalFont.getFamilyName(null).equalsIgnoreCase(name))
  804. && physicalFont.style == style) {
  805. return physicalFont;
  806. }
  807. }
  808. }
  809. return null;
  810. }
  811. /* This skips JRE installed fonts. */
  812. private static PhysicalFont findOtherDeferredFont(String name, int style) {
  813. for (String fileName : deferredFontFiles.keySet()) {
  814. File file = new File(fileName);
  815. String dir = file.getParent();
  816. String fname = file.getName();
  817. if (dir != null &&
  818. dir.equals(SunGraphicsEnvironment.jreFontDirName) &&
  819. jreLucidaFontFiles.contains(fname)) {
  820. continue;
  821. }
  822. PhysicalFont physicalFont = initialiseDeferredFont(fileName);
  823. if (physicalFont != null &&
  824. (physicalFont.getFontName(null).equalsIgnoreCase(name) ||
  825. physicalFont.getFamilyName(null).equalsIgnoreCase(name)) &&
  826. physicalFont.style == style) {
  827. return physicalFont;
  828. }
  829. }
  830. return null;
  831. }
  832. private static PhysicalFont findDeferredFont(String name, int style) {
  833. PhysicalFont physicalFont = findJREDeferredFont(name, style);
  834. if (physicalFont != null) {
  835. return physicalFont;
  836. } else {
  837. return findOtherDeferredFont(name, style);
  838. }
  839. }
  840. public static void registerDeferredFont(String fileNameKey,
  841. String fullPathName,
  842. String[] nativeNames,
  843. int fontFormat,
  844. boolean useJavaRasterizer,
  845. int fontRank) {
  846. FontRegistrationInfo regInfo =
  847. new FontRegistrationInfo(fullPathName, nativeNames, fontFormat,
  848. useJavaRasterizer, fontRank);
  849. deferredFontFiles.put(fileNameKey, regInfo);
  850. }
  851. public static synchronized
  852. PhysicalFont initialiseDeferredFont(String fileNameKey) {
  853. if (fileNameKey == null) {
  854. return null;
  855. }
  856. if (logging) {
  857. logger.info("Opening deferred font file " + fileNameKey);
  858. }
  859. PhysicalFont physicalFont;
  860. FontRegistrationInfo regInfo = deferredFontFiles.get(fileNameKey);
  861. if (regInfo != null) {
  862. deferredFontFiles.remove(fileNameKey);
  863. physicalFont = registerFontFile(regInfo.fontFilePath,
  864. regInfo.nativeNames,
  865. regInfo.fontFormat,
  866. regInfo.javaRasterizer,
  867. regInfo.fontRank);
  868. if (physicalFont != null) {
  869. /* Store the handle, so that if a font is bad, we
  870. * retrieve the substituted font.
  871. */
  872. initialisedFonts.put(fileNameKey, physicalFont.handle);
  873. } else {
  874. initialisedFonts.put(fileNameKey,
  875. getDefaultPhysicalFont().handle);
  876. }
  877. } else {
  878. Font2DHandle handle = initialisedFonts.get(fileNameKey);
  879. if (handle == null) {
  880. /* Probably shouldn't happen, but just in case */
  881. physicalFont = getDefaultPhysicalFont();
  882. } else {
  883. physicalFont = (PhysicalFont)(handle.font2D);
  884. }
  885. }
  886. return physicalFont;
  887. }
  888. /* Note that the return value from this method is not always
  889. * derived from this file, and may be null. See addToFontList for
  890. * some explanation of this.
  891. */
  892. public static PhysicalFont registerFontFile(String fileName,
  893. String[] nativeNames,
  894. int fontFormat,
  895. boolean useJavaRasterizer,
  896. int fontRank) {
  897. PhysicalFont regFont = registeredFontFiles.get(fileName);
  898. if (regFont != null) {
  899. return regFont;
  900. }
  901. PhysicalFont physicalFont = null;
  902. try {
  903. String name;
  904. switch (fontFormat) {
  905. case FontManager.FONTFORMAT_TRUETYPE:
  906. int fn = 0;
  907. TrueTypeFont ttf;
  908. do {
  909. ttf = new TrueTypeFont(fileName, nativeNames, fn++,
  910. useJavaRasterizer);
  911. PhysicalFont pf = addToFontList(ttf, fontRank);
  912. if (physicalFont == null) {
  913. physicalFont = pf;
  914. }
  915. }
  916. while (fn < ttf.getFontCount());
  917. break;
  918. case FontManager.FONTFORMAT_TYPE1:
  919. Type1Font t1f = new Type1Font(fileName, nativeNames);
  920. physicalFont = addToFontList(t1f, fontRank);
  921. break;
  922. case FontManager.FONTFORMAT_NATIVE:
  923. NativeFont nf = new NativeFont(fileName, false);
  924. physicalFont = addToFontList(nf, fontRank);
  925. default:
  926. }
  927. if (logging) {
  928. logger.info("Registered file " + fileName + " as font " +
  929. physicalFont + " rank=" + fontRank);
  930. }
  931. } catch (FontFormatException ffe) {
  932. if (logging) {
  933. logger.warning("Unusable font: " +
  934. fileName + " " + ffe.toString());
  935. }
  936. }
  937. if (physicalFont != null &&
  938. fontFormat != FontManager.FONTFORMAT_NATIVE) {
  939. registeredFontFiles.put(fileName, physicalFont);
  940. }
  941. return physicalFont;
  942. }
  943. public static void registerFonts(String[] fileNames,
  944. String[][] nativeNames,
  945. int fontCount,
  946. int fontFormat,
  947. boolean useJavaRasterizer,
  948. int fontRank, boolean defer) {
  949. for (int i=0; i < fontCount; i++) {
  950. if (defer) {
  951. registerDeferredFont(fileNames[i],fileNames[i], nativeNames[i],
  952. fontFormat, useJavaRasterizer, fontRank);
  953. } else {
  954. registerFontFile(fileNames[i], nativeNames[i],
  955. fontFormat, useJavaRasterizer, fontRank);
  956. }
  957. }
  958. }
  959. /*
  960. * This is the Physical font used when some other font on the system
  961. * can't be located. There has to be at least one font or the font
  962. * system is not useful and the graphics environment cannot sustain
  963. * the Java platform.
  964. */
  965. public static PhysicalFont getDefaultPhysicalFont() {
  966. if (defaultPhysicalFont == null) {
  967. /* findFont2D will load all fonts before giving up the search.
  968. * If the JRE Lucida isn't found (eg because the JRE fonts
  969. * directory is missing), it could find another version of Lucida
  970. * from the host system. This is OK because at that point we are
  971. * trying to gracefully handle/recover from a system
  972. * misconfiguration and this is probably a reasonable substitution.
  973. */
  974. defaultPhysicalFont = (PhysicalFont)
  975. findFont2D("Lucida Sans Regular", Font.PLAIN, NO_FALLBACK);
  976. if (defaultPhysicalFont == null) {
  977. defaultPhysicalFont = (PhysicalFont)
  978. findFont2D("Arial", Font.PLAIN, NO_FALLBACK);
  979. }
  980. if (defaultPhysicalFont == null) {
  981. /* Because of the findFont2D call above, if we reach here, we
  982. * know all fonts have already been loaded, just accept any
  983. * match at this point. If this fails we are in real trouble
  984. * and I don't know how to recover from there being absolutely
  985. * no fonts anywhere on the system.
  986. */
  987. Iterator i = physicalFonts.values().iterator();
  988. if (i.hasNext()) {
  989. defaultPhysicalFont = (PhysicalFont)i.next();
  990. } else {
  991. throw new Error("Probable fatal error:No fonts found.");
  992. }
  993. }
  994. }
  995. return defaultPhysicalFont;
  996. }
  997. public static CompositeFont getDefaultLogicalFont(int style) {
  998. return (CompositeFont)findFont2D("dialog", style, NO_FALLBACK);
  999. }
  1000. /*
  1001. * return String representation of style prepended with "."
  1002. * This is useful for performance to avoid unnecessary string operations.
  1003. */
  1004. private static String dotStyleStr(int num) {
  1005. switch(num){
  1006. case Font.BOLD:
  1007. return ".bold";
  1008. case Font.ITALIC:
  1009. return ".italic";
  1010. case Font.ITALIC | Font.BOLD:
  1011. return ".bolditalic";
  1012. default:
  1013. return ".plain";
  1014. }
  1015. }
  1016. static void initSGEnv() {
  1017. if (sgEnv == null) {
  1018. GraphicsEnvironment ge =
  1019. GraphicsEnvironment.getLocalGraphicsEnvironment();
  1020. if (ge instanceof HeadlessGraphicsEnvironment) {
  1021. HeadlessGraphicsEnvironment hgEnv =
  1022. (HeadlessGraphicsEnvironment)ge;
  1023. sgEnv = (SunGraphicsEnvironment)
  1024. hgEnv.getSunGraphicsEnvironment();
  1025. } else {
  1026. sgEnv = (SunGraphicsEnvironment)ge;
  1027. }
  1028. }
  1029. }
  1030. /* This is implemented only on windows and is called from code that
  1031. * executes only on windows. This isn't pretty but its not a precedent
  1032. * in this file. This very probably should be cleaned up at some point.
  1033. */
  1034. private static native void
  1035. populateFontFileNameMap(HashMap<String,String> fontToFileMap,
  1036. HashMap<String,String> fontToFamilyNameMap,
  1037. HashMap<String,ArrayList<String>>
  1038. familyToFontListMap,
  1039. Locale locale);
  1040. /* Obtained from Platform APIs (windows only)
  1041. * Map from lower-case font full name to basename of font file.
  1042. * Eg "arial bold" -> ARIALBD.TTF.
  1043. * For TTC files, there is a mapping for each font in the file.
  1044. */
  1045. private static HashMap<String,String> fontToFileMap = null;
  1046. /* Obtained from Platform APIs (windows only)
  1047. * Map from lower-case font full name to the name of its font family
  1048. * Eg "arial bold" -> "Arial"
  1049. */
  1050. private static HashMap<String,String> fontToFamilyNameMap = null;
  1051. /* Obtained from Platform APIs (windows only)
  1052. * Map from a lower-case family name to a list of full names of
  1053. * the member fonts, eg:
  1054. * "arial" -> ["Arial", "Arial Bold", "Arial Italic","Arial Bold Italic"]
  1055. */
  1056. private static HashMap<String,ArrayList<String>> familyToFontListMap= null;
  1057. /* The directories which contain platform fonts */
  1058. private static String[] pathDirs = null;
  1059. private static boolean haveCheckedUnreferencedFontFiles;
  1060. private static String[] getFontFilesFromPath(boolean noType1) {
  1061. final FilenameFilter filter;
  1062. if (noType1) {
  1063. filter = SunGraphicsEnvironment.ttFilter;
  1064. } else {
  1065. filter = new SunGraphicsEnvironment.TTorT1Filter();
  1066. }
  1067. return (String[])AccessController.doPrivileged(new PrivilegedAction() {
  1068. public Object run() {
  1069. if (pathDirs.length == 1) {
  1070. File dir = new File(pathDirs[0]);
  1071. String[] files = dir.list(filter);
  1072. if (files == null) {
  1073. return new String[0];
  1074. }
  1075. for (int f=0; f<files.length; f++) {
  1076. files[f] = files[f].toLowerCase();
  1077. }
  1078. return files;
  1079. } else {
  1080. ArrayList<String> fileList = new ArrayList<String>();
  1081. for (int i = 0; i< pathDirs.length; i++) {
  1082. File dir = new File(pathDirs[i]);
  1083. String[] files = dir.list(filter);
  1084. if (files == null) {
  1085. continue;
  1086. }
  1087. for (int f=0; f<files.length ; f++) {
  1088. fileList.add(files[f].toLowerCase());
  1089. }
  1090. }
  1091. return fileList.toArray(STR_ARRAY);
  1092. }
  1093. }
  1094. });
  1095. }
  1096. /* This is needed since some windows registry names don't match
  1097. * the font names.
  1098. * - UPC styled font names have a double space, but the
  1099. * registry entry mapping to a file doesn't.
  1100. * - Marlett is in a hidden file not listed in the registry
  1101. * - The registry advertises that the file david.ttf contains a
  1102. * font with the full name "David Regular" when in fact its
  1103. * just "David".
  1104. * Directly fix up these known cases as this is faster.
  1105. * If a font which doesn't match these known cases has no file,
  1106. * it may be a font that has been temporarily added to the known set
  1107. * or it may be an installed font with a missing registry entry.
  1108. * Installed fonts are those in the windows font directories.
  1109. * Make a best effort attempt to locate these.
  1110. * We obtain the list of TrueType fonts in these directories and
  1111. * filter out all the font files we already know about from the registry.
  1112. * What remains may be "bad" fonts, duplicate fonts, or perhaps the
  1113. * missing font(s) we are looking for.
  1114. * Open each of these files to find out.
  1115. */
  1116. private static void resolveWindowsFonts() {
  1117. ArrayList<String> unmappedFontNames = null;
  1118. for (String font : fontToFamilyNameMap.keySet()) {
  1119. String file = fontToFileMap.get(font);
  1120. if (file == null) {
  1121. if (font.indexOf(" ") > 0) {
  1122. String newName = font.replaceFirst(" ", " ");
  1123. file = fontToFileMap.get(newName);
  1124. /* If this name exists and isn't for a valid name
  1125. * replace the mapping to the file with this font
  1126. */
  1127. if (file != null &&
  1128. !fontToFamilyNameMap.containsKey(newName)) {
  1129. fontToFileMap.remove(newName);
  1130. fontToFileMap.put(font, file);
  1131. }
  1132. } else if (font.equals("marlett")) {
  1133. fontToFileMap.put(font, "marlett.ttf");
  1134. } else if (font.equals("david")) {
  1135. file = fontToFileMap.get("david regular");
  1136. if (file != null) {
  1137. fontToFileMap.remove("david regular");
  1138. fontToFileMap.put("david", file);
  1139. }
  1140. } else {
  1141. if (unmappedFontNames == null) {
  1142. unmappedFontNames = new ArrayList<String>();
  1143. }
  1144. unmappedFontNames.add(font);
  1145. }
  1146. }
  1147. }
  1148. if (unmappedFontNames != null) {
  1149. HashSet<String> unmappedFontFiles = new HashSet<String>();
  1150. /* Every font key in fontToFileMap ought to correspond to a
  1151. * font key in fontToFamilyNameMap. Entries that don't seem
  1152. * to correspond are likely fonts that were named differently
  1153. * by GDI than in the registry. One known cause of this is when
  1154. * Windows has had its regional settings changed so that from
  1155. * GDI we get a localised (eg Chinese or Japanese) name for the
  1156. * font, but the registry retains the English version of the name
  1157. * that corresponded to the "install" locale for windows.
  1158. * Since we are in this code block because there are unmapped
  1159. * font names, we can look to find unused font->file mappings
  1160. * and then open the files to read the names. We don't generally
  1161. * want to open font files, as its a performance hit, but this
  1162. * occurs only for a small number of fonts on specific system
  1163. * configs - ie is believed that a "true" Japanese windows would
  1164. * have JA names in the registry too.
  1165. * Clone fontToFileMap and remove from the clone all keys which
  1166. * match a fontToFamilyNameMap key. What remains maps to the
  1167. * files we want to open to find the fonts GDI returned.
  1168. * A font in such a file is added to the fontToFileMap after
  1169. * checking its one of the unmappedFontNames we are looking for.
  1170. * The original name that didn't map is removed from fontToFileMap
  1171. * so essentially this "fixes up" fontToFileMap to use the same
  1172. * name as GDI.
  1173. * Also note that typically the fonts for which this occurs in
  1174. * CJK locales are TTC fonts and not all fonts in a TTC may have
  1175. * localised names. Eg MSGOTHIC.TTC contains 3 fonts and one of
  1176. * them "MS UI Gothic" has no JA name whereas the other two do.
  1177. * So not every font in these files is unmapped or new.
  1178. */
  1179. HashMap<String,String> ffmapCopy =
  1180. (HashMap<String,String>)(fontToFileMap.clone());
  1181. for (String key : fontToFamilyNameMap.keySet()) {
  1182. ffmapCopy.remove(key);
  1183. }
  1184. for (String key : ffmapCopy.keySet()) {
  1185. unmappedFontFiles.add(ffmapCopy.get(key));
  1186. fontToFileMap.remove(key);
  1187. }
  1188. resolveFontFiles(unmappedFontFiles, unmappedFontNames);
  1189. /* If there are still unmapped font names, this means there's
  1190. * something that wasn't in the registry. We need to get all
  1191. * the font files directly and look at the ones that weren't
  1192. * found in the registry.
  1193. */
  1194. if (unmappedFontNames.size() > 0) {
  1195. /* getFontFilesFromPath() returns all lower case names.
  1196. * To compare we also need lower case
  1197. * versions of the names from the registry.
  1198. */
  1199. ArrayList<String> registryFiles = new ArrayList<String>();
  1200. for (String regFile : fontToFileMap.values()) {
  1201. registryFiles.add(regFile.toLowerCase());
  1202. }
  1203. /* We don't look for Type1 files here as windows will
  1204. * not enumerate these, so aren't useful in reconciling
  1205. * GDI's unmapped files. We do find these later when
  1206. * we enumerate all fonts.
  1207. */
  1208. for (String pathFile : getFontFilesFromPath(true)) {
  1209. if (!registryFiles.contains(pathFile)) {
  1210. unmappedFontFiles.add(pathFile);
  1211. }
  1212. }
  1213. resolveFontFiles(unmappedFontFiles, unmappedFontNames);
  1214. }
  1215. /* remove from the set of names that will be returned to the
  1216. * user any fonts that can't be mapped to files.
  1217. */
  1218. if (unmappedFontNames.size() > 0) {
  1219. int sz = unmappedFontNames.size();
  1220. for (int i=0; i<sz; i++) {
  1221. String name = unmappedFontNames.get(i);
  1222. String familyName = fontToFamilyNameMap.get(name);
  1223. if (familyName != null) {
  1224. ArrayList family = familyToFontListMap.get(familyName);
  1225. if (family != null) {
  1226. if (family.size() <= 1) {
  1227. familyToFontListMap.remove(familyName);
  1228. }
  1229. }
  1230. }
  1231. fontToFamilyNameMap.remove(name);
  1232. if (logging) {
  1233. logger.info("No file for font:" + name);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. }
  1239. /**
  1240. * In some cases windows may have fonts in the fonts folder that
  1241. * don't show up in the registry or in the GDI calls to enumerate fonts.
  1242. * The only way to find these is to list the directory. We invoke this
  1243. * only in getAllFonts/Families, so most searches for a specific
  1244. * font that is satisfied by the GDI/registry calls don't take the
  1245. * additional hit of listing the directory. This hit is small enough
  1246. * that its not significant in these 'enumerate all the fonts' cases.
  1247. * The basic approach is to cross-reference the files windows found
  1248. * with the ones in the directory listing approach, and for each
  1249. * in the latter list that is missing from the former list, register it.
  1250. */
  1251. private static synchronized void checkForUnreferencedFontFiles() {
  1252. if (haveCheckedUnreferencedFontFiles) {
  1253. return;
  1254. }
  1255. haveCheckedUnreferencedFontFiles = true;
  1256. if (!isWindows) {
  1257. return;
  1258. }
  1259. /* getFontFilesFromPath() returns all lower case names.
  1260. * To compare we also need lower case
  1261. * versions of the names from the registry.
  1262. */
  1263. ArrayList<String> registryFiles = new ArrayList<String>();
  1264. for (String regFile : fontToFileMap.values()) {
  1265. registryFiles.add(regFile.toLowerCase());
  1266. }
  1267. /* To avoid any issues with concurrent modification, create
  1268. * copies of the existing maps, add the new fonts into these
  1269. * and then replace the references to the old ones with the
  1270. * new maps. ConcurrentHashmap is another option but its a lot
  1271. * more changes and with this exception, these maps are intended
  1272. * to be static.
  1273. */
  1274. HashMap<String,String> fontToFileMap2 = null;
  1275. HashMap<String,String> fontToFamilyNameMap2 = null;
  1276. HashMap<String,ArrayList<String>> familyToFontListMap2 = null;;
  1277. for (String pathFile : getFontFilesFromPath(false)) {
  1278. if (!registryFiles.contains(pathFile)) {
  1279. if (logging) {
  1280. logger.info("Found non-registry file : " + pathFile);
  1281. }
  1282. PhysicalFont f = registerFontFile(getPathName(pathFile));
  1283. if (f == null) {
  1284. continue;
  1285. }
  1286. if (fontToFileMap2 == null) {
  1287. fontToFileMap2 = new HashMap<String,String>(fontToFileMap);
  1288. fontToFamilyNameMap2 =
  1289. new HashMap<String,String>(fontToFamilyNameMap);
  1290. familyToFontListMap2 = new
  1291. HashMap<String,ArrayList<String>>(familyToFontListMap);
  1292. }
  1293. String fontName = f.getFontName(null);
  1294. String family = f.getFamilyName(null);
  1295. String familyLC = family.toLowerCase();
  1296. fontToFamilyNameMap2.put(fontName, family);
  1297. fontToFileMap2.put(fontName, pathFile);
  1298. ArrayList<String> fonts = familyToFontListMap2.get(familyLC);
  1299. if (fonts == null) {
  1300. fonts = new ArrayList<String>();
  1301. } else {
  1302. fonts = new ArrayList<String>(fonts);
  1303. }
  1304. fonts.add(fontName);
  1305. familyToFontListMap2.put(familyLC, fonts);
  1306. }
  1307. }
  1308. if (fontToFileMap2 != null) {
  1309. fontToFileMap = fontToFileMap2;
  1310. familyToFontListMap = familyToFontListMap2;
  1311. fontToFamilyNameMap = fontToFamilyNameMap2;
  1312. }
  1313. }
  1314. private static void resolveFontFiles(HashSet<String> unmappedFiles,
  1315. ArrayList<String> unmappedFonts) {
  1316. Locale l = SunToolkit.getStartupLocale();
  1317. for (String file : unmappedFiles) {
  1318. try {
  1319. int fn = 0;
  1320. TrueTypeFont ttf;
  1321. String fullPath = getPathName(file);
  1322. if (logging) {
  1323. logger.info("Trying to resolve file " + fullPath);
  1324. }
  1325. do {
  1326. ttf = new TrueTypeFont(fullPath, null, fn++, true);
  1327. // prefer the font's locale name.
  1328. String fontName = ttf.getFontName(l).toLowerCase();
  1329. if (unmappedFonts.contains(fontName)) {
  1330. fontToFileMap.put(fontName, file);
  1331. unmappedFonts.remove(fontName);
  1332. if (logging) {
  1333. logger.info("Resolved absent registry entry for " +
  1334. fontName + " located in " + fullPath);
  1335. }
  1336. }
  1337. }
  1338. while (fn < ttf.getFontCount());
  1339. } catch (Exception e) {
  1340. }
  1341. }
  1342. }
  1343. private static synchronized HashMap<String,String> getFullNameToFileMap() {
  1344. if (fontToFileMap == null) {
  1345. initSGEnv();
  1346. pathDirs = sgEnv.getPlatformFontDirs();
  1347. fontToFileMap = new HashMap<String,String>(100);
  1348. fontToFamilyNameMap = new HashMap<String,String>(100);
  1349. familyToFontListMap = new HashMap<String,ArrayList<String>>(50);
  1350. populateFontFileNameMap(fontToFileMap,
  1351. fontToFamilyNameMap,
  1352. familyToFontListMap,
  1353. Locale.ENGLISH);
  1354. if (isWindows) {
  1355. resolveWindowsFonts();
  1356. }
  1357. if (logging) {
  1358. logPlatformFontInfo();
  1359. }
  1360. }
  1361. return fontToFileMap;
  1362. }
  1363. private static void logPlatformFontInfo() {
  1364. for (int i=0; i< pathDirs.length;i++) {
  1365. logger.info("fontdir="+pathDirs[i]);
  1366. }
  1367. for (String keyName : fontToFileMap.keySet()) {
  1368. logger.info("font="+keyName+" file="+ fontToFileMap.get(keyName));
  1369. }
  1370. for (String keyName : fontToFamilyNameMap.keySet()) {
  1371. logger.info("font="+keyName+" family="+
  1372. fontToFamilyNameMap.get(keyName));
  1373. }
  1374. for (String keyName : familyToFontListMap.keySet()) {
  1375. logger.info("family="+keyName+ " fonts="+
  1376. familyToFontListMap.get(keyName));
  1377. }
  1378. }
  1379. /* Note this return list excludes logical fonts and JRE fonts */
  1380. public static String[] getFontNamesFromPlatform() {
  1381. if (getFullNameToFileMap().size() == 0) {
  1382. return null;
  1383. }
  1384. checkForUnreferencedFontFiles();
  1385. /* This odd code with TreeMap is used to preserve a historical
  1386. * behaviour wrt the sorting order .. */
  1387. ArrayList<String> fontNames = new ArrayList<String>();
  1388. for (ArrayList<String> a : familyToFontListMap.values()) {
  1389. for (String s : a) {
  1390. fontNames.add(s);
  1391. }
  1392. }
  1393. return fontNames.toArray(STR_ARRAY);
  1394. }
  1395. public static boolean gotFontsFromPlatform() {
  1396. return getFullNameToFileMap().size() != 0;
  1397. }
  1398. public static String getFileNameForFontName(String fontName) {
  1399. String fontNameLC = fontName.toLowerCase(Locale.ENGLISH);
  1400. return fontToFileMap.get(fontNameLC);
  1401. }
  1402. private static PhysicalFont registerFontFile(String file) {
  1403. if (new File(file).isAbsolute() &&
  1404. !registeredFontFiles.contains(file)) {
  1405. int fontFormat = FONTFORMAT_NONE;
  1406. int fontRank = Font2D.UNKNOWN_RANK;
  1407. if (SunGraphicsEnvironment.ttFilter.accept(null, file)) {
  1408. fontFormat = FONTFORMAT_TRUETYPE;
  1409. fontRank = Font2D.TTF_RANK;
  1410. } else if
  1411. (SunGraphicsEnvironment.t1Filter.accept(null, file)) {
  1412. fontFormat = FONTFORMAT_TYPE1;
  1413. fontRank = Font2D.TYPE1_RANK;
  1414. }
  1415. if (fontFormat == FONTFORMAT_NONE) {
  1416. return null;
  1417. }
  1418. return registerFontFile(file, null, fontFormat, false, fontRank);
  1419. }
  1420. return null;
  1421. }
  1422. /* Used to register any font files that are found by platform APIs
  1423. * that weren't previously found in the standard font locations.
  1424. * the isAbsolute() check is needed since that's whats stored in the
  1425. * set, and on windows, the fonts in the system font directory that
  1426. * are in the fontToFileMap are just basenames. We don't want to try
  1427. * to register those again, but we do want to register other registry
  1428. * installed fonts.
  1429. */
  1430. public static void registerOtherFontFiles(HashSet registeredFontFiles) {
  1431. if (getFullNameToFileMap().size() == 0) {
  1432. return;
  1433. }
  1434. for (String file : fontToFileMap.values()) {
  1435. registerFontFile(file);
  1436. }
  1437. }
  1438. public static boolean
  1439. getFamilyNamesFromPlatform(TreeMap<String,String> familyNames,
  1440. Locale requestedLocale) {
  1441. if (getFullNameToFileMap().size() == 0) {
  1442. return false;
  1443. }
  1444. checkForUnreferencedFontFiles();
  1445. for (String name : fontToFamilyNameMap.values()) {
  1446. familyNames.put(name.toLowerCase(requestedLocale), name);
  1447. }
  1448. return true;
  1449. }
  1450. /* Path may be absolute or a base file name relative to one of
  1451. * the platform font directories
  1452. */
  1453. private static String getPathName(String s) {
  1454. File f = new File(s);
  1455. if (f.isAbsolute()) {
  1456. return s;
  1457. } else if (pathDirs.length==1) {
  1458. return pathDirs[0] + File.separator + s;
  1459. } else {
  1460. for (int p=0; p<pathDirs.length; p++) {
  1461. f = new File(pathDirs[p] + File.separator + s);
  1462. if (f.exists()) {
  1463. return f.getAbsolutePath();
  1464. }
  1465. }
  1466. }
  1467. return s; // shouldn't happen, but harmless
  1468. }
  1469. /* lcName is required to be lower case for use as a key.
  1470. * lcName may be a full name, or a family name, and style may
  1471. * be specified in addition to either of these. So be sure to
  1472. * get the right one. Since an app *could* ask for "Foo Regular"
  1473. * and later ask for "Foo Italic", if we don't register all the
  1474. * styles, then logic in findFont2D may try to style the original
  1475. * so we register the entire family if we get a match here.
  1476. * This is still a big win because this code is invoked where
  1477. * otherwise we would register all fonts.
  1478. * It's also useful for the case where "Foo Bold" was specified with
  1479. * style Font.ITALIC, as we would want in that case to try to return
  1480. * "Foo Bold Italic" if it exists, and it is only by locating "Foo Bold"
  1481. * and opening it that we really "know" it's Bold, and can look for
  1482. * a font that supports that and the italic style.
  1483. * The code in here is not overtly windows-specific but in fact it
  1484. * is unlikely to be useful as is on other platforms. It is maintained
  1485. * in this shared source file to be close to its sole client and
  1486. * because so much of the logic is intertwined with the logic in
  1487. * findFont2D.
  1488. */
  1489. private static Font2D findFontFromPlatform(String lcName, int style) {
  1490. if (getFullNameToFileMap().size() == 0) {
  1491. return null;
  1492. }
  1493. ArrayList<String> family = null;
  1494. String fontFile = null;
  1495. String familyName = fontToFamilyNameMap.get(lcName);
  1496. if (familyName != null) {
  1497. fontFile = fontToFileMap.get(lcName);
  1498. family = familyToFontListMap.get
  1499. (familyName.toLowerCase(Locale.ENGLISH));
  1500. } else {
  1501. family = familyToFontListMap.get(lcName); // is lcName is a family?
  1502. if (family != null && family.size() > 0) {
  1503. String lcFontName = family.get(0).toLowerCase(Locale.ENGLISH);
  1504. if (lcFontName != null) {
  1505. familyName = fontToFamilyNameMap.get(lcFontName);
  1506. }
  1507. }
  1508. }
  1509. if (family == null || familyName == null) {
  1510. return null;
  1511. }
  1512. String [] fontList = (String[])family.toArray(STR_ARRAY);
  1513. if (fontList.length == 0) {
  1514. return null;
  1515. }
  1516. /* first check that for every font in this family we can find
  1517. * a font file. The specific reason for doing this is that
  1518. * in at least one case on Windows a font has the face name "David"
  1519. * but the registry entry is "David Regular". That is the "unique"
  1520. * name of the font but in other cases the registry contains the
  1521. * "full" name. See the specifications of name ids 3 and 4 in the
  1522. * TrueType 'name' table.
  1523. * In general this could cause a problem that we fail to register
  1524. * if we all members of a family that we may end up mapping to
  1525. * the wrong font member: eg return Bold when Plain is needed.
  1526. */
  1527. for (int f=0;f<fontList.length;f++) {
  1528. String fontNameLC = fontList[f].toLowerCase(Locale.ENGLISH);
  1529. String fileName = fontToFileMap.get(fontNameLC);
  1530. if (fileName == null) {
  1531. if (logging) {
  1532. logger.info("Platform lookup : No file for font " +
  1533. fontList[f] + " in family " +familyName);
  1534. }
  1535. return null;
  1536. }
  1537. }
  1538. /* Currently this code only looks for TrueType fonts, so format
  1539. * and rank can be specified without looking at the filename.
  1540. */
  1541. PhysicalFont physicalFont = null;
  1542. if (fontFile != null) {
  1543. physicalFont = registerFontFile(getPathName(fontFile), null,
  1544. FONTFORMAT_TRUETYPE, false,
  1545. Font2D.TTF_RANK);
  1546. }
  1547. /* Register all fonts in this family. */
  1548. for (int f=0;f<fontList.length;f++) {
  1549. String fontNameLC = fontList[f].toLowerCase(Locale.ENGLISH);
  1550. String fileName = fontToFileMap.get(fontNameLC);
  1551. if (fontFile != null && fontFile.equals(fileName)) {
  1552. continue;
  1553. }
  1554. /* Currently this code only looks for TrueType fonts, so format
  1555. * and rank can be specified without looking at the filename.
  1556. */
  1557. registerFontFile(getPathName(fileName), null,
  1558. FONTFORMAT_TRUETYPE, false, Font2D.TTF_RANK);
  1559. }
  1560. Font2D font = null;
  1561. FontFamily fontFamily = FontFamily.getFamily(familyName);
  1562. /* Handle case where request "MyFont Bold", style=Font.ITALIC */
  1563. if (physicalFont != null) {
  1564. style |= physicalFont.style;
  1565. }
  1566. if (fontFamily != null) {
  1567. font = fontFamily.getFont(style);
  1568. if (font == null) {
  1569. font = fontFamily.getClosestStyle(style);
  1570. }
  1571. }
  1572. return font;
  1573. }
  1574. private static ConcurrentHashMap<String, Font2D> fontNameCache =
  1575. new ConcurrentHashMap<String, Font2D>();
  1576. /*
  1577. * The client supplies a name and a style.
  1578. * The name could be a family name, or a full name.
  1579. * A font may exist with the specified style, or it may
  1580. * exist only in some other style. For non-native fonts the scaler
  1581. * may be able to emulate the required style.
  1582. */
  1583. public static Font2D findFont2D(String name, int style, int fallback) {
  1584. String lowerCaseName = name.toLowerCase(Locale.ENGLISH);
  1585. String mapName = lowerCaseName + dotStyleStr(style);
  1586. Font2D font;
  1587. /* If preferLocaleFonts() or preferProportionalFonts() has been
  1588. * called we may be using an alternate set of composite fonts in this
  1589. * app context. The presence of a pre-built name map indicates whether
  1590. * this is so, and gives access to the alternate composite for the
  1591. * name.
  1592. */
  1593. if (usingPerAppContextComposites) {
  1594. ConcurrentHashMap<String, Font2D> altNameCache =
  1595. (ConcurrentHashMap<String, Font2D>)
  1596. AppContext.getAppContext().get(CompositeFont.class);
  1597. if (altNameCache != null) {
  1598. font = (Font2D)altNameCache.get(mapName);
  1599. } else {
  1600. font = null;
  1601. }
  1602. } else {
  1603. font = fontNameCache.get(mapName);
  1604. }
  1605. if (font != null) {
  1606. return font;
  1607. }
  1608. if (logging) {
  1609. logger.info("Search for font: " + name);
  1610. }
  1611. // The check below is just so that the bitmap fonts being set by
  1612. // AWT and Swing thru the desktop properties do not trigger the
  1613. // the load fonts case. The two bitmap fonts are now mapped to
  1614. // appropriate equivalents for serif and sansserif.
  1615. // Note that the cost of this comparison is only for the first
  1616. // call until the map is filled.
  1617. if (isWindows) {
  1618. if (lowerCaseName.equals("ms sans serif")) {
  1619. name = "sansserif";
  1620. } else if (lowerCaseName.equals("ms serif")) {
  1621. name = "serif";
  1622. }
  1623. }
  1624. /* This isn't intended to support a client passing in the
  1625. * string default, but if a client passes in null for the name
  1626. * the java.awt.Font class internally substitutes this name.
  1627. * So we need to recognise it here to prevent a loadFonts
  1628. * on the unrecognised name. The only potential problem with
  1629. * this is it would hide any real font called "default"!
  1630. * But that seems like a potential problem we can ignore for now.
  1631. */
  1632. if (lowerCaseName.equals("default")) {
  1633. name = "dialog";
  1634. }
  1635. /* First see if its a family name. */
  1636. FontFamily family = FontFamily.getFamily(name);
  1637. if (family != null) {
  1638. font = family.getFontWithExactStyleMatch(style);
  1639. if (font == null) {
  1640. font = findDeferredFont(name, style);
  1641. }
  1642. if (font == null) {
  1643. font = family.getFont(style);
  1644. }
  1645. if (font == null) {
  1646. font = family.getClosestStyle(style);
  1647. }
  1648. if (font != null) {
  1649. fontNameCache.put(mapName, font);
  1650. return font;
  1651. }
  1652. }
  1653. /* If it wasn't a family name, it should be a full name of
  1654. * either a composite, or a physical font
  1655. */
  1656. font = fullNameToFont.get(lowerCaseName);
  1657. if (font != null) {
  1658. /* Check that the requested style matches the matched font's style.
  1659. * But also match style automatically if the requested style is
  1660. * "plain". This because the existing behaviour is that the fonts
  1661. * listed via getAllFonts etc always list their style as PLAIN.
  1662. * This does lead to non-commutative behaviours where you might
  1663. * start with "Lucida Sans Regular" and ask for a BOLD version
  1664. * and get "Lucida Sans DemiBold" but if you ask for the PLAIN
  1665. * style of "Lucida Sans DemiBold" you get "Lucida Sans DemiBold".
  1666. * This consistent however with what happens if you have a bold
  1667. * version of a font and no plain version exists - alg. styling
  1668. * doesn't "unbolden" the font.
  1669. */
  1670. if (font.style == style || style == Font.PLAIN) {
  1671. fontNameCache.put(mapName, font);
  1672. return font;
  1673. } else {
  1674. /* If it was a full name like "Lucida Sans Regular", but
  1675. * the style requested is "bold", then we want to see if
  1676. * there's the appropriate match against another font in
  1677. * that family before trying to load all fonts, or applying a
  1678. * algorithmic styling
  1679. */
  1680. family = FontFamily.getFamily(font.getFamilyName(null));
  1681. if (family != null) {
  1682. Font2D familyFont = family.getFont(style|font.style);
  1683. /* We exactly matched the requested style, use it! */
  1684. if (familyFont != null) {
  1685. fontNameCache.put(mapName, familyFont);
  1686. return familyFont;
  1687. } else {
  1688. /* This next call is designed to support the case
  1689. * where bold italic is requested, and if we must
  1690. * style, then base it on either bold or italic -
  1691. * not on plain!
  1692. */
  1693. familyFont = family.getClosestStyle(style|font.style);
  1694. if (familyFont != null) {
  1695. /* The next check is perhaps one
  1696. * that shouldn't be done. ie if we get this
  1697. * far we have probably as close a match as we
  1698. * are going to get. We could load all fonts to
  1699. * see if somehow some parts of the family are
  1700. * loaded but not all of it.
  1701. */
  1702. if (familyFont.canDoStyle(style|font.style)) {
  1703. fontNameCache.put(mapName, familyFont);
  1704. return familyFont;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. }
  1710. }
  1711. /* If reach here its possible that this is in a client which never
  1712. * loaded the GraphicsEnvironment, so we haven't even loaded ANY of
  1713. * the fonts from the environment. Do so now and recurse.
  1714. */
  1715. if (sgEnv == null) {
  1716. initSGEnv();
  1717. return findFont2D(name, style, fallback);
  1718. }
  1719. if (isWindows) {
  1720. /* Don't want Windows to return a Lucida Sans font from
  1721. * C:\Windows\Fonts
  1722. */
  1723. if (deferredFontFiles.size() > 0) {
  1724. font = findJREDeferredFont(lowerCaseName, style);
  1725. if (font != null) {
  1726. fontNameCache.put(mapName, font);
  1727. return font;
  1728. }
  1729. }
  1730. font = findFontFromPlatform(lowerCaseName, style);
  1731. if (font != null) {
  1732. if (logging) {
  1733. logger.info("Found font via platform API for request:\"" +
  1734. name + "\":, style="+style+
  1735. " found font: " + font);
  1736. }
  1737. fontNameCache.put(mapName, font);
  1738. return font;
  1739. }
  1740. }
  1741. /* If reach here and no match has been located, then if there are
  1742. * uninitialised deferred fonts, load as many of those as needed
  1743. * to find the deferred font. If none is found through that
  1744. * search continue on.
  1745. * There is possibly a minor issue when more than one
  1746. * deferred font implements the same font face. Since deferred
  1747. * fonts are only those in font configuration files, this is a
  1748. * controlled situation, the known case being Solaris euro_fonts
  1749. * versions of Arial, Times New Roman, Courier New. However
  1750. * the larger font will transparently replace the smaller one
  1751. * - see addToFontList() - when it is needed by the composite font.
  1752. */
  1753. if (deferredFontFiles.size() > 0) {
  1754. font = findDeferredFont(name, style);
  1755. if (font != null) {
  1756. fontNameCache.put(mapName, font);
  1757. return font;
  1758. }
  1759. }
  1760. /* Some apps use deprecated 1.0 names such as helvetica and courier. On
  1761. * Solaris these are Type1 fonts in /usr/openwin/lib/X11/fonts/Type1.
  1762. * If running on Solaris will register all the fonts in this
  1763. * directory.
  1764. * May as well register the whole directory without actually testing
  1765. * the font name is one of the deprecated names as the next step would
  1766. * load all fonts which are in this directory anyway.
  1767. * In the event that this lookup is successful it potentially "hides"
  1768. * TrueType versions of such fonts that are elsewhere but since they
  1769. * do not exist on Solaris this is not a problem.
  1770. * Set a flag to indicate we've done this registration to avoid
  1771. * repetition and more seriously, to avoid recursion.
  1772. */
  1773. if (isSolaris&&!loaded1dot0Fonts) {
  1774. /* "timesroman" is a special case since that's not the
  1775. * name of any known font on Solaris or elsewhere.
  1776. */
  1777. if (lowerCaseName.equals("timesroman")) {
  1778. font = findFont2D("serif", style, fallback);
  1779. fontNameCache.put(mapName, font);
  1780. }
  1781. sgEnv.register1dot0Fonts();
  1782. loaded1dot0Fonts = true;
  1783. Font2D ff = findFont2D(name, style, fallback);
  1784. return ff;
  1785. }
  1786. /* We check for application registered fonts before
  1787. * explicitly loading all fonts as if necessary the registration
  1788. * code will have done so anyway. And we don't want to needlessly
  1789. * load the actual files for all fonts.
  1790. * Just as for installed fonts we check for family before fullname.
  1791. * We do not add these fonts to fontNameCache for the
  1792. * app context case which eliminates the overhead of a per context
  1793. * cache for these.
  1794. */
  1795. if (fontsAreRegistered || fontsAreRegisteredPerAppContext) {
  1796. Hashtable<String, FontFamily> familyTable = null;
  1797. Hashtable<String, Font2D> nameTable;
  1798. if (fontsAreRegistered) {
  1799. familyTable = createdByFamilyName;
  1800. nameTable = createdByFullName;
  1801. } else {
  1802. AppContext appContext = AppContext.getAppContext();
  1803. familyTable =
  1804. (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
  1805. nameTable =
  1806. (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
  1807. }
  1808. family = familyTable.get(lowerCaseName);
  1809. if (family != null) {
  1810. font = family.getFontWithExactStyleMatch(style);
  1811. if (font == null) {
  1812. font = family.getFont(style);
  1813. }
  1814. if (font == null) {
  1815. font = family.getClosestStyle(style);
  1816. }
  1817. if (font != null) {
  1818. if (fontsAreRegistered) {
  1819. fontNameCache.put(mapName, font);
  1820. }
  1821. return font;
  1822. }
  1823. }
  1824. font = nameTable.get(lowerCaseName);
  1825. if (font != null) {
  1826. if (fontsAreRegistered) {
  1827. fontNameCache.put(mapName, font);
  1828. }
  1829. return font;
  1830. }
  1831. }
  1832. /* If reach here and no match has been located, then if all fonts
  1833. * are not yet loaded, do so, and then recurse.
  1834. */
  1835. if (!loadedAllFonts) {
  1836. if (logging) {
  1837. logger.info("Load fonts looking for:" + name);
  1838. }
  1839. sgEnv.loadFonts();
  1840. loadedAllFonts = true;
  1841. return findFont2D(name, style, fallback);
  1842. }
  1843. if (!loadedAllFontFiles) {
  1844. if (logging) {
  1845. logger.info("Load font files looking for:" + name);
  1846. }
  1847. sgEnv.loadFontFiles();
  1848. loadedAllFontFiles = true;
  1849. return findFont2D(name, style, fallback);
  1850. }
  1851. /* The primary name is the locale default - ie not US/English but
  1852. * whatever is the default in this locale. This is the way it always
  1853. * has been but may be surprising to some developers if "Arial Regular"
  1854. * were hard-coded in their app and yet "Arial Regular" was not the
  1855. * default name. Fortunately for them, as a consequence of the JDK
  1856. * supporting returning names and family names for arbitrary locales,
  1857. * we also need to support searching all localised names for a match.
  1858. * But because this case of the name used to reference a font is not
  1859. * the same as the default for this locale is rare, it makes sense to
  1860. * search a much shorter list of default locale names and only go to
  1861. * a longer list of names in the event that no match was found.
  1862. * So add here code which searches localised names too.
  1863. * As in 1.4.x this happens only after loading all fonts, which
  1864. * is probably the right order.
  1865. */
  1866. if ((font = findFont2DAllLocales(name, style)) != null) {
  1867. fontNameCache.put(mapName, font);
  1868. return font;
  1869. }
  1870. /* Perhaps its a "compatibility" name - timesroman, helvetica,
  1871. * or courier, which 1.0 apps used for logical fonts.
  1872. * We look for these "late" after a loadFonts as we must not
  1873. * hide real fonts of these names.
  1874. * Map these appropriately:
  1875. * On windows this means according to the rules specified by the
  1876. * FontConfiguration : do it only for encoding==Cp1252
  1877. *
  1878. * REMIND: this is something we plan to remove.
  1879. */
  1880. if (isWindows) {
  1881. String compatName =
  1882. sgEnv.getFontConfiguration().getFallbackFamilyName(name, null);
  1883. if (compatName != null) {
  1884. font = findFont2D(compatName, style, fallback);
  1885. fontNameCache.put(mapName, font);
  1886. return font;
  1887. }
  1888. } else if (lowerCaseName.equals("timesroman")) {
  1889. font = findFont2D("serif", style, fallback);
  1890. fontNameCache.put(mapName, font);
  1891. return font;
  1892. } else if (lowerCaseName.equals("helvetica")) {
  1893. font = findFont2D("sansserif", style, fallback);
  1894. fontNameCache.put(mapName, font);
  1895. return font;
  1896. } else if (lowerCaseName.equals("courier")) {
  1897. font = findFont2D("monospaced", style, fallback);
  1898. fontNameCache.put(mapName, font);
  1899. return font;
  1900. }
  1901. if (logging) {
  1902. logger.info("No font found for:" + name);
  1903. }
  1904. switch (fallback) {
  1905. case PHYSICAL_FALLBACK: return getDefaultPhysicalFont();
  1906. case LOGICAL_FALLBACK: return getDefaultLogicalFont(style);
  1907. default: return null;
  1908. }
  1909. }
  1910. /* This method can be more efficient as it will only need to
  1911. * do the lookup once, and subsequent calls on the java.awt.Font
  1912. * instance can utilise the cached Font2D on that object.
  1913. * Its unfortunate it needs to be a native method, but the font2D
  1914. * variable has to be private.
  1915. */
  1916. public static native Font2D getFont2D(Font font);
  1917. /* Stuff below was in NativeFontWrapper and needed a new home */
  1918. /*
  1919. * Workaround for apps which are dependent on a font metrics bug
  1920. * in JDK 1.1. This is an unsupported win32 private setting.
  1921. */
  1922. public static boolean usePlatformFontMetrics() {
  1923. return usePlatformFontMetrics;
  1924. }
  1925. static native boolean getPlatformFontVar();
  1926. private static final short US_LCID = 0x0409; // US English - default
  1927. private static Map<String, Short> lcidMap;
  1928. // Return a Microsoft LCID from the given Locale.
  1929. // Used when getting localized font data.
  1930. public static short getLCIDFromLocale(Locale locale) {
  1931. // optimize for common case
  1932. if (locale.equals(Locale.US)) {
  1933. return US_LCID;
  1934. }
  1935. if (lcidMap == null) {
  1936. createLCIDMap();
  1937. }
  1938. String key = locale.toString();
  1939. while (!"".equals(key)) {
  1940. Short lcidObject = (Short) lcidMap.get(key);
  1941. if (lcidObject != null) {
  1942. return lcidObject.shortValue();
  1943. }
  1944. int pos = key.lastIndexOf('_');
  1945. if (pos < 1) {
  1946. return US_LCID;
  1947. }
  1948. key = key.substring(0, pos);
  1949. }
  1950. return US_LCID;
  1951. }
  1952. private static void addLCIDMapEntry(Map<String, Short> map,
  1953. String key, short value) {
  1954. map.put(key, new Short(value));
  1955. }
  1956. private static synchronized void createLCIDMap() {
  1957. if (lcidMap != null) {
  1958. return;
  1959. }
  1960. Map<String, Short> map = new HashMap<String, Short>(200);
  1961. // the following statements are derived from the langIDMap
  1962. // in src/windows/native/java/lang/java_props_md.c using the following
  1963. // awk script:
  1964. // $1~/\/\*/ { next}
  1965. // $3~/\?\?/ { next }
  1966. // $3!~/_/ { next }
  1967. // $1~/0x0409/ { next }
  1968. // $1~/0x0c0a/ { next }
  1969. // $1~/0x042c/ { next }
  1970. // $1~/0x0443/ { next }
  1971. // $1~/0x0812/ { next }
  1972. // $1~/0x04/ { print " addLCIDMapEntry(map, " substr($3, 0, 3) "\", (short) " substr($1, 0, 6) ");" ; next }
  1973. // $3~/,/ { print " addLCIDMapEntry(map, " $3 " (short) " substr($1, 0, 6) ");" ; next }
  1974. // { print " addLCIDMapEntry(map, " $3 ", (short) " substr($1, 0, 6) ");" ; next }
  1975. // The lines of this script:
  1976. // - eliminate comments
  1977. // - eliminate questionable locales
  1978. // - eliminate language-only locales
  1979. // - eliminate the default LCID value
  1980. // - eliminate a few other unneeded LCID values
  1981. // - print language-only locale entries for x04* LCID values
  1982. // (apparently Microsoft doesn't use language-only LCID values -
  1983. // see http://www.microsoft.com/OpenType/otspec/name.htm
  1984. // - print complete entries for all other LCID values
  1985. // Run
  1986. // awk -f awk-script langIDMap > statements
  1987. addLCIDMapEntry(map, "ar", (short) 0x0401);
  1988. addLCIDMapEntry(map, "bg", (short) 0x0402);
  1989. addLCIDMapEntry(map, "ca", (short) 0x0403);
  1990. addLCIDMapEntry(map, "zh", (short) 0x0404);
  1991. addLCIDMapEntry(map, "cs", (short) 0x0405);
  1992. addLCIDMapEntry(map, "da", (short) 0x0406);
  1993. addLCIDMapEntry(map, "de", (short) 0x0407);
  1994. addLCIDMapEntry(map, "el", (short) 0x0408);
  1995. addLCIDMapEntry(map, "es", (short) 0x040a);
  1996. addLCIDMapEntry(map, "fi", (short) 0x040b);
  1997. addLCIDMapEntry(map, "fr", (short) 0x040c);
  1998. addLCIDMapEntry(map, "iw", (short) 0x040d);
  1999. addLCIDMapEntry(map, "hu", (short) 0x040e);
  2000. addLCIDMapEntry(map, "is", (short) 0x040f);
  2001. addLCIDMapEntry(map, "it", (short) 0x0410);
  2002. addLCIDMapEntry(map, "ja", (short) 0x0411);
  2003. addLCIDMapEntry(map, "ko", (short) 0x0412);
  2004. addLCIDMapEntry(map, "nl", (short) 0x0413);
  2005. addLCIDMapEntry(map, "no", (short) 0x0414);
  2006. addLCIDMapEntry(map, "pl", (short) 0x0415);
  2007. addLCIDMapEntry(map, "pt", (short) 0x0416);
  2008. addLCIDMapEntry(map, "rm", (short) 0x0417);
  2009. addLCIDMapEntry(map, "ro", (short) 0x0418);
  2010. addLCIDMapEntry(map, "ru", (short) 0x0419);
  2011. addLCIDMapEntry(map, "hr", (short) 0x041a);
  2012. addLCIDMapEntry(map, "sk", (short) 0x041b);
  2013. addLCIDMapEntry(map, "sq", (short) 0x041c);
  2014. addLCIDMapEntry(map, "sv", (short) 0x041d);
  2015. addLCIDMapEntry(map, "th", (short) 0x041e);
  2016. addLCIDMapEntry(map, "tr", (short) 0x041f);
  2017. addLCIDMapEntry(map, "ur", (short) 0x0420);
  2018. addLCIDMapEntry(map, "in", (short) 0x0421);
  2019. addLCIDMapEntry(map, "uk", (short) 0x0422);
  2020. addLCIDMapEntry(map, "be", (short) 0x0423);
  2021. addLCIDMapEntry(map, "sl", (short) 0x0424);
  2022. addLCIDMapEntry(map, "et", (short) 0x0425);
  2023. addLCIDMapEntry(map, "lv", (short) 0x0426);
  2024. addLCIDMapEntry(map, "lt", (short) 0x0427);
  2025. addLCIDMapEntry(map, "fa", (short) 0x0429);
  2026. addLCIDMapEntry(map, "vi", (short) 0x042a);
  2027. addLCIDMapEntry(map, "hy", (short) 0x042b);
  2028. addLCIDMapEntry(map, "eu", (short) 0x042d);
  2029. addLCIDMapEntry(map, "mk", (short) 0x042f);
  2030. addLCIDMapEntry(map, "tn", (short) 0x0432);
  2031. addLCIDMapEntry(map, "xh", (short) 0x0434);
  2032. addLCIDMapEntry(map, "zu", (short) 0x0435);
  2033. addLCIDMapEntry(map, "af", (short) 0x0436);
  2034. addLCIDMapEntry(map, "ka", (short) 0x0437);
  2035. addLCIDMapEntry(map, "fo", (short) 0x0438);
  2036. addLCIDMapEntry(map, "hi", (short) 0x0439);
  2037. addLCIDMapEntry(map, "mt", (short) 0x043a);
  2038. addLCIDMapEntry(map, "se", (short) 0x043b);
  2039. addLCIDMapEntry(map, "gd", (short) 0x043c);
  2040. addLCIDMapEntry(map, "ms", (short) 0x043e);
  2041. addLCIDMapEntry(map, "kk", (short) 0x043f);
  2042. addLCIDMapEntry(map, "ky", (short) 0x0440);
  2043. addLCIDMapEntry(map, "sw", (short) 0x0441);
  2044. addLCIDMapEntry(map, "tt", (short) 0x0444);
  2045. addLCIDMapEntry(map, "bn", (short) 0x0445);
  2046. addLCIDMapEntry(map, "pa", (short) 0x0446);
  2047. addLCIDMapEntry(map, "gu", (short) 0x0447);
  2048. addLCIDMapEntry(map, "ta", (short) 0x0449);
  2049. addLCIDMapEntry(map, "te", (short) 0x044a);
  2050. addLCIDMapEntry(map, "kn", (short) 0x044b);
  2051. addLCIDMapEntry(map, "ml", (short) 0x044c);
  2052. addLCIDMapEntry(map, "mr", (short) 0x044e);
  2053. addLCIDMapEntry(map, "sa", (short) 0x044f);
  2054. addLCIDMapEntry(map, "mn", (short) 0x0450);
  2055. addLCIDMapEntry(map, "cy", (short) 0x0452);
  2056. addLCIDMapEntry(map, "gl", (short) 0x0456);
  2057. addLCIDMapEntry(map, "dv", (short) 0x0465);
  2058. addLCIDMapEntry(map, "qu", (short) 0x046b);
  2059. addLCIDMapEntry(map, "mi", (short) 0x0481);
  2060. addLCIDMapEntry(map, "ar_IQ", (short) 0x0801);
  2061. addLCIDMapEntry(map, "zh_CN", (short) 0x0804);
  2062. addLCIDMapEntry(map, "de_CH", (short) 0x0807);
  2063. addLCIDMapEntry(map, "en_GB", (short) 0x0809);
  2064. addLCIDMapEntry(map, "es_MX", (short) 0x080a);
  2065. addLCIDMapEntry(map, "fr_BE", (short) 0x080c);
  2066. addLCIDMapEntry(map, "it_CH", (short) 0x0810);
  2067. addLCIDMapEntry(map, "nl_BE", (short) 0x0813);
  2068. addLCIDMapEntry(map, "no_NO_NY", (short) 0x0814);
  2069. addLCIDMapEntry(map, "pt_PT", (short) 0x0816);
  2070. addLCIDMapEntry(map, "ro_MD", (short) 0x0818);
  2071. addLCIDMapEntry(map, "ru_MD", (short) 0x0819);
  2072. addLCIDMapEntry(map, "sr_CS", (short) 0x081a);
  2073. addLCIDMapEntry(map, "sv_FI", (short) 0x081d);
  2074. addLCIDMapEntry(map, "az_AZ", (short) 0x082c);
  2075. addLCIDMapEntry(map, "se_SE", (short) 0x083b);
  2076. addLCIDMapEntry(map, "ga_IE", (short) 0x083c);
  2077. addLCIDMapEntry(map, "ms_BN", (short) 0x083e);
  2078. addLCIDMapEntry(map, "uz_UZ", (short) 0x0843);
  2079. addLCIDMapEntry(map, "qu_EC", (short) 0x086b);
  2080. addLCIDMapEntry(map, "ar_EG", (short) 0x0c01);
  2081. addLCIDMapEntry(map, "zh_HK", (short) 0x0c04);
  2082. addLCIDMapEntry(map, "de_AT", (short) 0x0c07);
  2083. addLCIDMapEntry(map, "en_AU", (short) 0x0c09);
  2084. addLCIDMapEntry(map, "fr_CA", (short) 0x0c0c);
  2085. addLCIDMapEntry(map, "sr_CS", (short) 0x0c1a);
  2086. addLCIDMapEntry(map, "se_FI", (short) 0x0c3b);
  2087. addLCIDMapEntry(map, "qu_PE", (short) 0x0c6b);
  2088. addLCIDMapEntry(map, "ar_LY", (short) 0x1001);
  2089. addLCIDMapEntry(map, "zh_SG", (short) 0x1004);
  2090. addLCIDMapEntry(map, "de_LU", (short) 0x1007);
  2091. addLCIDMapEntry(map, "en_CA", (short) 0x1009);
  2092. addLCIDMapEntry(map, "es_GT", (short) 0x100a);
  2093. addLCIDMapEntry(map, "fr_CH", (short) 0x100c);
  2094. addLCIDMapEntry(map, "hr_BA", (short) 0x101a);
  2095. addLCIDMapEntry(map, "ar_DZ", (short) 0x1401);
  2096. addLCIDMapEntry(map, "zh_MO", (short) 0x1404);
  2097. addLCIDMapEntry(map, "de_LI", (short) 0x1407);
  2098. addLCIDMapEntry(map, "en_NZ", (short) 0x1409);
  2099. addLCIDMapEntry(map, "es_CR", (short) 0x140a);
  2100. addLCIDMapEntry(map, "fr_LU", (short) 0x140c);
  2101. addLCIDMapEntry(map, "bs_BA", (short) 0x141a);
  2102. addLCIDMapEntry(map, "ar_MA", (short) 0x1801);
  2103. addLCIDMapEntry(map, "en_IE", (short) 0x1809);
  2104. addLCIDMapEntry(map, "es_PA", (short) 0x180a);
  2105. addLCIDMapEntry(map, "fr_MC", (short) 0x180c);
  2106. addLCIDMapEntry(map, "sr_BA", (short) 0x181a);
  2107. addLCIDMapEntry(map, "ar_TN", (short) 0x1c01);
  2108. addLCIDMapEntry(map, "en_ZA", (short) 0x1c09);
  2109. addLCIDMapEntry(map, "es_DO", (short) 0x1c0a);
  2110. addLCIDMapEntry(map, "sr_BA", (short) 0x1c1a);
  2111. addLCIDMapEntry(map, "ar_OM", (short) 0x2001);
  2112. addLCIDMapEntry(map, "en_JM", (short) 0x2009);
  2113. addLCIDMapEntry(map, "es_VE", (short) 0x200a);
  2114. addLCIDMapEntry(map, "ar_YE", (short) 0x2401);
  2115. addLCIDMapEntry(map, "es_CO", (short) 0x240a);
  2116. addLCIDMapEntry(map, "ar_SY", (short) 0x2801);
  2117. addLCIDMapEntry(map, "en_BZ", (short) 0x2809);
  2118. addLCIDMapEntry(map, "es_PE", (short) 0x280a);
  2119. addLCIDMapEntry(map, "ar_JO", (short) 0x2c01);
  2120. addLCIDMapEntry(map, "en_TT", (short) 0x2c09);
  2121. addLCIDMapEntry(map, "es_AR", (short) 0x2c0a);
  2122. addLCIDMapEntry(map, "ar_LB", (short) 0x3001);
  2123. addLCIDMapEntry(map, "en_ZW", (short) 0x3009);
  2124. addLCIDMapEntry(map, "es_EC", (short) 0x300a);
  2125. addLCIDMapEntry(map, "ar_KW", (short) 0x3401);
  2126. addLCIDMapEntry(map, "en_PH", (short) 0x3409);
  2127. addLCIDMapEntry(map, "es_CL", (short) 0x340a);
  2128. addLCIDMapEntry(map, "ar_AE", (short) 0x3801);
  2129. addLCIDMapEntry(map, "es_UY", (short) 0x380a);
  2130. addLCIDMapEntry(map, "ar_BH", (short) 0x3c01);
  2131. addLCIDMapEntry(map, "es_PY", (short) 0x3c0a);
  2132. addLCIDMapEntry(map, "ar_QA", (short) 0x4001);
  2133. addLCIDMapEntry(map, "es_BO", (short) 0x400a);
  2134. addLCIDMapEntry(map, "es_SV", (short) 0x440a);
  2135. addLCIDMapEntry(map, "es_HN", (short) 0x480a);
  2136. addLCIDMapEntry(map, "es_NI", (short) 0x4c0a);
  2137. addLCIDMapEntry(map, "es_PR", (short) 0x500a);
  2138. lcidMap = map;
  2139. }
  2140. public static int getNumFonts() {
  2141. return physicalFonts.size()+maxCompFont;
  2142. }
  2143. private static boolean fontSupportsEncoding(Font font, String encoding) {
  2144. return getFont2D(font).supportsEncoding(encoding);
  2145. }
  2146. public synchronized static native String getFontPath(boolean noType1Fonts);
  2147. public synchronized static native void setNativeFontPath(String fontPath);
  2148. private static Thread fileCloser = null;
  2149. static Vector<File> tmpFontFiles = null;
  2150. public static Font2D createFont2D(File fontFile, int fontFormat,
  2151. boolean isCopy,
  2152. CreatedFontTracker tracker)
  2153. throws FontFormatException {
  2154. String fontFilePath = fontFile.getPath();
  2155. FileFont font2D = null;
  2156. final File fFile = fontFile;
  2157. final CreatedFontTracker _tracker = tracker;
  2158. try {
  2159. switch (fontFormat) {
  2160. case Font.TRUETYPE_FONT:
  2161. font2D = new TrueTypeFont(fontFilePath, null, 0, true);
  2162. break;
  2163. case Font.TYPE1_FONT:
  2164. font2D = new Type1Font(fontFilePath, null, isCopy);
  2165. break;
  2166. default:
  2167. throw new FontFormatException("Unrecognised Font Format");
  2168. }
  2169. } catch (FontFormatException e) {
  2170. if (isCopy) {
  2171. java.security.AccessController.doPrivileged(
  2172. new java.security.PrivilegedAction() {
  2173. public Object run() {
  2174. if (_tracker != null) {
  2175. _tracker.subBytes((int)fFile.length());
  2176. }
  2177. fFile.delete();
  2178. return null;
  2179. }
  2180. });
  2181. }
  2182. throw(e);
  2183. }
  2184. if (isCopy) {
  2185. font2D.setFileToRemove(fontFile, tracker);
  2186. synchronized (FontManager.class) {
  2187. if (tmpFontFiles == null) {
  2188. tmpFontFiles = new Vector<File>();
  2189. }
  2190. tmpFontFiles.add(fontFile);
  2191. if (fileCloser == null) {
  2192. final Runnable fileCloserRunnable = new Runnable() {
  2193. public void run() {
  2194. java.security.AccessController.doPrivileged(
  2195. new java.security.PrivilegedAction() {
  2196. public Object run() {
  2197. for (int i=0;i<CHANNELPOOLSIZE;i++) {
  2198. if (fontFileCache[i] != null) {
  2199. try {
  2200. fontFileCache[i].close();
  2201. } catch (Exception e) {
  2202. }
  2203. }
  2204. }
  2205. if (tmpFontFiles != null) {
  2206. File[] files = new File[tmpFontFiles.size()];
  2207. files = tmpFontFiles.toArray(files);
  2208. for (int f=0; f<files.length;f++) {
  2209. try {
  2210. files[f].delete();
  2211. } catch (Exception e) {
  2212. }
  2213. }
  2214. }
  2215. return null;
  2216. }
  2217. });
  2218. }
  2219. };
  2220. java.security.AccessController.doPrivileged(
  2221. new java.security.PrivilegedAction() {
  2222. public Object run() {
  2223. /* The thread must be a member of a thread group
  2224. * which will not get GCed before VM exit.
  2225. * Make its parent the top-level thread group.
  2226. */
  2227. ThreadGroup tg =
  2228. Thread.currentThread().getThreadGroup();
  2229. for (ThreadGroup tgn = tg;
  2230. tgn != null;
  2231. tg = tgn, tgn = tg.getParent());
  2232. fileCloser = new Thread(tg, fileCloserRunnable);
  2233. Runtime.getRuntime().addShutdownHook(fileCloser);
  2234. return null;
  2235. }
  2236. });
  2237. }
  2238. }
  2239. }
  2240. return font2D;
  2241. }
  2242. /* remind: used in X11GraphicsEnvironment and called often enough
  2243. * that we ought to obsolete this code
  2244. */
  2245. public synchronized static String getFullNameByFileName(String fileName) {
  2246. PhysicalFont[] physFonts = getPhysicalFonts();
  2247. for (int i=0;i<physFonts.length;i++) {
  2248. if (physFonts[i].platName.equals(fileName)) {
  2249. return (physFonts[i].getFontName(null));
  2250. }
  2251. }
  2252. return null;
  2253. }
  2254. /*
  2255. * This is called when font is determined to be invalid/bad.
  2256. * It designed to be called (for example) by the font scaler
  2257. * when in processing a font file it is discovered to be incorrect.
  2258. * This is different than the case where fonts are discovered to
  2259. * be incorrect during initial verification, as such fonts are
  2260. * never registered.
  2261. * Handles to this font held are re-directed to a default font.
  2262. * This default may not be an ideal substitute buts it better than
  2263. * crashing This code assumes a PhysicalFont parameter as it doesn't
  2264. * make sense for a Composite to be "bad".
  2265. */
  2266. public static synchronized void deRegisterBadFont(Font2D font2D) {
  2267. if (!(font2D instanceof PhysicalFont)) {
  2268. /* We should never reach here, but just in case */
  2269. return;
  2270. } else {
  2271. if (logging) {
  2272. logger.severe("Deregister bad font: " + font2D);
  2273. }
  2274. replaceFont((PhysicalFont)font2D, getDefaultPhysicalFont());
  2275. }
  2276. }
  2277. /*
  2278. * This encapsulates all the work that needs to be done when a
  2279. * Font2D is replaced by a different Font2D.
  2280. */
  2281. public static synchronized void replaceFont(PhysicalFont oldFont,
  2282. PhysicalFont newFont) {
  2283. if (oldFont.handle.font2D != oldFont) {
  2284. /* already done */
  2285. return;
  2286. }
  2287. /* If we try to replace the font with itself, that won't work,
  2288. * so pick any alternative physical font
  2289. */
  2290. if (oldFont == newFont) {
  2291. if (logging) {
  2292. logger.severe("Can't replace bad font with itself " + oldFont);
  2293. }
  2294. PhysicalFont[] physFonts = getPhysicalFonts();
  2295. for (int i=0; i<physFonts.length;i++) {
  2296. if (physFonts[i] != newFont) {
  2297. newFont = physFonts[i];
  2298. break;
  2299. }
  2300. }
  2301. if (oldFont == newFont) {
  2302. if (logging) {
  2303. logger.severe("This is bad. No good physicalFonts found.");
  2304. }
  2305. return;
  2306. }
  2307. }
  2308. /* eliminate references to this font, so it won't be located
  2309. * by future callers, and will be eligible for GC when all
  2310. * references are removed
  2311. */
  2312. oldFont.handle.font2D = newFont;
  2313. physicalFonts.remove(oldFont.fullName);
  2314. fullNameToFont.remove(oldFont.fullName.toLowerCase(Locale.ENGLISH));
  2315. FontFamily.remove(oldFont);
  2316. if (localeFullNamesToFont != null) {
  2317. Map.Entry[] mapEntries =
  2318. (Map.Entry[])localeFullNamesToFont.entrySet().
  2319. toArray(new Map.Entry[0]);
  2320. /* Should I be replacing these, or just I just remove
  2321. * the names from the map?
  2322. */
  2323. for (int i=0; i<mapEntries.length;i++) {
  2324. if (mapEntries[i].getValue() == oldFont) {
  2325. try {
  2326. mapEntries[i].setValue(newFont);
  2327. } catch (Exception e) {
  2328. /* some maps don't support this operation.
  2329. * In this case just give up and remove the entry.
  2330. */
  2331. localeFullNamesToFont.remove(mapEntries[i].getKey());
  2332. }
  2333. }
  2334. }
  2335. }
  2336. for (int i=0; i<maxCompFont; i++) {
  2337. /* Deferred initialization of composites shouldn't be
  2338. * a problem for this case, since a font must have been
  2339. * initialised to be discovered to be bad.
  2340. * Some JRE composites on Solaris use two versions of the same
  2341. * font. The replaced font isn't bad, just "smaller" so there's
  2342. * no need to make the slot point to the new font.
  2343. * Since composites have a direct reference to the Font2D (not
  2344. * via a handle) making this substitution is not safe and could
  2345. * cause an additional problem and so this substitution is
  2346. * warranted only when a font is truly "bad" and could cause
  2347. * a crash. So we now replace it only if its being substituted
  2348. * with some font other than a fontconfig rank font
  2349. * Since in practice a substitution will have the same rank
  2350. * this may never happen, but the code is safer even if its
  2351. * also now a no-op.
  2352. * The only obvious "glitch" from this stems from the current
  2353. * implementation that when asked for the number of glyphs in a
  2354. * composite it lies and returns the number in slot 0 because
  2355. * composite glyphs aren't contiguous. Since we live with that
  2356. * we can live with the glitch that depending on how it was
  2357. * initialised a composite may return different values for this.
  2358. * Fixing the issues with composite glyph ids is tricky as
  2359. * there are exclusion ranges and unlike other fonts even the
  2360. * true "numGlyphs" isn't a contiguous range. Likely the only
  2361. * solution is an API that returns an array of glyph ranges
  2362. * which takes precedence over the existing API. That might
  2363. * also need to address excluding ranges which represent a
  2364. * code point supported by an earlier component.
  2365. */
  2366. if (newFont.getRank() > Font2D.FONT_CONFIG_RANK) {
  2367. compFonts[i].replaceComponentFont(oldFont, newFont);
  2368. }
  2369. }
  2370. }
  2371. private static synchronized void loadLocaleNames() {
  2372. if (localeFullNamesToFont != null) {
  2373. return;
  2374. }
  2375. localeFullNamesToFont = new HashMap<String, TrueTypeFont>();
  2376. Font2D[] fonts = getRegisteredFonts();
  2377. for (int i=0; i<fonts.length; i++) {
  2378. if (fonts[i] instanceof TrueTypeFont) {
  2379. TrueTypeFont ttf = (TrueTypeFont)fonts[i];
  2380. String[] fullNames = ttf.getAllFullNames();
  2381. for (int n=0; n<fullNames.length; n++) {
  2382. localeFullNamesToFont.put(fullNames[n], ttf);
  2383. }
  2384. FontFamily family = FontFamily.getFamily(ttf.familyName);
  2385. if (family != null) {
  2386. FontFamily.addLocaleNames(family, ttf.getAllFamilyNames());
  2387. }
  2388. }
  2389. }
  2390. }
  2391. /* This replicate the core logic of findFont2D but operates on
  2392. * all the locale names. This hasn't been merged into findFont2D to
  2393. * keep the logic simpler and reduce overhead, since this case is
  2394. * almost never used. The main case in which it is called is when
  2395. * a bogus font name is used and we need to check all possible names
  2396. * before returning the default case.
  2397. */
  2398. private static Font2D findFont2DAllLocales(String name, int style) {
  2399. if (logging) {
  2400. logger.info("Searching localised font names for:" + name);
  2401. }
  2402. /* If reach here and no match has been located, then if we have
  2403. * not yet built the map of localeFullNamesToFont for TT fonts, do so
  2404. * now. This method must be called after all fonts have been loaded.
  2405. */
  2406. if (localeFullNamesToFont == null) {
  2407. loadLocaleNames();
  2408. }
  2409. String lowerCaseName = name.toLowerCase();
  2410. Font2D font = null;
  2411. /* First see if its a family name. */
  2412. FontFamily family = FontFamily.getLocaleFamily(lowerCaseName);
  2413. if (family != null) {
  2414. font = family.getFont(style);
  2415. if (font == null) {
  2416. font = family.getClosestStyle(style);
  2417. }
  2418. if (font != null) {
  2419. return font;
  2420. }
  2421. }
  2422. /* If it wasn't a family name, it should be a full name. */
  2423. synchronized (FontManager.class) {
  2424. font = localeFullNamesToFont.get(name);
  2425. }
  2426. if (font != null) {
  2427. if (font.style == style || style == Font.PLAIN) {
  2428. return font;
  2429. } else {
  2430. family = FontFamily.getFamily(font.getFamilyName(null));
  2431. if (family != null) {
  2432. Font2D familyFont = family.getFont(style);
  2433. /* We exactly matched the requested style, use it! */
  2434. if (familyFont != null) {
  2435. return familyFont;
  2436. } else {
  2437. familyFont = family.getClosestStyle(style);
  2438. if (familyFont != null) {
  2439. /* The next check is perhaps one
  2440. * that shouldn't be done. ie if we get this
  2441. * far we have probably as close a match as we
  2442. * are going to get. We could load all fonts to
  2443. * see if somehow some parts of the family are
  2444. * loaded but not all of it.
  2445. * This check is commented out for now.
  2446. */
  2447. if (!familyFont.canDoStyle(style)) {
  2448. familyFont = null;
  2449. }
  2450. return familyFont;
  2451. }
  2452. }
  2453. }
  2454. }
  2455. }
  2456. return font;
  2457. }
  2458. /* Supporting "alternate" composite fonts on 2D graphics objects
  2459. * is accessed by the application by calling methods on the local
  2460. * GraphicsEnvironment. The overall implementation is described
  2461. * in one place, here, since otherwise the implementation is spread
  2462. * around it may be difficult to track.
  2463. * The methods below call into SunGraphicsEnvironment which creates a
  2464. * new FontConfiguration instance. The FontConfiguration class,
  2465. * and its platform sub-classes are updated to take parameters requesting
  2466. * these behaviours. This is then used to create new composite font
  2467. * instances. Since this calls the initCompositeFont method in
  2468. * SunGraphicsEnvironment it performs the same initialization as is
  2469. * performed normally. There may be some duplication of effort, but
  2470. * that code is already written to be able to perform properly if called
  2471. * to duplicate work. The main difference is that if we detect we are
  2472. * running in an applet/browser/Java plugin environment these new fonts
  2473. * are not placed in the "default" maps but into an AppContext instance.
  2474. * The font lookup mechanism in java.awt.Font.getFont2D() is also updated
  2475. * so that look-up for composite fonts will in that case always
  2476. * do a lookup rather than returning a cached result.
  2477. * This is inefficient but necessary else singleton java.awt.Font
  2478. * instances would not retrieve the correct Font2D for the appcontext.
  2479. * sun.font.FontManager.findFont2D is also updated to that it uses
  2480. * a name map cache specific to that appcontext.
  2481. *
  2482. * Getting an AppContext is expensive, so there is a global variable
  2483. * that records whether these methods have ever been called and can
  2484. * avoid the expense for almost all applications. Once the correct
  2485. * CompositeFont is associated with the Font, everything should work
  2486. * through existing mechanisms.
  2487. * A special case is that GraphicsEnvironment.getAllFonts() must
  2488. * return an AppContext specific list.
  2489. *
  2490. * Calling the methods below is "heavyweight" but it is expected that
  2491. * these methods will be called very rarely.
  2492. *
  2493. * If usingPerAppContextComposites is true, we are in "applet"
  2494. * (eg browser) enviroment and at least one context has selected
  2495. * an alternate composite font behaviour.
  2496. * If usingAlternateComposites is true, we are not in an "applet"
  2497. * environment and the (single) application has selected
  2498. * an alternate composite font behaviour.
  2499. *
  2500. * - Printing: The implementation delegates logical fonts to an AWT
  2501. * mechanism which cannot use these alternate configurations.
  2502. * We can detect that alternate fonts are in use and back-off to 2D, but
  2503. * that uses outlines. Much of this can be fixed with additional work
  2504. * but that may have to wait. The results should be correct, just not
  2505. * optimal.
  2506. */
  2507. private static final Object altJAFontKey = new Object();
  2508. private static final Object localeFontKey = new Object();
  2509. private static final Object proportionalFontKey = new Object();
  2510. public static boolean usingPerAppContextComposites = false;
  2511. private static boolean usingAlternateComposites = false;
  2512. /* These values are used only if we are running as a standalone
  2513. * application, as determined by maybeMultiAppContext();
  2514. */
  2515. private static boolean gAltJAFont = false;
  2516. private static boolean gLocalePref = false;
  2517. private static boolean gPropPref = false;
  2518. /* This method doesn't check if alternates are selected in this app
  2519. * context. Its used by the FontMetrics caching code which in such
  2520. * a case cannot retrieve a cached metrics solely on the basis of
  2521. * the Font.equals() method since it needs to also check if the Font2D
  2522. * is the same.
  2523. * We also use non-standard composites for Swing native L&F fonts on
  2524. * Windows. In that case the policy is that the metrics reported are
  2525. * based solely on the physical font in the first slot which is the
  2526. * visible java.awt.Font. So in that case the metrics cache which tests
  2527. * the Font does what we want. In the near future when we expand the GTK
  2528. * logical font definitions we may need to revisit this if GTK reports
  2529. * combined metrics instead. For now though this test can be simple.
  2530. */
  2531. static boolean maybeUsingAlternateCompositeFonts() {
  2532. return usingAlternateComposites || usingPerAppContextComposites;
  2533. }
  2534. public static boolean usingAlternateCompositeFonts() {
  2535. return (usingAlternateComposites ||
  2536. (usingPerAppContextComposites &&
  2537. AppContext.getAppContext().get(CompositeFont.class) != null));
  2538. }
  2539. private static boolean maybeMultiAppContext() {
  2540. Boolean appletSM = (Boolean)
  2541. java.security.AccessController.doPrivileged(
  2542. new java.security.PrivilegedAction() {
  2543. public Object run() {
  2544. SecurityManager sm = System.getSecurityManager();
  2545. return new Boolean
  2546. (sm instanceof sun.applet.AppletSecurity);
  2547. }
  2548. });
  2549. return appletSM.booleanValue();
  2550. }
  2551. /* Modifies the behaviour of a subsequent call to preferLocaleFonts()
  2552. * to use Mincho instead of Gothic for dialoginput in JA locales
  2553. * on windows. Not needed on other platforms.
  2554. */
  2555. public static synchronized void useAlternateFontforJALocales() {
  2556. if (!isWindows) {
  2557. return;
  2558. }
  2559. initSGEnv();
  2560. if (!maybeMultiAppContext()) {
  2561. gAltJAFont = true;
  2562. } else {
  2563. AppContext appContext = AppContext.getAppContext();
  2564. appContext.put(altJAFontKey, altJAFontKey);
  2565. }
  2566. }
  2567. public static boolean usingAlternateFontforJALocales() {
  2568. if (!maybeMultiAppContext()) {
  2569. return gAltJAFont;
  2570. } else {
  2571. AppContext appContext = AppContext.getAppContext();
  2572. return appContext.get(altJAFontKey) == altJAFontKey;
  2573. }
  2574. }
  2575. public static synchronized void preferLocaleFonts() {
  2576. initSGEnv();
  2577. /* Test if re-ordering will have any effect */
  2578. if (!FontConfiguration.willReorderForStartupLocale()) {
  2579. return;
  2580. }
  2581. if (!maybeMultiAppContext()) {
  2582. if (gLocalePref == true) {
  2583. return;
  2584. }
  2585. gLocalePref = true;
  2586. sgEnv.createCompositeFonts(fontNameCache, gLocalePref, gPropPref);
  2587. usingAlternateComposites = true;
  2588. } else {
  2589. AppContext appContext = AppContext.getAppContext();
  2590. if (appContext.get(localeFontKey) == localeFontKey) {
  2591. return;
  2592. }
  2593. appContext.put(localeFontKey, localeFontKey);
  2594. boolean acPropPref =
  2595. appContext.get(proportionalFontKey) == proportionalFontKey;
  2596. ConcurrentHashMap<String, Font2D>
  2597. altNameCache = new ConcurrentHashMap<String, Font2D> ();
  2598. /* If there is an existing hashtable, we can drop it. */
  2599. appContext.put(CompositeFont.class, altNameCache);
  2600. usingPerAppContextComposites = true;
  2601. sgEnv.createCompositeFonts(altNameCache, true, acPropPref);
  2602. }
  2603. }
  2604. public static synchronized void preferProportionalFonts() {
  2605. /* If no proportional fonts are configured, there's no need
  2606. * to take any action.
  2607. */
  2608. if (!FontConfiguration.hasMonoToPropMap()) {
  2609. return;
  2610. }
  2611. initSGEnv();
  2612. if (!maybeMultiAppContext()) {
  2613. if (gPropPref == true) {
  2614. return;
  2615. }
  2616. gPropPref = true;
  2617. sgEnv.createCompositeFonts(fontNameCache, gLocalePref, gPropPref);
  2618. usingAlternateComposites = true;
  2619. } else {
  2620. AppContext appContext = AppContext.getAppContext();
  2621. if (appContext.get(proportionalFontKey) == proportionalFontKey) {
  2622. return;
  2623. }
  2624. appContext.put(proportionalFontKey, proportionalFontKey);
  2625. boolean acLocalePref =
  2626. appContext.get(localeFontKey) == localeFontKey;
  2627. ConcurrentHashMap<String, Font2D>
  2628. altNameCache = new ConcurrentHashMap<String, Font2D> ();
  2629. /* If there is an existing hashtable, we can drop it. */
  2630. appContext.put(CompositeFont.class, altNameCache);
  2631. usingPerAppContextComposites = true;
  2632. sgEnv.createCompositeFonts(altNameCache, acLocalePref, true);
  2633. }
  2634. }
  2635. private static HashSet<String> installedNames = null;
  2636. private static HashSet<String> getInstalledNames() {
  2637. if (installedNames == null) {
  2638. Locale l = sgEnv.getSystemStartupLocale();
  2639. String[] installedFamilies = sgEnv.getInstalledFontFamilyNames(l);
  2640. Font[] installedFonts = sgEnv.getAllInstalledFonts();
  2641. HashSet<String> names = new HashSet<String>();
  2642. for (int i=0; i<installedFamilies.length; i++) {
  2643. names.add(installedFamilies[i].toLowerCase(l));
  2644. }
  2645. for (int i=0; i<installedFonts.length; i++) {
  2646. names.add(installedFonts[i].getFontName(l).toLowerCase(l));
  2647. }
  2648. installedNames = names;
  2649. }
  2650. return installedNames;
  2651. }
  2652. /* Keys are used to lookup per-AppContext Hashtables */
  2653. private static final Object regFamilyKey = new Object();
  2654. private static final Object regFullNameKey = new Object();
  2655. private static Hashtable<String,FontFamily> createdByFamilyName;
  2656. private static Hashtable<String,Font2D> createdByFullName;
  2657. private static boolean fontsAreRegistered = false;
  2658. private static boolean fontsAreRegisteredPerAppContext = false;
  2659. public static boolean registerFont(Font font) {
  2660. /* This method should not be called with "null".
  2661. * It is the caller's responsibility to ensure that.
  2662. */
  2663. if (font == null) {
  2664. return false;
  2665. }
  2666. /* Initialise these objects only once we start to use this API */
  2667. synchronized (regFamilyKey) {
  2668. if (createdByFamilyName == null) {
  2669. createdByFamilyName = new Hashtable<String,FontFamily>();
  2670. createdByFullName = new Hashtable<String,Font2D>();
  2671. }
  2672. }
  2673. if (!isCreatedFont(font)) {
  2674. return false;
  2675. }
  2676. if (sgEnv == null) {
  2677. initSGEnv();
  2678. }
  2679. /* We want to ensure that this font cannot override existing
  2680. * installed fonts. Check these conditions :
  2681. * - family name is not that of an installed font
  2682. * - full name is not that of an installed font
  2683. * - family name is not the same as the full name of an installed font
  2684. * - full name is not the same as the family name of an installed font
  2685. * The last two of these may initially look odd but the reason is
  2686. * that (unfortunately) Font constructors do not distinuguish these.
  2687. * An extreme example of such a problem would be a font which has
  2688. * family name "Dialog.Plain" and full name of "Dialog".
  2689. * The one arguably overly stringent restriction here is that if an
  2690. * application wants to supply a new member of an existing family
  2691. * It will get rejected. But since the JRE can perform synthetic
  2692. * styling in many cases its not necessary.
  2693. * We don't apply the same logic to registered fonts. If apps want
  2694. * to do this lets assume they have a reason. It won't cause problems
  2695. * except for themselves.
  2696. */
  2697. HashSet<String> names = getInstalledNames();
  2698. Locale l = sgEnv.getSystemStartupLocale();
  2699. String familyName = font.getFamily(l).toLowerCase();
  2700. String fullName = font.getFontName(l).toLowerCase();
  2701. if (names.contains(familyName) || names.contains(fullName)) {
  2702. return false;
  2703. }
  2704. /* Checks passed, now register the font */
  2705. Hashtable<String,FontFamily> familyTable;
  2706. Hashtable<String,Font2D> fullNameTable;
  2707. if (!maybeMultiAppContext()) {
  2708. familyTable = createdByFamilyName;
  2709. fullNameTable = createdByFullName;
  2710. fontsAreRegistered = true;
  2711. } else {
  2712. AppContext appContext = AppContext.getAppContext();
  2713. familyTable =
  2714. (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
  2715. fullNameTable =
  2716. (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
  2717. if (familyTable == null) {
  2718. familyTable = new Hashtable<String,FontFamily>();
  2719. fullNameTable = new Hashtable<String,Font2D>();
  2720. appContext.put(regFamilyKey, familyTable);
  2721. appContext.put(regFullNameKey, fullNameTable);
  2722. }
  2723. fontsAreRegisteredPerAppContext = true;
  2724. }
  2725. /* Create the FontFamily and add font to the tables */
  2726. Font2D font2D = getFont2D(font);
  2727. int style = font2D.getStyle();
  2728. FontFamily family = familyTable.get(familyName);
  2729. if (family == null) {
  2730. family = new FontFamily(font.getFamily(l));
  2731. familyTable.put(familyName, family);
  2732. }
  2733. /* Remove name cache entries if not using app contexts.
  2734. * To accommodate a case where code may have registered first a plain
  2735. * family member and then used it and is now registering a bold family
  2736. * member, we need to remove all members of the family, so that the
  2737. * new style can get picked up rather than continuing to synthesise.
  2738. */
  2739. if (fontsAreRegistered) {
  2740. removeFromCache(family.getFont(Font.PLAIN));
  2741. removeFromCache(family.getFont(Font.BOLD));
  2742. removeFromCache(family.getFont(Font.ITALIC));
  2743. removeFromCache(family.getFont(Font.BOLD|Font.ITALIC));
  2744. removeFromCache(fullNameTable.get(fullName));
  2745. }
  2746. family.setFont(font2D, style);
  2747. fullNameTable.put(fullName, font2D);
  2748. return true;
  2749. }
  2750. /* Remove from the name cache all references to the Font2D */
  2751. private static void removeFromCache(Font2D font) {
  2752. if (font == null) {
  2753. return;
  2754. }
  2755. String[] keys = (String[])(fontNameCache.keySet().toArray(STR_ARRAY));
  2756. for (int k=0; k<keys.length;k++) {
  2757. if (fontNameCache.get(keys[k]) == font) {
  2758. fontNameCache.remove(keys[k]);
  2759. }
  2760. }
  2761. }
  2762. // It may look odd to use TreeMap but its more convenient to the caller.
  2763. public static TreeMap<String, String> getCreatedFontFamilyNames() {
  2764. Hashtable<String,FontFamily> familyTable;
  2765. if (fontsAreRegistered) {
  2766. familyTable = createdByFamilyName;
  2767. } else if (fontsAreRegisteredPerAppContext) {
  2768. AppContext appContext = AppContext.getAppContext();
  2769. familyTable =
  2770. (Hashtable<String,FontFamily>)appContext.get(regFamilyKey);
  2771. } else {
  2772. return null;
  2773. }
  2774. Locale l = sgEnv.getSystemStartupLocale();
  2775. synchronized (familyTable) {
  2776. TreeMap<String, String> map = new TreeMap<String, String>();
  2777. for (FontFamily f : familyTable.values()) {
  2778. Font2D font2D = f.getFont(Font.PLAIN);
  2779. if (font2D == null) {
  2780. font2D = f.getClosestStyle(Font.PLAIN);
  2781. }
  2782. String name = font2D.getFamilyName(l);
  2783. map.put(name.toLowerCase(l), name);
  2784. }
  2785. return map;
  2786. }
  2787. }
  2788. public static Font[] getCreatedFonts() {
  2789. Hashtable<String,Font2D> nameTable;
  2790. if (fontsAreRegistered) {
  2791. nameTable = createdByFullName;
  2792. } else if (fontsAreRegisteredPerAppContext) {
  2793. AppContext appContext = AppContext.getAppContext();
  2794. nameTable =
  2795. (Hashtable<String,Font2D>)appContext.get(regFullNameKey);
  2796. } else {
  2797. return null;
  2798. }
  2799. Locale l = sgEnv.getSystemStartupLocale();
  2800. synchronized (nameTable) {
  2801. Font[] fonts = new Font[nameTable.size()];
  2802. int i=0;
  2803. for (Font2D font2D : nameTable.values()) {
  2804. fonts[i++] = new Font(font2D.getFontName(l), Font.PLAIN, 1);
  2805. }
  2806. return fonts;
  2807. }
  2808. }
  2809. /* Begin support for GTK Look and Feel - query libfontconfig and
  2810. * return a composite Font to Swing that uses the desktop font(s).
  2811. */
  2812. /* A small "map" from GTK/fontconfig names to the equivalent JDK
  2813. * logical font name.
  2814. */
  2815. private static final String[][] nameMap = {
  2816. {"sans", "sansserif"},
  2817. {"sans-serif", "sansserif"},
  2818. {"serif", "serif"},
  2819. {"monospace", "monospaced"}
  2820. };
  2821. public static String mapFcName(String name) {
  2822. for (int i = 0; i < nameMap.length; i++) {
  2823. if (name.equals(nameMap[i][0])) {
  2824. return nameMap[i][1];
  2825. }
  2826. }
  2827. return null;
  2828. }
  2829. /* fontconfig recognises slants roman, italic, as well as oblique,
  2830. * and a slew of weights, where the ones that matter here are
  2831. * regular and bold.
  2832. * To fully qualify what we want, we can for example ask for (eg)
  2833. * Font.PLAIN : "serif:regular:roman"
  2834. * Font.BOLD : "serif:bold:roman"
  2835. * Font.ITALIC : "serif:regular:italic"
  2836. * Font.BOLD|Font.ITALIC : "serif:bold:italic"
  2837. */
  2838. private static String[] fontConfigNames = {
  2839. "sans:regular:roman",
  2840. "sans:bold:roman",
  2841. "sans:regular:italic",
  2842. "sans:bold:italic",
  2843. "serif:regular:roman",
  2844. "serif:bold:roman",
  2845. "serif:regular:italic",
  2846. "serif:bold:italic",
  2847. "monospace:regular:roman",
  2848. "monospace:bold:roman",
  2849. "monospace:regular:italic",
  2850. "monospace:bold:italic",
  2851. };
  2852. /* This class is just a data structure.
  2853. */
  2854. private static class FontConfigInfo {
  2855. String fcName; // eg sans
  2856. String fcFamily; // eg sans
  2857. String jdkName; // eg sansserif
  2858. int style; // eg 0=PLAIN
  2859. String familyName; // eg Bitstream Vera Sans
  2860. String fontFile; // eg /usr/X11/lib/fonts/foo.ttf
  2861. //boolean preferBitmaps; // if embedded bitmaps preferred over AA
  2862. CompositeFont compFont; // null if not yet created/known.
  2863. }
  2864. private static String getFCLocaleStr() {
  2865. Locale l = SunToolkit.getStartupLocale();
  2866. String localeStr = l.getLanguage();
  2867. String country = l.getCountry();
  2868. if (!country.equals("")) {
  2869. localeStr = localeStr + "-" + country;
  2870. }
  2871. return localeStr;
  2872. }
  2873. private static native int
  2874. getFontConfigAASettings(String locale, String fcFamily);
  2875. /* This is public solely so that for debugging purposes it can be called
  2876. * with other names, which might (eg) include a size, eg "sans-24"
  2877. * The return value is a text aa rendering hint value.
  2878. * Normally we should call the no-args version.
  2879. */
  2880. public static Object getFontConfigAAHint(String fcFamily) {
  2881. if (isWindows) {
  2882. return null;
  2883. } else {
  2884. int hint = getFontConfigAASettings(getFCLocaleStr(), fcFamily);
  2885. if (hint < 0) {
  2886. return null;
  2887. } else {
  2888. return SunHints.Value.get(SunHints.INTKEY_TEXT_ANTIALIASING,
  2889. hint);
  2890. }
  2891. }
  2892. }
  2893. /* Called from code that needs to know what are the AA settings
  2894. * that apps using FC would pick up for the default desktop font.
  2895. * Note apps can change the default desktop font. etc, so this
  2896. * isn't certain to be right but its going to correct for most cases.
  2897. * Native return values map to the text aa values in sun.awt.SunHints.
  2898. * which is used to look up the renderinghint value object.
  2899. */
  2900. public static Object getFontConfigAAHint() {
  2901. return getFontConfigAAHint("sans");
  2902. }
  2903. /* This array has the array elements created in Java code and is
  2904. * passed down to native to be filled in.
  2905. */
  2906. private static FontConfigInfo[] fontConfigFonts;
  2907. /* Return an array of FontConfigInfo structs describing the primary
  2908. * font located for each of fontconfig/GTK/Pango's logical font names.
  2909. */
  2910. private static native void getFontConfig(String locale,
  2911. FontConfigInfo[] fonts);
  2912. /* This can be made public if it's needed to force a re-read
  2913. * rather than using the cached values. The re-read would be needed
  2914. * only if some event signalled that the fontconfig has changed.
  2915. * In that event this method would need to return directly the array
  2916. * to be used by the caller in case it subsequently changed.
  2917. */
  2918. private static void initFontConfigFonts() {
  2919. if (fontConfigFonts != null) {
  2920. return;
  2921. }
  2922. if (isWindows) {
  2923. return;
  2924. }
  2925. long t0 = 0;
  2926. if (logging) {
  2927. t0 = System.currentTimeMillis();
  2928. }
  2929. FontConfigInfo[] fontArr = new FontConfigInfo[fontConfigNames.length];
  2930. for (int i = 0; i< fontArr.length; i++) {
  2931. fontArr[i] = new FontConfigInfo();
  2932. fontArr[i].fcName = fontConfigNames[i];
  2933. int colonPos = fontArr[i].fcName.indexOf(':');
  2934. fontArr[i].fcFamily = fontArr[i].fcName.substring(0, colonPos);
  2935. fontArr[i].jdkName = mapFcName(fontArr[i].fcFamily);
  2936. fontArr[i].style = i % 4; // depends on array order.
  2937. }
  2938. getFontConfig(getFCLocaleStr(), fontArr);
  2939. fontConfigFonts = fontArr;
  2940. if (logging) {
  2941. long t1 = System.currentTimeMillis();
  2942. logger.info("Time spent accessing fontconfig="+(t1-t0)+"ms.");
  2943. for (int i = 0; i< fontConfigFonts.length; i++) {
  2944. FontConfigInfo fci = fontConfigFonts[i];
  2945. logger.info("FC font " + fci.fcName+" maps to family " +
  2946. fci.familyName + " in file " + fci.fontFile);
  2947. }
  2948. }
  2949. }
  2950. private static PhysicalFont registerFromFcInfo(FontConfigInfo fcInfo) {
  2951. /* If it's a TTC file we need to know that as we will need to
  2952. * make sure we return the right font */
  2953. int offset = fcInfo.fontFile.length()-4;
  2954. if (offset <= 0) {
  2955. return null;
  2956. }
  2957. String ext = fcInfo.fontFile.substring(offset).toLowerCase();
  2958. boolean isTTC = ext.equals(".ttc");
  2959. /* If this file is already registered, can just return its font.
  2960. * However we do need to check in case it's a TTC as we need
  2961. * a specific font, so rather than directly returning it, let
  2962. * findFont2D resolve that.
  2963. */
  2964. PhysicalFont physFont = registeredFontFiles.get(fcInfo.fontFile);
  2965. if (physFont != null) {
  2966. if (isTTC) {
  2967. Font2D f2d = findFont2D(fcInfo.familyName,
  2968. fcInfo.style, NO_FALLBACK);
  2969. if (f2d instanceof PhysicalFont) { /* paranoia */
  2970. return (PhysicalFont)f2d;
  2971. } else {
  2972. return null;
  2973. }
  2974. } else {
  2975. return physFont;
  2976. }
  2977. }
  2978. /* If the font may hide a JRE font (eg fontconfig says it is
  2979. * Lucida Sans), we want to use the JRE version, so make it
  2980. * point to the JRE font.
  2981. */
  2982. physFont = findJREDeferredFont(fcInfo.familyName, fcInfo.style);
  2983. /* It is also possible the font file is on the "deferred" list,
  2984. * in which case we can just initialise it now.
  2985. */
  2986. if (physFont == null &&
  2987. deferredFontFiles.get(fcInfo.fontFile) != null) {
  2988. physFont = initialiseDeferredFont(fcInfo.fontFile);
  2989. /* use findFont2D to get the right font from TTC's */
  2990. if (physFont != null) {
  2991. if (isTTC) {
  2992. Font2D f2d = findFont2D(fcInfo.familyName,
  2993. fcInfo.style, NO_FALLBACK);
  2994. if (f2d instanceof PhysicalFont) { /* paranoia */
  2995. return (PhysicalFont)f2d;
  2996. } else {
  2997. return null;
  2998. }
  2999. } else {
  3000. return physFont;
  3001. }
  3002. }
  3003. }
  3004. /* In the majority of cases we reach here, and need to determine
  3005. * the type and rank to register the font.
  3006. */
  3007. if (physFont == null) {
  3008. int fontFormat = FONTFORMAT_NONE;
  3009. int fontRank = Font2D.UNKNOWN_RANK;
  3010. if (ext.equals(".ttf") || isTTC) {
  3011. fontFormat = FONTFORMAT_TRUETYPE;
  3012. fontRank = Font2D.TTF_RANK;
  3013. } else if (ext.equals(".pfa") || ext.equals(".pfb")) {
  3014. fontFormat = FONTFORMAT_TYPE1;
  3015. fontRank = Font2D.TYPE1_RANK;
  3016. }
  3017. physFont = registerFontFile(fcInfo.fontFile, null,
  3018. fontFormat, true, fontRank);
  3019. }
  3020. return physFont;
  3021. }
  3022. private static String[] getPlatformFontDirs() {
  3023. String path = getFontPath(true);
  3024. StringTokenizer parser =
  3025. new StringTokenizer(path, File.pathSeparator);
  3026. ArrayList<String> pathList = new ArrayList<String>();
  3027. try {
  3028. while (parser.hasMoreTokens()) {
  3029. pathList.add(parser.nextToken());
  3030. }
  3031. } catch (NoSuchElementException e) {
  3032. }
  3033. return pathList.toArray(new String[0]);
  3034. }
  3035. /** returns an array of two strings. The first element is the
  3036. * name of the font. The second element is the file name.
  3037. */
  3038. private static String[] defaultPlatformFont = null;
  3039. public static String[] getDefaultPlatformFont() {
  3040. if (defaultPlatformFont != null) {
  3041. return defaultPlatformFont;
  3042. }
  3043. String[] info = new String[2];
  3044. if (isWindows) {
  3045. info[0] = "Arial";
  3046. info[1] = "c:\\windows\\fonts";
  3047. final String[] dirs = getPlatformFontDirs();
  3048. if (dirs.length > 1) {
  3049. String dir = (String)
  3050. AccessController.doPrivileged(new PrivilegedAction() {
  3051. public Object run() {
  3052. for (int i=0; i<dirs.length; i++) {
  3053. String path =
  3054. dirs[i] + File.separator + "arial.ttf";
  3055. File file = new File(path);
  3056. if (file.exists()) {
  3057. return dirs[i];
  3058. }
  3059. }
  3060. return null;
  3061. }
  3062. });
  3063. if (dir != null) {
  3064. info[1] = dir;
  3065. }
  3066. } else {
  3067. info[1] = dirs[0];
  3068. }
  3069. info[1] = info[1] + File.separator + "arial.ttf";
  3070. } else {
  3071. initFontConfigFonts();
  3072. for (int i=0; i<fontConfigFonts.length; i++) {
  3073. if ("sans".equals(fontConfigFonts[i].fcFamily) &&
  3074. 0 == fontConfigFonts[i].style) {
  3075. info[0] = fontConfigFonts[i].familyName;
  3076. info[1] = fontConfigFonts[i].fontFile;
  3077. break;
  3078. }
  3079. }
  3080. /* Absolute last ditch attempt in the face of fontconfig problems.
  3081. * If we didn't match, pick the first, or just make something
  3082. * up so we don't NPE.
  3083. */
  3084. if (info[0] == null) {
  3085. if (fontConfigFonts.length > 0 &&
  3086. fontConfigFonts[0].fontFile != null) {
  3087. info[0] = fontConfigFonts[0].familyName;
  3088. info[1] = fontConfigFonts[0].fontFile;
  3089. } else {
  3090. info[0] = "Dialog";
  3091. info[1] = "/dialog.ttf";
  3092. }
  3093. }
  3094. }
  3095. defaultPlatformFont = info;
  3096. return defaultPlatformFont;
  3097. }
  3098. private FontConfigInfo getFontConfigInfo() {
  3099. initFontConfigFonts();
  3100. for (int i=0; i<fontConfigFonts.length; i++) {
  3101. if ("sans".equals(fontConfigFonts[i].fcFamily) &&
  3102. 0 == fontConfigFonts[i].style) {
  3103. return fontConfigFonts[i];
  3104. }
  3105. }
  3106. return null;
  3107. }
  3108. /*
  3109. * We need to return a Composite font which has as the font in
  3110. * its first slot one obtained from fontconfig.
  3111. */
  3112. private static CompositeFont getFontConfigFont(String name, int style) {
  3113. name = name.toLowerCase();
  3114. initFontConfigFonts();
  3115. FontConfigInfo fcInfo = null;
  3116. for (int i=0; i<fontConfigFonts.length; i++) {
  3117. if (name.equals(fontConfigFonts[i].fcFamily) &&
  3118. style == fontConfigFonts[i].style) {
  3119. fcInfo = fontConfigFonts[i];
  3120. break;
  3121. }
  3122. }
  3123. if (fcInfo == null) {
  3124. fcInfo = fontConfigFonts[0];
  3125. }
  3126. if (logging) {
  3127. logger.info("FC name=" + name + " style=" + style + " uses " +
  3128. fcInfo.familyName + " in file: " + fcInfo.fontFile);
  3129. }
  3130. if (fcInfo.compFont != null) {
  3131. return fcInfo.compFont;
  3132. }
  3133. /* jdkFont is going to be used for slots 1..N and as a fallback.
  3134. * Slot 0 will be the physical font from fontconfig.
  3135. */
  3136. CompositeFont jdkFont = (CompositeFont)
  3137. findFont2D(fcInfo.jdkName, style, LOGICAL_FALLBACK);
  3138. if (fcInfo.familyName == null || fcInfo.fontFile == null) {
  3139. return (fcInfo.compFont = jdkFont);
  3140. }
  3141. /* First, see if the family and exact style is already registered.
  3142. * If it is, use it. If it's not, then try to register it.
  3143. * If that registration fails (signalled by null) just return the
  3144. * regular JDK composite.
  3145. * Algorithmically styled fonts won't match on exact style, so
  3146. * will fall through this code, but the regisration code will
  3147. * find that file already registered and return its font.
  3148. */
  3149. FontFamily family = FontFamily.getFamily(fcInfo.familyName);
  3150. PhysicalFont physFont = null;
  3151. if (family != null) {
  3152. Font2D f2D = family.getFontWithExactStyleMatch(fcInfo.style);
  3153. if (f2D instanceof PhysicalFont) {
  3154. physFont = (PhysicalFont)f2D;
  3155. }
  3156. }
  3157. if (physFont == null || !fcInfo.fontFile.equals(physFont.platName)) {
  3158. physFont = registerFromFcInfo(fcInfo);
  3159. if (physFont == null) {
  3160. return (fcInfo.compFont = jdkFont);
  3161. }
  3162. family = FontFamily.getFamily(physFont.getFamilyName(null));
  3163. }
  3164. /* Now register the fonts in the family (the other styles) after
  3165. * checking that they aren't already registered and are actually in
  3166. * a different file. They may be the same file in CJK cases.
  3167. * For cases where they are different font files - eg as is common for
  3168. * Latin fonts, then we rely on fontconfig to report these correctly.
  3169. * Assume that all styles of this font are found by fontconfig,
  3170. * so we can find all the family members which must be registered
  3171. * together to prevent synthetic styling.
  3172. */
  3173. for (int i=0; i<fontConfigFonts.length; i++) {
  3174. FontConfigInfo fc = fontConfigFonts[i];
  3175. if (fc != fcInfo &&
  3176. physFont.getFamilyName(null).equals(fc.familyName) &&
  3177. !fc.fontFile.equals(physFont.platName) &&
  3178. family.getFontWithExactStyleMatch(fc.style) == null) {
  3179. registerFromFcInfo(fontConfigFonts[i]);
  3180. }
  3181. }
  3182. /* Now we have a physical font. We will back this up with the JDK
  3183. * logical font (sansserif, serif, or monospaced) that corresponds
  3184. * to the Pango/GTK/FC logical font name.
  3185. */
  3186. return (fcInfo.compFont = new CompositeFont(physFont, jdkFont));
  3187. }
  3188. /* This is called by Swing passing in a fontconfig family name
  3189. * such as "sans". In return Swing gets a FontUIResource instance
  3190. * that has queried fontconfig to resolve the font(s) used for this.
  3191. * Fontconfig will if asked return a list of fonts to give the largest
  3192. * possible code point coverage.
  3193. * For now we use only the first font returned by fontconfig, and
  3194. * back it up with the most closely matching JDK logical font.
  3195. * Essentially this means pre-pending what we return now with fontconfig's
  3196. * preferred physical font. This could lead to some duplication in cases,
  3197. * if we already included that font later. We probably should remove such
  3198. * duplicates, but it is not a significant problem. It can be addressed
  3199. * later as part of creating a Composite which uses more of the
  3200. * same fonts as fontconfig. At that time we also should pay more
  3201. * attention to the special rendering instructions fontconfig returns,
  3202. * such as whether we should prefer embedded bitmaps over antialiasing.
  3203. * There's no way to express that via a Font at present.
  3204. */
  3205. public static FontUIResource getFontConfigFUIR(String fcFamily,
  3206. int style, int size) {
  3207. String mappedName = mapFcName(fcFamily);
  3208. if (mappedName == null) {
  3209. mappedName = "sansserif";
  3210. }
  3211. /* If GTK L&F were to be used on windows, we need to return
  3212. * something. Since on windows Swing won't have the code to
  3213. * call fontconfig, even if it is present, fcFamily and mapped
  3214. * name will default to sans and therefore sansserif so this
  3215. * should be fine.
  3216. */
  3217. if (isWindows) {
  3218. return new FontUIResource(mappedName, style, size);
  3219. }
  3220. CompositeFont font2D = getFontConfigFont(fcFamily, style);
  3221. if (font2D == null) { // Not expected, just a precaution.
  3222. return new FontUIResource(mappedName, style, size);
  3223. }
  3224. /* The name of the font will be that of the physical font in slot,
  3225. * but by setting the handle to that of the CompositeFont it
  3226. * renders as that CompositeFont.
  3227. * It also needs to be marked as a created font which is the
  3228. * current mechanism to signal that deriveFont etc must copy
  3229. * the handle from the original font.
  3230. */
  3231. FontUIResource fuir =
  3232. new FontUIResource(font2D.getFamilyName(null), style, size);
  3233. setFont2D(fuir, font2D.handle);
  3234. setCreatedFont(fuir);
  3235. return fuir;
  3236. }
  3237. /* The following fields and methods which relate to layout
  3238. * perhaps belong in some other class but FontManager is already
  3239. * widely used as an entry point for other JDK code that needs
  3240. * access to the font system internals.
  3241. */
  3242. /**
  3243. * Referenced by code in the JDK which wants to test for the
  3244. * minimum char code for which layout may be required.
  3245. * Note that even basic latin text can benefit from ligatures,
  3246. * eg "ffi" but we presently apply those only if explicitly
  3247. * requested with TextAttribute.LIGATURES_ON.
  3248. * The value here indicates the lowest char code for which failing
  3249. * to invoke layout would prevent acceptable rendering.
  3250. */
  3251. public static final int MIN_LAYOUT_CHARCODE = 0x0300;
  3252. /**
  3253. * Referenced by code in the JDK which wants to test for the
  3254. * maximum char code for which layout may be required.
  3255. * Note this does not account for supplementary characters
  3256. * where the caller interprets 'layout' to mean any case where
  3257. * one 'char' (ie the java type char) does not map to one glyph
  3258. */
  3259. public static final int MAX_LAYOUT_CHARCODE = 0x206F;
  3260. /* If the character code falls into any of a number of unicode ranges
  3261. * where we know that simple left->right layout mapping chars to glyphs
  3262. * 1:1 and accumulating advances is going to produce incorrect results,
  3263. * we want to know this so the caller can use a more intelligent layout
  3264. * approach. A caller who cares about optimum performance may want to
  3265. * check the first case and skip the method call if its in that range.
  3266. * Although there's a lot of tests in here, knowing you can skip
  3267. * CTL saves a great deal more. The rest of the checks are ordered
  3268. * so that rather than checking explicitly if (>= start & <= end)
  3269. * which would mean all ranges would need to be checked so be sure
  3270. * CTL is not needed, the method returns as soon as it recognises
  3271. * the code point is outside of a CTL ranges.
  3272. * NOTE: Since this method accepts an 'int' it is asssumed to properly
  3273. * represent a CHARACTER. ie it assumes the caller has already
  3274. * converted surrogate pairs into supplementary characters, and so
  3275. * can handle this case and doesn't need to be told such a case is
  3276. * 'complex'.
  3277. */
  3278. static boolean isComplexCharCode(int code) {
  3279. if (code < MIN_LAYOUT_CHARCODE || code > MAX_LAYOUT_CHARCODE) {
  3280. return false;
  3281. }
  3282. else if (code <= 0x036f) {
  3283. // Trigger layout for combining diacriticals 0x0300->0x036f
  3284. return true;
  3285. }
  3286. else if (code < 0x0590) {
  3287. // No automatic layout for Greek, Cyrillic, Armenian.
  3288. return false;
  3289. }
  3290. else if (code <= 0x06ff) {
  3291. // Hebrew 0590 - 05ff
  3292. // Arabic 0600 - 06ff
  3293. return true;
  3294. }
  3295. else if (code < 0x0900) {
  3296. return false; // Syriac and Thaana
  3297. }
  3298. else if (code <= 0x0e7f) {
  3299. // if Indic, assume shaping for conjuncts, reordering:
  3300. // 0900 - 097F Devanagari
  3301. // 0980 - 09FF Bengali
  3302. // 0A00 - 0A7F Gurmukhi
  3303. // 0A80 - 0AFF Gujarati
  3304. // 0B00 - 0B7F Oriya
  3305. // 0B80 - 0BFF Tamil
  3306. // 0C00 - 0C7F Telugu
  3307. // 0C80 - 0CFF Kannada
  3308. // 0D00 - 0D7F Malayalam
  3309. // 0D80 - 0DFF Sinhala
  3310. // 0E00 - 0E7F if Thai, assume shaping for vowel, tone marks
  3311. return true;
  3312. }
  3313. else if (code < 0x1780) {
  3314. return false;
  3315. }
  3316. else if (code <= 0x17ff) { // 1780 - 17FF Khmer
  3317. return true;
  3318. }
  3319. else if (code < 0x200c) {
  3320. return false;
  3321. }
  3322. else if (code <= 0x200d) { // zwj or zwnj
  3323. return true;
  3324. }
  3325. else if (code >= 0x202a && code <= 0x202e) { // directional control
  3326. return true;
  3327. }
  3328. else if (code >= 0x206a && code <= 0x206f) { // directional control
  3329. return true;
  3330. }
  3331. return false;
  3332. }
  3333. /* This is almost the same as the method above, except it takes a
  3334. * char which means it may include undecoded surrogate pairs.
  3335. * The distinction is made so that code which needs to identify all
  3336. * cases in which we do not have a simple mapping from
  3337. * char->unicode character->glyph can be be identified.
  3338. * For example measurement cannot simply sum advances of 'chars',
  3339. * the caret in editable text cannot advance one 'char' at a time, etc.
  3340. * These callers really are asking for more than whether 'layout'
  3341. * needs to be run, they need to know if they can assume 1->1
  3342. * char->glyph mapping.
  3343. */
  3344. static boolean isNonSimpleChar(char ch) {
  3345. return
  3346. isComplexCharCode(ch) ||
  3347. (ch >= CharToGlyphMapper.HI_SURROGATE_START &&
  3348. ch <= CharToGlyphMapper.LO_SURROGATE_END);
  3349. }
  3350. /**
  3351. * If there is anything in the text which triggers a case
  3352. * where char->glyph does not map 1:1 in straightforward
  3353. * left->right ordering, then this method returns true.
  3354. * Scripts which might require it but are not treated as such
  3355. * due to JDK implementations will not return true.
  3356. * ie a 'true' return is an indication of the treatment by
  3357. * the implementation.
  3358. * Whether supplementary characters should be considered is dependent
  3359. * on the needs of the caller. Since this method accepts the 'char' type
  3360. * then such chars are always represented by a pair. From a rendering
  3361. * perspective these will all (in the cases I know of) still be one
  3362. * unicode character -> one glyph. But if a caller is using this to
  3363. * discover any case where it cannot make naive assumptions about
  3364. * the number of chars, and how to index through them, then it may
  3365. * need the option to have a 'true' return in such a case.
  3366. */
  3367. public static boolean isComplexText(char [] chs, int start, int limit) {
  3368. for (int i = start; i < limit; i++) {
  3369. if (chs[i] < MIN_LAYOUT_CHARCODE) {
  3370. continue;
  3371. }
  3372. else if (isNonSimpleChar(chs[i])) {
  3373. return true;
  3374. }
  3375. }
  3376. return false;
  3377. }
  3378. /**
  3379. * Used by windows printing to assess if a font is likely to
  3380. * be layout compatible with JDK
  3381. * TrueType fonts should be, but if they have no GPOS table,
  3382. * but do have a GSUB table, then they are probably older
  3383. * fonts GDI handles differently.
  3384. */
  3385. public static boolean textLayoutIsCompatible(Font font) {
  3386. Font2D font2D = FontManager.getFont2D(font);
  3387. if (font2D instanceof TrueTypeFont) {
  3388. TrueTypeFont ttf = (TrueTypeFont)font2D;
  3389. return
  3390. ttf.getDirectoryEntry(TrueTypeFont.GSUBTag) == null ||
  3391. ttf.getDirectoryEntry(TrueTypeFont.GPOSTag) != null;
  3392. } else {
  3393. return false;
  3394. }
  3395. }
  3396. private static FontScaler nullScaler = null;
  3397. private static Constructor<FontScaler> scalerConstructor = null;
  3398. //Find preferred font scaler
  3399. //
  3400. //NB: we can allow property based preferences
  3401. // (theoretically logic can be font type specific)
  3402. static {
  3403. Class scalerClass = null;
  3404. Class arglst[] = new Class[] {Font2D.class, int.class,
  3405. boolean.class, int.class};
  3406. try {
  3407. if (SunGraphicsEnvironment.isOpenJDK()) {
  3408. scalerClass = Class.forName("sun.font.FreetypeFontScaler");
  3409. } else {
  3410. scalerClass = Class.forName("sun.font.T2KFontScaler");
  3411. }
  3412. } catch (ClassNotFoundException e) {
  3413. scalerClass = NullFontScaler.class;
  3414. }
  3415. //NB: rewrite using factory? constructor is ugly way
  3416. try {
  3417. scalerConstructor = scalerClass.getConstructor(arglst);
  3418. } catch (NoSuchMethodException e) {
  3419. //should not happen
  3420. }
  3421. }
  3422. /* At the moment it is harmless to create 2 null scalers
  3423. so, technically, syncronized keyword is not needed.
  3424. But it is safer to keep it to avoid subtle problems if we will be
  3425. adding checks like whether scaler is null scaler. */
  3426. public synchronized static FontScaler getNullScaler() {
  3427. if (nullScaler == null) {
  3428. nullScaler = new NullFontScaler();
  3429. }
  3430. return nullScaler;
  3431. }
  3432. /* This is the only place to instantiate new FontScaler.
  3433. * Therefore this is very convinient place to register
  3434. * scaler with Disposer as well as trigger deregistring bad font
  3435. * in case when scaler reports this.
  3436. */
  3437. public static FontScaler getScaler(Font2D font,
  3438. int indexInCollection,
  3439. boolean supportsCJK,
  3440. int filesize) {
  3441. FontScaler scaler = null;
  3442. try {
  3443. Object args[] = new Object[] {font, indexInCollection,
  3444. supportsCJK, filesize};
  3445. scaler = scalerConstructor.newInstance(args);
  3446. Disposer.addObjectRecord(font, scaler);
  3447. } catch (Throwable e) {
  3448. scaler = nullScaler;
  3449. //if we can not instantiate scaler assume bad font
  3450. //NB: technically it could be also because of internal scaler
  3451. // error but here we are assuming scaler is ok.
  3452. deRegisterBadFont(font);
  3453. }
  3454. return scaler;
  3455. }
  3456. }