1 /* 2 * Copyright (c) 2003, 2020, 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 26 package sun.font; 27 28 import java.awt.Font; 29 import java.awt.FontFormatException; 30 import java.awt.GraphicsEnvironment; 31 import java.awt.geom.Point2D; 32 import java.io.FileNotFoundException; 33 import java.io.IOException; 34 import java.io.RandomAccessFile; 35 import java.io.UnsupportedEncodingException; 36 import java.nio.ByteBuffer; 37 import java.nio.CharBuffer; 38 import java.nio.IntBuffer; 39 import java.nio.ShortBuffer; 40 import java.nio.channels.ClosedChannelException; 41 import java.nio.channels.FileChannel; 42 import java.security.AccessController; 43 import java.security.PrivilegedActionException; 44 import java.security.PrivilegedExceptionAction; 45 import java.util.HashMap; 46 import java.util.HashSet; 47 import java.util.Locale; 48 import java.util.Map; 49 50 import sun.java2d.Disposer; 51 import sun.java2d.DisposerRecord; 52 import sun.security.action.GetPropertyAction; 53 54 /** 55 * TrueTypeFont is not called SFntFont because it is not expected 56 * to handle all types that may be housed in a such a font file. 57 * If additional types are supported later, it may make sense to 58 * create an SFnt superclass. Eg to handle sfnt-housed postscript fonts. 59 * OpenType fonts are handled by this class, and possibly should be 60 * represented by a subclass. 61 * An instance stores some information from the font file to faciliate 62 * faster access. File size, the table directory and the names of the font 63 * are the most important of these. It amounts to approx 400 bytes 64 * for a typical font. Systems with mutiple locales sometimes have up to 400 65 * font files, and an app which loads all font files would need around 66 * 160Kbytes. So storing any more info than this would be expensive. 67 */ 68 public class TrueTypeFont extends FileFont { 69 70 /* -- Tags for required TrueType tables */ 71 public static final int cmapTag = 0x636D6170; // 'cmap' 72 public static final int glyfTag = 0x676C7966; // 'glyf' 73 public static final int headTag = 0x68656164; // 'head' 74 public static final int hheaTag = 0x68686561; // 'hhea' 75 public static final int hmtxTag = 0x686D7478; // 'hmtx' 76 public static final int locaTag = 0x6C6F6361; // 'loca' 77 public static final int maxpTag = 0x6D617870; // 'maxp' 78 public static final int nameTag = 0x6E616D65; // 'name' 79 public static final int postTag = 0x706F7374; // 'post' 80 public static final int os_2Tag = 0x4F532F32; // 'OS/2' 81 82 /* -- Tags for opentype related tables */ 83 public static final int GDEFTag = 0x47444546; // 'GDEF' 84 public static final int GPOSTag = 0x47504F53; // 'GPOS' 85 public static final int GSUBTag = 0x47535542; // 'GSUB' 86 public static final int mortTag = 0x6D6F7274; // 'mort' 87 public static final int morxTag = 0x6D6F7278; // 'morx' 88 89 /* -- Tags for non-standard tables */ 90 public static final int fdscTag = 0x66647363; // 'fdsc' - gxFont descriptor 91 public static final int fvarTag = 0x66766172; // 'fvar' - gxFont variations 92 public static final int featTag = 0x66656174; // 'feat' - layout features 93 public static final int EBLCTag = 0x45424C43; // 'EBLC' - embedded bitmaps 94 public static final int gaspTag = 0x67617370; // 'gasp' - hint/smooth sizes 95 96 /* -- Other tags */ 97 public static final int ttcfTag = 0x74746366; // 'ttcf' - TTC file 98 public static final int v1ttTag = 0x00010000; // 'v1tt' - Version 1 TT font 99 public static final int trueTag = 0x74727565; // 'true' - Version 2 TT font 100 public static final int ottoTag = 0x4f54544f; // 'otto' - OpenType font 101 102 /* -- ID's used in the 'name' table */ 103 public static final int MAC_PLATFORM_ID = 1; 104 public static final int MACROMAN_SPECIFIC_ID = 0; 105 public static final int MACROMAN_ENGLISH_LANG = 0; 106 107 public static final int MS_PLATFORM_ID = 3; 108 /* MS locale id for US English is the "default" */ 109 public static final short ENGLISH_LOCALE_ID = 0x0409; // 1033 decimal 110 public static final int FAMILY_NAME_ID = 1; 111 // public static final int STYLE_WEIGHT_ID = 2; // currently unused. 112 public static final int FULL_NAME_ID = 4; 113 public static final int POSTSCRIPT_NAME_ID = 6; 114 115 private static final short US_LCID = 0x0409; // US English - default 116 117 private static Map<String, Short> lcidMap; 118 119 static class DirectoryEntry { 120 int tag; 121 int offset; 122 int length; 123 } 124 125 /* There is a pool which limits the number of fd's that are in 126 * use. Normally fd's are closed as they are replaced in the pool. 127 * But if an instance of this class becomes unreferenced, then there 128 * needs to be a way to close the fd. A finalize() method could do this, 129 * but using the Disposer class will ensure its called in a more timely 130 * manner. This is not something which should be relied upon to free 131 * fd's - its a safeguard. 132 */ 133 private static class TTDisposerRecord implements DisposerRecord { 134 135 FileChannel channel = null; 136 137 public synchronized void dispose() { 138 try { 139 if (channel != null) { 140 channel.close(); 141 } 142 } catch (IOException e) { 143 } finally { 144 channel = null; 145 } 146 } 147 } 148 149 TTDisposerRecord disposerRecord = new TTDisposerRecord(); 150 151 /* > 0 only if this font is a part of a collection */ 152 int fontIndex = 0; 153 154 /* Number of fonts in this collection. ==1 if not a collection */ 155 int directoryCount = 1; 156 157 /* offset in file of table directory for this font */ 158 int directoryOffset; // 12 if its not a collection. 159 160 /* number of table entries in the directory/offsets table */ 161 int numTables; 162 163 /* The contents of the directory/offsets table */ 164 DirectoryEntry []tableDirectory; 165 166 // protected byte []gposTable = null; 167 // protected byte []gdefTable = null; 168 // protected byte []gsubTable = null; 169 // protected byte []mortTable = null; 170 // protected boolean hintsTabledChecked = false; 171 // protected boolean containsHintsTable = false; 172 173 /* These fields are set from os/2 table info. */ 174 private boolean supportsJA; 175 private boolean supportsCJK; 176 177 /* These are for faster access to the name of the font as 178 * typically exposed via API to applications. 179 */ 180 private Locale nameLocale; 181 private String localeFamilyName; 182 private String localeFullName; 183 184 /* 185 * Used on Windows to validate the font selected by GDI for (sub-pixel 186 * antialiased) rendering. For 'standalone' fonts it's equal to the font 187 * file size, for collection (TTC, OTC) members it's the number of bytes in 188 * the collection file from the start of this font's offset table till the 189 * end of the file. 190 */ 191 int fontDataSize; 192 193 public TrueTypeFont(String platname, Object nativeNames, int fIndex, 194 boolean javaRasterizer) 195 throws FontFormatException 196 { 197 this(platname, nativeNames, fIndex, javaRasterizer, true); 198 } 199 200 /** 201 * - does basic verification of the file 202 * - reads the header table for this font (within a collection) 203 * - reads the names (full, family). 204 * - determines the style of the font. 205 * - initializes the CMAP 206 * @throws FontFormatException if the font can't be opened 207 * or fails verification, or there's no usable cmap 208 */ 209 public TrueTypeFont(String platname, Object nativeNames, int fIndex, 210 boolean javaRasterizer, boolean useFilePool) 211 throws FontFormatException { 212 super(platname, nativeNames); 213 useJavaRasterizer = javaRasterizer; 214 fontRank = Font2D.TTF_RANK; 215 try { 216 verify(useFilePool); 217 init(fIndex); 218 if (!useFilePool) { 219 close(); 220 } 221 } catch (Throwable t) { 222 close(); 223 if (t instanceof FontFormatException) { 224 throw (FontFormatException)t; 225 } else { 226 throw new FontFormatException("Unexpected runtime exception."); 227 } 228 } 229 Disposer.addObjectRecord(this, disposerRecord); 230 } 231 232 private synchronized FileChannel open() throws FontFormatException { 233 return open(true); 234 } 235 236 /* This is intended to be called, and the returned value used, 237 * from within a block synchronized on this font object. 238 * ie the channel returned may be nulled out at any time by "close()" 239 * unless the caller holds a lock. 240 * Deadlock warning: FontManager.addToPool(..) acquires a global lock, 241 * which means nested locks may be in effect. 242 */ 243 private synchronized FileChannel open(boolean usePool) 244 throws FontFormatException { 245 if (disposerRecord.channel == null) { 246 FontUtilities.logInfo("open TTF: " + platName); 247 try { 248 RandomAccessFile raf = AccessController.doPrivileged( 249 new PrivilegedExceptionAction<RandomAccessFile>() { 250 public RandomAccessFile run() throws FileNotFoundException { 251 return new RandomAccessFile(platName, "r"); 252 } 253 }); 254 disposerRecord.channel = raf.getChannel(); 255 fileSize = (int)disposerRecord.channel.size(); 256 if (usePool) { 257 FontManager fm = FontManagerFactory.getInstance(); 258 if (fm instanceof SunFontManager) { 259 ((SunFontManager) fm).addToPool(this); 260 } 261 } 262 } catch (PrivilegedActionException e) { 263 close(); 264 Throwable reason = e.getCause(); 265 if (reason == null) { 266 reason = e; 267 } 268 throw new FontFormatException(reason.toString()); 269 } catch (ClosedChannelException e) { 270 /* NIO I/O is interruptible, recurse to retry operation. 271 * The call to channel.size() above can throw this exception. 272 * Clear interrupts before recursing in case NIO didn't. 273 * Note that close() sets disposerRecord.channel to null. 274 */ 275 Thread.interrupted(); 276 close(); 277 open(); 278 } catch (IOException e) { 279 close(); 280 throw new FontFormatException(e.toString()); 281 } 282 } 283 return disposerRecord.channel; 284 } 285 286 protected synchronized void close() { 287 disposerRecord.dispose(); 288 } 289 290 291 int readBlock(ByteBuffer buffer, int offset, int length) { 292 int bread = 0; 293 try { 294 synchronized (this) { 295 if (disposerRecord.channel == null) { 296 open(); 297 } 298 if (offset + length > fileSize) { 299 if (offset >= fileSize) { 300 /* Since the caller ensures that offset is < fileSize 301 * this condition suggests that fileSize is now 302 * different than the value we originally provided 303 * to native when the scaler was created. 304 * Also fileSize is updated every time we 305 * open() the file here, but in native the value 306 * isn't updated. If the file has changed whilst we 307 * are executing we want to bail, not spin. 308 */ 309 String msg = "Read offset is " + offset + 310 " file size is " + fileSize+ 311 " file is " + platName; 312 FontUtilities.logSevere(msg); 313 return -1; 314 } else { 315 length = fileSize - offset; 316 } 317 } 318 buffer.clear(); 319 disposerRecord.channel.position(offset); 320 while (bread < length) { 321 int cnt = disposerRecord.channel.read(buffer); 322 if (cnt == -1) { 323 String msg = "Unexpected EOF " + this; 324 int currSize = (int)disposerRecord.channel.size(); 325 if (currSize != fileSize) { 326 msg += " File size was " + fileSize + 327 " and now is " + currSize; 328 } 329 FontUtilities.logSevere(msg); 330 // We could still flip() the buffer here because 331 // it's possible that we did read some data in 332 // an earlier loop, and we probably should 333 // return that to the caller. Although if 334 // the caller expected 8K of data and we return 335 // only a few bytes then maybe it's better instead to 336 // set bread = -1 to indicate failure. 337 // The following is therefore using arbitrary values 338 // but is meant to allow cases where enough 339 // data was read to probably continue. 340 if (bread > length/2 || bread > 16384) { 341 buffer.flip(); 342 msg = "Returning " + bread + " bytes instead of " + length; 343 FontUtilities.logSevere(msg); 344 } else { 345 bread = -1; 346 } 347 throw new IOException(msg); 348 } 349 bread += cnt; 350 } 351 buffer.flip(); 352 if (bread > length) { // possible if buffer.size() > length 353 bread = length; 354 } 355 } 356 } catch (FontFormatException e) { 357 if (FontUtilities.isLogging()) { 358 FontUtilities.getLogger().severe( 359 "While reading " + platName, e); 360 } 361 bread = -1; // signal EOF 362 deregisterFontAndClearStrikeCache(); 363 } catch (ClosedChannelException e) { 364 /* NIO I/O is interruptible, recurse to retry operation. 365 * Clear interrupts before recursing in case NIO didn't. 366 */ 367 Thread.interrupted(); 368 close(); 369 return readBlock(buffer, offset, length); 370 } catch (IOException e) { 371 /* If we did not read any bytes at all and the exception is 372 * not a recoverable one (ie is not ClosedChannelException) then 373 * we should indicate that there is no point in re-trying. 374 * Other than an attempt to read past the end of the file it 375 * seems unlikely this would occur as problems opening the 376 * file are handled as a FontFormatException. 377 */ 378 if (FontUtilities.isLogging()) { 379 FontUtilities.getLogger().severe( 380 "While reading " + platName, e); 381 } 382 if (bread == 0) { 383 bread = -1; // signal EOF 384 deregisterFontAndClearStrikeCache(); 385 } 386 } 387 return bread; 388 } 389 390 ByteBuffer readBlock(int offset, int length) { 391 392 ByteBuffer buffer = ByteBuffer.allocate(length); 393 try { 394 synchronized (this) { 395 if (disposerRecord.channel == null) { 396 open(); 397 } 398 if (offset + length > fileSize) { 399 if (offset > fileSize) { 400 return null; // assert? 401 } else { 402 buffer = ByteBuffer.allocate(fileSize-offset); 403 } 404 } 405 disposerRecord.channel.position(offset); 406 disposerRecord.channel.read(buffer); 407 buffer.flip(); 408 } 409 } catch (FontFormatException e) { 410 return null; 411 } catch (ClosedChannelException e) { 412 /* NIO I/O is interruptible, recurse to retry operation. 413 * Clear interrupts before recursing in case NIO didn't. 414 */ 415 Thread.interrupted(); 416 close(); 417 readBlock(buffer, offset, length); 418 } catch (IOException e) { 419 return null; 420 } 421 return buffer; 422 } 423 424 /* This is used by native code which can't allocate a direct byte 425 * buffer because of bug 4845371. It, and references to it in native 426 * code in scalerMethods.c can be removed once that bug is fixed. 427 * 4845371 is now fixed but we'll keep this around as it doesn't cost 428 * us anything if its never used/called. 429 */ 430 byte[] readBytes(int offset, int length) { 431 ByteBuffer buffer = readBlock(offset, length); 432 if (buffer.hasArray()) { 433 return buffer.array(); 434 } else { 435 byte[] bufferBytes = new byte[buffer.limit()]; 436 buffer.get(bufferBytes); 437 return bufferBytes; 438 } 439 } 440 441 private void verify(boolean usePool) throws FontFormatException { 442 open(usePool); 443 } 444 445 /* sizes, in bytes, of TT/TTC header records */ 446 private static final int TTCHEADERSIZE = 12; 447 private static final int DIRECTORYHEADERSIZE = 12; 448 private static final int DIRECTORYENTRYSIZE = 16; 449 450 protected void init(int fIndex) throws FontFormatException { 451 int headerOffset = 0; 452 ByteBuffer buffer = readBlock(0, TTCHEADERSIZE); 453 try { 454 switch (buffer.getInt()) { 455 456 case ttcfTag: 457 buffer.getInt(); // skip TTC version ID 458 directoryCount = buffer.getInt(); 459 if (fIndex >= directoryCount) { 460 throw new FontFormatException("Bad collection index"); 461 } 462 fontIndex = fIndex; 463 buffer = readBlock(TTCHEADERSIZE+4*fIndex, 4); 464 headerOffset = buffer.getInt(); 465 fontDataSize = Math.max(0, fileSize - headerOffset); 466 break; 467 468 case v1ttTag: 469 case trueTag: 470 case ottoTag: 471 fontDataSize = fileSize; 472 break; 473 474 default: 475 throw new FontFormatException("Unsupported sfnt " + 476 getPublicFileName()); 477 } 478 479 /* Now have the offset of this TT font (possibly within a TTC) 480 * After the TT version/scaler type field, is the short 481 * representing the number of tables in the table directory. 482 * The table directory begins at 12 bytes after the header. 483 * Each table entry is 16 bytes long (4 32-bit ints) 484 */ 485 buffer = readBlock(headerOffset+4, 2); 486 numTables = buffer.getShort(); 487 directoryOffset = headerOffset+DIRECTORYHEADERSIZE; 488 ByteBuffer bbuffer = readBlock(directoryOffset, 489 numTables*DIRECTORYENTRYSIZE); 490 IntBuffer ibuffer = bbuffer.asIntBuffer(); 491 DirectoryEntry table; 492 tableDirectory = new DirectoryEntry[numTables]; 493 for (int i=0; i<numTables;i++) { 494 tableDirectory[i] = table = new DirectoryEntry(); 495 table.tag = ibuffer.get(); 496 /* checksum */ ibuffer.get(); 497 table.offset = ibuffer.get(); 498 table.length = ibuffer.get(); 499 if (table.offset + table.length > fileSize) { 500 throw new FontFormatException("bad table, tag="+table.tag); 501 } 502 } 503 504 if (getDirectoryEntry(headTag) == null) { 505 throw new FontFormatException("missing head table"); 506 } 507 if (getDirectoryEntry(maxpTag) == null) { 508 throw new FontFormatException("missing maxp table"); 509 } 510 if (getDirectoryEntry(hmtxTag) != null 511 && getDirectoryEntry(hheaTag) == null) { 512 throw new FontFormatException("missing hhea table"); 513 } 514 initNames(); 515 } catch (Exception e) { 516 FontUtilities.logSevere(e.toString()); 517 if (e instanceof FontFormatException) { 518 throw (FontFormatException)e; 519 } else { 520 throw new FontFormatException(e.toString()); 521 } 522 } 523 if (familyName == null || fullName == null) { 524 throw new FontFormatException("Font name not found"); 525 } 526 /* The os2_Table is needed to gather some info, but we don't 527 * want to keep it around (as a field) so obtain it once and 528 * pass it to the code that needs it. 529 */ 530 ByteBuffer os2_Table = getTableBuffer(os_2Tag); 531 setStyle(os2_Table); 532 setCJKSupport(os2_Table); 533 } 534 535 /* The array index corresponds to a bit offset in the TrueType 536 * font's OS/2 compatibility table's code page ranges fields. 537 * These are two 32 bit unsigned int fields at offsets 78 and 82. 538 * We are only interested in determining if the font supports 539 * the windows encodings we expect as the default encoding in 540 * supported locales, so we only map the first of these fields. 541 */ 542 static final String[] encoding_mapping = { 543 "cp1252", /* 0:Latin 1 */ 544 "cp1250", /* 1:Latin 2 */ 545 "cp1251", /* 2:Cyrillic */ 546 "cp1253", /* 3:Greek */ 547 "cp1254", /* 4:Turkish/Latin 5 */ 548 "cp1255", /* 5:Hebrew */ 549 "cp1256", /* 6:Arabic */ 550 "cp1257", /* 7:Windows Baltic */ 551 "", /* 8:reserved for alternate ANSI */ 552 "", /* 9:reserved for alternate ANSI */ 553 "", /* 10:reserved for alternate ANSI */ 554 "", /* 11:reserved for alternate ANSI */ 555 "", /* 12:reserved for alternate ANSI */ 556 "", /* 13:reserved for alternate ANSI */ 557 "", /* 14:reserved for alternate ANSI */ 558 "", /* 15:reserved for alternate ANSI */ 559 "ms874", /* 16:Thai */ 560 "ms932", /* 17:JIS/Japanese */ 561 "gbk", /* 18:PRC GBK Cp950 */ 562 "ms949", /* 19:Korean Extended Wansung */ 563 "ms950", /* 20:Chinese (Taiwan, Hongkong, Macau) */ 564 "ms1361", /* 21:Korean Johab */ 565 "", /* 22 */ 566 "", /* 23 */ 567 "", /* 24 */ 568 "", /* 25 */ 569 "", /* 26 */ 570 "", /* 27 */ 571 "", /* 28 */ 572 "", /* 29 */ 573 "", /* 30 */ 574 "", /* 31 */ 575 }; 576 577 /* This maps two letter language codes to a Windows code page. 578 * Note that eg Cp1252 (the first subarray) is not exactly the same as 579 * Latin-1 since Windows code pages are do not necessarily correspond. 580 * There are two codepages for zh and ko so if a font supports 581 * only one of these ranges then we need to distinguish based on 582 * country. So far this only seems to matter for zh. 583 * REMIND: Unicode locales such as Hindi do not have a code page so 584 * this whole mechanism needs to be revised to map languages to 585 * the Unicode ranges either when this fails, or as an additional 586 * validating test. Basing it on Unicode ranges should get us away 587 * from needing to map to this small and incomplete set of Windows 588 * code pages which looks odd on non-Windows platforms. 589 */ 590 private static final String[][] languages = { 591 592 /* cp1252/Latin 1 */ 593 { "en", "ca", "da", "de", "es", "fi", "fr", "is", "it", 594 "nl", "no", "pt", "sq", "sv", }, 595 596 /* cp1250/Latin2 */ 597 { "cs", "cz", "et", "hr", "hu", "nr", "pl", "ro", "sk", 598 "sl", "sq", "sr", }, 599 600 /* cp1251/Cyrillic */ 601 { "bg", "mk", "ru", "sh", "uk" }, 602 603 /* cp1253/Greek*/ 604 { "el" }, 605 606 /* cp1254/Turkish,Latin 5 */ 607 { "tr" }, 608 609 /* cp1255/Hebrew */ 610 { "he" }, 611 612 /* cp1256/Arabic */ 613 { "ar" }, 614 615 /* cp1257/Windows Baltic */ 616 { "et", "lt", "lv" }, 617 618 /* ms874/Thai */ 619 { "th" }, 620 621 /* ms932/Japanese */ 622 { "ja" }, 623 624 /* gbk/Chinese (PRC GBK Cp950) */ 625 { "zh", "zh_CN", }, 626 627 /* ms949/Korean Extended Wansung */ 628 { "ko" }, 629 630 /* ms950/Chinese (Taiwan, Hongkong, Macau) */ 631 { "zh_HK", "zh_TW", }, 632 633 /* ms1361/Korean Johab */ 634 { "ko" }, 635 }; 636 637 private static final String[] codePages = { 638 "cp1252", 639 "cp1250", 640 "cp1251", 641 "cp1253", 642 "cp1254", 643 "cp1255", 644 "cp1256", 645 "cp1257", 646 "ms874", 647 "ms932", 648 "gbk", 649 "ms949", 650 "ms950", 651 "ms1361", 652 }; 653 654 private static String defaultCodePage = null; 655 static String getCodePage() { 656 657 if (defaultCodePage != null) { 658 return defaultCodePage; 659 } 660 661 if (FontUtilities.isWindows) { 662 defaultCodePage = 663 AccessController.doPrivileged(new GetPropertyAction("file.encoding")); 664 } else { 665 if (languages.length != codePages.length) { 666 throw new InternalError("wrong code pages array length"); 667 } 668 Locale locale = sun.awt.SunToolkit.getStartupLocale(); 669 670 String language = locale.getLanguage(); 671 if (language != null) { 672 if (language.equals("zh")) { 673 String country = locale.getCountry(); 674 if (country != null) { 675 language = language + "_" + country; 676 } 677 } 678 for (int i=0; i<languages.length;i++) { 679 for (int l=0;l<languages[i].length; l++) { 680 if (language.equals(languages[i][l])) { 681 defaultCodePage = codePages[i]; 682 return defaultCodePage; 683 } 684 } 685 } 686 } 687 } 688 if (defaultCodePage == null) { 689 defaultCodePage = ""; 690 } 691 return defaultCodePage; 692 } 693 694 /* Theoretically, reserved bits must not be set, include symbol bits */ 695 public static final int reserved_bits1 = 0x80000000; 696 public static final int reserved_bits2 = 0x0000ffff; 697 @Override 698 boolean supportsEncoding(String encoding) { 699 if (encoding == null) { 700 encoding = getCodePage(); 701 } 702 if ("".equals(encoding)) { 703 return false; 704 } 705 706 encoding = encoding.toLowerCase(); 707 708 /* java_props_md.c has a couple of special cases 709 * if language packs are installed. In these encodings the 710 * fontconfig files pick up different fonts : 711 * SimSun-18030 and MingLiU_HKSCS. Since these fonts will 712 * indicate they support the base encoding, we need to rewrite 713 * these encodings here before checking the map/array. 714 */ 715 if (encoding.equals("gb18030")) { 716 encoding = "gbk"; 717 } else if (encoding.equals("ms950_hkscs")) { 718 encoding = "ms950"; 719 } 720 721 ByteBuffer buffer = getTableBuffer(os_2Tag); 722 /* required info is at offsets 78 and 82 */ 723 if (buffer == null || buffer.capacity() < 86) { 724 return false; 725 } 726 727 int range1 = buffer.getInt(78); /* ulCodePageRange1 */ 728 // int range2 = buffer.getInt(82); /* ulCodePageRange2 */ 729 730 /* This test is too stringent for Arial on Solaris (and perhaps 731 * other fonts). Arial has at least one reserved bit set for an 732 * unknown reason. 733 */ 734 // if (((range1 & reserved_bits1) | (range2 & reserved_bits2)) != 0) { 735 // return false; 736 // } 737 738 for (int em=0; em<encoding_mapping.length; em++) { 739 if (encoding_mapping[em].equals(encoding)) { 740 if (((1 << em) & range1) != 0) { 741 return true; 742 } 743 } 744 } 745 return false; 746 } 747 748 749 /* Use info in the os_2Table to test CJK support */ 750 private void setCJKSupport(ByteBuffer os2Table) { 751 /* required info is in ulong at offset 46 */ 752 if (os2Table == null || os2Table.capacity() < 50) { 753 return; 754 } 755 int range2 = os2Table.getInt(46); /* ulUnicodeRange2 */ 756 757 /* Any of these bits set in the 32-63 range indicate a font with 758 * support for a CJK range. We aren't looking at some other bits 759 * in the 64-69 range such as half width forms as its unlikely a font 760 * would include those and none of these. 761 */ 762 supportsCJK = ((range2 & 0x29bf0000) != 0); 763 764 /* This should be generalised, but for now just need to know if 765 * Hiragana or Katakana ranges are supported by the font. 766 * In the 4 longs representing unicode ranges supported 767 * bits 49 & 50 indicate hiragana and katakana 768 * This is bits 17 & 18 in the 2nd ulong. If either is supported 769 * we presume this is a JA font. 770 */ 771 supportsJA = ((range2 & 0x60000) != 0); 772 } 773 774 boolean supportsJA() { 775 return supportsJA; 776 } 777 778 ByteBuffer getTableBuffer(int tag) { 779 DirectoryEntry entry = null; 780 781 for (int i=0;i<numTables;i++) { 782 if (tableDirectory[i].tag == tag) { 783 entry = tableDirectory[i]; 784 break; 785 } 786 } 787 if (entry == null || entry.length == 0 || 788 entry.offset+entry.length > fileSize) { 789 return null; 790 } 791 792 int bread = 0; 793 ByteBuffer buffer = ByteBuffer.allocate(entry.length); 794 synchronized (this) { 795 try { 796 if (disposerRecord.channel == null) { 797 open(); 798 } 799 disposerRecord.channel.position(entry.offset); 800 bread = disposerRecord.channel.read(buffer); 801 buffer.flip(); 802 } catch (ClosedChannelException e) { 803 /* NIO I/O is interruptible, recurse to retry operation. 804 * Clear interrupts before recursing in case NIO didn't. 805 */ 806 Thread.interrupted(); 807 close(); 808 return getTableBuffer(tag); 809 } catch (IOException e) { 810 return null; 811 } catch (FontFormatException e) { 812 return null; 813 } 814 815 if (bread < entry.length) { 816 return null; 817 } else { 818 return buffer; 819 } 820 } 821 } 822 823 @Override 824 protected byte[] getTableBytes(int tag) { 825 ByteBuffer buffer = getTableBuffer(tag); 826 if (buffer == null) { 827 return null; 828 } else if (buffer.hasArray()) { 829 try { 830 return buffer.array(); 831 } catch (Exception re) { 832 } 833 } 834 byte []data = new byte[getTableSize(tag)]; 835 buffer.get(data); 836 return data; 837 } 838 839 int getTableSize(int tag) { 840 for (int i=0;i<numTables;i++) { 841 if (tableDirectory[i].tag == tag) { 842 return tableDirectory[i].length; 843 } 844 } 845 return 0; 846 } 847 848 int getTableOffset(int tag) { 849 for (int i=0;i<numTables;i++) { 850 if (tableDirectory[i].tag == tag) { 851 return tableDirectory[i].offset; 852 } 853 } 854 return 0; 855 } 856 857 DirectoryEntry getDirectoryEntry(int tag) { 858 for (int i=0;i<numTables;i++) { 859 if (tableDirectory[i].tag == tag) { 860 return tableDirectory[i]; 861 } 862 } 863 return null; 864 } 865 866 /* Used to determine if this size has embedded bitmaps, which 867 * for CJK fonts should be used in preference to LCD glyphs. 868 */ 869 boolean useEmbeddedBitmapsForSize(int ptSize) { 870 if (!supportsCJK) { 871 return false; 872 } 873 if (getDirectoryEntry(EBLCTag) == null) { 874 return false; 875 } 876 ByteBuffer eblcTable = getTableBuffer(EBLCTag); 877 int numSizes = eblcTable.getInt(4); 878 /* The bitmapSizeTable's start at offset of 8. 879 * Each bitmapSizeTable entry is 48 bytes. 880 * The offset of ppemY in the entry is 45. 881 */ 882 for (int i=0;i<numSizes;i++) { 883 int ppemY = eblcTable.get(8+(i*48)+45) &0xff; 884 if (ppemY == ptSize) { 885 return true; 886 } 887 } 888 return false; 889 } 890 891 public String getFullName() { 892 return fullName; 893 } 894 895 /* This probably won't get called but is there to support the 896 * contract() of setStyle() defined in the superclass. 897 */ 898 @Override 899 protected void setStyle() { 900 setStyle(getTableBuffer(os_2Tag)); 901 } 902 903 private int fontWidth = 0; 904 @Override 905 public int getWidth() { 906 return (fontWidth > 0) ? fontWidth : super.getWidth(); 907 } 908 909 private int fontWeight = 0; 910 @Override 911 public int getWeight() { 912 return (fontWeight > 0) ? fontWeight : super.getWeight(); 913 } 914 915 /* TrueTypeFont can use the fsSelection fields of OS/2 table 916 * to determine the style. In the unlikely case that doesn't exist, 917 * can use macStyle in the 'head' table but simpler to 918 * fall back to super class algorithm of looking for well known string. 919 * A very few fonts don't specify this information, but I only 920 * came across one: Lucida Sans Thai Typewriter Oblique in 921 * /usr/openwin/lib/locale/th_TH/X11/fonts/TrueType/lucidai.ttf 922 * that explicitly specified the wrong value. It says its regular. 923 * I didn't find any fonts that were inconsistent (ie regular plus some 924 * other value). 925 */ 926 private static final int fsSelectionItalicBit = 0x00001; 927 private static final int fsSelectionBoldBit = 0x00020; 928 private static final int fsSelectionRegularBit = 0x00040; 929 private void setStyle(ByteBuffer os_2Table) { 930 if (os_2Table == null) { 931 return; 932 } 933 if (os_2Table.capacity() >= 8) { 934 fontWeight = os_2Table.getChar(4) & 0xffff; 935 fontWidth = os_2Table.getChar(6) & 0xffff; 936 } 937 /* fsSelection is unsigned short at buffer offset 62 */ 938 if (os_2Table.capacity() < 64) { 939 super.setStyle(); 940 return; 941 } 942 int fsSelection = os_2Table.getChar(62) & 0xffff; 943 int italic = fsSelection & fsSelectionItalicBit; 944 int bold = fsSelection & fsSelectionBoldBit; 945 int regular = fsSelection & fsSelectionRegularBit; 946 // System.out.println("platname="+platName+" font="+fullName+ 947 // " family="+familyName+ 948 // " R="+regular+" I="+italic+" B="+bold); 949 if (regular!=0 && ((italic|bold)!=0)) { 950 /* This is inconsistent. Try using the font name algorithm */ 951 super.setStyle(); 952 return; 953 } else if ((regular|italic|bold) == 0) { 954 /* No style specified. Try using the font name algorithm */ 955 super.setStyle(); 956 return; 957 } 958 switch (bold|italic) { 959 case fsSelectionItalicBit: 960 style = Font.ITALIC; 961 break; 962 case fsSelectionBoldBit: 963 style = Font.BOLD; 964 break; 965 case fsSelectionBoldBit|fsSelectionItalicBit: 966 style = Font.BOLD|Font.ITALIC; 967 } 968 } 969 970 private float stSize, stPos, ulSize, ulPos; 971 972 private void setStrikethroughMetrics(ByteBuffer os_2Table, int upem) { 973 if (os_2Table == null || os_2Table.capacity() < 30 || upem < 0) { 974 stSize = .05f; 975 stPos = -.4f; 976 return; 977 } 978 ShortBuffer sb = os_2Table.asShortBuffer(); 979 stSize = sb.get(13) / (float)upem; 980 stPos = -sb.get(14) / (float)upem; 981 } 982 983 private void setUnderlineMetrics(ByteBuffer postTable, int upem) { 984 if (postTable == null || postTable.capacity() < 12 || upem < 0) { 985 ulSize = .05f; 986 ulPos = .1f; 987 return; 988 } 989 ShortBuffer sb = postTable.asShortBuffer(); 990 ulSize = sb.get(5) / (float)upem; 991 ulPos = -sb.get(4) / (float)upem; 992 } 993 994 @Override 995 public void getStyleMetrics(float pointSize, float[] metrics, int offset) { 996 997 if (ulSize == 0f && ulPos == 0f) { 998 999 ByteBuffer head_Table = getTableBuffer(headTag); 1000 int upem = -1; 1001 if (head_Table != null && head_Table.capacity() >= 18) { 1002 ShortBuffer sb = head_Table.asShortBuffer(); 1003 upem = sb.get(9) & 0xffff; 1004 if (upem < 16 || upem > 16384) { 1005 upem = 2048; 1006 } 1007 } 1008 1009 ByteBuffer os2_Table = getTableBuffer(os_2Tag); 1010 setStrikethroughMetrics(os2_Table, upem); 1011 1012 ByteBuffer post_Table = getTableBuffer(postTag); 1013 setUnderlineMetrics(post_Table, upem); 1014 } 1015 1016 metrics[offset] = stPos * pointSize; 1017 metrics[offset+1] = stSize * pointSize; 1018 1019 metrics[offset+2] = ulPos * pointSize; 1020 metrics[offset+3] = ulSize * pointSize; 1021 } 1022 1023 private String makeString(byte[] bytes, int len, 1024 short platformID, short encoding) { 1025 1026 if (platformID == MAC_PLATFORM_ID) { 1027 encoding = -1; // hack so we can re-use the code below. 1028 } 1029 1030 /* Check for fonts using encodings 2->6 is just for 1031 * some old DBCS fonts, apparently mostly on Solaris. 1032 * Some of these fonts encode ascii names as double-byte characters. 1033 * ie with a leading zero byte for what properly should be a 1034 * single byte-char. 1035 */ 1036 if (encoding >=2 && encoding <= 6) { 1037 byte[] oldbytes = bytes; 1038 int oldlen = len; 1039 bytes = new byte[oldlen]; 1040 len = 0; 1041 for (int i=0; i<oldlen; i++) { 1042 if (oldbytes[i] != 0) { 1043 bytes[len++] = oldbytes[i]; 1044 } 1045 } 1046 } 1047 1048 String charset; 1049 switch (encoding) { 1050 case -1: charset = "US-ASCII";break; 1051 case 1: charset = "UTF-16"; break; // most common case first. 1052 case 0: charset = "UTF-16"; break; // symbol uses this 1053 case 2: charset = "SJIS"; break; 1054 case 3: charset = "GBK"; break; 1055 case 4: charset = "MS950"; break; 1056 case 5: charset = "EUC_KR"; break; 1057 case 6: charset = "Johab"; break; 1058 default: charset = "UTF-16"; break; 1059 } 1060 1061 try { 1062 return new String(bytes, 0, len, charset); 1063 } catch (UnsupportedEncodingException e) { 1064 FontUtilities.logWarning(e + " EncodingID=" + encoding); 1065 return new String(bytes, 0, len); 1066 } catch (Throwable t) { 1067 return null; 1068 } 1069 } 1070 1071 protected void initNames() { 1072 1073 byte[] name = new byte[256]; 1074 ByteBuffer buffer = getTableBuffer(nameTag); 1075 1076 if (buffer != null) { 1077 ShortBuffer sbuffer = buffer.asShortBuffer(); 1078 sbuffer.get(); // format - not needed. 1079 short numRecords = sbuffer.get(); 1080 /* The name table uses unsigned shorts. Many of these 1081 * are known small values that fit in a short. 1082 * The values that are sizes or offsets into the table could be 1083 * greater than 32767, so read and store those as ints 1084 */ 1085 int stringPtr = sbuffer.get() & 0xffff; 1086 1087 nameLocale = sun.awt.SunToolkit.getStartupLocale(); 1088 short nameLocaleID = getLCIDFromLocale(nameLocale); 1089 languageCompatibleLCIDs = 1090 getLanguageCompatibleLCIDsFromLocale(nameLocale); 1091 1092 for (int i=0; i<numRecords; i++) { 1093 short platformID = sbuffer.get(); 1094 if (platformID != MS_PLATFORM_ID && 1095 platformID != MAC_PLATFORM_ID) { 1096 sbuffer.position(sbuffer.position()+5); 1097 continue; // skip over this record. 1098 } 1099 short encodingID = sbuffer.get(); 1100 short langID = sbuffer.get(); 1101 short nameID = sbuffer.get(); 1102 int nameLen = ((int) sbuffer.get()) & 0xffff; 1103 int namePtr = (((int) sbuffer.get()) & 0xffff) + stringPtr; 1104 String tmpName = null; 1105 1106 // only want MacRoman encoding and English name on Mac. 1107 if ((platformID == MAC_PLATFORM_ID) && 1108 (encodingID != MACROMAN_SPECIFIC_ID || 1109 langID != MACROMAN_ENGLISH_LANG)) { 1110 continue; 1111 } 1112 1113 switch (nameID) { 1114 1115 case FAMILY_NAME_ID: 1116 boolean compatible = false; 1117 if (familyName == null || langID == ENGLISH_LOCALE_ID || 1118 langID == nameLocaleID || 1119 (localeFamilyName == null && 1120 (compatible = isLanguageCompatible(langID)))) 1121 { 1122 buffer.position(namePtr); 1123 buffer.get(name, 0, nameLen); 1124 tmpName = makeString(name, nameLen, platformID, encodingID); 1125 if (familyName == null || langID == ENGLISH_LOCALE_ID){ 1126 familyName = tmpName; 1127 } 1128 if (langID == nameLocaleID || 1129 (localeFamilyName == null && compatible)) 1130 { 1131 localeFamilyName = tmpName; 1132 } 1133 } 1134 /* 1135 for (int ii=0;ii<nameLen;ii++) { 1136 int val = (int)name[ii]&0xff; 1137 System.err.print(Integer.toHexString(val)+ " "); 1138 } 1139 System.err.println(); 1140 System.err.println("familyName="+familyName + 1141 " nameLen="+nameLen+ 1142 " langID="+langID+ " eid="+encodingID + 1143 " str len="+familyName.length()); 1144 1145 */ 1146 break; 1147 1148 case FULL_NAME_ID: 1149 compatible = false; 1150 if (fullName == null || langID == ENGLISH_LOCALE_ID || 1151 langID == nameLocaleID || 1152 (localeFullName == null && 1153 (compatible = isLanguageCompatible(langID)))) 1154 { 1155 buffer.position(namePtr); 1156 buffer.get(name, 0, nameLen); 1157 tmpName = makeString(name, nameLen, platformID, encodingID); 1158 1159 if (fullName == null || langID == ENGLISH_LOCALE_ID) { 1160 fullName = tmpName; 1161 } 1162 if (langID == nameLocaleID || 1163 (localeFullName == null && compatible)) 1164 { 1165 localeFullName = tmpName; 1166 } 1167 } 1168 break; 1169 } 1170 } 1171 if (localeFamilyName == null) { 1172 localeFamilyName = familyName; 1173 } 1174 if (localeFullName == null) { 1175 localeFullName = fullName; 1176 } 1177 } 1178 } 1179 1180 /* Return the requested name in the requested locale, for the 1181 * MS platform ID. If the requested locale isn't found, return US 1182 * English, if that isn't found, return null and let the caller 1183 * figure out how to handle that. 1184 */ 1185 protected String lookupName(short findLocaleID, int findNameID) { 1186 String foundName = null; 1187 byte[] name = new byte[1024]; 1188 1189 ByteBuffer buffer = getTableBuffer(nameTag); 1190 if (buffer != null) { 1191 ShortBuffer sbuffer = buffer.asShortBuffer(); 1192 sbuffer.get(); // format - not needed. 1193 short numRecords = sbuffer.get(); 1194 1195 /* The name table uses unsigned shorts. Many of these 1196 * are known small values that fit in a short. 1197 * The values that are sizes or offsets into the table could be 1198 * greater than 32767, so read and store those as ints 1199 */ 1200 int stringPtr = ((int) sbuffer.get()) & 0xffff; 1201 1202 for (int i=0; i<numRecords; i++) { 1203 short platformID = sbuffer.get(); 1204 if (platformID != MS_PLATFORM_ID) { 1205 sbuffer.position(sbuffer.position()+5); 1206 continue; // skip over this record. 1207 } 1208 short encodingID = sbuffer.get(); 1209 short langID = sbuffer.get(); 1210 short nameID = sbuffer.get(); 1211 int nameLen = ((int) sbuffer.get()) & 0xffff; 1212 int namePtr = (((int) sbuffer.get()) & 0xffff) + stringPtr; 1213 if (nameID == findNameID && 1214 ((foundName == null && langID == ENGLISH_LOCALE_ID) 1215 || langID == findLocaleID)) { 1216 buffer.position(namePtr); 1217 buffer.get(name, 0, nameLen); 1218 foundName = makeString(name, nameLen, platformID, encodingID); 1219 if (langID == findLocaleID) { 1220 return foundName; 1221 } 1222 } 1223 } 1224 } 1225 return foundName; 1226 } 1227 1228 /** 1229 * @return number of logical fonts. Is "1" for all but TTC files 1230 */ 1231 public int getFontCount() { 1232 return directoryCount; 1233 } 1234 1235 protected synchronized FontScaler getScaler() { 1236 if (scaler == null) { 1237 scaler = FontScaler.getScaler(this, fontIndex, 1238 supportsCJK, fileSize); 1239 } 1240 return scaler; 1241 } 1242 1243 1244 /* Postscript name is rarely requested. Don't waste cycles locating it 1245 * as part of font creation, nor storage to hold it. Get it only on demand. 1246 */ 1247 @Override 1248 public String getPostscriptName() { 1249 String name = lookupName(ENGLISH_LOCALE_ID, POSTSCRIPT_NAME_ID); 1250 if (name == null) { 1251 return fullName; 1252 } else { 1253 return name; 1254 } 1255 } 1256 1257 @Override 1258 public String getFontName(Locale locale) { 1259 if (locale == null) { 1260 return fullName; 1261 } else if (locale.equals(nameLocale) && localeFullName != null) { 1262 return localeFullName; 1263 } else { 1264 short localeID = getLCIDFromLocale(locale); 1265 String name = lookupName(localeID, FULL_NAME_ID); 1266 if (name == null) { 1267 return fullName; 1268 } else { 1269 return name; 1270 } 1271 } 1272 } 1273 1274 // Return a Microsoft LCID from the given Locale. 1275 // Used when getting localized font data. 1276 1277 private static void addLCIDMapEntry(Map<String, Short> map, 1278 String key, short value) { 1279 map.put(key, Short.valueOf(value)); 1280 } 1281 1282 private static synchronized void createLCIDMap() { 1283 if (lcidMap != null) { 1284 return; 1285 } 1286 1287 Map<String, Short> map = new HashMap<>(200); 1288 1289 // the following statements are derived from the langIDMap 1290 // in src/windows/native/java/lang/java_props_md.c using the following 1291 // awk script: 1292 // $1~/\/\*/ { next} 1293 // $3~/\?\?/ { next } 1294 // $3!~/_/ { next } 1295 // $1~/0x0409/ { next } 1296 // $1~/0x0c0a/ { next } 1297 // $1~/0x042c/ { next } 1298 // $1~/0x0443/ { next } 1299 // $1~/0x0812/ { next } 1300 // $1~/0x04/ { print " addLCIDMapEntry(map, " substr($3, 0, 3) "\", (short) " substr($1, 0, 6) ");" ; next } 1301 // $3~/,/ { print " addLCIDMapEntry(map, " $3 " (short) " substr($1, 0, 6) ");" ; next } 1302 // { print " addLCIDMapEntry(map, " $3 ", (short) " substr($1, 0, 6) ");" ; next } 1303 // The lines of this script: 1304 // - eliminate comments 1305 // - eliminate questionable locales 1306 // - eliminate language-only locales 1307 // - eliminate the default LCID value 1308 // - eliminate a few other unneeded LCID values 1309 // - print language-only locale entries for x04* LCID values 1310 // (apparently Microsoft doesn't use language-only LCID values - 1311 // see http://www.microsoft.com/OpenType/otspec/name.htm 1312 // - print complete entries for all other LCID values 1313 // Run 1314 // awk -f awk-script langIDMap > statements 1315 addLCIDMapEntry(map, "ar", (short) 0x0401); 1316 addLCIDMapEntry(map, "bg", (short) 0x0402); 1317 addLCIDMapEntry(map, "ca", (short) 0x0403); 1318 addLCIDMapEntry(map, "zh", (short) 0x0404); 1319 addLCIDMapEntry(map, "cs", (short) 0x0405); 1320 addLCIDMapEntry(map, "da", (short) 0x0406); 1321 addLCIDMapEntry(map, "de", (short) 0x0407); 1322 addLCIDMapEntry(map, "el", (short) 0x0408); 1323 addLCIDMapEntry(map, "es", (short) 0x040a); 1324 addLCIDMapEntry(map, "fi", (short) 0x040b); 1325 addLCIDMapEntry(map, "fr", (short) 0x040c); 1326 addLCIDMapEntry(map, "iw", (short) 0x040d); 1327 addLCIDMapEntry(map, "hu", (short) 0x040e); 1328 addLCIDMapEntry(map, "is", (short) 0x040f); 1329 addLCIDMapEntry(map, "it", (short) 0x0410); 1330 addLCIDMapEntry(map, "ja", (short) 0x0411); 1331 addLCIDMapEntry(map, "ko", (short) 0x0412); 1332 addLCIDMapEntry(map, "nl", (short) 0x0413); 1333 addLCIDMapEntry(map, "no", (short) 0x0414); 1334 addLCIDMapEntry(map, "pl", (short) 0x0415); 1335 addLCIDMapEntry(map, "pt", (short) 0x0416); 1336 addLCIDMapEntry(map, "rm", (short) 0x0417); 1337 addLCIDMapEntry(map, "ro", (short) 0x0418); 1338 addLCIDMapEntry(map, "ru", (short) 0x0419); 1339 addLCIDMapEntry(map, "hr", (short) 0x041a); 1340 addLCIDMapEntry(map, "sk", (short) 0x041b); 1341 addLCIDMapEntry(map, "sq", (short) 0x041c); 1342 addLCIDMapEntry(map, "sv", (short) 0x041d); 1343 addLCIDMapEntry(map, "th", (short) 0x041e); 1344 addLCIDMapEntry(map, "tr", (short) 0x041f); 1345 addLCIDMapEntry(map, "ur", (short) 0x0420); 1346 addLCIDMapEntry(map, "in", (short) 0x0421); 1347 addLCIDMapEntry(map, "uk", (short) 0x0422); 1348 addLCIDMapEntry(map, "be", (short) 0x0423); 1349 addLCIDMapEntry(map, "sl", (short) 0x0424); 1350 addLCIDMapEntry(map, "et", (short) 0x0425); 1351 addLCIDMapEntry(map, "lv", (short) 0x0426); 1352 addLCIDMapEntry(map, "lt", (short) 0x0427); 1353 addLCIDMapEntry(map, "fa", (short) 0x0429); 1354 addLCIDMapEntry(map, "vi", (short) 0x042a); 1355 addLCIDMapEntry(map, "hy", (short) 0x042b); 1356 addLCIDMapEntry(map, "eu", (short) 0x042d); 1357 addLCIDMapEntry(map, "mk", (short) 0x042f); 1358 addLCIDMapEntry(map, "tn", (short) 0x0432); 1359 addLCIDMapEntry(map, "xh", (short) 0x0434); 1360 addLCIDMapEntry(map, "zu", (short) 0x0435); 1361 addLCIDMapEntry(map, "af", (short) 0x0436); 1362 addLCIDMapEntry(map, "ka", (short) 0x0437); 1363 addLCIDMapEntry(map, "fo", (short) 0x0438); 1364 addLCIDMapEntry(map, "hi", (short) 0x0439); 1365 addLCIDMapEntry(map, "mt", (short) 0x043a); 1366 addLCIDMapEntry(map, "se", (short) 0x043b); 1367 addLCIDMapEntry(map, "gd", (short) 0x043c); 1368 addLCIDMapEntry(map, "ms", (short) 0x043e); 1369 addLCIDMapEntry(map, "kk", (short) 0x043f); 1370 addLCIDMapEntry(map, "ky", (short) 0x0440); 1371 addLCIDMapEntry(map, "sw", (short) 0x0441); 1372 addLCIDMapEntry(map, "tt", (short) 0x0444); 1373 addLCIDMapEntry(map, "bn", (short) 0x0445); 1374 addLCIDMapEntry(map, "pa", (short) 0x0446); 1375 addLCIDMapEntry(map, "gu", (short) 0x0447); 1376 addLCIDMapEntry(map, "ta", (short) 0x0449); 1377 addLCIDMapEntry(map, "te", (short) 0x044a); 1378 addLCIDMapEntry(map, "kn", (short) 0x044b); 1379 addLCIDMapEntry(map, "ml", (short) 0x044c); 1380 addLCIDMapEntry(map, "mr", (short) 0x044e); 1381 addLCIDMapEntry(map, "sa", (short) 0x044f); 1382 addLCIDMapEntry(map, "mn", (short) 0x0450); 1383 addLCIDMapEntry(map, "cy", (short) 0x0452); 1384 addLCIDMapEntry(map, "gl", (short) 0x0456); 1385 addLCIDMapEntry(map, "dv", (short) 0x0465); 1386 addLCIDMapEntry(map, "qu", (short) 0x046b); 1387 addLCIDMapEntry(map, "mi", (short) 0x0481); 1388 addLCIDMapEntry(map, "ar_IQ", (short) 0x0801); 1389 addLCIDMapEntry(map, "zh_CN", (short) 0x0804); 1390 addLCIDMapEntry(map, "de_CH", (short) 0x0807); 1391 addLCIDMapEntry(map, "en_GB", (short) 0x0809); 1392 addLCIDMapEntry(map, "es_MX", (short) 0x080a); 1393 addLCIDMapEntry(map, "fr_BE", (short) 0x080c); 1394 addLCIDMapEntry(map, "it_CH", (short) 0x0810); 1395 addLCIDMapEntry(map, "nl_BE", (short) 0x0813); 1396 addLCIDMapEntry(map, "no_NO_NY", (short) 0x0814); 1397 addLCIDMapEntry(map, "pt_PT", (short) 0x0816); 1398 addLCIDMapEntry(map, "ro_MD", (short) 0x0818); 1399 addLCIDMapEntry(map, "ru_MD", (short) 0x0819); 1400 addLCIDMapEntry(map, "sr_CS", (short) 0x081a); 1401 addLCIDMapEntry(map, "sv_FI", (short) 0x081d); 1402 addLCIDMapEntry(map, "az_AZ", (short) 0x082c); 1403 addLCIDMapEntry(map, "se_SE", (short) 0x083b); 1404 addLCIDMapEntry(map, "ga_IE", (short) 0x083c); 1405 addLCIDMapEntry(map, "ms_BN", (short) 0x083e); 1406 addLCIDMapEntry(map, "uz_UZ", (short) 0x0843); 1407 addLCIDMapEntry(map, "qu_EC", (short) 0x086b); 1408 addLCIDMapEntry(map, "ar_EG", (short) 0x0c01); 1409 addLCIDMapEntry(map, "zh_HK", (short) 0x0c04); 1410 addLCIDMapEntry(map, "de_AT", (short) 0x0c07); 1411 addLCIDMapEntry(map, "en_AU", (short) 0x0c09); 1412 addLCIDMapEntry(map, "fr_CA", (short) 0x0c0c); 1413 addLCIDMapEntry(map, "sr_CS", (short) 0x0c1a); 1414 addLCIDMapEntry(map, "se_FI", (short) 0x0c3b); 1415 addLCIDMapEntry(map, "qu_PE", (short) 0x0c6b); 1416 addLCIDMapEntry(map, "ar_LY", (short) 0x1001); 1417 addLCIDMapEntry(map, "zh_SG", (short) 0x1004); 1418 addLCIDMapEntry(map, "de_LU", (short) 0x1007); 1419 addLCIDMapEntry(map, "en_CA", (short) 0x1009); 1420 addLCIDMapEntry(map, "es_GT", (short) 0x100a); 1421 addLCIDMapEntry(map, "fr_CH", (short) 0x100c); 1422 addLCIDMapEntry(map, "hr_BA", (short) 0x101a); 1423 addLCIDMapEntry(map, "ar_DZ", (short) 0x1401); 1424 addLCIDMapEntry(map, "zh_MO", (short) 0x1404); 1425 addLCIDMapEntry(map, "de_LI", (short) 0x1407); 1426 addLCIDMapEntry(map, "en_NZ", (short) 0x1409); 1427 addLCIDMapEntry(map, "es_CR", (short) 0x140a); 1428 addLCIDMapEntry(map, "fr_LU", (short) 0x140c); 1429 addLCIDMapEntry(map, "bs_BA", (short) 0x141a); 1430 addLCIDMapEntry(map, "ar_MA", (short) 0x1801); 1431 addLCIDMapEntry(map, "en_IE", (short) 0x1809); 1432 addLCIDMapEntry(map, "es_PA", (short) 0x180a); 1433 addLCIDMapEntry(map, "fr_MC", (short) 0x180c); 1434 addLCIDMapEntry(map, "sr_BA", (short) 0x181a); 1435 addLCIDMapEntry(map, "ar_TN", (short) 0x1c01); 1436 addLCIDMapEntry(map, "en_ZA", (short) 0x1c09); 1437 addLCIDMapEntry(map, "es_DO", (short) 0x1c0a); 1438 addLCIDMapEntry(map, "sr_BA", (short) 0x1c1a); 1439 addLCIDMapEntry(map, "ar_OM", (short) 0x2001); 1440 addLCIDMapEntry(map, "en_JM", (short) 0x2009); 1441 addLCIDMapEntry(map, "es_VE", (short) 0x200a); 1442 addLCIDMapEntry(map, "ar_YE", (short) 0x2401); 1443 addLCIDMapEntry(map, "es_CO", (short) 0x240a); 1444 addLCIDMapEntry(map, "ar_SY", (short) 0x2801); 1445 addLCIDMapEntry(map, "en_BZ", (short) 0x2809); 1446 addLCIDMapEntry(map, "es_PE", (short) 0x280a); 1447 addLCIDMapEntry(map, "ar_JO", (short) 0x2c01); 1448 addLCIDMapEntry(map, "en_TT", (short) 0x2c09); 1449 addLCIDMapEntry(map, "es_AR", (short) 0x2c0a); 1450 addLCIDMapEntry(map, "ar_LB", (short) 0x3001); 1451 addLCIDMapEntry(map, "en_ZW", (short) 0x3009); 1452 addLCIDMapEntry(map, "es_EC", (short) 0x300a); 1453 addLCIDMapEntry(map, "ar_KW", (short) 0x3401); 1454 addLCIDMapEntry(map, "en_PH", (short) 0x3409); 1455 addLCIDMapEntry(map, "es_CL", (short) 0x340a); 1456 addLCIDMapEntry(map, "ar_AE", (short) 0x3801); 1457 addLCIDMapEntry(map, "es_UY", (short) 0x380a); 1458 addLCIDMapEntry(map, "ar_BH", (short) 0x3c01); 1459 addLCIDMapEntry(map, "es_PY", (short) 0x3c0a); 1460 addLCIDMapEntry(map, "ar_QA", (short) 0x4001); 1461 addLCIDMapEntry(map, "es_BO", (short) 0x400a); 1462 addLCIDMapEntry(map, "es_SV", (short) 0x440a); 1463 addLCIDMapEntry(map, "es_HN", (short) 0x480a); 1464 addLCIDMapEntry(map, "es_NI", (short) 0x4c0a); 1465 addLCIDMapEntry(map, "es_PR", (short) 0x500a); 1466 1467 lcidMap = map; 1468 } 1469 1470 private static short getLCIDFromLocale(Locale locale) { 1471 // optimize for common case 1472 if (locale.equals(Locale.US)) { 1473 return US_LCID; 1474 } 1475 1476 if (lcidMap == null) { 1477 createLCIDMap(); 1478 } 1479 1480 String key = locale.toString(); 1481 while (!"".equals(key)) { 1482 Short lcidObject = lcidMap.get(key); 1483 if (lcidObject != null) { 1484 return lcidObject.shortValue(); 1485 } 1486 int pos = key.lastIndexOf('_'); 1487 if (pos < 1) { 1488 return US_LCID; 1489 } 1490 key = key.substring(0, pos); 1491 } 1492 1493 return US_LCID; 1494 } 1495 1496 @Override 1497 public String getFamilyName(Locale locale) { 1498 if (locale == null) { 1499 return familyName; 1500 } else if (locale.equals(nameLocale) && localeFamilyName != null) { 1501 return localeFamilyName; 1502 } else { 1503 short localeID = getLCIDFromLocale(locale); 1504 String name = lookupName(localeID, FAMILY_NAME_ID); 1505 if (name == null) { 1506 return familyName; 1507 } else { 1508 return name; 1509 } 1510 } 1511 } 1512 1513 public CharToGlyphMapper getMapper() { 1514 if (mapper == null) { 1515 mapper = new TrueTypeGlyphMapper(this); 1516 } 1517 return mapper; 1518 } 1519 1520 /* This duplicates initNames() but that has to run fast as its used 1521 * during typical start-up and the information here is likely never 1522 * needed. 1523 */ 1524 protected void initAllNames(int requestedID, HashSet<String> names) { 1525 byte[] name = new byte[256]; 1526 ByteBuffer buffer = getTableBuffer(nameTag); 1527 1528 if (buffer != null) { 1529 ShortBuffer sbuffer = buffer.asShortBuffer(); 1530 sbuffer.get(); // format - not needed. 1531 short numRecords = sbuffer.get(); 1532 1533 /* The name table uses unsigned shorts. Many of these 1534 * are known small values that fit in a short. 1535 * The values that are sizes or offsets into the table could be 1536 * greater than 32767, so read and store those as ints 1537 */ 1538 int stringPtr = ((int) sbuffer.get()) & 0xffff; 1539 for (int i=0; i<numRecords; i++) { 1540 short platformID = sbuffer.get(); 1541 if (platformID != MS_PLATFORM_ID) { 1542 sbuffer.position(sbuffer.position()+5); 1543 continue; // skip over this record. 1544 } 1545 short encodingID = sbuffer.get(); 1546 /* short langID = */ sbuffer.get(); 1547 short nameID = sbuffer.get(); 1548 int nameLen = ((int) sbuffer.get()) & 0xffff; 1549 int namePtr = (((int) sbuffer.get()) & 0xffff) + stringPtr; 1550 1551 if (nameID == requestedID) { 1552 buffer.position(namePtr); 1553 buffer.get(name, 0, nameLen); 1554 names.add(makeString(name, nameLen, platformID, encodingID)); 1555 } 1556 } 1557 } 1558 } 1559 1560 String[] getAllFamilyNames() { 1561 HashSet<String> aSet = new HashSet<>(); 1562 try { 1563 initAllNames(FAMILY_NAME_ID, aSet); 1564 } catch (Exception e) { 1565 /* In case of malformed font */ 1566 } 1567 return aSet.toArray(new String[0]); 1568 } 1569 1570 String[] getAllFullNames() { 1571 HashSet<String> aSet = new HashSet<>(); 1572 try { 1573 initAllNames(FULL_NAME_ID, aSet); 1574 } catch (Exception e) { 1575 /* In case of malformed font */ 1576 } 1577 return aSet.toArray(new String[0]); 1578 } 1579 1580 /* Used by the OpenType engine for mark positioning. 1581 */ 1582 @Override 1583 Point2D.Float getGlyphPoint(long pScalerContext, 1584 int glyphCode, int ptNumber) { 1585 try { 1586 return getScaler().getGlyphPoint(pScalerContext, 1587 glyphCode, ptNumber); 1588 } catch(FontScalerException fe) { 1589 return null; 1590 } 1591 } 1592 1593 private char[] gaspTable; 1594 1595 private char[] getGaspTable() { 1596 1597 if (gaspTable != null) { 1598 return gaspTable; 1599 } 1600 1601 ByteBuffer buffer = getTableBuffer(gaspTag); 1602 if (buffer == null) { 1603 return gaspTable = new char[0]; 1604 } 1605 1606 CharBuffer cbuffer = buffer.asCharBuffer(); 1607 char format = cbuffer.get(); 1608 /* format "1" has appeared for some Windows Vista fonts. 1609 * Its presently undocumented but the existing values 1610 * seem to be still valid so we can use it. 1611 */ 1612 if (format > 1) { // unrecognised format 1613 return gaspTable = new char[0]; 1614 } 1615 1616 char numRanges = cbuffer.get(); 1617 if (4+numRanges*4 > getTableSize(gaspTag)) { // sanity check 1618 return gaspTable = new char[0]; 1619 } 1620 gaspTable = new char[2*numRanges]; 1621 cbuffer.get(gaspTable); 1622 return gaspTable; 1623 } 1624 1625 /* This is to obtain info from the TT 'gasp' (grid-fitting and 1626 * scan-conversion procedure) table which specifies three combinations: 1627 * Hint, Smooth (greyscale), Hint and Smooth. 1628 * In this simplified scheme we don't distinguish the latter two. We 1629 * hint even at small sizes, so as to preserve metrics consistency. 1630 * If the information isn't available default values are substituted. 1631 * The more precise defaults we'd do if we distinguished the cases are: 1632 * Bold (no other style) fonts : 1633 * 0-8 : Smooth ( do grey) 1634 * 9+ : Hint + smooth (gridfit + grey) 1635 * Plain, Italic and Bold-Italic fonts : 1636 * 0-8 : Smooth ( do grey) 1637 * 9-17 : Hint (gridfit) 1638 * 18+ : Hint + smooth (gridfit + grey) 1639 * The defaults should rarely come into play as most TT fonts provide 1640 * better defaults. 1641 * REMIND: consider unpacking the table into an array of booleans 1642 * for faster use. 1643 */ 1644 @Override 1645 public boolean useAAForPtSize(int ptsize) { 1646 1647 char[] gasp = getGaspTable(); 1648 if (gasp.length > 0) { 1649 for (int i=0;i<gasp.length;i+=2) { 1650 if (ptsize <= gasp[i]) { 1651 return ((gasp[i+1] & 0x2) != 0); // bit 2 means DO_GRAY; 1652 } 1653 } 1654 return true; 1655 } 1656 1657 if (style == Font.BOLD) { 1658 return true; 1659 } else { 1660 return ptsize <= 8 || ptsize >= 18; 1661 } 1662 } 1663 1664 @Override 1665 public boolean hasSupplementaryChars() { 1666 return ((TrueTypeGlyphMapper)getMapper()).hasSupplementaryChars(); 1667 } 1668 1669 @Override 1670 public String toString() { 1671 return "** TrueType Font: Family="+familyName+ " Name="+fullName+ 1672 " style="+style+" fileName="+getPublicFileName(); 1673 } 1674 1675 1676 private static Map<String, short[]> lcidLanguageCompatibilityMap; 1677 private static final short[] EMPTY_COMPATIBLE_LCIDS = new short[0]; 1678 1679 // the language compatible LCIDs for this font's nameLocale 1680 private short[] languageCompatibleLCIDs; 1681 1682 /* 1683 * Returns true if the given lcid's language is compatible 1684 * to the language of the startup Locale. I.e. if 1685 * startupLocale.getLanguage().equals(lcidLocale.getLanguage()) would 1686 * return true. 1687 */ 1688 private boolean isLanguageCompatible(short lcid){ 1689 for (short s : languageCompatibleLCIDs) { 1690 if (s == lcid) { 1691 return true; 1692 } 1693 } 1694 return false; 1695 } 1696 1697 /* 1698 * Returns an array of all the language compatible LCIDs for the 1699 * given Locale. This array is later used to find compatible 1700 * locales. 1701 */ 1702 private static short[] getLanguageCompatibleLCIDsFromLocale(Locale locale) { 1703 if (lcidLanguageCompatibilityMap == null) { 1704 createLCIDMap(); 1705 createLCIDLanguageCompatibilityMap(); 1706 } 1707 String language = locale.getLanguage(); 1708 short[] result = lcidLanguageCompatibilityMap.get(language); 1709 return result == null ? EMPTY_COMPATIBLE_LCIDS : result; 1710 } 1711 1712 // private static void prtLine(String s) { 1713 // System.out.println(s); 1714 // } 1715 1716 // /* 1717 // * Initializes the map from Locale keys (e.g. "en_BZ" or "de") 1718 // * to language compatible LCIDs. 1719 // * This map could be statically created based on the fixed known set 1720 // * added to lcidMap. 1721 // */ 1722 // private static void createLCIDLanguageCompatibilityMap() { 1723 // if (lcidLanguageCompatibilityMap != null) { 1724 // return; 1725 // } 1726 // HashMap<String, List<Short>> result = new HashMap<>(); 1727 // for (Entry<String, Short> e : lcidMap.entrySet()) { 1728 // String language = e.getKey(); 1729 // int index = language.indexOf('_'); 1730 // if (index != -1) { 1731 // language = language.substring(0, index); 1732 // } 1733 // List<Short> list = result.get(language); 1734 // if (list == null) { 1735 // list = new ArrayList<>(); 1736 // result.put(language, list); 1737 // } 1738 // if (index == -1) { 1739 // list.add(0, e.getValue()); 1740 // } else{ 1741 // list.add(e.getValue()); 1742 // } 1743 // } 1744 // Map<String, short[]> compMap = new HashMap<>(); 1745 // for (Entry<String, List<Short>> e : result.entrySet()) { 1746 // if (e.getValue().size() > 1) { 1747 // List<Short> list = e.getValue(); 1748 // short[] shorts = new short[list.size()]; 1749 // for (int i = 0; i < shorts.length; i++) { 1750 // shorts[i] = list.get(i); 1751 // } 1752 // compMap.put(e.getKey(), shorts); 1753 // } 1754 // } 1755 1756 // /* Now dump code to init the map to System.out */ 1757 // prtLine(" private static void createLCIDLanguageCompatibilityMap() {"); 1758 // prtLine(""); 1759 1760 // prtLine(" Map<String, short[]> map = new HashMap<>();"); 1761 // prtLine(""); 1762 // prtLine(" short[] sarr;"); 1763 // for (Entry<String, short[]> e : compMap.entrySet()) { 1764 // String lang = e.getKey(); 1765 // short[] ids = e.getValue(); 1766 // StringBuilder sb = new StringBuilder("sarr = new short[] { "); 1767 // for (int i = 0; i < ids.length; i++) { 1768 // sb.append(ids[i]+", "); 1769 // } 1770 // sb.append("}"); 1771 // prtLine(" " + sb + ";"); 1772 // prtLine(" map.put(\"" + lang + "\", sarr);"); 1773 // } 1774 // prtLine(""); 1775 // prtLine(" lcidLanguageCompatibilityMap = map;"); 1776 // prtLine(" }"); 1777 // /* done dumping map */ 1778 1779 // lcidLanguageCompatibilityMap = compMap; 1780 // } 1781 1782 private static void createLCIDLanguageCompatibilityMap() { 1783 1784 Map<String, short[]> map = new HashMap<>(); 1785 1786 short[] sarr; 1787 sarr = new short[] { 1031, 3079, 5127, 2055, 4103, }; 1788 map.put("de", sarr); 1789 sarr = new short[] { 1044, 2068, }; 1790 map.put("no", sarr); 1791 sarr = new short[] { 1049, 2073, }; 1792 map.put("ru", sarr); 1793 sarr = new short[] { 1053, 2077, }; 1794 map.put("sv", sarr); 1795 sarr = new short[] { 1046, 2070, }; 1796 map.put("pt", sarr); 1797 sarr = new short[] { 1131, 3179, 2155, }; 1798 map.put("qu", sarr); 1799 sarr = new short[] { 1086, 2110, }; 1800 map.put("ms", sarr); 1801 sarr = new short[] { 11273, 3081, 12297, 8201, 10249, 4105, 13321, 6153, 7177, 5129, 2057, }; 1802 map.put("en", sarr); 1803 sarr = new short[] { 1050, 4122, }; 1804 map.put("hr", sarr); 1805 sarr = new short[] { 1040, 2064, }; 1806 map.put("it", sarr); 1807 sarr = new short[] { 1036, 5132, 6156, 2060, 3084, 4108, }; 1808 map.put("fr", sarr); 1809 sarr = new short[] { 1034, 12298, 14346, 2058, 8202, 19466, 17418, 9226, 13322, 5130, 7178, 11274, 16394, 4106, 10250, 6154, 18442, 20490, 15370, }; 1810 map.put("es", sarr); 1811 sarr = new short[] { 1028, 3076, 5124, 4100, 2052, }; 1812 map.put("zh", sarr); 1813 sarr = new short[] { 1025, 8193, 16385, 9217, 2049, 14337, 15361, 11265, 13313, 10241, 7169, 12289, 4097, 5121, 6145, 3073, }; 1814 map.put("ar", sarr); 1815 sarr = new short[] { 1083, 3131, 2107, }; 1816 map.put("se", sarr); 1817 sarr = new short[] { 1048, 2072, }; 1818 map.put("ro", sarr); 1819 sarr = new short[] { 1043, 2067, }; 1820 map.put("nl", sarr); 1821 sarr = new short[] { 7194, 3098, }; 1822 map.put("sr", sarr); 1823 1824 lcidLanguageCompatibilityMap = map; 1825 } 1826 }