PageRenderTime 75ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

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