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