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