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